from appservices.common.util import *
from appservices.common.form_schemas import *
from flask import session
admin = Blueprint("admin",__name__)


@admin.route("/test_server",methods=["GET"])
def test_server():
    return "Server check successful!"

@admin.errorhandler(500)
def handle_500_error(error):
    # You can log the error here or perform additional processing if needed
    return jsonify({"error": "Internal Server Error", "message": str(error)}), 500
# Admin Create API

# Admin Create API
@admin.route("/create_admin",methods=["POST"])
@csrf_protect
def create_admin():
    data_status={"responseStatus":0,"result":""}
    csrf_token = request.form.get("csrf_token")
    userName = request.json.get("userName","")
    email = request.json.get("email","")
    password = request.json.get("password","")
    phoneNumber = request.json.get("phoneNumber","")
    profilePicture = request.json.get("profilePicture","")

    if userName and email and password and phoneNumber:
        try:
            admin_create_table=SuperAdmin(
                userName=userName,
                email=email,
                password=generate_password_hash(password),
                phoneNumber=phoneNumber,
                createdOn=datetime.datetime.now(),
                status=1
                )
            admin_save=admin_create_table.save()
            adminId=str(admin_save.id)          
            data_status["responseStatus"]=1
            data_status["result"]="Admin created successfully!"
            return data_status
        except Exception as e:
            app.logger.error(traceback.format_exc())
            data_status["result"]="Unable to create admin!!"
            return data_status
    else:
        data_status["result"]="Required fields are missing!"
        return data_status

# Old Admin Login Code
# @admin.route("/admin_login",methods=["POST","GET"])
# def admin_login():
#     data_status={"responseStatus":0,"result":""}
#     email=request.form.get("email","")
#     password=request.form.get("password","")

#     if email and password:
#         try:
#             admin_queryset=SuperAdmin.objects(email__iexact=email).first()
#             if admin_queryset:
#                 adminId = str(admin_queryset.id)
#                 if check_password_hash(admin_queryset.password,password):
#                     if admin_queryset.status == 1:
#                         adminData=fetch_admin_details(admin_queryset)
#                         first_chars = re.findall(r'\b\w', admin_queryset.userName)
#                         imageString = ''.join(first_chars)

#                         # permissionsList = check_permissions(str(admin_queryset.id),"")

#                         session["adminId"] = str(admin_queryset.id)
#                         session["userName"] = admin_queryset.userName
#                         session["imageString"] = imageString
#                         # session["permissionsList"] = permissionsList
#                         return redirect(url_for("admin.dashboard"))
#                     else:
#                         error = "In-active account!"
#                         return render_template("super_admin_templates/admin_login.html",error=error)
#                 else:
#                     error = "Wrong password!"
#                     return render_template("super_admin_templates/admin_login.html",error=error)
#             else:
#                 error = "Invaild email id!"
#                 return render_template("super_admin_templates/admin_login.html",error=error)
#         except Exception as e:
#             app.logger.error(traceback.format_exc())
#             return render_template("super_admin_templates/admin_login.html")
#     else:
#         error = ""
#         return render_template("super_admin_templates/admin_login.html",error=error)




@admin.route("/admin_login", methods=["POST", "GET"])
@csrf_protect
@nocache
def admin_login():
    data_status = {"responseStatus": 0, "result": ""}
    # print("accessToken ",session.get("accessToken"))
    # print("'adminId ",session.get("adminId"))
    
    if session.get("adminId") and session.get("accessToken") and request.cookies.get("access_token_cookie"):
        return redirect(url_for("admin.dashboard")) 
    
    csrf_token = request.form.get("csrf_token")
    email = request.form.get("email", "")
    password = request.form.get("password", "")
    userAgent = request.headers.get("User-Agent")
    latitude = request.form.get("latitude", "")
    longitude = request.form.get("longitude", "")
    
    # print("Latitude ", latitude)
    # print("Longitude ",longitude)
    loginBrowser = request.headers.get("Sec-Ch-Ua","")

    if loginBrowser:
        loginBrowseData = loginBrowser.split(";")
        browser = loginBrowseData[0]
    else:
        loginBrowseData = request.headers.get('User-Agent',"").split(";")
        browser = loginBrowseData[0]

    existing_record=""
    client_ip=0
    # Extracting client IP address
    if request.headers.getlist("X-Forwarded-For"):
        client_ip = request.headers.getlist("X-Forwarded-For")[0]
    else:
        client_ip = request.remote_addr

    actionDate=datetime.datetime.now()

    jsonData = request.form.to_dict(flat=True)

    requestData = [existing_record]
    updatedrequestData = [jsonData]
    save_admin_log_table = save_admin_logs_data(None,None,None,"admin_login","login",actionDate,client_ip,browser,"",requestData,updatedrequestData,latitude,longitude)
    # print(str(save_admin_log_table.id),"((((((((save_admin_log_table))))))))")

    # form = AdminLoginForm()
    # if form.validate_on_submit():
    if email and password:
        try:
            admin_queryset = SuperAdmin.objects(email__iexact=email).first()
            if admin_queryset:
                if not validate_email(email):
                    # # flash("Invalid email format!")
                    # data_status['responseStatus']=2
                    # data_status['result']={"email":"Invalid email format!"}
                    err_msg = "Invalid email format"
                    return render_template("super_admin_templates/admin_login.html",email_error=err_msg, password_error="")
                
                if not validate_password(password):
                    # flash("Password must be 8-30 characters long, include at least one uppercase letter, one lowercase letter, one number, and one special character.")
                    # data_status['responseStatus']=2
                    # data_status['result']={"password":"Password must be 8-30 characters long, include at least one uppercase letter, one lowercase letter, one number, and one special character."}
                    err_msg = "Password must be 8-30 characters long, include at least one uppercase letter, one lowercase letter, one number, and one special character."
                    return render_template("super_admin_templates/admin_login.html",email_error="", password_error=err_msg)

                if check_password_hash(admin_queryset.password, password):
                    phoneNumber=str(admin_queryset.phoneNumber)
                    if admin_queryset.status == 1:
                        accessToken=str(random_alphanumeric_generate(32))
                        # print(accessToken,"((((((((((((accessToken)))))))))))aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)")
                        message=admin_queryset.userName+" admin login successfully!"
                        token = generate_token(identity=admin_queryset.userName, expiration_time=token_expiration_time) ### in minutes

                        admin_queryset.update(accessToken=accessToken)
                        admin_queryset.update(loginLatitude=latitude)
                        admin_queryset.update(loginLongitude=longitude)
            
                        save_admin_log_table.update(message=message, adminId=ObjectId(admin_queryset.id))
                        authenticationEnabled=admin_queryset.authenticationEnabled
            
                        if authenticationEnabled == True:
                            # print(accessToken,"((((((((((((accessToken)))))))))))###$%%@#%@#%@#%@#%%%%%%%%%%%%%%%%%%%%)")
                            # otpCode = str(random.randint(100000, 999999))
                            status=0
                            try:
                                # smsmessage="Your Graam Pay Admin Login OTP is "+str(otpCode)
                                otpType = "Common_Otp"
                                adminName = str(admin_queryset.userName)

                                smsresponse=send_sms(phoneNumber,otpType,adminName)

                                # print(smsresponse,"((((((((((smsresponse))))))))))")
                                
                                otpCode = smsresponse.get('otp')
                                otpcheck_queryset=OtpChecks(
                                    userId=None,
                                    otpCode=str(otpCode),
                                    phoneNumber=str(phoneNumber),
                                    attempts=0,
                                    status=0,
                                    createdOn=datetime.datetime.now(),
                                    otpReason=message
                                    ).save()
                                otpCheckId=str(otpcheck_queryset.id)

                                try:
                                    email=admin_queryset.email
                                    # email="saikerla@viyonafintech.com"
                                    if email:
                                        mail_subject = "Otp verification for GraamPay Admin Login!"
                                        recipients_list = [email]
                                        template_name = "emails/emailotpverification.html"
                                        mail_data = {
                                        "userName":adminName,
                                        "otpCode":otpCode,
                                        }
                                        send_asynchronous_email(mail_subject, recipients_list, template_name, mail_data)
                                        # mailoutputData = send_asynchronous_email(mail_subject, recipients_list, template_name, mail_data)
                                except Exception as e:
                                    app.logger.error(traceback.format_exc())
                                    pass

                                adminId = str(admin_queryset.id)
                                admin_login_report_table = SuperAdminLogs(
                                    adminId = adminId,
                                    ipAddress = client_ip,
                                    loginBrowser = browser.strip('"'),
                                    userAgent = userAgent,
                                    createdOn = datetime.datetime.now(),
                                    otpCode=str(otpCode),
                                    attempts=0,
                                    authenticationEnabled=authenticationEnabled,
                                    status = status
                                    ).save()
                                adminLogId=str(admin_login_report_table.id)
                            except Exception as e:
                                adminLogId=""
                                app.logger.error(traceback.format_exc())
                                pass
                            print("aasdad before otp page")
                            response = make_response(render_template("super_admin_templates/admin_login_otp.html", adminLogId=adminLogId,otpCheckId=otpCheckId))
                            set_access_cookies(response, token)
                            return response
                            # return render_template("super_admin_templates/admin_login_otp.html", adminLogId=adminLogId,otpCheckId=otpCheckId)
                        else:
                            try:
                                adminId = str(admin_queryset.id)
                                admin_login_report_table = SuperAdminLogs(
                                    adminId = adminId,
                                    ipAddress = client_ip,
                                    loginBrowser = browser.strip('"'),
                                    userAgent = userAgent,
                                    createdOn = datetime.datetime.now(),
                                    otpCode="",
                                    attempts=0,
                                    authenticationEnabled=authenticationEnabled,
                                    status = 1
                                    ).save()
                                adminLogId=str(admin_login_report_table.id)
                            except Exception as e:
                                adminLogId=""
                                app.logger.error(traceback.format_exc())
                                pass

                            todaySignupCount = 0

                            startDate = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
                            endDate = datetime.datetime.now().replace(hour=23, minute=59, second=59, microsecond=999999)
                            merchant_queryset = Users.objects(createdOn__gte=startDate,createdOn__lte=endDate).order_by('-createdOn')
                            todaySignupCount = merchant_queryset.count()
                            merchantList = []
                            for each_merchant in merchant_queryset:
                                merchantDict = {
                                "merchantName":each_merchant.fullName,
                                "createdOn":each_merchant.createdOn.strftime("%d-%m-%Y %H:%M:%S %p")
                                }
                                merchantList.append(merchantDict)

                            adminData=fetch_admin_details(admin_queryset)
                            first_chars = re.findall(r'\b\w', admin_queryset.userName)
                            imageString = ''.join(first_chars)


                            rejected_count = 0
                            pending_count = 0
                            submitted_count = 0
                            approved_count = 0
                            processing_count = 0  
                            pending_user_kyc_count = 0 

                            users_kyc_queryset = UserKYC.objects(status__in=[0, 1]).order_by("-id")
    
                            for each_user_kyc in users_kyc_queryset:

                                kycStatusList = [
                                    each_user_kyc.panStatus,
                                    each_user_kyc.aadharStatus,
                                    each_user_kyc.bankStatus,
                                    each_user_kyc.videoVerificationStatus,
                                    each_user_kyc.agreementVerificationStatus
                                ]

                                non_approved_status_count = len([status for status in kycStatusList if status != "Approved"])

                                if non_approved_status_count > 0:
                                    pending_user_kyc_count += 1

                            admin_queryset.update(
                                accessToken=accessToken,
                                # accessToken=accessToken,
                                # accessToken=accessToken
                            )
                            session["adminId"] = str(admin_queryset.id)
                            session["userName"] = admin_queryset.userName
                            session["imageString"] = imageString
                            session["pendingUsersCount"] = pending_user_kyc_count
                            session["merchantList"] = merchantList
                            session["todaySignupCount"] = todaySignupCount
                            session["accessToken"] = accessToken
                            session["user_email"] = email
                            # print(session["accessToken"],"((((((((((((((session token))))))))))))))")
                            response = make_response(redirect(url_for("admin.dashboard")))
                            set_access_cookies(response, token)
                            return response
                            # return redirect(url_for("admin.dashboard"))
                    else:
                        error = "Inactive account!"
                        return render_template("super_admin_templates/admin_login.html", error=error)
                else:
                    print("aaaaaaaaaaaaaaaaaaaaaaaa oworng passweod")
                    # error = "Wrong password!"
                    # print("error",error)
                    # return render_template("super_admin_templates/admin_login.html", error=error)
                    # data_status['responseStatus']=2
                    # data_status['result']={"password":"Wrong password"}
                    err_msg = "Wrong password"
                    return render_template("super_admin_templates/admin_login.html",email_error="", password_error=err_msg)
            else:
                # error = "Invalid email id!"
                # return render_template("super_admin_templates/admin_login.html", error=error)
                # flash("Invalid email id")
                data_status['responseStatus']=2
                data_status['result']={"email":"Invalid email id"}
                err_msg = "Invalid email id"
                return render_template("super_admin_templates/admin_login.html",email_error=err_msg, password_error="")
        except Exception as e:
            app.logger.error(traceback.format_exc())
            return render_template("super_admin_templates/admin_login.html")
    else:
        # error = "Required fields are missing!!"
        return render_template("super_admin_templates/admin_login.html")
    # else:
    #     data_status['result']=form.errors
    #     return data_status







@admin.route("/admin_logout",methods=["GET","POST"])
def admin_logout():
    adminId = session.get("adminId")
    # print("((((((((((((((((((((((((adminID)))))))))))))))))))))))) in logout",adminId)
    accessToken = session.get("accessToken")
    admin_queryset = SuperAdmin.objects(id=adminId,accessToken=accessToken).first()

    if admin_queryset:
        admin_queryset.update(accessToken="")
    session.clear()
    return redirect(url_for("admin.admin_login"))


@admin.route("/admin_login_otp", methods=["GET", "POST"])
@csrf_protect
def admin_login_otp():
    csrf_token = request.form.get("csrf_token")
    if request.method == "POST":
        otp = request.form.get("otp", "")
        adminLogId = request.form.get("adminLogId")
        otpCheckId = request.form.get("otpCheckId")
        userAgent = request.headers.get("User-Agent")

        print(otpCheckId,"((((((((((otpCheckId))))))))))")
 
        loginBrowser = request.headers.get("Sec-Ch-Ua")
        if loginBrowser:
            loginBrowseData = loginBrowser.split(";")
            browser = loginBrowseData[0]
        else:
            loginBrowseData = request.headers.get('User-Agent').split(";")
            browser = loginBrowseData[0]
 
        client_ip=0
        # Extracting client IP address
        if request.headers.getlist("X-Forwarded-For"): 
            client_ip = request.headers.getlist("X-Forwarded-For")[0]
        else:
            client_ip = request.remote_addr
        requestData = []
        updatedrequestData = []
        actionDate=datetime.datetime.now()
        save_admin_log_table = save_admin_logs_data(None,None,None,"admin_login","login",actionDate,client_ip,browser,"",requestData,updatedrequestData)
 
        if otp and adminLogId and otpCheckId:
            try:
                admin_queryset = SuperAdminLogs.objects(id=str(adminLogId),status=0).first()
                message=admin_queryset.adminId.userName+" OTP sent successfully!"
                save_admin_log_table.update(message=message,adminId=ObjectId(admin_queryset.adminId.id))
                # attempts=admin_queryset.attempts+1
 
                otpcheck_querryset=OtpChecks.objects(id=str(otpCheckId),status=0).first()
                if otpcheck_querryset:
                    attempts=otpcheck_querryset.attempts+1
                    if otpcheck_querryset.otpCode==otp:
                        otpcheck_querryset.update(status=1,attempts=attempts)
 
                        admin_login_queryset = SuperAdmin.objects(id=str(admin_queryset.adminId.id)).first()
 
                        todaySignupCount = 0
 
                        startDate = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
                        endDate = datetime.datetime.now().replace(hour=23, minute=59, second=59, microsecond=999999)
                        merchant_queryset = Users.objects(createdOn__gte=startDate,createdOn__lte=endDate).order_by('-createdOn')
                        todaySignupCount = merchant_queryset.count()
                        merchantList = []
                        for each_merchant in merchant_queryset:
                            merchantDict = {
                            "merchantName":each_merchant.fullName,
                            "createdOn":each_merchant.createdOn.strftime("%d-%m-%Y %H:%M:%S %p")
                            }
                            merchantList.append(merchantDict)
                        pending_user_kyc_count = UserKYC.objects(status=0).count()
                        session["adminId"] = str(admin_login_queryset.id)
                        session["userName"] = admin_login_queryset.userName
                        session["merchantList"] = merchantList
                        session["pendingUsersCount"] = pending_user_kyc_count
                        first_chars = re.findall(r'\b\w', admin_login_queryset.userName)
                        session["imageString"] = ''.join(first_chars)
                        return redirect(url_for('admin.dashboard'))
 
                    else:
                        otpcheck_querryset.update(attempts=attempts)
                        error = "Invalid OTP!"
                        return render_template("super_admin_templates/admin_login_otp.html", error=error,adminLogId=adminLogId,otpCheckId=otpCheckId)
                else:
                    otpcheck_querryset.update(attempts=attempts)
                    error = "Invalid OTP!"
                    return render_template("super_admin_templates/admin_login_otp.html", error=error,adminLogId=adminLogId,otpCheckId=otpCheckId)
            except Exception as e:
                app.logger.error(traceback.format_exc())
                return redirect(url_for('admin.admin_login'))
        else:
            error = "Please enter the OTP!"
            return render_template("super_admin_templates/admin_login_otp.html", error=error,adminLogId=adminLogId,otpCheckId=otpCheckId)
    else:
        return render_template("super_admin_templates/admin_login_otp.html",adminLogId=adminLogId)
 


@admin.route("/resend_otp", methods=["POST"])
@csrf_protect
def resend_otp():
    csrf_token = request.form.get("csrf_token")
    adminLogId = request.form.get("adminLogId")
    otpCheckId = request.form.get("otpCheckId")

    print(f"Resending OTP for: AdminLogID={adminLogId}, OTPCheckID={otpCheckId}")

    if not adminLogId:
        return render_template("super_admin_templates/admin_login_otp.html", error="Invalid request!")

    try:
        admin_login_queryset = SuperAdminLogs.objects(id=adminLogId, status=0).first()
        if not admin_login_queryset:
            return render_template("super_admin_templates/admin_login_otp.html", error="Invalid login session!")

        admin_queryset = SuperAdmin.objects(id=str(admin_login_queryset.adminId.id)).first()
        if not admin_queryset:
            return render_template("super_admin_templates/admin_login_otp.html", error="Admin not found!")

        phoneNumber = str(admin_queryset.phoneNumber)
        adminName = str(admin_queryset.userName)

        if otpCheckId:
            otpcheck_queryset = OtpChecks.objects(id=str(otpCheckId)).first()
            if otpcheck_queryset:
                otpcheck_queryset.update(status=1)  # Expire old OTP

        # Generate new OTP
        otpType = "Common_Otp"
        smsresponse = send_sms(phoneNumber, otpType, adminName)
        print(f"New OTP Response: {smsresponse}")

        otpCode = smsresponse.get("otp")
        if not otpCode:
            return render_template("super_admin_templates/admin_login_otp.html", error="Failed to generate OTP!")

        new_otp_entry = OtpChecks(
            phoneNumber=phoneNumber,
            otpCode=str(otpCode),
            status=0,  # Active OTP
            attempts=0,
            createdOn=datetime.datetime.now(),
            otpReason="Login"
        ).save()

        newOtpCheckId = str(new_otp_entry.id)

        # Send OTP via email
        email = admin_queryset.email
        if email:
            mail_subject = "Resend OTP for GraamPay Admin Login"
            recipients_list = [email]
            template_name = "emails/emailotpverification.html"
            mail_data = {
                "userName": adminName,
                "otpCode": otpCode,
            }
            send_asynchronous_email(mail_subject, recipients_list, template_name, mail_data)

        flash("New OTP has been sent.", "success")
        return render_template(
            "super_admin_templates/admin_login_otp.html",
            adminLogId=adminLogId,
            otpCheckId=newOtpCheckId,  # Pass new OTP ID
            success="New OTP has been sent to your registered mobile number."
        )

    except Exception as e:
        app.logger.error(traceback.format_exc())
        return render_template("super_admin_templates/admin_login_otp.html", error="Error resending OTP!")


@admin.route("/dashboard",methods=["POST","GET"])
# @adminid_access_token_required
def dashboard():
    try:
        if not session.get("adminId"):
            print(" no admin id send back to login")
            return redirect("admin_login")
        adminId = session.get("adminId")
        # if not check_latitude_and_longitude(accessToken, adminId):
        # 	return redirect("admin_login")
        adminDict = {}
        commissionsDict = {}
        payInTop10MerchantsList = []
        payoutsTop10MerchantsList = []
        payoutsList = []
        payinsList = []
        adminDict = {}
        totalWalletBalance = 0
        merchants_count = 0
        totalPayInBalance = 0
        payinTotalchargeAmount = 0
        payinTotaltdsAmount = 0
        payinTotalgstAmount = 0
        totalPayinAmount = 0
        payoutTotalchargeAmount = 0
        payoutTotaltdsAmount = 0
        payoutTotalgstAmount = 0
        totalPayoutAmount = 0
        todayTotalPayinAmount = 0
        todayTotalPayoutAmount = 0
        yesterdayTotalPayinAmount = 0
        yesterdayTotalPayoutAmount = 0
        approved_count = 0
        total_merchants_count = 0
        rejected_count = 0
        pending_count = 0
        submitted_count = 0
        payoutTotalPgchargeAmount = 0
        payoutTotalPggstAmount = 0
        totalPgPayoutAmount = 0
        currentMonthPayoutPGCharges = 0
        currentMonthPayoutCommissionAmount = 0
        currentMonthPayoutPgGstAmount = 0
        currentMonthpgtotalAmount = 0
        currentMonthPayoutChargesAmount = 0


        previousMonthPayoutCommissionAmount = 0
        previousMonthPayoutCharges = 0
        previousMonthPGCharges = 0
        previousMonthoPayoutPgGstAmount = 0

        pgAdditionalChargeAmount = 0 
        pgCurrentMonthAdditionalChargeAmount = 0
        pgPreviousMonthAdditionalChargeAmount = 0

        admin_queryset = SuperAdmin.objects(id=adminId,status__in=[1]).first()

        todayStartDateTime = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
        todayEndDateTime = todayStartDateTime.replace(hour=23, minute=59, second=59, microsecond=59)
        # print(todayStartDateTime,"((((((((todayStartDateTime))))))))")
        # print(todayEndDateTime,"((((((((todayEndDateTime))))))))")

        # Today Payin & Payout Amounts
        todayTotalPayinAmount = WalletTransactions.objects(createdOn__gte=todayStartDateTime,createdOn__lte=todayEndDateTime,creditType="Credit",status=1,userType="user").sum('amount')
        todayTotalPayoutAmount = FundTransfers.objects(createdOn__gte=todayStartDateTime,createdOn__lte=todayEndDateTime,transferType__nin=["Credit"],status=1,userType__ne='admin').sum('amount')

        # Yesterday Payin & Payout Amounts
        yesterdayStartDate = todayStartDateTime - datetime.timedelta(days=1)
        yesterdayEndDate = yesterdayStartDate.replace(hour=23, minute=59, second=59, microsecond=999999)

        # print("Yesterday Start:", yesterdayStartDate)
        # print("Yesterday End:", yesterdayEndDate)

        yesterdayTotalPayinAmount = WalletTransactions.objects(createdOn__gte=yesterdayStartDate,createdOn__lte=yesterdayEndDate,creditType="Credit",status=1,userType="user").sum('amount')
        yesterdayTotalPayoutAmount = FundTransfers.objects(createdOn__gte=yesterdayStartDate,createdOn__lte=yesterdayEndDate,transferType__nin=["Credit"],status=1,userType__ne='admin').sum('amount')


        #totalWalletBalance = Users.objects(status__in=[1]).sum('walletBalance')

        #merchants_count = Users.objects(status__in=[1]).count()


        totalPayInBalance = WalletTransactions.objects(creditType="Credit",status=1,userType="user").sum('amount')

        totalPayOutBalance = FundTransfers.objects(transferType__nin=["Credit"],status=1,userType__ne='admin').sum('amount')


        # Get the first and last day of the current month
        today = datetime.datetime.today()
        first_day_of_current_month = today.replace(day=1,hour=0, minute=0, second=0, microsecond=0)

        last_day_of_previous_month = first_day_of_current_month - datetime.timedelta(days=1)
        last_day_of_previous_month = last_day_of_previous_month.replace(hour=23, minute=59, second=59, microsecond=59)

        first_day_of_previous_month=last_day_of_previous_month.replace(day=1,hour=0, minute=0, second=0, microsecond=0)

        # Get the last day of the current month
        last_day_of_current_month = first_day_of_current_month + timedelta(days=calendar.monthrange(today.year, today.month)[1] - 1)
        last_day_of_current_month = last_day_of_current_month.replace(hour=23, minute=59, second=59, microsecond=999999)


        # Payout Current Month and Current Year
        totalCurrentMonthPayoutBalance = 0

        totalCurrentMonthPayoutBalance = FundTransfers.objects(createdOn__gte=first_day_of_current_month,createdOn__lte=today,status=1,transferType__nin=["Credit","Refund"],userType__ne='admin').sum("amount")

        totalPreviousMonthPayoutBalance = 0
        totalPreviousMonthPayoutBalance = FundTransfers.objects(createdOn__gte=first_day_of_previous_month,createdOn__lte=last_day_of_previous_month,status=1,transferType__nin=["Credit","Refund"],userType__ne='admin').sum("amount")

        # Payout Increase or Decrease Growth

        if totalPreviousMonthPayoutBalance > 0:
            payoutGrowth = (totalCurrentMonthPayoutBalance - totalPreviousMonthPayoutBalance)*100/totalPreviousMonthPayoutBalance
        else:
            payoutGrowth = 100

        # Payin Current Month and Current Year

        totalCurrentMonthPayinBalance = 0
        totalCurrentMonthPayinBalance = WalletTransactions.objects(createdOn__gte=first_day_of_current_month,createdOn__lte=today,status=1,creditType="Credit",userType="user").sum("amount")

        totalPreviousMonthPayinBalance = 0
        totalPreviousMonthPayinBalance = WalletTransactions.objects(createdOn__gte=first_day_of_previous_month,createdOn__lte=last_day_of_previous_month,status=1,creditType="Credit",userType="user").sum("amount")

        # Payout Increase or Decrease Growth

        if totalPreviousMonthPayinBalance > 0:
            payinGrowth = (totalCurrentMonthPayinBalance - totalPreviousMonthPayinBalance)*100/totalPreviousMonthPayinBalance
        else:
            payinGrowth = 100
    
        payOutSuccessRatio=0
        payoutsList = []
        payoutDataPipeline = [
            {
                "$match": {
                        "transferType": {"$nin": ["Credit", "Refund"]},
                        # "transactionAPIId": str(each_payout.id),
                        "userType": {"$ne": 'admin'}
                    }
                },
         # Step 1: Group by apiId and status in `funds`
            {
                "$group": {
                    "_id": {
                        "apiId": "$transactionAPIId",
                        "status": "$status"
                    },
                    "count": { "$sum": 1 }
                }
            },

            # Step 2: Regroup by apiId to get total and success counts
            {
                "$group": {
                    "_id": "$_id.apiId",
                    "totalCount": { "$sum": "$count" },
                    "successCount": {
                        "$sum": {
                            "$cond": [
                                { "$eq": ["$_id.status", 1] }, "$count", 0
                            ]
                        }
                    }
                }
            },

            # Step 3: Add successRatio field
            {
                "$project": {
                    "totalCount": 1,
                    "successCount": 1,
                    "successRatio": {
                        "$cond": [
                            { "$gt": ["$totalCount", 0] },
                            {"$round" :[{"$multiply":[{ "$divide": ["$successCount", "$totalCount"] },100]},
                                    2
                                ]},
                            0
                        ]
                    }
                }
            },

            # Step 4: Lookup latest balance from `balances` collection
            {
                "$lookup": {
                    "from": "admin_payout_balances",
                    "let": { "apiId": "$_id" },
                    "pipeline": [
                        { "$match": { "$expr": { "$eq": ["$apiTransactionId", "$$apiId"] } } },
                        { "$sort": { "createdOn": -1 } },
                        { "$limit": 1 },
                        { "$project": { "currentBalance": 1, "_id": 0 } }
                    ],
                    "as": "latestBalance"
                }
            },
            # Step 5: Lookup API name from `apis`
            {
                "$lookup": {
                    "from": "transaction_a_p_i",
                    "localField": "_id",
                    "foreignField": "_id",
                    "as": "apiInfo"
                }
            },

            # Step 5: Optional — project `latest_amount` safely from the joined balance
            {
                "$project": {
                    "apiId": "$_id",
                    "apiName": { "$arrayElemAt": ["$apiInfo.apiName", 0] },
                    "successRatio": 1,
                    "currentBalance": { "$arrayElemAt": ["$latestBalance.currentBalance", 0] }
                }
            }
        ]
        
        payoutsList = list(FundTransfers.objects.aggregate(*payoutDataPipeline))
        # print("payoutsList",payoutsList)

        # Payin Balance
        payinsList = []
        payInSuccessRatio=0
            ############################################################ payin success ratio pipeline ############################################################
        payinDataPipeline = [
                {
                    "$match": {
                            "creditType": {"$in": ["Credit"]},
                            "userType": {"$eq": 'user'},
                            "status": { "$in": [0, 1] }
                        }
                    },
            # Step 1: Group by apiId and status in `funds`
                {
                "$group": {
                    "_id": "$paymentGatewayId",                 
                    "totalCount": { "$sum": 1 },     
                    "successCount": {
                    "$sum": {
                        "$cond": [
                        { "$eq": ["$status", 1] },  
                        1,                          
                        0                           
                        ]
                    }
                    },
                    "totalAmount": {
                    "$sum": {
                        "$cond": [
                        { "$eq": ["$status", 1] },  
                        "$amount",                  
                        0                           
                        ]
                    }
                    }
                }
                },

                # Step 2: Add successRatio field
                {
                    "$project": {
                        "totalCount": 1,
                        "successCount": 1,
                        "totalAmount": 1,
                        "successRatio": {
                            "$cond": [
                                { "$gt": ["$totalCount", 0] },
                                {"$round" :[{"$multiply":[{ "$divide": ["$successCount", "$totalCount"] },100]},
                                        2
                                    ]},
                                0
                            ]
                        }
                    }
                },
                # Step 5: Lookup API name from `apis`
                {
                    "$lookup": {
                        "from": "transaction_a_p_i",
                        "localField": "_id",
                        "foreignField": "_id",
                        "as": "apiInfo"
                    }
                },
                # Step 5: Optional — project `latest_amount` safely from the joined balance
                {
                    "$project": {
                        "apiId": "$_id",
                        "apiName": { "$arrayElemAt": ["$apiInfo.apiName", 0] },
                        "successRatio": 1,
                        "currentBalance": "$totalAmount"
                    }
                }
            ]

        payinsList = list(WalletTransactions.objects.aggregate(*payinDataPipeline)) ### payin Volumes 
        # print("payinsList",payinsList)
            ############################################################ payin success ratio pipeline ############################################################
        
        
        # Filter for successful PayIn transactions for the current month
        pipeline = [
            {"$lookup": {
                "from": "users",
                "localField": "userId",
                "foreignField": "_id",
                "as": "userDetails"
            }},
            {"$match": {
                "creditType": "Credit",
                "status": 1,
                "userType":"user",
                "createdOn": {
                    "$gte": first_day_of_current_month,
                    "$lte": last_day_of_current_month
                }
            }},
            {"$unwind": "$userDetails"},  # Unwind the array returned by $lookup
            {"$group": {"_id": "$userId", "totalAmount": {"$sum": "$amount"}}},
            {"$sort": {"totalAmount": -1}},
            {"$limit": 10}
        ]

        # Execute the aggregation pipeline
        payins_top_10_merchants = list(WalletTransactions.objects.aggregate(*pipeline))
        payInTop10MerchantsList = []

        for each_merchant in payins_top_10_merchants:
            merchant_queryset = Users.objects(id=each_merchant.get("_id")).first()
            if merchant_queryset:
                first_chars = re.findall(r'\b\w', merchant_queryset.fullName)

                imageString = ''.join(first_chars)

                payInDict = {
                "merchantId":str(merchant_queryset.id),
                "merchantName":merchant_queryset.fullName,
                "phoneNumber":merchant_queryset.phoneNumber,
                "imageString":imageString,
                "totalMerchantAmount":formatINR("{:.2f}".format(float(each_merchant.get("totalAmount"))))
                }
                payInTop10MerchantsList.append(payInDict)

        # Filter for successful Payout transactions for the current month
        payout_pipeline = [
            {"$match": {
                "transferType": "Debit",
                "userType": {"$ne":"admin"},
                "status": 1,
                "createdOn": {
                    "$gte": first_day_of_current_month,
                    "$lte": last_day_of_current_month
                }
            }},  # Filtering
            {"$group": {"_id": "$userId", "totalAmount": {"$sum": "$amount"}}},  # Grouping and summing amounts
            {"$sort": {"totalAmount": -1}},  # Sorting by total amount in descending order
            {"$limit": 10}  # Limiting to top 10
        ]

        # Execute the aggregation payout_pipeline
        payouts_top_10_merchants = list(FundTransfers.objects.aggregate(*payout_pipeline))
        payoutsTop10MerchantsList = []
        for each_payout_merchant in payouts_top_10_merchants:
            payout_merchant_queryset = Users.objects(id=each_payout_merchant.get("_id")).first()
            if payout_merchant_queryset:
                first_chars = re.findall(r'\b\w', payout_merchant_queryset.fullName)

                imageString = ''.join(first_chars)

                payOutDict = {
                "merchantId":str(payout_merchant_queryset.id),
                "merchantName":payout_merchant_queryset.fullName,
                "phoneNumber":payout_merchant_queryset.phoneNumber,
                "imageString":imageString,
                "totalMerchantAmount":formatINR("{:.2f}".format(float(each_payout_merchant.get("totalAmount"))))
                }
                payoutsTop10MerchantsList.append(payOutDict)

        # Commissions For Payin And Payout Calculations
        # payinTotalchargeAmount = WalletTransactions.objects(status=1).sum('commissionCharges.chargeAmount')
        # payinTotaltdsAmount = WalletTransactions.objects(status=1).sum('commissionCharges.tdsAmount')
        # payinTotalgstAmount = WalletTransactions.objects(status=1).sum('commissionCharges.gstAmount')

        # Commissions For Payin And Payout Calculations

        # comm_pipeline_payin = [
        #         {
        #             '$project': {
        #                 'chargeAmount': '$commissionCharges.chargeAmount',
        #                 'tdsAmount': '$commissionCharges.tdsAmount',
        #                 'gstAmount': '$commissionCharges.gstAmount'
        #             }
        #         },
        #         {
        #             '$group': {
        #                 '_id': None,
        #                 'payinTotalchargeAmount': {'$sum': '$chargeAmount'},
        #                 'payinTotaltdsAmount': {'$sum': '$tdsAmount'},
        #                 'payinTotalgstAmount': {'$sum': '$gstAmount'}
        #             }
        #         }
        #     ]
        # result = WalletTransactions.objects(status=1).aggregate(comm_pipeline_payin)

        # if result:
        #     payinTotalchargeAmount = result[0]['payinTotalchargeAmount']
        #     payinTotaltdsAmount = result[0]['payinTotaltdsAmount']
        #     payinTotalgstAmount = result[0]['payinTotalgstAmount']

        # totalPayinAmount  = payinTotalchargeAmount + payinTotaltdsAmount + payinTotalgstAmount

        ################################## Payout ############################################################

        pipeline = [
            {"$match": {"status": 1,"fundTransferType":{"$in":["Instant","bulk"]}}},  # Match documents with status=1
            {
                "$group": {
                    "_id": None,  # We don't need to group by any field
                    "totalChargeAmount": {"$sum": "$commissionCharges.chargeAmount"},
                    "totalGstAmount": {"$sum": "$commissionCharges.gstAmount"},
                    "totalPgChargeAmount": {"$sum": "$aggregatorCharges.chargeAmount"},
                    "totalPgGstAmount": {"$sum": "$aggregatorCharges.gstAmount"}
                }
            }
        ]

        result = list(FundTransfers.objects.aggregate(*pipeline))

        payoutTotalchargeAmount = result[0]["totalChargeAmount"]
        payoutTotalgstAmount = result[0]["totalGstAmount"]
        payoutTotalPgchargeAmount = result[0]["totalPgChargeAmount"]
        payoutTotalPggstAmount = result[0]["totalPgGstAmount"]


        # payoutTotalchargeAmount = FundTransfers.objects(fundTransferType__in=["Instant","bulk"],status=1).sum('commissionCharges.chargeAmount')
        # payoutTotaltdsAmount = FundTransfers.objects(status=1).sum('commissionCharges.tdsAmount')
        # payoutTotalgstAmount = FundTransfers.objects(fundTransferType__in=["Instant","bulk"],status=1).sum('commissionCharges.gstAmount')

        totalPayoutAmount  = payoutTotalchargeAmount + payoutTotaltdsAmount + payoutTotalgstAmount


        # payoutTotalPgchargeAmount = FundTransfers.objects(fundTransferType__in=["Instant","bulk"],status=1).sum('aggregatorCharges.chargeAmount')
        # payoutTotalPggstAmount = FundTransfers.objects(fundTransferType__in=["Instant","bulk"],status=1).sum('aggregatorCharges.gstAmount')
        totalPgPayoutAmount  = payoutTotalPgchargeAmount + payoutTotalPggstAmount

        pgAdditionalChargeAmount = PgSettlements.objects(status=1).sum('additionalChargeAmount')

        ######################################################################################################


        ####################################          Bene Charges    #################################################################
        beneficiaryTypeQueryset =  FundTransfers.objects(fundTransferType__in=["beneficiary"],status=1).all()
        beneficiaryTotalChargesAmount = FundTransfers.objects(fundTransferType__in=["beneficiary"],status=1).sum('grandTotal')
        beneficiaryGstAmount = FundTransfers.objects(fundTransferType__in=["beneficiary"],status=1).sum('commissionCharges.gstAmount')
        beneficiaryTransactionsCount = FundTransfers.objects(fundTransferType__in=["beneficiary"],status=1).count()

        ######################################################################################################


        #####################################          Bene Currrent Charges    #################################################################
        beneficiaryCurrentMonthTypeQueryset =  FundTransfers.objects(fundTransferType__in=["beneficiary"],createdOn__gte=first_day_of_current_month,createdOn__lte=today,status=1).all()
        beneficiaryCurrentMonthTotalChargesAmount = FundTransfers.objects(fundTransferType__in=["beneficiary"],createdOn__gte=first_day_of_current_month,createdOn__lte=today,status=1).sum('grandTotal')
        beneficiaryCurrentMonthGstAmount = FundTransfers.objects(fundTransferType__in=["beneficiary"],createdOn__gte=first_day_of_current_month,createdOn__lte=today,status=1).sum('commissionCharges.gstAmount')
        beneficiaryCurrentMonthTransactionsCount = FundTransfers.objects(fundTransferType__in=["beneficiary"],createdOn__gte=first_day_of_current_month,createdOn__lte=today,status=1).count()

        ######################################################################################################

        
        #####################################          Bene Previous Charges    #################################################################
        beneficiaryPreviousTypeQueryset =  FundTransfers.objects(fundTransferType__in=["beneficiary"],createdOn__gte=first_day_of_previous_month,createdOn__lte=last_day_of_previous_month,status=1).all()
        beneficiaryPreviousTotalChargesAmount = FundTransfers.objects(fundTransferType__in=["beneficiary"],createdOn__gte=first_day_of_previous_month,createdOn__lte=last_day_of_previous_month,status=1).sum('grandTotal')
        beneficiaryPreviousGstAmount = FundTransfers.objects(fundTransferType__in=["beneficiary"],createdOn__gte=first_day_of_previous_month,createdOn__lte=last_day_of_previous_month,status=1).sum('commissionCharges.gstAmount')
        beneficiaryPreviousTransactionsCount = FundTransfers.objects(fundTransferType__in=["beneficiary"],createdOn__gte=first_day_of_previous_month,createdOn__lte=last_day_of_previous_month,status=1).count()

        ######################################################################################################



        #################################################### Bene Data Pipeline###############################################
        # beneficiaryTotalChargesAmount = 0
        # beneficiaryGstAmount = 0
        # beneficiaryTransactionsCount = 0
        # beneficiaryCurrentMonthTotalChargesAmount = 0
        # beneficiaryCurrentMonthGstAmount = 0
        # beneficiaryCurrentMonthTransactionsCount = 0
        # beneficiaryPreviousTotalChargesAmount = 0
        # beneficiaryPreviousGstAmount = 0
        # beneficiaryPreviousTransactionsCount = 0

        # beneficiary_data_pipeline = [
        #     # Step 1: Filter documents by beneficiary type and status
        #     {
        #         "$match": {
        #             "fundTransferType": "beneficiary",  # Filter by 'beneficiary' type
        #             "status": 1               # Filter by 'status' = 1 (active beneficiaries)
        #         }
        #     },
            
        #     # Step 2: Group by date range and perform aggregation (total charges, GST, and transaction count)
        #     {
        #         "$group": {
        #             "_id": None,  # No grouping (will aggregate for all records)
        #             "totalCharges": { "$sum": "$grandTotal" },  # Sum of grandTotal (total charges)
        #             "totalGst": { "$sum": "$commissionCharges.gstAmount" },           # Sum of commissionCharges.gstAmount (GST)
        #             "totalTransactions": { "$sum": 1 }          # Count of total transactions
        #         }
        #     },

        #     # Optional: Add calculations for current month and previous month using date filters
        #     # Current month filter (from first day to today)
        #     {
        #         "$facet": {
        #             "total": [
        #                 {
        #                     "$match": {
        #                         "fundTransferType": "beneficiary",
        #                         "status": 1
        #                     }
        #                 },
        #                 {
        #                     "$group": {
        #                         "_id": None,
        #                         "totalCharges": { "$sum": "$grandTotal" },
        #                         "totalGst": { "$sum": "$commissionCharges.gstAmount" },
        #                         "totalTransactions": { "$sum": 1 }
        #                     }
        #                 }
        #             ],
        #             "currentMonth": [
        #                 {
        #                     "$match": {
        #                         "fundTransferType": "beneficiary",
        #                         "status": 1,
        #                         "createdOn": { "$gte": first_day_of_current_month, "$lte": today }  # Current month range
        #                     }
        #                 },
        #                 {
        #                     "$group": {
        #                         "_id": None,
        #                         "totalCharges": { "$sum": "$grandTotal" },
        #                         "totalGst": { "$sum": "$commissionCharges.gstAmount" },
        #                         "totalTransactions": { "$sum": 1 }
        #                     }
        #                 }
        #             ],
        #             "previousMonth": [
        #                 {
        #                     "$match": {
        #                         "fundTransferType": "beneficiary",
        #                         "status": 1,
        #                         "createdOn": { "$gte": first_day_of_previous_month, "$lte": last_day_of_previous_month }  # Previous month range
        #                     }
        #                 },
        #                 {
        #                     "$group": {
        #                         "_id": None,
        #                         "totalCharges": { "$sum": "$grandTotal" },
        #                         "totalGst": { "$sum": "$commissionCharges.gstAmount" },
        #                         "totalTransactions": { "$sum": 1 }
        #                     }
        #                 }
        #             ]
        #         }
        #     },

        #     # Step 3: Project the results to make them more readable
        #     {
        #     "$project": {
        #         "totalCharges": { "$ifNull": [{ "$arrayElemAt": ["$total.totalCharges", 0] }, 0] },
        #         "totalGst": { "$ifNull": [{ "$arrayElemAt": ["$total.totalGst", 0] }, 0] },
        #         "totalTransactions": { "$ifNull": [{ "$arrayElemAt": ["$total.totalTransactions", 0] }, 0] },
        #         "currentMonthTotalCharges": { "$ifNull": [{ "$arrayElemAt": ["$currentMonth.totalCharges", 0] }, 0] },
        #         "currentMonthTotalGst": { "$ifNull": [{ "$arrayElemAt": ["$currentMonth.totalGst", 0] }, 0] },
        #         "currentMonthTotalTransactions": { "$ifNull": [{ "$arrayElemAt": ["$currentMonth.totalTransactions", 0] }, 0] },
        #         "previousMonthTotalCharges": { "$ifNull": [{ "$arrayElemAt": ["$previousMonth.totalCharges", 0] }, 0] },
        #         "previousMonthTotalGst": { "$ifNull": [{ "$arrayElemAt": ["$previousMonth.totalGst", 0] }, 0] },
        #         "previousMonthTotalTransactions": { "$ifNull": [{ "$arrayElemAt": ["$previousMonth.totalTransactions", 0] }, 0] }
        #     }
        #     }
        # ]

        # # Run the aggregation
        # beneficiary_data_aggregator_results = list(FundTransfers.objects.aggregate(*beneficiary_data_pipeline))
        # print("((((((((beneficiary_data_aggregator_results))))))))",beneficiary_data_aggregator_results )
        
        # # Extract the results
        # for each_beneficiary_data_result in beneficiary_data_aggregator_results:
        #     beneficiaryTotalChargesAmount = each_beneficiary_data_result['totalCharges']
        #     beneficiaryGstAmount = each_beneficiary_data_result['totalGst']
        #     beneficiaryTransactionsCount = each_beneficiary_data_result['totalTransactions']
        #     beneficiaryCurrentMonthTotalChargesAmount = each_beneficiary_data_result['currentMonthTotalCharges']
        #     beneficiaryCurrentMonthGstAmount = each_beneficiary_data_result['currentMonthTotalGst']
        #     beneficiaryCurrentMonthTransactionsCount = each_beneficiary_data_result['currentMonthTotalTransactions']
        #     beneficiaryPreviousTotalChargesAmount = each_beneficiary_data_result['previousMonthTotalCharges']
        #     beneficiaryPreviousGstAmount = each_beneficiary_data_result['previousMonthTotalGst']
        #     beneficiaryPreviousTransactionsCount = each_beneficiary_data_result['previousMonthTotalTransactions']


        ######################################################################################################


        ################################## Current Month For Payout Commissions ############################################################

        # current_month_payout_queryset = FundTransfers.objects(fundTransferType__in=["Instant","bulk"],createdOn__gte=first_day_of_current_month,createdOn__lte=today,status=1)
        # currentMonthPayoutCommissionAmount = current_month_payout_queryset.filter().sum('aggregatorCharges.commissionAmount') #
        # currentMonthPayoutCommissionAmount=round(currentMonthPayoutCommissionAmount,2) ####1

        # currentMonthPayoutChargesAmount = current_month_payout_queryset.filter().sum('commissionCharges.chargeAmount')
        # currentMonthPayoutChargesAmount=round(currentMonthPayoutChargesAmount,2) ####2

        # currentMonthPayoutPGCharges = current_month_payout_queryset.filter().sum('aggregatorCharges.chargeAmount')3
        # currentMonthPayoutPgGstAmount = current_month_payout_queryset.filter().sum('aggregatorCharges.gstAmount')4
        # currentMonthPayoutPgGstAmount=round(float(currentMonthPayoutPgGstAmount),2) 
        # currentMonthpgtotalAmount = round(float(currentMonthPayoutPGCharges + currentMonthPayoutPgGstAmount),2)   #### 5



        ##########pipeline
        current_month_payout_comm_pipeline = [
            {"$match": {"status": 1,"fundTransferType":{"$in":["Instant","bulk"]},
            'status': 1,
            'createdOn': {
                        "$gte": first_day_of_current_month,
                        "$lte": today,
                    }
            }},  # Match documents with status=1
            
            {
                "$group": {
                    "_id": None,  # We don't need to group by any field
                    "currentMonthPayoutCommissionAmount": {"$sum": "$commissionCharges.commissionAmount"},
                    "currentMonthPayoutChargesAmount": {"$sum": "$commissionCharges.chargeAmount"},
                    "currentMonthPayoutPGCharges": {"$sum": "$aggregatorCharges.chargeAmount"},
                    "currentMonthPayoutPgGstAmount": {"$sum": "$aggregatorCharges.gstAmount"}
                }
            }
        ]
        current_month_payout_commissions_result = list(FundTransfers.objects.aggregate(current_month_payout_comm_pipeline))
        # print("current_month_payout_commissions_result",current_month_payout_commissions_result)

        if current_month_payout_commissions_result:
            currentMonthPayoutCommissionAmount= round(float(current_month_payout_commissions_result[0]["currentMonthPayoutCommissionAmount"]),2)
            currentMonthPayoutChargesAmount= round(float(current_month_payout_commissions_result[0]["currentMonthPayoutChargesAmount"]),2)
            currentMonthPayoutPGCharges= round(float(current_month_payout_commissions_result[0]["currentMonthPayoutPGCharges"]),2)
            currentMonthPayoutPgGstAmount= round(float(current_month_payout_commissions_result[0]["currentMonthPayoutPgGstAmount"]),2)
            currentMonthpgtotalAmount = round(float(currentMonthPayoutPGCharges + currentMonthPayoutPgGstAmount),2) 


        pgCurrentMonthAdditionalChargeAmount = PgSettlements.objects(createdOn__gte=first_day_of_current_month,createdOn__lte=today,status=1).sum('additionalChargeAmount')





        ########################################################################################################################################

        ############################################################### Previous Month For Payout Commissions ####################################################################
        

        # payouts_all_queryset = FundTransfers.objects(createdOn__gte=first_day_of_previous_month,createdOn__lte=last_day_of_previous_month,status=1)
        # previous_month_payout_queryset = payouts_all_queryset.filter(fundTransferType__in=["Instant","bulk"])
        # previousMonthPayoutCommissionAmount = previous_month_payout_queryset.filter().sum('commissionCharges.commissionAmount')
        # previousMonthPayoutCommissionAmount=round(previousMonthPayoutCommissionAmount,2) ####
        # previousMonthPayoutCharges = previous_month_payout_queryset.filter().sum('commissionCharges.chargeAmount')

        # previousMonthPGCharges = previous_month_payout_queryset.filter().sum('aggregatorCharges.chargeAmount')
        # previousMonthoPayoutPgGstAmount = previous_month_payout_queryset.filter().sum('aggregatorCharges.gstAmount')
        # previousMonthoPayoutPgGstAmount=round(float(previousMonthoPayoutPgGstAmount),2)


        ##########pipeline
        previous_month_payout_comm_pipeline = [
            {"$match": {"status": 1,"fundTransferType":{"$in":["Instant","bulk"]},
            'status': 1,
            'createdOn': {
                        "$gte": first_day_of_previous_month,
                        "$lte": last_day_of_previous_month,
                    }
            }},  # Match documents with status=1
            
            {
                "$group": {
                    "_id": None,  # We don't need to group by any field
                    "previousMonthPayoutCommissionAmount": {"$sum": "$commissionCharges.commissionAmount"},
                    "previousMonthPayoutCharges": {"$sum": "$commissionCharges.chargeAmount"},
                    "previousMonthPGCharges": {"$sum": "$aggregatorCharges.chargeAmount"},
                    "previousMonthoPayoutPgGstAmount": {"$sum": "$aggregatorCharges.gstAmount"}
                }
            }
        ]
        previous_month_payout_commissions_result = list(FundTransfers.objects.aggregate(previous_month_payout_comm_pipeline))
        # print("previous_month_payout_commissions_result",previous_month_payout_commissions_result)

        if previous_month_payout_commissions_result:
            previousMonthPayoutCommissionAmount= round(float(previous_month_payout_commissions_result[0]["previousMonthPayoutCommissionAmount"]),2)
            previousMonthPayoutCharges= round(float(previous_month_payout_commissions_result[0]["previousMonthPayoutCharges"]),2)
            previousMonthPGCharges= round(float(previous_month_payout_commissions_result[0]["previousMonthPGCharges"]),2)
            previousMonthoPayoutPgGstAmount= round(float(previous_month_payout_commissions_result[0]["previousMonthoPayoutPgGstAmount"]),2)


        pgPreviousMonthAdditionalChargeAmount = PgSettlements.objects(createdOn__gte=first_day_of_previous_month,createdOn__lte=last_day_of_previous_month,status=1).sum('additionalChargeAmount')
        ##########################################################################################################################################################################

        
        total_merchants_count = Users.objects(status__nin=[2,6]).count()

        users_kyc_queryset = UserKYC.objects(status__in=[0,1]).order_by("-id")
        for each_user_kyc in users_kyc_queryset:
            kycStatusList = []
            kycStatusList = [
            each_user_kyc.panStatus,
            each_user_kyc.aadharStatus,
            each_user_kyc.bankStatus,
            each_user_kyc.videoVerificationStatus,
            each_user_kyc.agreementVerificationStatus
            ]
            if each_user_kyc.userId.entityTypeId!=None and each_user_kyc.userId.entityTypeId.isIndividual==False:
                kycStatusList.append(each_user_kyc.shopVideoStatus)
                kycStatusList.append(each_user_kyc.businessStatus)
                if each_user_kyc.documentsList==[]:
                    kycStatusList.append('Pending')
                else:
                    for each_document in each_user_kyc.documentsList:
                        kycStatusList.append(each_document.get('documentStatus'))

                if each_user_kyc.shopImagesList==[]:
                    kycStatusList.append('Pending')
                else:
                    for each_simg in each_user_kyc.shopImagesList:
                        kycStatusList.append(each_simg.get('shopImageStatus'))

            if "Rejected" in kycStatusList:
                rejected_count += 1
            elif "Pending" in kycStatusList or "" in kycStatusList or  None in kycStatusList: ########## new code for count adding "" or none as pending
                pending_count += 1
            elif "Submitted" in kycStatusList:
                submitted_count += 1
            else:
                approved_count += 1

        # print(rejected_count,"(((((((((((rejected_count)))))))))))")
        # print(pending_count,"(((((((((((pending_count)))))))))))")
        # print(submitted_count,"(((((((((((submitted_count)))))))))))")
        # print(approved_count,"(((((((((((approved_count)))))))))))")
        # rejected_count = rejected_count
        # pending_count = pending_count
        # submitted_count=submitted_count
        approved_count=approved_count
        overPGCharges= 0
        overallTransactionChargesDatewise=0
        overPgGstAmount=0
        overallTransactionChargesDatewise=0
        overallTransactionGstAmountDatewise=0
        
        cwCommissionAmount=0 ####
        pgtotalAmount=0  ####
        totalTransactionAmount=0  ####
        agentCommissionAmount=0  ####

        currentMonthcwCommissionAmount = 0 
        currentMonthpgtotalAmount=0
        currentMonthTotalTransactionAmount = 0
        currentMonthAgentCommissionAmount = 0
        
        previousMonthcwCommissionAmount = 0 
        previousMonthpgtotalAmount=0
        previousMonthTotalTransactionAmount = 0
        previousMonthAgentCommissionAmount = 0

        ####### Overall #######
        transferType_query_val = "Credit"
        status_query_val = 1
        cw_commission_pipeline = pipeline = [
            {
                '$match': {
                    'transferType': transferType_query_val,  # Match documents with the specified type
                    'status': status_query_val,  # Match documents with the specified status
                }
            },
            {
                '$group': {
                    '_id': None,  # Group everything into one result
                    'cwCommissionAmount': {'$sum': '$commissionAmount'},  # Sum the field 'your_field'
                    'overPGCharges': {'$sum': '$aggregatorCommissionAmount'}, ## not in html
                    'overPgGstAmount': {'$sum': '$aggregatorCommissionCharges.gstAmount'},
                    'overallTransactionChargesDatewise': {'$sum': '$transactionCommissionCharges.chargeAmount'}, ## not in html## not in html
                    'overallTransactionGstAmountDatewise': {'$sum': '$transactionCommissionCharges.gstAmount'},
                }
            },
            {
            '$project': {
                'cwCommissionAmount': 1,
                'overPgGstAmount': 1,
                'overallTransactionGstAmountDatewise': 1,
                'pgtotalAmount': {'$add': ['$overPGCharges', '$overPgGstAmount']},  # Add the two sums together
                'totalTransactionAmount': {'$add': ['$overallTransactionChargesDatewise', '$overallTransactionGstAmountDatewise']}  # Add the two sums together
            }
            }
        ]

        over_all_cw_commission_result = list(CompanyCommissions.objects.aggregate(cw_commission_pipeline))
        # print("over_all_cw_commission_result",over_all_cw_commission_result)

        if over_all_cw_commission_result:
            cwCommissionAmount= round(float(over_all_cw_commission_result[0]["cwCommissionAmount"]),2)
            overPgGstAmount= round(float(over_all_cw_commission_result[0]["overPgGstAmount"]),2)
            overallTransactionGstAmountDatewise= round(float(over_all_cw_commission_result[0]["overallTransactionGstAmountDatewise"]),2)
            pgtotalAmount= round(float(over_all_cw_commission_result[0]["pgtotalAmount"]),2)
            totalTransactionAmount= round(float(over_all_cw_commission_result[0]["totalTransactionAmount"]),2)


        agentCommissionAmount = UserCommissions.objects(status=1).sum('parrentCommissionAmount')
        agentCommissionAmount = round(float(agentCommissionAmount),2) ####


        

        ####### Current Month #######
        current_month_cw_commission_pipeline = pipeline = [
            {
                '$match': {
                    'transferType': transferType_query_val,  # Match documents with the specified type
                    'status': status_query_val,  # Match documents with the specified status
                    'createdOn': {
                        "$gte": first_day_of_current_month,
                        "$lte": today,
                    }
                }
            },
            {
                '$group': {
                    '_id': None,  # Group everything into one result
                    'currentMonthcwCommissionAmount': {'$sum': '$commissionAmount'},  # Sum the field 'your_field'
                    'currentMonthoverPGCharges': {'$sum': '$aggregatorCommissionAmount'}, ## not in html
                    'currentMonthoverPgGstAmount': {'$sum': '$aggregatorCommissionCharges.gstAmount'},
                    'currentMonthOverallTransactionChargesDatewise': {'$sum': '$transactionCommissionCharges.chargeAmount'}, ## not in html## not in html
                    'currentMonthOverallTransactionGstAmountDatewise': {'$sum': '$transactionCommissionCharges.gstAmount'},
                }
            },
            {
            '$project': {
                'currentMonthcwCommissionAmount': 1,
                'currentMonthoverPgGstAmount': 1,
                'currentMonthOverallTransactionGstAmountDatewise': 1,
                'currentMonthpgtotalAmount': {'$add': ['$currentMonthoverPGCharges', '$currentMonthoverPgGstAmount']},  # Add the two sums together
                'currentMonthTotalTransactionAmount': {'$add': ['$currentMonthOverallTransactionChargesDatewise', '$currentMonthOverallTransactionGstAmountDatewise']}  # Add the two sums together
            }
            }
        ]

        current_month_over_all_cw_commission_result = list(CompanyCommissions.objects.aggregate(current_month_cw_commission_pipeline))
        # print("current_month_over_all_cw_commission_result",current_month_over_all_cw_commission_result)

        if current_month_over_all_cw_commission_result:
            currentMonthcwCommissionAmount= round(float(current_month_over_all_cw_commission_result[0]["currentMonthcwCommissionAmount"]),2)
            currentMonthoverPgGstAmount= round(float(current_month_over_all_cw_commission_result[0]["currentMonthoverPgGstAmount"]),2)
            currentMonthOverallTransactionGstAmountDatewise= round(float(current_month_over_all_cw_commission_result[0]["currentMonthOverallTransactionGstAmountDatewise"]),2)
            currentMonthpgtotalAmount= round(float(current_month_over_all_cw_commission_result[0]["currentMonthpgtotalAmount"]),2)
            currentMonthTotalTransactionAmount= round(float(current_month_over_all_cw_commission_result[0]["currentMonthTotalTransactionAmount"]),2)


        currentMonthAgentCommissionAmount = UserCommissions.objects(createdOn__gte=first_day_of_current_month,createdOn__lte=today,status=1).sum('parrentCommissionAmount')
        currentMonthAgentCommissionAmount = round(float(currentMonthAgentCommissionAmount),2) ####



        ####### Previous Month #######
        previous_month_cw_commission_pipeline  = [
            {
                '$match': {
                    'transferType': transferType_query_val,  # Match documents with the specified type
                    'status': status_query_val,  # Match documents with the specified status
                    'createdOn': {
                        "$gte": first_day_of_previous_month,
                        "$lte": last_day_of_previous_month,
                    }
                }
            },
            {
                '$group': {
                    '_id': None,  # Group everything into one result
                    'previousMonthcwCommissionAmount': {'$sum': '$commissionAmount'},  # Sum the field 'your_field'
                    'previousMonthoverPGCharges': {'$sum': '$aggregatorCommissionAmount'}, ## not in html
                    'previousMonthoverPgGstAmount': {'$sum': '$aggregatorCommissionCharges.gstAmount'},
                    'previousMonthOverallTransactionChargesDatewise': {'$sum': '$transactionCommissionCharges.chargeAmount'}, ## not in html## not in html
                    'previousMonthOverallTransactionGstAmountDatewise': {'$sum': '$transactionCommissionCharges.gstAmount'},
                }
            },
            {
            '$project': {
                'previousMonthcwCommissionAmount': 1,
                'previousMonthoverPgGstAmount': 1,
                'previousMonthOverallTransactionGstAmountDatewise': 1,
                'previousMonthpgtotalAmount': {'$add': ['$previousMonthoverPGCharges', '$previousMonthoverPgGstAmount']},  # Add the two sums together
                'previousMonthTotalTransactionAmount': {'$add': ['$previousMonthOverallTransactionChargesDatewise', '$previousMonthOverallTransactionGstAmountDatewise']}  # Add the two sums together
            }
            }
        ]

        previous_month_over_all_cw_commission_result = list(CompanyCommissions.objects.aggregate(previous_month_cw_commission_pipeline))
        # print("previous_month_over_all_cw_commission_result",previous_month_over_all_cw_commission_result)

        if previous_month_over_all_cw_commission_result:
            previousMonthcwCommissionAmount= round(float(previous_month_over_all_cw_commission_result[0]["previousMonthcwCommissionAmount"]),2)
            previousMonthoverPgGstAmount= round(float(previous_month_over_all_cw_commission_result[0]["previousMonthoverPgGstAmount"]),2)
            previousMonthOverallTransactionGstAmountDatewise= round(float(previous_month_over_all_cw_commission_result[0]["previousMonthOverallTransactionGstAmountDatewise"]),2)
            previousMonthpgtotalAmount= round(float(previous_month_over_all_cw_commission_result[0]["previousMonthpgtotalAmount"]),2)
            previousMonthTotalTransactionAmount= round(float(previous_month_over_all_cw_commission_result[0]["previousMonthTotalTransactionAmount"]),2)

        previousMonthAgentCommissionAmount = UserCommissions.objects(createdOn__gte=first_day_of_previous_month,createdOn__lte=last_day_of_previous_month,status=1).sum('parrentCommissionAmount')
        previousMonthAgentCommissionAmount = round(float(previousMonthAgentCommissionAmount),2) ####



        

        adminDict = {
        "userName":admin_queryset.userName,
        "merchantsCount":merchants_count,
        "payoutGrowth":round(payoutGrowth,2),
        "payinGrowth":round(payinGrowth,2),
        "payInSuccessRatio":round(payInSuccessRatio,2),
        "payOutSuccessRatio":round(payOutSuccessRatio,2),
        "totalPayOutBalance":formatINR("{:.2f}".format(float(totalPayOutBalance))),
        "totalPayInBalance":formatINR("{:.2f}".format(float(totalPayInBalance))),
        "totalWalletBalance":formatINR("{:.2f}".format(float(totalWalletBalance))),
        "totalCurrentMonthPayoutBalance":formatINR("{:.2f}".format(float(totalCurrentMonthPayoutBalance))),
        "totalPreviousMonthPayoutBalance":formatINR("{:.2f}".format(float(totalPreviousMonthPayoutBalance))),
        "totalPreviousMonthPayinBalance":formatINR("{:.2f}".format(float(totalPreviousMonthPayinBalance))),
        "totalCurrentMonthPayinBalance":formatINR("{:.2f}".format(float(totalCurrentMonthPayinBalance))),
        # "totalPayinCommissionsAmount":formatINR("{:.2f}".format(float(payinTotalchargeAmount))),
        # "totalPayinTdsAmount":formatINR("{:.2f}".format(float(payinTotaltdsAmount))),
        # "totalPayinGstAmount":formatINR("{:.2f}".format(float(payinTotalgstAmount))),
        "totalPayoutCommissionsAmount":formatINR("{:.2f}".format(float(payoutTotalchargeAmount))),
        "totalPayoutTdsAmount":formatINR("{:.2f}".format(float(payoutTotaltdsAmount))),
        "totalPayoutGstAmount":formatINR("{:.2f}".format(float(payoutTotalgstAmount))),
        "totalPayoutAmount":formatINR("{:.2f}".format(float(totalPayoutAmount))),
        "totalPayinAmount":formatINR("{:.2f}".format(float(totalPayinAmount))),
        "todayTotalPayinAmount":formatINR("{:.2f}".format(float(todayTotalPayinAmount))),
        "todayTotalPayoutAmount":formatINR("{:.2f}".format(float(todayTotalPayoutAmount))),
        "yesterdayTotalPayinAmount":formatINR("{:.2f}".format(float(yesterdayTotalPayinAmount))),
        "yesterdayTotalPayoutAmount":formatINR("{:.2f}".format(float(yesterdayTotalPayoutAmount))),
        "cwCommissionAmount":formatINR("{:.2f}".format(float(cwCommissionAmount))),
        "pgtotalAmount":formatINR("{:.2f}".format(float(pgtotalAmount))),
        "overallTransactionGstAmountDatewise":formatINR("{:.2f}".format(float(overallTransactionGstAmountDatewise))),
        "currentMonthTotalTransactionAmount":formatINR("{:.2f}".format(float(currentMonthTotalTransactionAmount))),
        # "companyCharges":formatINR("{:.2f}".format(float(companyCharges))),
        "agentCommissionAmount":formatINR("{:.2f}".format(float(agentCommissionAmount))),
        "currentMonthcwCommissionAmount":formatINR("{:.2f}".format(float(currentMonthcwCommissionAmount))),
        "currentMonthpgtotalAmount":formatINR("{:.2f}".format(float(currentMonthpgtotalAmount))),
        "totalTransactionAmount":formatINR("{:.2f}".format(float(totalTransactionAmount))),
        "currentMonthAgentCommissionAmount":formatINR("{:.2f}".format(float(currentMonthAgentCommissionAmount))),
        "previousMonthcwCommissionAmount":formatINR("{:.2f}".format(float(previousMonthcwCommissionAmount))),
        "previousMonthpgtotalAmount":formatINR("{:.2f}".format(float(previousMonthpgtotalAmount))),
        "previousMonthTotalTransactionAmount":formatINR("{:.2f}".format(float(previousMonthTotalTransactionAmount))),
        "previousMonthAgentCommissionAmount":formatINR("{:.2f}".format(float(previousMonthAgentCommissionAmount))),
        "payoutTotalPgchargeAmount":formatINR("{:.2f}".format(float(payoutTotalPgchargeAmount))),
        "payoutTotalPggstAmount":formatINR("{:.2f}".format(float(payoutTotalPggstAmount))),
        "overallPayinPgGstAmount":formatINR("{:.2f}".format(float(overPgGstAmount))),
        "currentMonthPayoutChargesAmount":formatINR("{:.2f}".format(float(currentMonthPayoutChargesAmount))),
        "previousMonthPayoutCommissionAmount":formatINR("{:.2f}".format(float(previousMonthPayoutCommissionAmount))),
        "previousMonthPayoutCharges":formatINR("{:.2f}".format(float(previousMonthPayoutCharges))),
        "previousMonthPGCharges":formatINR("{:.2f}".format(float(previousMonthPGCharges))),
        "previousMonthoPayoutPgGstAmount":formatINR("{:.2f}".format(float(previousMonthoPayoutPgGstAmount))),
        "currentMonthPayoutCommissionAmount":formatINR("{:.2f}".format(float(currentMonthPayoutCommissionAmount))),
        "currentMonthPayoutPGCharges":formatINR("{:.2f}".format(float(currentMonthPayoutPGCharges))),
        "currentMonthPayoutPgGstAmount":formatINR("{:.2f}".format(float(currentMonthPayoutPgGstAmount))),
        "approvedMerchantsCount":approved_count,
        "rejectedMerchantsCount":rejected_count,
        "pendingMerchantsCount":pending_count,
        "totalMerchantsCount":total_merchants_count,
        "beneficiaryTransactionsCount":beneficiaryTransactionsCount,
        "beneficiaryGstAmount":formatINR("{:.2f}".format(float(beneficiaryGstAmount))),
        "beneficiaryTotalChargesAmount":formatINR("{:.2f}".format(float(beneficiaryTotalChargesAmount))),

        "beneficiaryCurrentMonthTransactionsCount":beneficiaryCurrentMonthTransactionsCount,
        "beneficiaryCurrentMonthGstAmount":formatINR("{:.2f}".format(float(beneficiaryCurrentMonthGstAmount))),
        "beneficiaryCurrentMonthTotalChargesAmount":formatINR("{:.2f}".format(float(beneficiaryCurrentMonthTotalChargesAmount))),


        "beneficiaryTransactionsCount":beneficiaryTransactionsCount,
        "beneficiaryPreviousGstAmount":formatINR("{:.2f}".format(float(beneficiaryPreviousGstAmount))),
        "beneficiaryPreviousTransactionsCount":formatINR("{:.2f}".format(float(beneficiaryPreviousTransactionsCount))),



        "pgAdditionalChargeAmount":formatINR("{:.2f}".format(float(pgAdditionalChargeAmount))),
        "pgCurrentMonthAdditionalChargeAmount":formatINR("{:.2f}".format(float(pgCurrentMonthAdditionalChargeAmount))),
        "pgPreviousMonthAdditionalChargeAmount":formatINR("{:.2f}".format(float(pgPreviousMonthAdditionalChargeAmount))),
        }
        # print("(((((((((((((payInTop10MerchantsList)))))))))))))",payInTop10MerchantsList)
        # print("(((((((((((((payoutsTop10MerchantsList)))))))))))))",payoutsTop10MerchantsList)
        return render_template(
            "super_admin_templates/dashboard.html",
            adminDict=adminDict,
            payInTop10MerchantsList=payInTop10MerchantsList,
            payoutsTop10MerchantsList=payoutsTop10MerchantsList,
            payoutsList=payoutsList,
            payinsList=payinsList,
            )
    except Exception as e:
        app.logger.error(traceback.format_exc())
        return redirect(url_for('admin.admin_login'))

@admin.route("/admin_profile_details",methods=["POST","GET"])
@adminid_access_token_required
@csrf_protect
def admin_profile_details():
    try:
        if not session.get("adminId"):
            return redirect("admin_login")

        adminId = session.get("adminId")
        csrf_token = request.form.get("csrf_token")
        
        
        admin_queryset = SuperAdmin.objects(id=adminId).first()

        if admin_queryset:
            adminDict = fetch_admin_details(admin_queryset)
            return render_template("super_admin_templates/admin_profile_details.html",adminDict=adminDict)
        else:
            return redirect(url_for('admin.dashboard'))
    except Exception as e:
        app.logger.error(traceback.format_exc())
        return redirect(url_for('admin.dashboard'))


def fetch_admin_details(admin_queryset):
    loginDict={}
    try:
        loginDict={
        "id":str(admin_queryset.id),
        "userName":admin_queryset.userName,
        "email":admin_queryset.email,
        "phoneNumber":admin_queryset.phoneNumber,
        "createdOn":admin_queryset.createdOn.astimezone(tzinfo),
        "status":admin_queryset.status
        }
        if admin_queryset.profilePicture:
            loginDict["profilePicture"]=domain+admin_queryset.profilePicture
        else:
            loginDict["profilePicture"]=""
    except Exception as e:
        app.logger.error(traceback.format_exc())
    return loginDict


@admin.route("/admin_change_password", methods=["POST", "GET"])
@adminid_access_token_required
@csrf_protect
def admin_change_password():
    if not session.get("adminId"):
        return redirect(url_for("admin.admin_login"))
    adminId = session.get("adminId")
    csrf_token = request.form.get("csrf_token")
    latitude = request.form.get("latitude", "")
    longitude = request.form.get("longitude", "")
    loginBrowser = request.headers.get("Sec-Ch-Ua")
    userAgent = request.headers.get("User-Agent")
    if loginBrowser:
        loginBrowseData = loginBrowser.split(";")
        browser = loginBrowseData[0]
    else:
        loginBrowseData = request.headers.get('User-Agent').split(";")
        browser = loginBrowseData[0]

    client_ip=0
    # Extracting client IP address
    if request.headers.getlist("X-Forwarded-For"): 
        client_ip = request.headers.getlist("X-Forwarded-For")[0]
    else:
        client_ip = request.remote_addr

    actionDate=datetime.datetime.now()
    existing_record = ""
    requestData = []

    
    if request.method == "GET":
        try:
            admin_queryset = SuperAdmin.objects(id=adminId).first()
            

            if not admin_queryset:
                flash("Invalid admin id!")
                return redirect(url_for("admin.admin_login"))
            adminDict = fetch_admin_details(admin_queryset)
            return render_template("super_admin_templates/admin_profile_details.html", adminDict=adminDict)
        except Exception as e:
            app.logger.error(traceback.format_exc())
            flash("Server Connection Error. Please try again!")
            return redirect(url_for("admin.admin_login"))

    if request.method == "POST":
        try:
            data_status = {"responseStatus": 0, "result": ""}
            form = AdminChangePasswordForm(request.form)
            oldPassword = request.form.get("oldPassword", "")
            newPassword = request.form.get("newPassword", "")
            confirmNewPassword = request.form.get("confirmNewPassword", "")

            if form.validate():
                if not oldPassword or not newPassword or not confirmNewPassword:
                    flash("Required fields are missing!")
                    data_status["result"] = 4
                    return data_status


            # if newPassword and not validate_password(newPassword):
            #     flash("Password must be 8-30 characters long, include at least one uppercase letter, one lowercase letter, one number, and one special character.")
            #     return redirect(url_for("admin.admin_change_password"))

                print(f"Form Data: oldPassword={oldPassword}, newPassword={newPassword}, confirmNewPassword={confirmNewPassword}")

                try:
                    admin_queryset = SuperAdmin.objects(id=adminId).first()
                    existing_record = admin_queryset.to_json()
                    updatedrequestData = [existing_record]
                    save_admin_log_table = save_admin_logs_data(adminId,None,None,"admin_login","login",actionDate,client_ip,browser,"",requestData,updatedrequestData,latitude,longitude)
                    message=admin_queryset.userName+" Successfully changed the password!"
                    save_admin_log_table.update(message=message)
                    if not admin_queryset:
                        flash("Invalid admin id!")
                        return redirect(url_for("admin.admin_login"))

                    print(f"Admin Query Result: {admin_queryset}")

                    if check_password_hash(admin_queryset.password, oldPassword):
                        if newPassword == confirmNewPassword:
                            admin_queryset.update(password=generate_password_hash(newPassword))
                            flash("Successfully changed the password!")
                            data_status["responseStatus"] = 1
                            return data_status
                        else:
                            flash("New password and confirm new password do not match!")
                            data_status["responseStatus"] = 4
                            data_status["result"] = "New password and confirm new password do not match!"
                            return data_status
                    else:
                        flash("Old password is incorrect!")
                        data_status["responseStatus"] = 4
                        data_status["result"] = "Old password is incorrect!"
                        return data_status
                except Exception as e:
                    app.logger.error(traceback.format_exc())
                    flash("Unable to update the Password!")
                    data_status["responseStatus"] = 4
                    return data_status
            else:
                data_status["result"] = form.errors
                return data_status
        except Exception as e:
            app.logger.error(traceback.format_exc())
            flash("Server Connection Error. Please try again!")
            return redirect(url_for("admin.admin_login"))
        


# @admin.route("/admin_login_otp", methods=["POST"])
# def admin_login_otp():
#     if not session.get("adminId"):
#         return redirect("admin_login")
#     email=request.form.get("email","")
#     password=request.form.get("password","")
#     otp=request.form.get("otp","")

#     if email and password and otp:
#         try:
#             admin_queryset=SuperAdmin.objects(email=email,status__in=[1]).first()
#             if not admin_queryset:
#                 flash("Please give admin email!")
#                 return redirect(url_for('admin.admin_login'))

#             otp_number = str(random.randint(111111, 999999))

#             admin_queryset.update(otp=otp_number,otpGeneratedOn = datetime.datetime.now())

#             userName=admin_queryset.userName
#             # try:
#             #     adminData={}
#             #     adminData={
#             #     "userName":userName,
#             #     "otp":otp_number,
#             #     "domain":domain
#             #     }
#             #     msg=Message("Reset your password!!",sender=sender_email, recipients=[email])
#             #     msg.html=render_template("admin/password_reset.html",adminInfo=adminData)
#             #     mail.send(msg)
#             # except Exception as e:
#             #     app.logger.error(traceback.format_exc())
#             #     pass
#             return render_template("superadmin/admin_login_otp.html")
#         except Exception as e:
#             app.logger.error(traceback.format_exc())
#             return redirect(url_for('admin.admin_login'))
#     else:
#         return redirect(url_for('admin.admin_login'))

# # Admin password reset API
# @admin.route("/admin_password_reset", methods=["POST"])
# def admin_password_reset():
#     if not session.get("adminId"):
#         return redirect("admin_login")
#     data_status = {"responseStatus": 0, "result": ""}
#     email=request.form.get("email","")

#     if email:
#         try:
#             admin_queryset=MonemeSuperAdmin.objects(email__exact=email,status__in=[1]).first()
#             if not admin_queryset:
#                 data_status["result"]="Admin does not exist with given email!"
#                 return data_status
#             otp_number = str(random.randint(111111, 999999))
#             admin_queryset.update(
#                 otp=generate_password_hash(otp_number),
#                 otpGeneratedOn = datetime.datetime.now()
#                 )
#             userName=admin_queryset.userName
#             try:
#                 adminData={}
#                 adminData={
#                 "userName":userName,
#                 "otp":otp_number,
#                 "domain":domain
#                 }
#                 msg=Message("Reset your password!!",sender=sender_email, recipients=[email])
#                 msg.html=render_template("admin/password_reset.html",adminInfo=adminData)
#                 mail.send(msg)
#             except Exception as e:
#                 app.logger.error(traceback.format_exc())
#                 pass
#             return render_template("superadmin/forgotpassword.html")
#             # data_status["responseStatus"]=1
#             # data_status["result"]="OTP sent, Please check your email!"
#             # return data_status
#         except Exception as e:
#             app.logger.error(traceback.format_exc())
#             return render_template("superadmin/resetPassword.html")
#     else:
#         return render_template("superadmin/resetPassword.html")

# # Admin forgot password API
# @admin.route("/admin_forgot_password", methods=["POST"])
# def admin_forgot_password():
#     if not session.get("adminId"):
#         return redirect("admin_login")
#     data_status = {"responseStatus": 0, "result": ""}
#     otp = request.form.get("otp","")
#     email = request.form.get("email","")
#     newPassword = request.form.get("newPassword","")
#     confirmNewPassword = request.form.get("confirmNewPassword","")

#     if otp and email and newPassword and confirmNewPassword:
#         if newPassword == confirmNewPassword:
#             try:
#                 admin_queryset=MonemeSuperAdmin.objects(email__exact=email,status__in=[1]).first()
#                 if admin_queryset:
#                     otpGeneratedOn = admin_queryset.otpGeneratedOn
#                     currentTime = datetime.datetime.now()
#                     time_diff = currentTime - otpGeneratedOn
#                     if int(time_diff.total_seconds()) > 1800:#30min validity
#                         data_status["result"] = "OTP Expired!"
#                         return data_status
#                     if not admin_queryset.otp:
#                         data_status["result"] = "Wrong OTP!"
#                         return data_status
#                     if check_password_hash(admin_queryset.otp, otp):
#                         admin_queryset.update(password=generate_password_hash(newPassword))
#                         admin_queryset.otp = None
#                         admin_queryset.save()
#                         userName=admin_queryset.userName
#                         try:
#                             adminData={}
#                             adminData={
#                             "userName":userName,
#                             "domain":domain
#                             }
#                             msg=Message("Reset your password!!",sender=sender_email, recipients=[email])
#                             msg.html=render_template("admin/forgot_password.html",adminInfo=adminData)
#                             mail.send(msg)
#                         except Exception as e:
#                             app.logger.error(traceback.format_exc())
#                             pass
#                         return render_template("superadmin/index.html")
#                         # data_status["responseStatus"] = 1
#                         # data_status["result"]="Admin Password Changed Successfully!"
#                         # return data_status
#                     else:
#                         return render_template("superadmin/forgotpassword.html")
#                         # data_status["result"]="Wrong OTP!"
#                         # return data_status
#                 else:
#                     return render_template("superadmin/forgotpassword.html")
#                     # data_status["result"]="Invaild email!"
#                     # return data_status
#             except Exception as e:
#                 app.logger.error(traceback.format_exc())
#                 return render_template("superadmin/forgotpassword.html")
#         else:
#             return render_template("superadmin/forgotpassword.html")
#             # data_status["result"]="New Password and Confirm Password Mis-Matched!!"
#             # return data_status
#     else:
#         return render_template("superadmin/forgotpassword.html")


# @admin.route("/dashboard",methods=["POST","GET"])
# def dashboard():
#     try:
#         if not session.get("adminId"):
#             return redirect("admin_login")
#         adminId = session.get("adminId")

#         payInTop10MerchantsList = []
#         payoutsTop10MerchantsList = []
#         payoutsList = []
#         payinsList = []
#         adminDict = {}
#         totalWalletBalance = 0
#         merchants_count = 0
#         totalPayInBalance = 0

#         admin_queryset = SuperAdmin.objects(id=adminId,status__in=[1]).first()

#         totalWalletBalance = Users.objects(status__in=[1]).sum('walletBalance')

#         merchants_count = Users.objects(status__in=[1]).count()


#         totalPayInBalance = WalletTransactions.objects(creditType="Credit",status=1).sum('amount')

#         totalPayOutBalance = FundTransfers.objects(transferType__nin=["Credit"],status=1).sum('amount')


#         # Get the first and last day of the current month
#         today = datetime.datetime.today()
#         first_day_of_current_month = today.replace(day=1,hour=0, minute=0, second=0, microsecond=0)

#         last_day_of_previous_month = first_day_of_current_month - datetime.timedelta(days=1)
#         last_day_of_previous_month = last_day_of_previous_month.replace(hour=23, minute=59, second=59, microsecond=59)

#         first_day_of_previous_month=last_day_of_previous_month.replace(day=1,hour=0, minute=0, second=0, microsecond=0)

#         # Get the last day of the current month
#         last_day_of_current_month = first_day_of_current_month + timedelta(days=calendar.monthrange(today.year, today.month)[1] - 1)
#         last_day_of_current_month = last_day_of_current_month.replace(hour=23, minute=59, second=59, microsecond=999999)


#         # Payout Current Month and Current Year
#         payout_current_month_pipeline = [
#             {"$match": {"transferType": {"$nin": ["Credit"]}, "status": 1,"createdOn": {"$gte": first_day_of_current_month, "$lte": today}}},  # Filtering
#             {"$group": {"_id": None,"totalAmount": {"$sum": "$amount"}}},  # Grouping and summing amounts
#             {"$sort": {"totalAmount": -1}},  # Sorting by total amount in descending order
#         ]

#         currentMonthTotalPayoutAmount = list(FundTransfers.objects.aggregate(*payout_current_month_pipeline))
#         if currentMonthTotalPayoutAmount == []:
#             totalCurrentMonthPayoutBalance = 0
#         else:
#             totalCurrentMonthPayoutBalance = currentMonthTotalPayoutAmount[0]["totalAmount"]

#         payout_previous_month_pipeline = [
#             {"$match": {"transferType": {"$nin": ["Credit"]}, "status": 1,"createdOn": {"$gte": first_day_of_previous_month, "$lte": last_day_of_previous_month}}},  # Filtering
#             {"$group": {"_id": None,"totalAmount": {"$sum": "$amount"}}},  # Grouping and summing amounts
#             {"$sort": {"totalAmount": -1}},  # Sorting by total amount in descending order
#         ]

#         # Execute the aggregation payout_pipeline
#         previousMonthTotalPayoutAmount = list(FundTransfers.objects.aggregate(*payout_previous_month_pipeline))
#         if previousMonthTotalPayoutAmount == []:
#             totalPreviousMonthPayoutBalance = 0
#         else:
#             totalPreviousMonthPayoutBalance = previousMonthTotalPayoutAmount[0]["totalAmount"]

#         # Payout Increase or Decrease Growth

#         if totalPreviousMonthPayoutBalance > 0:
#             payoutGrowth = (totalCurrentMonthPayoutBalance - totalPreviousMonthPayoutBalance)*100/totalPreviousMonthPayoutBalance
#         else:
#             payoutGrowth = 100



#         # Payin Current Month and Current Year
#         payin_current_month_pipeline = [
#             {"$match": {"creditType": "Credit", "status": 1,"createdOn": {"$gte": first_day_of_current_month, "$lte": today}}},  # Filtering
#             {"$group": {"_id": None,"totalAmount": {"$sum": "$amount"}}},  # Grouping and summing amounts
#             {"$sort": {"totalAmount": -1}},  # Sorting by total amount in descending order
#         ]

#         currentMonthTotalPayinAmount = list(WalletTransactions.objects.aggregate(*payin_current_month_pipeline))
#         if currentMonthTotalPayinAmount == []:
#             totalCurrentMonthPayinBalance = 0
#         else:
#             totalCurrentMonthPayinBalance = currentMonthTotalPayinAmount[0]["totalAmount"]

#         payout_previous_month_pipeline = [
#             {"$match": {"creditType": "Credit", "status": 1,"createdOn": {"$gte": first_day_of_previous_month, "$lte": last_day_of_previous_month}}},  # Filtering
#             {"$group": {"_id": None,"totalAmount": {"$sum": "$amount"}}},  # Grouping and summing amounts
#             {"$sort": {"totalAmount": -1}},  # Sorting by total amount in descending order
#         ]

#         # Execute the aggregation payout_pipeline
#         previousMonthTotalPayinAmount = list(WalletTransactions.objects.aggregate(*payout_previous_month_pipeline))
#         if previousMonthTotalPayinAmount == []:
#             totalPreviousMonthPayinBalance = 0
#         else:
#             totalPreviousMonthPayinBalance = previousMonthTotalPayinAmount[0]["totalAmount"]

#         # Payout Increase or Decrease Growth

#         if totalPreviousMonthPayinBalance > 0:
#             payinGrowth = (totalCurrentMonthPayinBalance - totalPreviousMonthPayinBalance)*100/totalPreviousMonthPayinBalance
#         else:
#             payinGrowth = 100

#         # Payout Balance
#         payoutsList = []
#         transaction_apis_queryset = TransactionAPI.objects(transactionType="Payout",status__in=[0,1]).order_by("-id")
#         for each_payout in transaction_apis_queryset:
#             admin_balance_queryset = AdminPayoutBalances.objects(apiTransactionId=str(each_payout.id)).first()
#             if admin_balance_queryset:
#                 previousBalance = admin_balance_queryset.previousBalance
#                 currentBalance = admin_balance_queryset.currentBalance
#                 updatedOn = admin_balance_queryset.createdOn.astimezone(ist_timezone).strftime("%d-%m-%Y %I:%M %p")
#             else:
#                 previousBalance = 0
#                 currentBalance = 0
#                 updatedOn = datetime.datetime.now().astimezone(ist_timezone).strftime("%d-%m-%Y %I:%M %p")

#             payOutSuccessRatio=0
#             # PayOut Success Ratio
#             payout_success_ratio = FundTransfers.objects(transferType__nin=["Credit"],transactionAPIId=str(each_payout.id)).order_by("-id")
#             if payout_success_ratio:
#                 totalPayOutCount = payout_success_ratio.count()
#                 totalPayOutSuccessCount = payout_success_ratio.filter(status=1).count()
#                 payOutSuccessRatio = (totalPayOutSuccessCount*100)/totalPayOutCount
            
            
#             payoutDict = {
#             "id":str(each_payout.id),
#             "apiName":each_payout.apiName,
#             "transactionType":each_payout.transactionType,
#             "successRatio":"{:.2f}".format(float(payOutSuccessRatio)),
#             "updatedOn":updatedOn,
#             "previousBalance":formatINR(previousBalance),
#             "currentBalance":formatINR("{:.2f}".format(float(currentBalance)))
#             }
#             payoutsList.append(payoutDict)

#         # Payin Balance
#         payinsList = []
#         transaction_apis_queryset = TransactionAPI.objects(transactionType="PaymentGateway",status__in=[0,1]).order_by("-id")
#         for each_payin in transaction_apis_queryset:
#             admin_balance_queryset = PayinBalances.objects(transactionAPIId=str(each_payin.id)).all()
#             if admin_balance_queryset:
#                 currentBalance = admin_balance_queryset.filter().sum('currentBalance')
#             else:
#                 currentBalance = 0

#             payInSuccessRatio=0
#             # Payin Success Ratio
#             payin_success_ratio = WalletTransactions.objects(paymentGatewayId=str(each_payin.id),status__in=[0,1],creditType="Credit").order_by("-id")
#             if payin_success_ratio:
#                 totalPayInCount = payin_success_ratio.count()
#                 totalPayInSuccessCount = payin_success_ratio.filter(status=1).count()
#                 payInSuccessRatio = (totalPayInSuccessCount*100)/totalPayInCount
            
#             updatedOn = datetime.datetime.now().astimezone(ist_timezone).strftime("%d-%m-%Y %I:%M %p")
#             payinDict = {
#             "id":str(each_payin.id),
#             "apiName":each_payin.apiName,
#             "transactionType":each_payin.transactionType,
#             "successRatio":"{:.2f}".format(float(payInSuccessRatio)),
#             "updatedOn":updatedOn,
#             "currentBalance":formatINR("{:.2f}".format(float(currentBalance)))
#             }
#             payinsList.append(payinDict)

#         adminDict = {
#         "userName":admin_queryset.userName,
#         "merchantsCount":merchants_count,
#         "payoutGrowth":payoutGrowth,
#         "payinGrowth":payinGrowth,
#         "payInSuccessRatio":round(payInSuccessRatio,2),
#         "payOutSuccessRatio":round(payOutSuccessRatio,2),
#         "totalPayOutBalance":formatINR("{:.2f}".format(float(totalPayOutBalance))),
#         "totalPayInBalance":formatINR("{:.2f}".format(float(totalPayInBalance))),
#         "totalWalletBalance":formatINR("{:.2f}".format(float(totalWalletBalance))),
#         "totalCurrentMonthPayoutBalance":formatINR("{:.2f}".format(float(totalCurrentMonthPayoutBalance))),
#         "totalPreviousMonthPayoutBalance":formatINR("{:.2f}".format(float(totalPreviousMonthPayoutBalance))),
#         "totalPreviousMonthPayinBalance":formatINR("{:.2f}".format(float(totalPreviousMonthPayinBalance))),
#         "totalCurrentMonthPayinBalance":formatINR("{:.2f}".format(float(totalCurrentMonthPayinBalance))),
#         "totalPayinCommissionsAmount":0,
#         "totalPayinTdsAmount":0,
#         "totalPayinGstAmount":0,
#         "totalPayoutCommissionsAmount":0,
#         "totalPayoutTdsAmount":0,
#         "totalPayoutGstAmount":0,
#         "totalPayoutAmount":0,
#         "totalPayinAmount":0,
#         }
#         return render_template(
#             "super_admin_templates/dashboard.html",
#             adminDict=adminDict,
#             payInTop10MerchantsList=payInTop10MerchantsList,
#             payoutsTop10MerchantsList=payoutsTop10MerchantsList,
#             payoutsList=payoutsList,
#             payinsList=payinsList,
#             )
#     except Exception as e:
#         app.logger.error(traceback.format_exc())
#         return redirect(url_for('admin.admin_login'))

# @admin.route("/dashboard_data",methods=["POST","GET"])
# def dashboard_data():
#     data_status = {"responseStatus":0,"result":""}
#     try:
#         if not session.get("adminId"):
#             data_status['responseStatus']=2
#             return data_status

#         # Get the first and last day of the current month
#         today = datetime.datetime.today()
#         first_day_of_current_month = today.replace(day=1,hour=0, minute=0, second=0, microsecond=0)

#         last_day_of_previous_month = first_day_of_current_month - datetime.timedelta(days=1)
#         last_day_of_previous_month = last_day_of_previous_month.replace(hour=23, minute=59, second=59, microsecond=59)

#         first_day_of_previous_month=last_day_of_previous_month.replace(day=1,hour=0, minute=0, second=0, microsecond=0)

#         # Get the last day of the current month
#         last_day_of_current_month = first_day_of_current_month + timedelta(days=calendar.monthrange(today.year, today.month)[1] - 1)
#         last_day_of_current_month = last_day_of_current_month.replace(hour=23, minute=59, second=59, microsecond=999999)

#         # Filter for successful PayIn transactions for the current month
#         pipeline = [
#             {"$match": {
#                 "creditType": "Credit",
#                 "status": 1,
#                 "createdOn": {
#                     "$gte": first_day_of_current_month,
#                     "$lte": last_day_of_current_month
#                 }
#             }},  # Filtering
#             {"$group": {"_id": "$userId", "totalAmount": {"$sum": "$amount"}}},  # Grouping and summing amounts
#             {"$sort": {"totalAmount": -1}},  # Sorting by total amount in descending order
#             {"$limit": 10}  # Limiting to top 10
#         ]

#         # Execute the aggregation pipeline
#         payins_top_10_merchants = list(WalletTransactions.objects.aggregate(*pipeline))
#         payInTop10MerchantsList = []
#         for each_merchant in payins_top_10_merchants:
#             merchant_queryset = Users.objects(id=each_merchant.get("_id")).first()

#             first_chars = re.findall(r'\b\w', merchant_queryset.fullName)

#             imageString = ''.join(first_chars)

#             payInDict = {
#             "merchantId":str(merchant_queryset.id),
#             "merchantName":merchant_queryset.fullName,
#             "phoneNumber":merchant_queryset.phoneNumber,
#             "imageString":imageString,
#             "totalMerchantAmount":formatINR("{:.2f}".format(float(each_merchant.get("totalAmount"))))
#             }
#             payInTop10MerchantsList.append(payInDict)

#         # Filter for successful Payout transactions for the current month
#         payout_pipeline = [
#             {"$match": {
#                 "transferType": "Debit",
#                 "status": 1,
#                 "createdOn": {
#                     "$gte": first_day_of_current_month,
#                     "$lte": last_day_of_current_month
#                 }
#             }},  # Filtering
#             {"$group": {"_id": "$userId", "totalAmount": {"$sum": "$amount"}}},  # Grouping and summing amounts
#             {"$sort": {"totalAmount": -1}},  # Sorting by total amount in descending order
#             {"$limit": 10}  # Limiting to top 10
#         ]

#         # Execute the aggregation payout_pipeline
#         payouts_top_10_merchants = list(FundTransfers.objects.aggregate(*payout_pipeline))
#         payoutsTop10MerchantsList = []
#         for each_payout_merchant in payouts_top_10_merchants:
#             payout_merchant_queryset = Users.objects(id=each_payout_merchant.get("_id")).first()

#             first_chars = re.findall(r'\b\w', payout_merchant_queryset.fullName)

#             imageString = ''.join(first_chars)

#             payOutDict = {
#             "merchantId":str(payout_merchant_queryset.id),
#             "merchantName":payout_merchant_queryset.fullName,
#             "phoneNumber":payout_merchant_queryset.phoneNumber,
#             "imageString":imageString,
#             "totalMerchantAmount":formatINR("{:.2f}".format(float(each_payout_merchant.get("totalAmount"))))
#             }
#             payoutsTop10MerchantsList.append(payOutDict)

#         data_status["responseStatus"]=1
#         data_status["result"]="Dashboard data fetched successfully!"
#         data_status["payInTop10MerchantsList"]=payInTop10MerchantsList
#         data_status["payoutsTop10MerchantsList"]=payoutsTop10MerchantsList
#         return data_status
#     except Exception as e:
#         app.logger.error(traceback.format_exc())
#         data_status["result"]="Unable to fetched dashboard data!!"
#         data_status["payInTop10MerchantsList"]=[]
#         data_status["payoutsTop10MerchantsList"]=[]
#         return data_status


# @admin.route("/dashboard_commissions_data",methods=["POST","GET"])
# def dashboard_commissions_data():
#     data_status = {"responseStatus":0,"result":""}
#     try:
#         if not session.get("adminId"):
#             data_status['responseStatus']=2
#             return data_status
#         commissionsDict = {}
#         payinTotalchargeAmount = 0
#         payinTotaltdsAmount = 0
#         payinTotalgstAmount = 0
#         totalPayinAmount = 0
#         payoutTotalchargeAmount = 0
#         payoutTotaltdsAmount = 0
#         payoutTotalgstAmount = 0
#         totalPayoutAmount = 0

#         payinTotalchargeAmount = WalletTransactions.objects(status=1).sum('commissionCharges.chargeAmount')
#         payinTotaltdsAmount = WalletTransactions.objects(status=1).sum('commissionCharges.tdsAmount')
#         payinTotalgstAmount = WalletTransactions.objects(status=1).sum('commissionCharges.gstAmount')

#         totalPayinAmount  = payinTotalchargeAmount + payinTotaltdsAmount + payinTotalgstAmount

#         print(totalPayinAmount,"totalPayinAmount Commissions")
        
#         payoutTotalchargeAmount = FundTransfers.objects(status=1).sum('commissionCharges.chargeAmount')
#         payoutTotaltdsAmount = FundTransfers.objects(status=1).sum('commissionCharges.tdsAmount')
#         payoutTotalgstAmount = FundTransfers.objects(status=1).sum('commissionCharges.gstAmount')

#         totalPayoutAmount  = payoutTotalchargeAmount + payoutTotaltdsAmount + payoutTotalgstAmount

#         print(totalPayoutAmount,"totalPayoutAmount Commissions")
        
#         commissionsDict = {
#         "totalPayinCommissionsAmount":formatINR("{:.2f}".format(float(payinTotalchargeAmount))),
#         "totalPayinTdsAmount":formatINR("{:.2f}".format(float(payinTotaltdsAmount))),
#         "totalPayinGstAmount":formatINR("{:.2f}".format(float(payinTotalgstAmount))),
#         "totalPayoutCommissionsAmount":formatINR("{:.2f}".format(float(payoutTotalchargeAmount))),
#         "totalPayoutTdsAmount":formatINR("{:.2f}".format(float(payoutTotaltdsAmount))),
#         "totalPayoutGstAmount":formatINR("{:.2f}".format(float(payoutTotalgstAmount))),
#         "totalPayoutAmount":formatINR("{:.2f}".format(float(totalPayoutAmount))),
#         "totalPayinAmount":formatINR("{:.2f}".format(float(totalPayinAmount))),
#         }

#         data_status["responseStatus"]=1
#         data_status["result"]="Commissions data fetched successfully!"
#         data_status["commissionsDict"]=commissionsDict
#         return data_status
#     except Exception as e:
#         app.logger.error(traceback.format_exc())
#         data_status["result"]="Unable to fetched commissions data!!"
#         data_status["commissionsDict"]={}
#         return data_status



class MerchantWisePayinPayout(FlaskForm):
    startDate = StringField('',validators=[ Optional(), Regexp( r"^\d{2}-\d{2}-\d{4}$", message="Date must be in DD-MM-YYYY format")])
    endDate = StringField('', validators=[ Optional(), Regexp( r"^\d{2}-\d{2}-\d{4}$", message="Date must be in DD-MM-YYYY format")])
    merchantId = SelectField('', choices=[],validate_choice=False,validators=[Optional()])
    def validate_merchantId(self, field):
        if field.data:
            if not ObjectId.is_valid(field.data): 
                raise ValidationError("Invalid Merchant Id.")
            merchant_queryset = Users.objects(id=field.data,status__nin=[2]).first()
            if not merchant_queryset:
                raise ValidationError("Please select a Valid Merchant Id")
    class Meta:
        csrf = False 

@admin.route("/merchant_wise_transaction_report",methods=["POST","GET"])
@adminid_access_token_required
def merchant_wise_transaction_report():
    page=None
    pagination=None
    payoutsList=[]
    pgList=[]
    merchantsList=[]
    overalPayoutClosingBalance=0
    overalPayoutOpeningBalance=0
    merchantId=None
    form=MerchantWisePayinPayout(request.args)
    try:
        if not session.get("adminId"):
            return redirect("admin_login")
        adminId = session.get("adminId")
        permissionsList = check_permissions(session.get("adminId"),"merchantWiseTransactionPermissions")
        if "view" in permissionsList:
            payoutsList = []
            overalPayoutOpeningBalance=0
            overalPayoutClosingBalance=0
            
            startDate = request.args.get("startDate","")
            endDate = request.args.get("endDate","")
            merchantId = request.args.get("merchantId","")

            usersDataList = []

            # Set default date format
            date_format = "%d-%m-%Y"
            pagination = None

            try:
                if startDate:
                    startDate = datetime.datetime.strptime(startDate, date_format)
                    startDate = startDate.replace(hour=0, minute=0, second=0, microsecond=0)
                else:
                    startDate = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)

                if endDate:
                    endDate = datetime.datetime.strptime(endDate, date_format)
                    endDate = endDate.replace(hour=23, minute=59, second=59, microsecond=999999)
                else:
                    endDate = datetime.datetime.now().replace(hour=23, minute=59, second=59, microsecond=999999)
            except Exception as ve:
                app.logger.error("Date parsing error: %s", ve)
                startDate = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
                endDate = datetime.datetime.now().replace(hour=23, minute=59, second=59, microsecond=999999)
            print(form.validate(),"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
            if form.validate():
                if startDate > endDate:
                    error= "Invalid Date Range (Start date must be less than end date)!!"
                    return render_template("super_admin_templates/merchant_wise_transaction_report_list.html",error=error)

                openingpipeline = [
                    {"$match": {
                        "createdOn": {"$lte": startDate},
                        "status":{"$in":[1,2]}
                    }},
                    
                    
                    {"$sort": {"userId": 1, "createdOn": -1}},
                    
                
                    {"$group": {
                        "_id": "$userId",
                        "latest_amount": {"$first": "$currentBalance"}
                    }},
                    
                    
                    {"$group": {
                        "_id": None,
                        "total_amount_sum": {"$sum": "$latest_amount"}
                    }}
                ]

                payoutopeningTotalresult = list(FundTransfers.objects.aggregate(*openingpipeline))
                print("(((((((((((payoutopeningTotalresult)))))))))))",payoutopeningTotalresult)
                if payoutopeningTotalresult:
                    overalPayoutOpeningBalance=float(payoutopeningTotalresult[0].get('total_amount_sum'))

                closingpipeline = [
                    
                    {"$match": {
                        "createdOn": {"$lte": endDate},
                        "status":{"$in":[1,2]}
                    }},
                    
                
                    {"$sort": {"userId": 1, "createdOn": -1}},
                    
                    
                    {"$group": {
                        "_id": "$userId",
                        "latest_amount": {"$first": "$currentBalance"}
                    }},
                    
                
                    {"$group": {
                        "_id": None,
                        "total_amount_sum": {"$sum": "$latest_amount"}
                    }}
                ]
                payoutclosingTotalresult = list(FundTransfers.objects.aggregate(*closingpipeline))
                if payoutclosingTotalresult:
                    overalPayoutClosingBalance=float(payoutclosingTotalresult[0].get('total_amount_sum'))


                page =  request.args.get(get_page_parameter(), type=int, default=1)
                per_page = 20
                start = (page - 1) * per_page

                total_count=0

                filters = Q(status__nin=[2])
                # print("(((((((((((((((((((search_element)))))))))))))))))))",search_element)
                if merchantId:
                    filters &= Q(id__in=[merchantId])

                total_count = Users.objects(filters).count()



                user_queryset_dropdown = (
                    Users.objects()
                    .only("id", "fullName", "phoneNumber",)
                    .order_by("_id")
                )

                user_queryset_dropdown = list(user_queryset_dropdown)

                

                for each_merchant in user_queryset_dropdown:
                    
                    # merchantDict = fetching_user_details(each_merchant)
                    merchantDict = {
                        "id": str(each_merchant.id),
                        "fullName": str(each_merchant.fullName),
                        "phoneNumber": str(each_merchant.phoneNumber),
                    }
                    merchantsList.append(merchantDict)

                user_queryset = (
                    Users.objects(filters)
                    .only("id", "fullName", "phoneNumber", "walletBalance", "payoutBalance")
                    .order_by("_id")
                    .skip(start)
                    .limit(per_page)
                )
                # if merchantId:
                #     user_queryset = user_queryset.filter()
                snoCount = start
                for each_user in user_queryset:
                    snoCount+=1
                    payOutSuccessTotalAmount = 0.0
                    payInSuccessTotalAmount = 0.0
                    payoutOpeningBalance = None
                    payoutClosingBalance = None

                    currentPayinBalance = round(float(each_user.walletBalance),2)
                    currentPayoutBalance = round(float(each_user.payoutBalance),2)
                
                    wallet_transaction_queryset = WalletTransactions.objects(userId=each_user.id,status=1,createdOn__gte=startDate,createdOn__lte=endDate,creditType="Credit").order_by("_id").sum("grandTotal")
                    payInSuccessTotalAmount = round(float(wallet_transaction_queryset),2)

                    overall_payouts_queryset = FundTransfers.objects(transferType="Debit",status__in=[1,2],userId=each_user.id,createdOn__gte=startDate,createdOn__lte=endDate).order_by("_id").sum("grandTotal")
                    payOutSuccessTotalAmount = round(float(overall_payouts_queryset),2)

                    first_fund_transfer_transaction_queryset = FundTransfers.objects(userId=each_user.id,status__in=[1,2],createdOn__gte=startDate,createdOn__lte=endDate).order_by("createdOn").first()
                    if first_fund_transfer_transaction_queryset:
                        payoutOpeningBalance = round(first_fund_transfer_transaction_queryset.previousBalance,2)
                    else:
                        payoutOpeningBalance = currentPayoutBalance

                    last_fund_transfer_transaction_queryset = FundTransfers.objects(userId=each_user.id,status__in=[1,2],createdOn__gte=startDate,createdOn__lte=endDate).order_by("-createdOn").first()
                    if last_fund_transfer_transaction_queryset:
                        payoutClosingBalance = round(last_fund_transfer_transaction_queryset.currentBalance,2)
                    else:
                        payoutClosingBalance = currentPayoutBalance
                        
                    userDataDict = {
                        "userId": str(each_user.id),
                        "merchantName": str(each_user.fullName),
                        "phoneNumber": str(each_user.phoneNumber),
                        "payOutSuccessTotalAmount": payOutSuccessTotalAmount,
                        "payInSuccessTotalAmount": payInSuccessTotalAmount,
                        "payoutOpeningBalance": payoutOpeningBalance,
                        "payoutClosingBalance": payoutClosingBalance,
                        "currentPayinBalance": currentPayinBalance,
                        "currentPayoutBalance": currentPayoutBalance,
                        "snoCount": snoCount,
                    }
                    usersDataList.append(userDataDict)

                # Pagination object for rendering pagination controls in the template
                pagination = Pagination(page=page, total=total_count, per_page=per_page, alignment="right", record_name="payouts")
                print(len(merchantsList),"(((((((((((())))))))))))")

                
                return render_template("super_admin_templates/merchant_wise_transaction_report_list.html",
                    pagination=pagination,
                    pgList=pgList,
                    payoutsList=payoutsList,
                    startDate=startDate.strftime(date_format),
                    endDate=endDate.strftime(date_format),
                    merchantsList=merchantsList,
                    merchantId=merchantId,
                    overalPayoutClosingBalance= round(float(overalPayoutClosingBalance),2),
                    overalPayoutOpeningBalance= round(float(overalPayoutOpeningBalance),2),
                    usersDataList=usersDataList,
                    form=form
                    )
            else:
                print("form ",form.errors)
                return render_template("super_admin_templates/merchant_wise_transaction_report_list.html",
                    pagination=pagination,
                    pgList=pgList,
                    payoutsList=payoutsList,
                    startDate=startDate.strftime(date_format),
                    endDate=endDate.strftime(date_format),
                    merchantsList=merchantsList,
                    merchantId=merchantId,
                    overalPayoutClosingBalance= round(float(overalPayoutClosingBalance),2),
                    overalPayoutOpeningBalance= round(float(overalPayoutOpeningBalance),2),
                    usersDataList=usersDataList,
                    form=form
                    )
        else:
            flash("The staff member does not have permission to view Merchant wise.", "danger")
            return render_template("super_admin_templates/merchant_wise_transaction_report_list.html")
    except Exception as e:
        app.logger.error(traceback.format_exc())
        error = "Unable to fetch merchant wise payin payout total data!!"
        return render_template("super_admin_templates/merchant_wise_transaction_report_list.html", 
            error=error,
            pagination=pagination,
            payoutsList=payoutsList,
            pgList=pgList,
            startDate=startDate.strftime(date_format),
            endDate=endDate.strftime(date_format),
            merchantsList=merchantsList,
            overalPayoutClosingBalance= round(float(overalPayoutClosingBalance),2),
            overalPayoutOpeningBalance= round(float(overalPayoutOpeningBalance),2),   
            usersDataList=[],
            merchantId=merchantId,
            form=form
            )



@admin.route("/commissionStructure",methods=["GET","POST"])
@adminid_access_token_required
def commissionStructure():
    date_format = "%d-%m-%Y"
    overAllCWCommissionsAmount=0
    overPGCharges=0
    overPgGstAmount=0
    overallTransactionChargesDatewise=0
    overallTransactionGstAmountDatewise=0

    cwCommissionsAmount=0
    pgCharges=0
    pgGstAmount=0
    transactionChargesDatewise=0
    transactionGstAmountDatewise=0
    pgTop10chargesList=[] 
    subPaymentmodeDataList=[] 
    siteWiseDataList=[]
    form = CommissionStructureForm(request.args)
    try:
        permissionsList = check_permissions(session.get("adminId"),"commissionStructurePermissions")
        if "view" in permissionsList:
            startDate = request.args.get("startDate","")
            endDate = request.args.get("endDate","")

            # print("(((((((endDate)1111111111))))))",endDate)
            # print("(((((((startDate)12222222222222))))))",startDate)
            
            
            try:
                if startDate:
                    startDate = datetime.datetime.strptime(startDate, date_format)  # Use YYYY-MM-DD format
                    startDate = startDate.replace(hour=0, minute=0, second=0, microsecond=0)
                else:
                    startDate = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)

                if endDate:
                    endDate = datetime.datetime.strptime(endDate, date_format)
                    endDate = endDate.replace(hour=23, minute=59, second=59, microsecond=999999)
                else:
                    endDate = datetime.datetime.now().replace(hour=23, minute=59, second=59, microsecond=999999)
            except Exception as ve:
                app.logger.error("Date parsing error: %s", ve)
                startDate = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
                endDate = datetime.datetime.now().replace(hour=23, minute=59, second=59, microsecond=999999)

            ### All Data without any time frame
            # company_queryset = CompanyCommissions.objects(transferType="Credit",status=1).all()
            # overAllCWCommissionsAmount = company_queryset.filter().sum('commissionAmount')
            # overAllCWCommissionsAmount=formatINR("{:.2f}".format(round(float(overAllCWCommissionsAmount),2)))

            # # companyCommissionsQueryset = CompanyCommissions.objects(transferType="Credit",status=1).all()

            # totalSuccessTxnscount = len(company_queryset)

            # totalSuccessAmount = company_queryset.filter().sum('totalAmount')
            # totalSuccessAmount=formatINR("{:.2f}".format(round(float(totalSuccessAmount),2)))

            # overPGCharges = formatINR("{:.2f}".format(company_queryset.filter().sum('aggregatorCommissionAmount')))

            # overPgGstAmount = formatINR("{:.2f}".format(company_queryset.filter().sum('aggregatorCommissionCharges.gstAmount')))

            # overallTransactionChargesDatewise = formatINR("{:.2f}".format(company_queryset.filter().sum('transactionCommissionCharges.chargeAmount')))

            # overallTransactionGstAmountDatewise = formatINR("{:.2f}".format(company_queryset.filter().sum('transactionCommissionCharges.gstAmount')))
            if form.validate():

                company_commission_query_pipeline = [
                    {
                        "$match": {
                            "transferType": "Credit",
                            "status": 1,
                            #  "createdOn": {
                            #              "$gte": startDate,
                            #              "$lte": endDate
                            #          }
                    }
                    },
                    {
                    "$group": {
                        "_id": None,  
                        "totalSuccessTxnscount": { "$sum": 1 },
                        "overAllCWCommissionsAmount": {"$sum": "$commissionAmount"},
                        "totalSuccessAmount": {"$sum": "$totalAmount"},
                        "overPGCharges": {"$sum": "$aggregatorCommissionAmount"},
                        "overPgGstAmount": {"$sum": "$aggregatorCommissionCharges.gstAmount"},
                        "overallTransactionChargesDatewise": {"$sum": "$transactionCommissionCharges.chargeAmount"},
                        "overallTransactionGstAmountDatewise": {"$sum": "$transactionCommissionCharges.gstAmount"}
                    }
                }
                ]

                company_commission_query_result = list(CompanyCommissions.objects.aggregate(*company_commission_query_pipeline))
                print("company_commission_query_result",company_commission_query_result)

                if len(company_commission_query_result) > 0:
                    totalSuccessTxnscount = company_commission_query_result[0]["totalSuccessTxnscount"]
                    overAllCWCommissionsAmount = company_commission_query_result[0]["overAllCWCommissionsAmount"]
                    totalSuccessAmount = company_commission_query_result[0]["totalSuccessAmount"]
                    overPGCharges = company_commission_query_result[0]["overPGCharges"]
                    overPgGstAmount = company_commission_query_result[0]["overPgGstAmount"]
                    overallTransactionChargesDatewise = company_commission_query_result[0]["overallTransactionChargesDatewise"]
                    overallTransactionGstAmountDatewise = company_commission_query_result[0]["overallTransactionGstAmountDatewise"]
                else:
                    totalSuccessTxnscount = 0
                    overAllCWCommissionsAmount = 0
                    totalSuccessAmount = 0
                    overPGCharges = 0
                    overPgGstAmount = 0
                    overallTransactionChargesDatewise = 0
                    overallTransactionGstAmountDatewise = 0
                


                
                ### Data with given time frame
                # company_queryset = CompanyCommissions.objects(transferType="Credit",status=1).all()
                # company_commission_queryset = company_queryset.filter(createdOn__gte=startDate,createdOn__lte=endDate).all()

                # cwCommissionsAmount = company_commission_queryset.filter().sum('commissionAmount')
                # cwCommissionsAmount=formatINR("{:.2f}".format(round(cwCommissionsAmount,2)))

                # pgCharges = formatINR("{:.2f}".format(company_commission_queryset.filter().sum('aggregatorCommissionAmount')))
        
                # pgGstAmount = formatINR("{:.2f}".format(company_commission_queryset.filter().sum('aggregatorCommissionCharges.gstAmount')))


                # transactionChargesDatewise = formatINR("{:.2f}".format(company_commission_queryset.filter().sum('transactionCommissionCharges.chargeAmount')))

                # transactionGstAmountDatewise = formatINR("{:.2f}".format(company_commission_queryset.filter().sum('transactionCommissionCharges.gstAmount')))

                # # companyCommissionsQueryset = CompanyCommissions.objects(createdOn__gte=startDate,createdOn__lte=endDate,transferType="Credit",status=1).all()

                # successTxnscountDatewise = len(company_commission_queryset)

                # successAmountDatewise = company_commission_queryset.filter().sum('totalAmount')
                # successAmountDatewise=formatINR("{:.2f}".format(round(float(successAmountDatewise),2)))
                company_commission_query_date_wise_pipeline = [
                    {
                        "$match": {
                            "transferType": "Credit",
                            "status": 1,
                            #  "createdOn": {
                            #              "$gte": startDate,
                            #              "$lte": endDate
                            #          }
                    }
                    },
                    {
                    "$group": {
                        "_id": None,  
                        "successTxnscountDatewise": { "$sum": 1 },
                        "cwCommissionsAmount": {"$sum": "$commissionAmount"},
                        "successAmountDatewise": {"$sum": "$totalAmount"},
                        "pgCharges": {"$sum": "$aggregatorCommissionAmount"},
                        "pgGstAmount": {"$sum": "$aggregatorCommissionCharges.gstAmount"},
                        "transactionChargesDatewise": {"$sum": "$transactionCommissionCharges.chargeAmount"},
                        "transactionGstAmountDatewise": {"$sum": "$transactionCommissionCharges.gstAmount"}
                    }
                }
                ]

                company_commission_query_date_wise_result = list(CompanyCommissions.objects.aggregate(*company_commission_query_date_wise_pipeline))
                print("company_commission_query_date_wise_result",company_commission_query_date_wise_result)

                if len(company_commission_query_date_wise_result) > 0:
                    successTxnscountDatewise = company_commission_query_date_wise_result[0]["successTxnscountDatewise"]
                    cwCommissionsAmount = company_commission_query_date_wise_result[0]["cwCommissionsAmount"]
                    successAmountDatewise = company_commission_query_date_wise_result[0]["successAmountDatewise"]
                    pgCharges = company_commission_query_date_wise_result[0]["pgCharges"]
                    pgGstAmount = company_commission_query_date_wise_result[0]["pgGstAmount"]
                    transactionChargesDatewise = company_commission_query_date_wise_result[0]["transactionChargesDatewise"]
                    transactionGstAmountDatewise = company_commission_query_date_wise_result[0]["transactionGstAmountDatewise"]
                else:
                    successTxnscountDatewise = 0
                    cwCommissionsAmount = 0
                    successAmountDatewise = 0
                    pgCharges = 0
                    pgGstAmount = 0
                    transactionChargesDatewise = 0
                    transactionGstAmountDatewise = 0


                # overPgGstAmount = formatINR("{:.2f}".format(round(float(overPgGstAmount),2)))
                pg_wise_pipeline = [
                    {"$match": {
                        "transferType": "Credit",
                        "status": 1,
                        "createdOn": {
                            "$gte": startDate,
                            "$lte": endDate
                        }
                    }},  # Filtering
                    {"$group": {"_id": "$transactionAPIId", 
                        "transactionsCount": {"$sum": 1},
                            "aggregatorChargeAmount": {"$sum": "$aggregatorCommissionAmount"},
                            "aggregatorGstAmount":    {"$sum": "$aggregatorCommissionCharges.gstAmount"},
                            "companyCommissionAmount":       {"$sum": "$commissionAmount"},
                            "transactionChargeAmount": {"$sum": "$transactionCommissionCharges.chargeAmount"},
                        "transactionGstAmount":    {"$sum": "$transactionCommissionCharges.gstAmount"},
                        "totalVolumeAmount":    {"$sum": "$totalAmount"},
                    }},  # Grouping and summing amounts
                    {"$sort": {"chargeAmount": -1}},  # Sorting by total amount in descending order
                ]

                # Execute the aggregation pg_wise_pipeline
                payouts_top_10_merchants = list(CompanyCommissions.objects.aggregate(*pg_wise_pipeline))
                pgTop10chargesList = []
                print(payouts_top_10_merchants,"()))))))))))")
                counter = 0
                for each_payout_merchant in payouts_top_10_merchants:
                    counter+=1
                    payout_merchant_queryset = TransactionAPI.objects(id=each_payout_merchant.get("_id")).first()
                    if payout_merchant_queryset:
                        # first_chars = re.findall(r'\b\w', payout_merchant_queryset.fullName)

                        # imageString = ''.join(first_chars)
                        transactionChargeAmount = float(each_payout_merchant.get("transactionChargeAmount"))
                        transactionGstAmount = float(each_payout_merchant.get("transactionGstAmount"))
                        transactionTotalAmount = float(transactionChargeAmount + transactionGstAmount)

                        aggregatorChargeAmount = float(each_payout_merchant.get("aggregatorChargeAmount"))
                        aggregatorGstAmount = float(each_payout_merchant.get("aggregatorGstAmount"))
                        aggregatorTotalAmount = float(aggregatorChargeAmount + aggregatorGstAmount)

                        companyChargeAmount = float(transactionChargeAmount - aggregatorChargeAmount)
                        companyGstAmount = float(transactionGstAmount - aggregatorGstAmount)
                        companyTotalAmount = float(transactionTotalAmount - aggregatorTotalAmount)
                        
                        companyCommissionAmount = float(each_payout_merchant.get("companyCommissionAmount"))
                        payOutDict = {
                            "snoCount":counter,
                            "apiId":str(payout_merchant_queryset.id),
                            "apiName":payout_merchant_queryset.apiName,

                            "transactionChargeAmount": formatINR("{:.2f}".format(transactionChargeAmount)),
                            "transactionGstAmount": formatINR("{:.2f}".format(transactionGstAmount)),
                            "transactionTotalAmount": formatINR("{:.2f}".format(transactionTotalAmount)),

                            "aggregatorChargeAmount": formatINR("{:.2f}".format(aggregatorChargeAmount)),
                            "aggregatorGstAmount": formatINR("{:.2f}".format(aggregatorGstAmount)),
                            "aggregatorTotalAmount": formatINR("{:.2f}".format(aggregatorTotalAmount)),
                        
                            "companyChargeAmount":formatINR("{:.2f}".format(companyChargeAmount)),
                            "companyGstAmount":formatINR("{:.2f}".format(companyGstAmount)),
                            "companyTotalAmount":formatINR("{:.2f}".format(companyTotalAmount)),

                            "companyCommissionAmount":formatINR("{:.2f}".format(companyCommissionAmount)),

                            "totalVolumeAmount":formatINR("{:.2f}".format(each_payout_merchant.get("totalVolumeAmount"))),
                            "transactionsCount":each_payout_merchant.get("transactionsCount"),
                        }
                        pgTop10chargesList.append(payOutDict)
                    # print("each_payout_merchant",each_payout_merchant)

                subpayment_mode_wise_pipeline = [
                    {"$match": {
                        "transferType": "Credit",
                        "status": 1,
                        "createdOn": {
                            "$gte": startDate,
                            "$lte": endDate
                        }
                    }},  # Filtering
                    {"$group": {"_id": "$subPaymentModeId", 
                        "transactionsCount": {"$sum": 1},
                        "aggregatorChargeAmount": {"$sum": "$aggregatorCommissionAmount"},
                        "aggregatorGstAmount":    {"$sum": "$aggregatorCommissionCharges.gstAmount"},
                        "companyCommissionAmount":       {"$sum": "$commissionAmount"},
                        "transactionChargeAmount": {"$sum": "$transactionCommissionCharges.chargeAmount"},
                        "transactionGstAmount":    {"$sum": "$transactionCommissionCharges.gstAmount"},
                        "totalVolumeAmount":    {"$sum": "$totalAmount"},
                    }},  # Grouping and summing amounts
                    {"$sort": {"chargeAmount": -1}},  # Sorting by total amount in descending order
                ]

                sub_payment_mode_data = list(CompanyCommissions.objects.aggregate(*subpayment_mode_wise_pipeline))
            
                # print(sub_payment_mode_data,"()))))))))))")
                counter = 0
                for each_sub_payment_mode_rec in sub_payment_mode_data:
                    counter+=1
                    each_subpm_queryset = SubPaymentModes.objects(id=each_sub_payment_mode_rec.get("_id")).first() ####################!@#13
                    if each_subpm_queryset:
                        # first_chars = re.findall(r'\b\w', each_subpm_queryset.fullName)

                        # imageString = ''.join(first_chars)
                        transactionChargeAmount = float(each_sub_payment_mode_rec.get("transactionChargeAmount"))
                        transactionGstAmount = float(each_sub_payment_mode_rec.get("transactionGstAmount"))
                        transactionTotalAmount = float(transactionChargeAmount + transactionGstAmount)

                        aggregatorChargeAmount = float(each_sub_payment_mode_rec.get("aggregatorChargeAmount"))
                        aggregatorGstAmount = float(each_sub_payment_mode_rec.get("aggregatorGstAmount"))
                        aggregatorTotalAmount = float(aggregatorChargeAmount + aggregatorGstAmount)

                        companyChargeAmount = float(transactionChargeAmount - aggregatorChargeAmount)
                        companyGstAmount = float(transactionGstAmount - aggregatorGstAmount)
                        companyTotalAmount = float(transactionTotalAmount - aggregatorTotalAmount)
                        
                        companyCommissionAmount = float(each_sub_payment_mode_rec.get("companyCommissionAmount"))
                        payOutDict = {
                            "snoCount":counter,
                            "apiId":str(each_subpm_queryset.id),
                            "subPaymentModeType":each_subpm_queryset.subPaymentModeType,

                            "transactionChargeAmount": formatINR("{:.2f}".format(transactionChargeAmount)),
                            "transactionGstAmount": formatINR("{:.2f}".format(transactionGstAmount)),
                            "transactionTotalAmount": formatINR("{:.2f}".format(transactionTotalAmount)),

                            "aggregatorChargeAmount": formatINR("{:.2f}".format(aggregatorChargeAmount)),
                            "aggregatorGstAmount": formatINR("{:.2f}".format(aggregatorGstAmount)),
                            "aggregatorTotalAmount": formatINR("{:.2f}".format(aggregatorTotalAmount)),
                        
                            "companyChargeAmount":formatINR("{:.2f}".format(companyChargeAmount)),
                            "companyGstAmount":formatINR("{:.2f}".format(companyGstAmount)),
                            "companyTotalAmount":formatINR("{:.2f}".format(companyTotalAmount)),

                            "companyCommissionAmount":formatINR("{:.2f}".format(companyCommissionAmount)),

                            "totalVolumeAmount":formatINR("{:.2f}".format(each_sub_payment_mode_rec.get("totalVolumeAmount"))),
                            "transactionsCount":each_sub_payment_mode_rec.get("transactionsCount"),
                        }
                        subPaymentmodeDataList.append(payOutDict)
                    # print("each_payout_merchant",each_sub_payment_mode_rec)
                
                
                
                sitewise_pipeline = [
                    {"$match": {
                        "transferType": "Credit",
                        "status": 1,
                        "createdOn": {
                            "$gte": startDate,
                            "$lte": endDate
                        }
                    }},  # Filtering
                    {"$group": {"_id": "$siteTitle", 
                        "transactionsCount": {"$sum": 1},
                        "aggregatorChargeAmount": {"$sum": "$aggregatorCommissionAmount"},
                        "aggregatorGstAmount":    {"$sum": "$aggregatorCommissionCharges.gstAmount"},
                        "companyCommissionAmount":       {"$sum": "$commissionAmount"},
                        "transactionChargeAmount": {"$sum": "$transactionCommissionCharges.chargeAmount"},
                        "transactionGstAmount":    {"$sum": "$transactionCommissionCharges.gstAmount"},
                        "totalVolumeAmount":    {"$sum": "$totalAmount"},
                    }},  # Grouping and summing amounts
                    {"$sort": {"chargeAmount": -1}},  # Sorting by total amount in descending order
                ]

                sitewise_data = list(CompanyCommissions.objects.aggregate(*sitewise_pipeline))
            
                # print(sitewise_data,"()))))))))))")
                counter = 0
                for each_sitewise_rec in sitewise_data:
                    counter+=1
                    print("(((((((((((((((((((each_sitewise_rec.get())))))))))))))))))))",each_sitewise_rec.get("_id"))
                    multiple_app_queryset = MultipleAppSites.objects(siteCode=each_sitewise_rec.get("_id")).first() ####################!@#13

                    if multiple_app_queryset:
                        print("(****************************record multiple site found)")
                        # first_chars = re.findall(r'\b\w', multiple_app_queryset.fullName)

                        # imageString = ''.join(first_chars)
                        transactionChargeAmount = float(each_sitewise_rec.get("transactionChargeAmount"))
                        transactionGstAmount = float(each_sitewise_rec.get("transactionGstAmount"))
                        transactionTotalAmount = float(transactionChargeAmount + transactionGstAmount)

                        aggregatorChargeAmount = float(each_sitewise_rec.get("aggregatorChargeAmount"))
                        aggregatorGstAmount = float(each_sitewise_rec.get("aggregatorGstAmount"))
                        aggregatorTotalAmount = float(aggregatorChargeAmount + aggregatorGstAmount)

                        companyChargeAmount = float(transactionChargeAmount - aggregatorChargeAmount)
                        companyGstAmount = float(transactionGstAmount - aggregatorGstAmount)
                        companyTotalAmount = float(transactionTotalAmount - aggregatorTotalAmount)
                        
                        companyCommissionAmount = float(each_sitewise_rec.get("companyCommissionAmount"))
                        sitewiseDict = {
                            "snoCount":counter,
                            "apiId":str(multiple_app_queryset.id),
                            "siteTitle":multiple_app_queryset.siteTitle,

                            "transactionChargeAmount": formatINR("{:.2f}".format(transactionChargeAmount)),
                            "transactionGstAmount": formatINR("{:.2f}".format(transactionGstAmount)),
                            "transactionTotalAmount": formatINR("{:.2f}".format(transactionTotalAmount)),

                            "aggregatorChargeAmount": formatINR("{:.2f}".format(aggregatorChargeAmount)),
                            "aggregatorGstAmount": formatINR("{:.2f}".format(aggregatorGstAmount)),
                            "aggregatorTotalAmount": formatINR("{:.2f}".format(aggregatorTotalAmount)),
                        
                            "companyChargeAmount":formatINR("{:.2f}".format(companyChargeAmount)),
                            "companyGstAmount":formatINR("{:.2f}".format(companyGstAmount)),
                            "companyTotalAmount":formatINR("{:.2f}".format(companyTotalAmount)),

                            "companyCommissionAmount":formatINR("{:.2f}".format(companyCommissionAmount)),

                            "totalVolumeAmount":formatINR("{:.2f}".format(each_sitewise_rec.get("totalVolumeAmount"))),
                            "transactionsCount":each_sitewise_rec.get("transactionsCount"),
                        }
                        siteWiseDataList.append(sitewiseDict)
                        # print("(((((((((((((((((((((siteWiseDataList)))))))))))))))))))))",siteWiseDataList)
                        # print("(((((((((((((((((((((sitewiseDict)))))))))))))))))))))",sitewiseDict)
                    else:
                        print("(****************************none found)")
                    # print("(((((((((((((((((((((each_payout_merchant)))))))))))))))))))))",each_sitewise_rec)

                # print("(((((((endDate)))))))",endDate)
                # print("(((((((startDate)))))))",startDate)
                # print("(((((((pgTop10chargesList)))))))",pgTop10chargesList)
                # print("(((((((subPaymentmodeDataList)))))))",subPaymentmodeDataList)
                print("(((((((siteWiseDataList)))))))",siteWiseDataList)

            else: 
                print(form.errors,"form.errors")

                return render_template(
                        "super_admin_templates/commissions_structure.html",
                        startDate=startDate.strftime(date_format),
                        endDate=endDate.strftime(date_format),
                        overAllCWCommissionsAmount=overAllCWCommissionsAmount,
                        overallTransactionGstAmountDatewise=overallTransactionGstAmountDatewise,
                        overallTransactionChargesDatewise=overallTransactionChargesDatewise,
                        overPGCharges=overPGCharges,
                        overPgGstAmount=overPgGstAmount,
                        cwCommissionsAmount=cwCommissionsAmount,
                        pgCharges=pgCharges,
                        pgGstAmount=pgGstAmount,
                        transactionChargesDatewise=transactionChargesDatewise,
                        transactionGstAmountDatewise=transactionGstAmountDatewise,
                        pgTop10chargesList =pgTop10chargesList,
                        totalSuccessTxnscount=totalSuccessTxnscount,
                        successTxnscountDatewise=successTxnscountDatewise,
                        totalSuccessAmount=totalSuccessAmount,
                        successAmountDatewise=successAmountDatewise,
                        subPaymentmodeDataList=subPaymentmodeDataList,
                        siteWiseDataList=siteWiseDataList,
                        form = form
                        )
            
            
            
        else:
            flash("The staff member does not have permission to view Commission structure", "danger")
            return redirect(url_for("admin.dashboard"))
    except Exception as e:
        app.logger.error(traceback.format_exc())
        error = "Unable to fetched payout ledger report data!!"
        return render_template(
                "super_admin_templates/commissions_structure.html",
                startDate=startDate.strftime(date_format),
                endDate=endDate.strftime(date_format),
                overAllCWCommissionsAmount=overAllCWCommissionsAmount,
                overallTransactionGstAmountDatewise=overallTransactionGstAmountDatewise,
                overallTransactionChargesDatewise=overallTransactionChargesDatewise,
                overPGCharges=overPGCharges,
                overPgGstAmount=overPgGstAmount,
                cwCommissionsAmount=cwCommissionsAmount,
                pgCharges=pgCharges,
                pgGstAmount=pgGstAmount,
                pgTop10chargesList =pgTop10chargesList,
                subPaymentmodeDataList=subPaymentmodeDataList,
                siteWiseDataList=siteWiseDataList,
                form = form
                )

@admin.route("/generateOtp",methods=["POST","GET"])
@csrf.exempt
def generateOtp():
    data_status={"responseStatus":0,"result":""}
    try:
        mail_type = request.form.get("mailType", "").strip()
        defaultVerificationId = request.form.get("defaultVerificationId", "").strip()
        print("(((((((((((((((((((((((((((((((((((((((((((((((((((((mail_type)))))))))))))))))))))))))))))))))))))))))))))))))))))",defaultVerificationId,mail_type)
        if not mail_type:
            data_status["result"]= "mailType is required!"
            return data_status
        generateResponse = generate_otp_helper(mail_type,defaultVerificationId)
        print(generateResponse,"====generateResponse===")
        return generateResponse
    except Exception as e:
        app.logger.error(traceback.format_exc())
        data_status["result"]="Unable to generate otp!!"
        return data_status
    
@admin.route("/resendOtp",methods=["POST","GET"])
@csrf.exempt
def resendOtp():
    data_status={"responseStatus":0,"result":""}
    try:
        mail_type = request.form.get("mailType", "").strip()
        defaultVerificationId = request.form.get("defaultVerificationId", "").strip()
        otpCheckId = request.form.get("otpCheckId")
        print("(((((((((((((((((((((((((((((((((((((((((((((((((((((mail_type)))))))))))))))))))))))))))))))))))))))))))))))))))))",defaultVerificationId,mail_type)
        if not mail_type:
            data_status["result"]= "mailType is required!"
            return data_status
        send_type="resend_otp"
        generateResponse = generate_otp_helper(mail_type=mail_type,defaultVerificationId=defaultVerificationId,otpCheckId=otpCheckId,send_type=send_type)
        print(generateResponse,"====generateResponse===")
        return generateResponse
    except Exception as e:
        app.logger.error(traceback.format_exc())
        data_status["result"]="Unable to generate otp!!"
        return data_status

@admin.route("/verifyOtp",methods=["POST","GET"])
@csrf.exempt
def verifyOtp():
    data_status={"responseStatus":0,"result":""}
    try:
      
        otp_check_id = request.form.get("otpCheckId","")
        otp_code = request.form.get("otpCode","")
        defaultVerificationId= request.form.get("defaultVerificationId","")
        print("(((((((((((((((((((((((((((((((((((((((((((((((((((((defaultVerificationId)333333333333333333333333333333333333333333333",defaultVerificationId)
        form=OTPForm()
        if form.validate_on_submit():
            if not otp_check_id or not otp_code:
                data_status["result"]= "Required fields are missing!"
                return data_status
            verifyResponse = verify_otp_helper(otp_check_id, otp_code,defaultVerificationId)
            return verifyResponse
        else:
            data_status["responseStatus"]=2
            data_status["result"]=form.errors["otpCode"]
            return data_status
    except Exception as e:
        app.logger.error(traceback.format_exc())
        data_status["result"]="Unable to verify otp!!"
        return data_status
    
@admin.route("/admin_forgot_password",methods=["POST","GET"])
@csrf_protect
def admin_forgot_password():
    csrf_token = request.form.get("csrf_token")
    
    if request.method == "POST":
        email = request.form.get("email", "")
        if not email:
            flash("Email is required")
            return redirect(url_for("admin.admin_forgot_password"))

        if email and not validate_email(email):
            flash("Invalid email format!")
            return redirect(url_for("admin.admin_forgot_password"))
        
        admin_queryset = SuperAdmin.objects(email=email).first()
        if not admin_queryset:
            flash("Email not found! Please check and try again.")
            return redirect(url_for("admin.admin_forgot_password"))
        
        otpCode = str(random.randint(100000, 999999))
        print("(((((((((((((((((((((((((((((((((forgot password otp code )))))))))))))))))))))))))))))))))",otpCode)
        try:
            adminId=str(admin_queryset.id)
            mail_subject = "Reset Your Password"
            recipients_list = [email]
            template_name = "emails/forgot_password_email.html"
            ist_timezone = datetime.timezone(datetime.timedelta(hours=5, minutes=30))  # Indian Standard Time
            createdOn = datetime.datetime.now().astimezone(ist_timezone).strftime("%d-%m-%Y %I:%M %p")
 
            mail_data = {
                "email": email,
                "otp": otpCode,
                "domain": domain,
                "company_name":"Graam Pay",
                "createdOn": createdOn,
            }
            email_otp_record = OtpChecks(
                adminId=adminId,
                emailId=email,
                otpCode=str(otpCode),
                createdOn=datetime.datetime.now(),
                attempts=0,
                status=0
            )
            save_table=email_otp_record.save()
            emailOtpCheckId=str(save_table.id)
            send_asynchronous_email(mail_subject, recipients_list, template_name, mail_data)
 
            flash("An OTP has been sent to your registered email address.")
            return render_template("super_admin_templates/admin_reset_password.html", email=email,emailOtpCheckId=emailOtpCheckId)
        except Exception as e:
            app.logger.error(traceback.format_exc())
            flash("Failed to send OTP. Please try again later.")
            return render_template("super_admin_templates/admin_forgot_password.html")
    flash("Please enter your registered email address. We will send an OTP to your registered email to reset your password.")
    return render_template("super_admin_templates/admin_forgot_password.html")

@admin.route("/admin_reset_password", methods=["POST", "GET"])
@csrf_protect
def admin_reset_password():
    csrf_token = request.form.get("csrf_token")
    print(csrf_token,"(((((((((otp  csrf_token)))))))))")
    if request.method == "POST":
        email = request.form.get("email","")
        otp = request.form.get("otp","")
        new_password = request.form.get("new_password", "")
        confirm_password = request.form.get("confirm_password", "")
        emailOtpCheckId = request.form.get("emailOtpCheckId","")
 
        admin_queryset = SuperAdmin.objects(email__iexact=email,status=1).first()
        if not admin_queryset:
            flash("Invalid email!")
            return render_template("super_admin_templates/admin_reset_password.html", email=email)
 
        email_otp_check_queryset = OtpChecks.objects(id=emailOtpCheckId,status=1).first()
        if not email_otp_check_queryset:
            flash("Invalid OTP!!")
            return render_template("super_admin_templates/admin_reset_password.html", email=email)
        if email_otp_check_queryset.otpCode != otp:
            flash("Invalid OTP!")
            return render_template("super_admin_templates/admin_reset_password.html", email=email)
        
        email_otp_check_queryset.update(status=2)
        if new_password != confirm_password:
            flash("Passwords do not match!")
            return render_template("super_admin_templates/admin_reset_password.html", email=email)
 
        if new_password and not validate_password(new_password):
            flash("Password must meet the required criteria.")
            return render_template("super_admin_templates/admin_reset_password.html", email=email)
 
        # Update password and clear OTP
        admin_queryset.update(password=generate_password_hash(new_password))
        flash("Your password has been reset successfully. Please log in.")
        return redirect(url_for("admin.admin_login"))
 
    return render_template("super_admin_templates/admin_reset_password.html")
        


@admin.route("/get_pg_wise_commission_data",methods=["GET"])
@adminid_access_token_required
def get_pg_wise_commission_data():
    data_status = {"responseStatus":0,"result":""}
    date_format = "%d-%m-%Y"

    subPaymentmodeDataList=[] 
    try:
        permissionsList = check_permissions(session.get("adminId"),"commissionStructurePermissions")
        if "view" in permissionsList:
            apiId = request.args.get("apiId", "")
            startDate = request.args.get("startDate", "")
            endDate = request.args.get("endDate", "")
            
            try:
                if startDate:
                    startDate = datetime.datetime.strptime(startDate, date_format)  # Use YYYY-MM-DD format
                    startDate = startDate.replace(hour=0, minute=0, second=0, microsecond=0)
                else:
                    startDate = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)

                if endDate:
                    endDate = datetime.datetime.strptime(endDate, date_format)
                    endDate = endDate.replace(hour=23, minute=59, second=59, microsecond=999999)
                else:
                    endDate = datetime.datetime.now().replace(hour=23, minute=59, second=59, microsecond=999999)
            except Exception as ve:
                app.logger.error("Date parsing error: %s", ve)
                startDate = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
                endDate = datetime.datetime.now().replace(hour=23, minute=59, second=59, microsecond=999999)


            subpayment_mode_wise_pipeline = [
                {"$match": {
                    "transferType": "Credit",
                    "status": 1,
                    "createdOn": {
                        "$gte": startDate,
                        "$lte": endDate
                    }
                }},  # Filtering
                {"$group": {"_id": {
                            "transactionAPIId":"$transactionAPIId",
                            "subPaymentModeId":"$subPaymentModeId"
                            }, 
                    "transactionsCount": {"$sum": 1},
                       "aggregatorChargeAmount": {"$sum": "$aggregatorCommissionAmount"},
                    "aggregatorGstAmount":    {"$sum": "$aggregatorCommissionCharges.gstAmount"},
                    "companyCommissionAmount":       {"$sum": "$commissionAmount"},
                       "transactionChargeAmount": {"$sum": "$transactionCommissionCharges.chargeAmount"},
                    "transactionGstAmount":    {"$sum": "$transactionCommissionCharges.gstAmount"},
                    "totalVolumeAmount":    {"$sum": "$totalAmount"},
                   }},  # Grouping and summing amounts
                {"$sort": {"chargeAmount": -1}},  # Sorting by total amount in descending order
            ]

            sub_payment_mode_data = list(CompanyCommissions.objects.aggregate(*subpayment_mode_wise_pipeline))
        
            print(sub_payment_mode_data,"()))))))))))")
            counter = 0
            for each_sub_payment_mode_rec in sub_payment_mode_data:
                counter+=1
                transactionAPIId = each_sub_payment_mode_rec["_id"]["transactionAPIId"]
                subPaymentModeId = each_sub_payment_mode_rec["_id"]["subPaymentModeId"]
                each_subpm_queryset = SubPaymentModes.objects(id=subPaymentModeId).first() ####################!@#13
                if each_subpm_queryset:
                    # first_chars = re.findall(r'\b\w', each_subpm_queryset.fullName)

                    # imageString = ''.join(first_chars)
                    transactionChargeAmount = float(each_sub_payment_mode_rec.get("transactionChargeAmount"))
                    transactionGstAmount = float(each_sub_payment_mode_rec.get("transactionGstAmount"))
                    transactionTotalAmount = float(transactionChargeAmount + transactionGstAmount)

                    aggregatorChargeAmount = float(each_sub_payment_mode_rec.get("aggregatorChargeAmount"))
                    aggregatorGstAmount = float(each_sub_payment_mode_rec.get("aggregatorGstAmount"))
                    aggregatorTotalAmount = float(aggregatorChargeAmount + aggregatorGstAmount)

                    companyChargeAmount = float(transactionChargeAmount - aggregatorChargeAmount)
                    companyGstAmount = float(transactionGstAmount - aggregatorGstAmount)
                    companyTotalAmount = float(transactionTotalAmount - aggregatorTotalAmount)
                    
                    companyCommissionAmount = float(each_sub_payment_mode_rec.get("companyCommissionAmount"))
                    payOutDict = {
                        "snoCount":counter,
                        "apiId":str(each_subpm_queryset.id),
                        "subPaymentModeType":each_subpm_queryset.subPaymentModeType,

                        "transactionChargeAmount": formatINR("{:.2f}".format(transactionChargeAmount)),
                        "transactionGstAmount": formatINR("{:.2f}".format(transactionGstAmount)),
                        "transactionTotalAmount": formatINR("{:.2f}".format(transactionTotalAmount)),

                        "aggregatorChargeAmount": formatINR("{:.2f}".format(aggregatorChargeAmount)),
                        "aggregatorGstAmount": formatINR("{:.2f}".format(aggregatorGstAmount)),
                        "aggregatorTotalAmount": formatINR("{:.2f}".format(aggregatorTotalAmount)),
                    
                        "companyChargeAmount":formatINR("{:.2f}".format(companyChargeAmount)),
                        "companyGstAmount":formatINR("{:.2f}".format(companyGstAmount)),
                        "companyTotalAmount":formatINR("{:.2f}".format(companyTotalAmount)),

                        "companyCommissionAmount":formatINR("{:.2f}".format(companyCommissionAmount)),

                        "totalVolumeAmount":formatINR("{:.2f}".format(each_sub_payment_mode_rec.get("totalVolumeAmount"))),
                        "transactionsCount":each_sub_payment_mode_rec.get("transactionsCount"),
                    }
                    subPaymentmodeDataList.append(payOutDict)
                print("each_payout_merchant",each_sub_payment_mode_rec)
            apiName=""
            transaction_apis = TransactionAPI.objects(id=ObjectId(apiId),transactionType="PaymentGateway",status__in=[0,1]).first()
            if transaction_apis:
                apiName = transaction_apis.apiName
            print("(((((((endDate)))))))",endDate)
            print("(((((((startDate)))))))",startDate)
            print("(((((((subPaymentmodeDataList)))))))",subPaymentmodeDataList)

            data_status["responseStatus"] = 1
            data_status["result"] = "Success"
            data_status["subPaymentmodeDataList"] = subPaymentmodeDataList
            data_status["apiName"] = apiName
            return data_status
        else:
          data_status["result"] ="The staff member does not have permission to view commission structure."
          return data_status
    except Exception as e:
        app.logger.error(traceback.format_exc())
        data_status["result"] = "Unable to fetched payout ledger report data!!"
        return data_status

#################################################################### downloads####################################################################
@admin.route("/admin_download_pgwise_commission_structure_excel_report",methods=["GET"])
@adminid_access_token_required
def admin_download_pgwise_commission_structure_excel_report():
    data_status = {"responseStatus":0,"result":""}
    date_format = "%d-%m-%Y"

    subPaymentmodeDataList=[] 
    try:
        permissionsList = check_permissions(session.get("adminId"),"commissionStructurePermissions")
        if "view" in permissionsList:
            startDate = request.args.get("startDate", "")
            endDate = request.args.get("endDate", "")
            
            try:
                if startDate:
                    startDate = datetime.datetime.strptime(startDate, date_format)  # Use YYYY-MM-DD format
                    startDate = startDate.replace(hour=0, minute=0, second=0, microsecond=0)
                else:
                    startDate = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)

                if endDate:
                    endDate = datetime.datetime.strptime(endDate, date_format)
                    endDate = endDate.replace(hour=23, minute=59, second=59, microsecond=999999)
                else:
                    endDate = datetime.datetime.now().replace(hour=23, minute=59, second=59, microsecond=999999)
            except Exception as ve:
                app.logger.error("Date parsing error: %s", ve)
                startDate = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
                endDate = datetime.datetime.now().replace(hour=23, minute=59, second=59, microsecond=999999)

            start_date_str = startDate.strftime("%d-%m-%Y")+"_"
            end_date_str = endDate.strftime("%d-%m-%Y")+"_"

            # overPgGstAmount = formatINR("{:.2f}".format(round(float(overPgGstAmount),2)))
            pg_wise_pipeline = [
                {"$match": {
                    "transferType": "Credit",
                    "status": 1,
                    "createdOn": {
                        "$gte": startDate,
                        "$lte": endDate
                    }
                }},  # Filtering
                {"$group": {"_id": "$transactionAPIId", 
                    "transactionsCount": {"$sum": 1},
                       "aggregatorChargeAmount": {"$sum": "$aggregatorCommissionAmount"},
                    "aggregatorGstAmount":    {"$sum": "$aggregatorCommissionCharges.gstAmount"},
                    "companyCommissionAmount":       {"$sum": "$commissionAmount"},
                       "transactionChargeAmount": {"$sum": "$transactionCommissionCharges.chargeAmount"},
                    "transactionGstAmount":    {"$sum": "$transactionCommissionCharges.gstAmount"},
                    "totalVolumeAmount":    {"$sum": "$totalAmount"},
                   }},  # Grouping and summing amounts
                {"$sort": {"chargeAmount": -1}},  # Sorting by total amount in descending order
            ]

            # Execute the aggregation pg_wise_pipeline
            payouts_top_10_merchants = list(CompanyCommissions.objects.aggregate(*pg_wise_pipeline))
            pgTop10chargesList = []
            print(payouts_top_10_merchants,"()))))))))))")
            counter = 0
            for each_payout_merchant in payouts_top_10_merchants:
                counter+=1
                payout_merchant_queryset = TransactionAPI.objects(id=each_payout_merchant.get("_id")).first()
                if payout_merchant_queryset:
                    # first_chars = re.findall(r'\b\w', payout_merchant_queryset.fullName)

                    # imageString = ''.join(first_chars)
                    transactionChargeAmount = float(each_payout_merchant.get("transactionChargeAmount"))
                    transactionGstAmount = float(each_payout_merchant.get("transactionGstAmount"))
                    transactionTotalAmount = float(transactionChargeAmount + transactionGstAmount)

                    aggregatorChargeAmount = float(each_payout_merchant.get("aggregatorChargeAmount"))
                    aggregatorGstAmount = float(each_payout_merchant.get("aggregatorGstAmount"))
                    aggregatorTotalAmount = float(aggregatorChargeAmount + aggregatorGstAmount)

                    companyChargeAmount = float(transactionChargeAmount - aggregatorChargeAmount)
                    companyGstAmount = float(transactionGstAmount - aggregatorGstAmount)
                    companyTotalAmount = float(transactionTotalAmount - aggregatorTotalAmount)
                    
                    companyCommissionAmount = float(each_payout_merchant.get("companyCommissionAmount"))
                    payOutDict = {
                        "snoCount":counter,
                        "apiId":str(payout_merchant_queryset.id),
                        "apiName":payout_merchant_queryset.apiName,

                        "transactionChargeAmount": formatINR("{:.2f}".format(transactionChargeAmount)),
                        "transactionGstAmount": formatINR("{:.2f}".format(transactionGstAmount)),
                        "transactionTotalAmount": formatINR("{:.2f}".format(transactionTotalAmount)),

                        "aggregatorChargeAmount": formatINR("{:.2f}".format(aggregatorChargeAmount)),
                        "aggregatorGstAmount": formatINR("{:.2f}".format(aggregatorGstAmount)),
                        "aggregatorTotalAmount": formatINR("{:.2f}".format(aggregatorTotalAmount)),
                    
                        "companyChargeAmount":formatINR("{:.2f}".format(companyChargeAmount)),
                        "companyGstAmount":formatINR("{:.2f}".format(companyGstAmount)),
                        "companyTotalAmount":formatINR("{:.2f}".format(companyTotalAmount)),

                        "companyCommissionAmount":formatINR("{:.2f}".format(companyCommissionAmount)),

                        "totalVolumeAmount":formatINR("{:.2f}".format(each_payout_merchant.get("totalVolumeAmount"))),
                        "transactionsCount":each_payout_merchant.get("transactionsCount"),
                    }
                    pgTop10chargesList.append(payOutDict)
            fileName = f"{start_date_str}{end_date_str}pgwise_commission_structures.xlsx"
                
            reportData = admin_download_pg_wise_commission_structure_excel_reports_data(pgTop10chargesList,fileName)
            return reportData
        else:
          data_status["result"] ="The staff member does not have permission to view commission structure."
          return data_status
    except Exception as e:
        app.logger.error(traceback.format_exc())
        data_status["result"] = "Unable to download PG wise Commission Data report data!!"
        return data_status


def admin_download_pg_wise_commission_structure_excel_reports_data(commissionStructuresDataList,fileName):
    relative_temp_excel_file_name = ""
    try:
        commission_structure_data = {
            "snoCount" : [],
            # "apiId" : [],
            "apiName" : [],
            "transactionsCount(₹)" : [],
            "totalVolumeAmount(₹)" : [],
            "transactionChargeAmount(₹)" : [],
            "transactionGstAmount(₹)" : [],
            "transactionTotalAmount(₹)" : [],
            "aggregatorChargeAmount(₹)" : [],
            "aggregatorGstAmount(₹)" : [],
            "aggregatorTotalAmount(₹)" : [],
            "companyChargeAmount(₹)" : [],
            "companyGstAmount(₹)" : [],
            "companyTotalAmount(₹)" : [],
            "companyCommissionAmount(₹)" : [],
        }
        for each_commission_record in commissionStructuresDataList:

            commission_structure_data["snoCount"].append(each_commission_record.get("snoCount"))
            # commission_structure_data["apiId"].append(each_commission_record.get("apiId"))
            commission_structure_data["apiName"].append(each_commission_record.get("apiName"))
            commission_structure_data["transactionChargeAmount(₹)"].append(each_commission_record.get("transactionChargeAmount"))
            commission_structure_data["transactionGstAmount(₹)"].append(each_commission_record.get("transactionGstAmount"))
            commission_structure_data["transactionTotalAmount(₹)"].append(each_commission_record.get("transactionTotalAmount"))
            commission_structure_data["aggregatorChargeAmount(₹)"].append(each_commission_record.get("aggregatorChargeAmount"))
            commission_structure_data["aggregatorGstAmount(₹)"].append(each_commission_record.get("aggregatorGstAmount"))
            commission_structure_data["aggregatorTotalAmount(₹)"].append(each_commission_record.get("aggregatorTotalAmount"))
            commission_structure_data["companyChargeAmount(₹)"].append(each_commission_record.get("companyChargeAmount"))
            commission_structure_data["companyGstAmount(₹)"].append(each_commission_record.get("companyGstAmount"))
            commission_structure_data["companyTotalAmount(₹)"].append(each_commission_record.get("companyTotalAmount"))
            commission_structure_data["companyCommissionAmount(₹)"].append(each_commission_record.get("companyCommissionAmount"))
            commission_structure_data["totalVolumeAmount(₹)"].append(each_commission_record.get("totalVolumeAmount"))
            commission_structure_data["transactionsCount(₹)"].append(each_commission_record.get("transactionsCount"))
           
            lengths = [len(value) for value in commission_structure_data.values()]
    
            # If the lengths are not all the same, print the iteration and lengths
            # if len(set(lengths)) == 1:
                # print(f"**********************************Inconsistent lengths found at iteration {each_record.transactionId}. Lengths: {lengths}")
            # print(commission_structure_data,"payin_transacion_reports")
        # Create DataFrame
        df = pd.DataFrame(commission_structure_data)

        # Define file path
        base_dir = os.path.join(app.config['SITE_ROOT'], "media/commissionStructured", "pgwise")
        if not os.path.exists(base_dir):
            os.makedirs(base_dir)

        relative_temp_excel_file_name = os.path.join("media/commissionStructured", "pgwise", fileName)
        os.makedirs(base_dir, exist_ok=True)
        full_file_name = os.path.join(app.config['SITE_ROOT'], relative_temp_excel_file_name)

        # Save DataFrame to Excel
        df.to_excel(full_file_name, index=False)

        # Send the file as a downloadable attachment
        return send_file(
            full_file_name,
            mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            download_name=fileName,
            as_attachment=True
        )
    except Exception as e:
        app.logger.error(traceback.format_exc())
        return relative_temp_excel_file_name

@admin.route("/admin_download_subpaymentmode_wise_commission_structure_excel_report",methods=["GET"])
@adminid_access_token_required
def admin_download_subpaymentmode_wise_commission_structure_excel_report():
    data_status = {"responseStatus":0,"result":""}
    date_format = "%d-%m-%Y"

    subPaymentmodeDataList=[] 
    try:
        permissionsList = check_permissions(session.get("adminId"),"commissionStructurePermissions")
        if "view" in permissionsList:
            startDate = request.args.get("startDate", "")
            endDate = request.args.get("endDate", "")
            
            try:
                if startDate:
                    startDate = datetime.datetime.strptime(startDate, date_format)  # Use YYYY-MM-DD format
                    startDate = startDate.replace(hour=0, minute=0, second=0, microsecond=0)
                else:
                    startDate = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)

                if endDate:
                    endDate = datetime.datetime.strptime(endDate, date_format)
                    endDate = endDate.replace(hour=23, minute=59, second=59, microsecond=999999)
                else:
                    endDate = datetime.datetime.now().replace(hour=23, minute=59, second=59, microsecond=999999)
            except Exception as ve:
                app.logger.error("Date parsing error: %s", ve)
                startDate = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
                endDate = datetime.datetime.now().replace(hour=23, minute=59, second=59, microsecond=999999)

            start_date_str = startDate.strftime("%d-%m-%Y")+"_"
            end_date_str = endDate.strftime("%d-%m-%Y")+"_"

            # overPgGstAmount = formatINR("{:.2f}".format(round(float(overPgGstAmount),2)))
            subpayment_mode_wise_pipeline = [
                {"$match": {
                    "transferType": "Credit",
                    "status": 1,
                    "createdOn": {
                        "$gte": startDate,
                        "$lte": endDate
                    }
                }},  # Filtering
                {"$group": {"_id": "$subPaymentModeId", 
                    "transactionsCount": {"$sum": 1},
                       "aggregatorChargeAmount": {"$sum": "$aggregatorCommissionAmount"},
                    "aggregatorGstAmount":    {"$sum": "$aggregatorCommissionCharges.gstAmount"},
                    "companyCommissionAmount":       {"$sum": "$commissionAmount"},
                       "transactionChargeAmount": {"$sum": "$transactionCommissionCharges.chargeAmount"},
                    "transactionGstAmount":    {"$sum": "$transactionCommissionCharges.gstAmount"},
                    "totalVolumeAmount":    {"$sum": "$totalAmount"},
                   }},  # Grouping and summing amounts
                {"$sort": {"chargeAmount": -1}},  # Sorting by total amount in descending order
            ]

            sub_payment_mode_data = list(CompanyCommissions.objects.aggregate(*subpayment_mode_wise_pipeline))
            subPaymentmodeDataList = []
            # print(sub_payment_mode_data,"()))))))))))")
            counter = 0
            for each_sub_payment_mode_rec in sub_payment_mode_data:
                counter+=1
                each_subpm_queryset = SubPaymentModes.objects(id=each_sub_payment_mode_rec.get("_id")).first() ####################!@#13
                if each_subpm_queryset:
                    # first_chars = re.findall(r'\b\w', each_subpm_queryset.fullName)

                    # imageString = ''.join(first_chars)
                    transactionChargeAmount = float(each_sub_payment_mode_rec.get("transactionChargeAmount"))
                    transactionGstAmount = float(each_sub_payment_mode_rec.get("transactionGstAmount"))
                    transactionTotalAmount = float(transactionChargeAmount + transactionGstAmount)

                    aggregatorChargeAmount = float(each_sub_payment_mode_rec.get("aggregatorChargeAmount"))
                    aggregatorGstAmount = float(each_sub_payment_mode_rec.get("aggregatorGstAmount"))
                    aggregatorTotalAmount = float(aggregatorChargeAmount + aggregatorGstAmount)

                    companyChargeAmount = float(transactionChargeAmount - aggregatorChargeAmount)
                    companyGstAmount = float(transactionGstAmount - aggregatorGstAmount)
                    companyTotalAmount = float(transactionTotalAmount - aggregatorTotalAmount)
                    
                    companyCommissionAmount = float(each_sub_payment_mode_rec.get("companyCommissionAmount"))
                    payOutDict = {
                        "snoCount":counter,
                        "apiId":str(each_subpm_queryset.id),
                        "subPaymentModeType":each_subpm_queryset.subPaymentModeType,

                        "transactionChargeAmount": formatINR("{:.2f}".format(transactionChargeAmount)),
                        "transactionGstAmount": formatINR("{:.2f}".format(transactionGstAmount)),
                        "transactionTotalAmount": formatINR("{:.2f}".format(transactionTotalAmount)),

                        "aggregatorChargeAmount": formatINR("{:.2f}".format(aggregatorChargeAmount)),
                        "aggregatorGstAmount": formatINR("{:.2f}".format(aggregatorGstAmount)),
                        "aggregatorTotalAmount": formatINR("{:.2f}".format(aggregatorTotalAmount)),
                    
                        "companyChargeAmount":formatINR("{:.2f}".format(companyChargeAmount)),
                        "companyGstAmount":formatINR("{:.2f}".format(companyGstAmount)),
                        "companyTotalAmount":formatINR("{:.2f}".format(companyTotalAmount)),

                        "companyCommissionAmount":formatINR("{:.2f}".format(companyCommissionAmount)),

                        "totalVolumeAmount":formatINR("{:.2f}".format(each_sub_payment_mode_rec.get("totalVolumeAmount"))),
                        "transactionsCount":each_sub_payment_mode_rec.get("transactionsCount"),
                    }
                    subPaymentmodeDataList.append(payOutDict)
            fileName = f"{start_date_str}{end_date_str}subpaymentmode_wise_commission_structure.xlsx"
                
            reportData = admin_download_subpaymentmode_wise_commission_structure_excel_reports_data(subPaymentmodeDataList,fileName)
            return reportData
        else:
          data_status["result"] ="The staff member does not have permission to view commission structure."
          return data_status
    except Exception as e:
        app.logger.error(traceback.format_exc())
        data_status["result"] = "Unable to download Sub Payment Mode Wise data!!"
        return data_status

def admin_download_subpaymentmode_wise_commission_structure_excel_reports_data(commissionStructurespgwiseDataList,fileName):
    relative_temp_excel_file_name = ""
    try:
        commission_structure_data = {
            "snoCount" : [],
            # "apiId" : [],
            "subPaymentModeType" : [],
            "transactionsCount(₹)" : [],
            "totalVolumeAmount(₹)" : [],
            "transactionChargeAmount(₹)" : [],
            "transactionGstAmount(₹)" : [],
            "transactionTotalAmount(₹)" : [],
            "aggregatorChargeAmount(₹)" : [],
            "aggregatorGstAmount(₹)" : [],
            "aggregatorTotalAmount(₹)" : [],
            "companyChargeAmount(₹)" : [],
            "companyGstAmount(₹)" : [],
            "companyTotalAmount(₹)" : [],
            "companyCommissionAmount(₹)" : [],
        }
        for each_commission_record in commissionStructurespgwiseDataList:

            commission_structure_data["snoCount"].append(each_commission_record.get("snoCount"))
            # commission_structure_data["apiId"].append(each_commission_record.get("apiId"))
            commission_structure_data["subPaymentModeType"].append(each_commission_record.get("subPaymentModeType"))
            commission_structure_data["transactionChargeAmount(₹)"].append(each_commission_record.get("transactionChargeAmount"))
            commission_structure_data["transactionGstAmount(₹)"].append(each_commission_record.get("transactionGstAmount"))
            commission_structure_data["transactionTotalAmount(₹)"].append(each_commission_record.get("transactionTotalAmount"))
            commission_structure_data["aggregatorChargeAmount(₹)"].append(each_commission_record.get("aggregatorChargeAmount"))
            commission_structure_data["aggregatorGstAmount(₹)"].append(each_commission_record.get("aggregatorGstAmount"))
            commission_structure_data["aggregatorTotalAmount(₹)"].append(each_commission_record.get("aggregatorTotalAmount"))
            commission_structure_data["companyChargeAmount(₹)"].append(each_commission_record.get("companyChargeAmount"))
            commission_structure_data["companyGstAmount(₹)"].append(each_commission_record.get("companyGstAmount"))
            commission_structure_data["companyTotalAmount(₹)"].append(each_commission_record.get("companyTotalAmount"))
            commission_structure_data["companyCommissionAmount(₹)"].append(each_commission_record.get("companyCommissionAmount"))
            commission_structure_data["totalVolumeAmount(₹)"].append(each_commission_record.get("totalVolumeAmount"))
            commission_structure_data["transactionsCount(₹)"].append(each_commission_record.get("transactionsCount"))
           
            # lengths = [len(value) for value in commission_structure_data.values()]
    
            # If the lengths are not all the same, print the iteration and lengths
            # if len(set(lengths)) == 1:
                # print(f"**********************************Inconsistent lengths found at iteration {each_record.transactionId}. Lengths: {lengths}")
            # print(commission_structure_data,"payin_transacion_reports")
        # Create DataFrame
        df = pd.DataFrame(commission_structure_data)

        # Define file path
        base_dir = os.path.join(app.config['SITE_ROOT'], "media/commissionStructures", "subpaymentmodewise")
        if not os.path.exists(base_dir):
            os.makedirs(base_dir)

        relative_temp_excel_file_name = os.path.join("media/commissionStructures", "subpaymentmodewise", fileName)
        os.makedirs(base_dir, exist_ok=True)
        full_file_name = os.path.join(app.config['SITE_ROOT'], relative_temp_excel_file_name)

        # Save DataFrame to Excel
        df.to_excel(full_file_name, index=False)

        # Send the file as a downloadable attachment
        return send_file(
            full_file_name,
            mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            download_name=fileName,
            as_attachment=True
        )
    except Exception as e:
        app.logger.error(traceback.format_exc())
        return relative_temp_excel_file_name

@admin.route("/admin_download_site_wise_commission_structure_excel_report",methods=["GET"])
@adminid_access_token_required
def admin_download_site_wise_commission_structure_excel_report():
    data_status = {"responseStatus":0,"result":""}
    date_format = "%d-%m-%Y"

    siteWiseDataList=[] 
    try:
        permissionsList = check_permissions(session.get("adminId"),"commissionStructurePermissions")
        if "view" in permissionsList:
            startDate = request.args.get("startDate", "")
            endDate = request.args.get("endDate", "")
            
            try:
                if startDate:
                    startDate = datetime.datetime.strptime(startDate, date_format)  # Use YYYY-MM-DD format
                    startDate = startDate.replace(hour=0, minute=0, second=0, microsecond=0)
                else:
                    startDate = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)

                if endDate:
                    endDate = datetime.datetime.strptime(endDate, date_format)
                    endDate = endDate.replace(hour=23, minute=59, second=59, microsecond=999999)
                else:
                    endDate = datetime.datetime.now().replace(hour=23, minute=59, second=59, microsecond=999999)
            except Exception as ve:
                app.logger.error("Date parsing error: %s", ve)
                startDate = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
                endDate = datetime.datetime.now().replace(hour=23, minute=59, second=59, microsecond=999999)

            start_date_str = startDate.strftime("%d-%m-%Y")+"_"
            end_date_str = endDate.strftime("%d-%m-%Y")+"_"

            # overPgGstAmount = formatINR("{:.2f}".format(round(float(overPgGstAmount),2)))
            sitewise_pipeline = [
                {"$match": {
                    "transferType": "Credit",
                    "status": 1,
                    "createdOn": {
                        "$gte": startDate,
                        "$lte": endDate
                    }
                }},  # Filtering
                {"$group": {"_id": "$siteTitle", 
                    "transactionsCount": {"$sum": 1},
                       "aggregatorChargeAmount": {"$sum": "$aggregatorCommissionAmount"},
                    "aggregatorGstAmount":    {"$sum": "$aggregatorCommissionCharges.gstAmount"},
                    "companyCommissionAmount":       {"$sum": "$commissionAmount"},
                       "transactionChargeAmount": {"$sum": "$transactionCommissionCharges.chargeAmount"},
                    "transactionGstAmount":    {"$sum": "$transactionCommissionCharges.gstAmount"},
                    "totalVolumeAmount":    {"$sum": "$totalAmount"},
                   }},  # Grouping and summing amounts
                {"$sort": {"chargeAmount": -1}},  # Sorting by total amount in descending order
            ]

            sitewise_data = list(CompanyCommissions.objects.aggregate(*sitewise_pipeline))
        
            # print(sitewise_data,"()))))))))))")
            counter = 0
            for each_sitewise_rec in sitewise_data:
                counter+=1
                print("(((((((((((((((((((each_sitewise_rec.get())))))))))))))))))))",each_sitewise_rec.get("_id"))
                multiple_app_queryset = MultipleAppSites.objects(siteCode=each_sitewise_rec.get("_id")).first() ####################!@#13

                if multiple_app_queryset:
                    print("(****************************record multiple site found)")
                    # first_chars = re.findall(r'\b\w', multiple_app_queryset.fullName)

                    # imageString = ''.join(first_chars)
                    transactionChargeAmount = float(each_sitewise_rec.get("transactionChargeAmount"))
                    transactionGstAmount = float(each_sitewise_rec.get("transactionGstAmount"))
                    transactionTotalAmount = float(transactionChargeAmount + transactionGstAmount)

                    aggregatorChargeAmount = float(each_sitewise_rec.get("aggregatorChargeAmount"))
                    aggregatorGstAmount = float(each_sitewise_rec.get("aggregatorGstAmount"))
                    aggregatorTotalAmount = float(aggregatorChargeAmount + aggregatorGstAmount)

                    companyChargeAmount = float(transactionChargeAmount - aggregatorChargeAmount)
                    companyGstAmount = float(transactionGstAmount - aggregatorGstAmount)
                    companyTotalAmount = float(transactionTotalAmount - aggregatorTotalAmount)
                    
                    companyCommissionAmount = float(each_sitewise_rec.get("companyCommissionAmount"))
                    sitewiseDict = {
                        "snoCount":counter,
                        "apiId":str(multiple_app_queryset.id),
                        "siteTitle":multiple_app_queryset.siteTitle,

                        "transactionChargeAmount": formatINR("{:.2f}".format(transactionChargeAmount)),
                        "transactionGstAmount": formatINR("{:.2f}".format(transactionGstAmount)),
                        "transactionTotalAmount": formatINR("{:.2f}".format(transactionTotalAmount)),

                        "aggregatorChargeAmount": formatINR("{:.2f}".format(aggregatorChargeAmount)),
                        "aggregatorGstAmount": formatINR("{:.2f}".format(aggregatorGstAmount)),
                        "aggregatorTotalAmount": formatINR("{:.2f}".format(aggregatorTotalAmount)),
                    
                        "companyChargeAmount":formatINR("{:.2f}".format(companyChargeAmount)),
                        "companyGstAmount":formatINR("{:.2f}".format(companyGstAmount)),
                        "companyTotalAmount":formatINR("{:.2f}".format(companyTotalAmount)),

                        "companyCommissionAmount":formatINR("{:.2f}".format(companyCommissionAmount)),

                        "totalVolumeAmount":formatINR("{:.2f}".format(each_sitewise_rec.get("totalVolumeAmount"))),
                        "transactionsCount":each_sitewise_rec.get("transactionsCount"),
                    }
                    siteWiseDataList.append(sitewiseDict)
            fileName = f"{start_date_str}{end_date_str}site_wise_commission_structure.xlsx"
                
            reportData = admin_download_site_wise_commission_structure_excel_report_data(siteWiseDataList,fileName)
            return reportData
        else:
          data_status["result"] ="The staff member does not have permission to view commission structure."
          return data_status
    except Exception as e:
        app.logger.error(traceback.format_exc())
        data_status["result"] = "Unable to download Site Wise data!!"
        return data_status

def admin_download_site_wise_commission_structure_excel_report_data(siteWiseDataList,fileName):
    relative_temp_excel_file_name = ""
    try:
        commission_structure_data = {
            "snoCount" : [],
            # "apiId" : [],
            "siteTitle" : [],
            "transactionsCount(₹)" : [],
            "totalVolumeAmount(₹)" : [],
            "transactionChargeAmount(₹)" : [],
            "transactionGstAmount(₹)" : [],
            "transactionTotalAmount(₹)" : [],
            "aggregatorChargeAmount(₹)" : [],
            "aggregatorGstAmount(₹)" : [],
            "aggregatorTotalAmount(₹)" : [],
            "companyChargeAmount(₹)" : [],
            "companyGstAmount(₹)" : [],
            "companyTotalAmount(₹)" : [],
            "companyCommissionAmount(₹)" : [],
        }
        for each_sitewise_commission_record in siteWiseDataList:

            commission_structure_data["snoCount"].append(each_sitewise_commission_record.get("snoCount"))
            # commission_structure_data["apiId"].append(each_sitewise_commission_record.get("apiId"))
            commission_structure_data["siteTitle"].append(each_sitewise_commission_record.get("siteTitle"))
            commission_structure_data["transactionChargeAmount(₹)"].append(each_sitewise_commission_record.get("transactionChargeAmount"))
            commission_structure_data["transactionGstAmount(₹)"].append(each_sitewise_commission_record.get("transactionGstAmount"))
            commission_structure_data["transactionTotalAmount(₹)"].append(each_sitewise_commission_record.get("transactionTotalAmount"))
            commission_structure_data["aggregatorChargeAmount(₹)"].append(each_sitewise_commission_record.get("aggregatorChargeAmount"))
            commission_structure_data["aggregatorGstAmount(₹)"].append(each_sitewise_commission_record.get("aggregatorGstAmount"))
            commission_structure_data["aggregatorTotalAmount(₹)"].append(each_sitewise_commission_record.get("aggregatorTotalAmount"))
            commission_structure_data["companyChargeAmount(₹)"].append(each_sitewise_commission_record.get("companyChargeAmount"))
            commission_structure_data["companyGstAmount(₹)"].append(each_sitewise_commission_record.get("companyGstAmount"))
            commission_structure_data["companyTotalAmount(₹)"].append(each_sitewise_commission_record.get("companyTotalAmount"))
            commission_structure_data["companyCommissionAmount(₹)"].append(each_sitewise_commission_record.get("companyCommissionAmount"))
            commission_structure_data["totalVolumeAmount(₹)"].append(each_sitewise_commission_record.get("totalVolumeAmount"))
            commission_structure_data["transactionsCount(₹)"].append(each_sitewise_commission_record.get("transactionsCount"))
           
            # lengths = [len(value) for value in commission_structure_data.values()]
    
            # If the lengths are not all the same, print the iteration and lengths
            # if len(set(lengths)) == 1:
                # print(f"**********************************Inconsistent lengths found at iteration {each_record.transactionId}. Lengths: {lengths}")
            # print(commission_structure_data,"payin_transacion_reports")
        # Create DataFrame
        df = pd.DataFrame(commission_structure_data)

        # Define file path
        base_dir = os.path.join(app.config['SITE_ROOT'], "media/commissionStructures", "subpaymentmodewise")
        if not os.path.exists(base_dir):
            os.makedirs(base_dir)

        relative_temp_excel_file_name = os.path.join("media/commissionStructures", "subpaymentmodewise", fileName)
        os.makedirs(base_dir, exist_ok=True)
        full_file_name = os.path.join(app.config['SITE_ROOT'], relative_temp_excel_file_name)

        # Save DataFrame to Excel
        df.to_excel(full_file_name, index=False)

        # Send the file as a downloadable attachment
        return send_file(
            full_file_name,
            mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            download_name=fileName,
            as_attachment=True
        )
    except Exception as e:
        app.logger.error(traceback.format_exc())
        return relative_temp_excel_file_name

@admin.route("/admin_download_pgbased_subpaymentmode_wise_commission_structure_excel_report",methods=["GET"])
@adminid_access_token_required
def admin_download_pgbased_subpaymentmode_wise_commission_structure_excel_report():
    data_status = {"responseStatus":0,"result":""}
    date_format = "%d-%m-%Y"

    subPaymentmodeDataList=[] 
    try:
        permissionsList = check_permissions(session.get("adminId"),"commissionStructurePermissions")
        if "view" in permissionsList:
            apiId = request.args.get("apiId", "")
            startDate = request.args.get("startDate", "")
            endDate = request.args.get("endDate", "")
            print("form",request.form)
            print("argss",request.args)
            print("apiId",apiId)
            try:
                if startDate:
                    startDate = datetime.datetime.strptime(startDate, date_format)  # Use YYYY-MM-DD format
                    startDate = startDate.replace(hour=0, minute=0, second=0, microsecond=0)
                else:
                    startDate = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)

                if endDate:
                    endDate = datetime.datetime.strptime(endDate, date_format)
                    endDate = endDate.replace(hour=23, minute=59, second=59, microsecond=999999)
                else:
                    endDate = datetime.datetime.now().replace(hour=23, minute=59, second=59, microsecond=999999)
            except Exception as ve:
                app.logger.error("Date parsing error: %s", ve)
                startDate = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
                endDate = datetime.datetime.now().replace(hour=23, minute=59, second=59, microsecond=999999)

            start_date_str = startDate.strftime("%d-%m-%Y")+"_"
            end_date_str = endDate.strftime("%d-%m-%Y")+"_"

            transaction_apis_queryset = TransactionAPI.objects(transactionType="Payout",status__in=[0,1]).first()
            if not transaction_apis_queryset:
                data_status["result"] = "Unable to download PG based Sub Payment Mode Wise data!!"
                return data_status
            apiName = transaction_apis_queryset.apiName
                
            # overPgGstAmount = formatINR("{:.2f}".format(round(float(overPgGstAmount),2)))
            subpayment_mode_wise_pipeline = [
                {"$match": {
                    "transferType": "Credit",
                    "status": 1,
                    "createdOn": {
                        "$gte": startDate,
                        "$lte": endDate
                    }
                }},  # Filtering
                {"$group": {"_id": {
                            "transactionAPIId":apiId,
                            "subPaymentModeId":"$subPaymentModeId"
                            }, 
                    "transactionsCount": {"$sum": 1},
                       "aggregatorChargeAmount": {"$sum": "$aggregatorCommissionAmount"},
                    "aggregatorGstAmount":    {"$sum": "$aggregatorCommissionCharges.gstAmount"},
                    "companyCommissionAmount":       {"$sum": "$commissionAmount"},
                       "transactionChargeAmount": {"$sum": "$transactionCommissionCharges.chargeAmount"},
                    "transactionGstAmount":    {"$sum": "$transactionCommissionCharges.gstAmount"},
                    "totalVolumeAmount":    {"$sum": "$totalAmount"},
                   }},  # Grouping and summing amounts
                {"$sort": {"chargeAmount": -1}},  # Sorting by total amount in descending order
            ]

            sub_payment_mode_data = list(CompanyCommissions.objects.aggregate(*subpayment_mode_wise_pipeline))
        
            print(sub_payment_mode_data,"(sub_payment_mode_data)))))))))))")
            counter = 0
            for each_sub_payment_mode_rec in sub_payment_mode_data:
                counter+=1
                transactionAPIId = each_sub_payment_mode_rec["_id"]["transactionAPIId"]
                subPaymentModeId = each_sub_payment_mode_rec["_id"]["subPaymentModeId"]
                each_subpm_queryset = SubPaymentModes.objects(id=subPaymentModeId).first() ####################!@#13
                if each_subpm_queryset:
                    # first_chars = re.findall(r'\b\w', each_subpm_queryset.fullName)

                    # imageString = ''.join(first_chars)
                    transactionChargeAmount = float(each_sub_payment_mode_rec.get("transactionChargeAmount"))
                    transactionGstAmount = float(each_sub_payment_mode_rec.get("transactionGstAmount"))
                    transactionTotalAmount = float(transactionChargeAmount + transactionGstAmount)

                    aggregatorChargeAmount = float(each_sub_payment_mode_rec.get("aggregatorChargeAmount"))
                    aggregatorGstAmount = float(each_sub_payment_mode_rec.get("aggregatorGstAmount"))
                    aggregatorTotalAmount = float(aggregatorChargeAmount + aggregatorGstAmount)

                    companyChargeAmount = float(transactionChargeAmount - aggregatorChargeAmount)
                    companyGstAmount = float(transactionGstAmount - aggregatorGstAmount)
                    companyTotalAmount = float(transactionTotalAmount - aggregatorTotalAmount)
                    
                    companyCommissionAmount = float(each_sub_payment_mode_rec.get("companyCommissionAmount"))
                    payOutDict = {
                        "snoCount":counter,
                        # "apiId":str(each_subpm_queryset.id),
                        "subPaymentModeType":each_subpm_queryset.subPaymentModeType,

                        "transactionChargeAmount": formatINR("{:.2f}".format(transactionChargeAmount)),
                        "transactionGstAmount": formatINR("{:.2f}".format(transactionGstAmount)),
                        "transactionTotalAmount": formatINR("{:.2f}".format(transactionTotalAmount)),

                        "aggregatorChargeAmount": formatINR("{:.2f}".format(aggregatorChargeAmount)),
                        "aggregatorGstAmount": formatINR("{:.2f}".format(aggregatorGstAmount)),
                        "aggregatorTotalAmount": formatINR("{:.2f}".format(aggregatorTotalAmount)),
                    
                        "companyChargeAmount":formatINR("{:.2f}".format(companyChargeAmount)),
                        "companyGstAmount":formatINR("{:.2f}".format(companyGstAmount)),
                        "companyTotalAmount":formatINR("{:.2f}".format(companyTotalAmount)),

                        "companyCommissionAmount":formatINR("{:.2f}".format(companyCommissionAmount)),

                        "totalVolumeAmount":formatINR("{:.2f}".format(each_sub_payment_mode_rec.get("totalVolumeAmount"))),
                        "transactionsCount":each_sub_payment_mode_rec.get("transactionsCount"),
                    }
                    subPaymentmodeDataList.append(payOutDict)
            fileName = f"{start_date_str}{end_date_str}{apiName}_subpaymentmode_wise_commission_structure.xlsx"
                
            reportData = admin_download_pgbased_subpaymentmode_wise_commission_structure_excel_reports_data(subPaymentmodeDataList,fileName)
            return reportData
        else:
          data_status["result"] ="The staff member does not have permission to view commission structure."
          return data_status
    except Exception as e:
        app.logger.error(traceback.format_exc())
        data_status["result"] = "Unable to download PG based Sub Payment Mode Wise data!!"
        return data_status

def admin_download_pgbased_subpaymentmode_wise_commission_structure_excel_reports_data(commissionStructurespgwiseDataList,fileName):
    relative_temp_excel_file_name = ""
    try:
        commission_structure_data = {
            "snoCount" : [],
            # "apiId" : [],
            "subPaymentModeType" : [],
            "transactionsCount(₹)" : [],
            "totalVolumeAmount(₹)" : [],
            "transactionChargeAmount(₹)" : [],
            "transactionGstAmount(₹)" : [],
            "transactionTotalAmount(₹)" : [],
            "aggregatorChargeAmount(₹)" : [],
            "aggregatorGstAmount(₹)" : [],
            "aggregatorTotalAmount(₹)" : [],
            "companyChargeAmount(₹)" : [],
            "companyGstAmount(₹)" : [],
            "companyTotalAmount(₹)" : [],
            "companyCommissionAmount(₹)" : [],
        }
        for each_commission_record in commissionStructurespgwiseDataList:

            commission_structure_data["snoCount"].append(each_commission_record.get("snoCount"))
            # commission_structure_data["apiId"].append(each_commission_record.get("apiId"))
            commission_structure_data["subPaymentModeType"].append(each_commission_record.get("subPaymentModeType"))
            commission_structure_data["transactionChargeAmount(₹)"].append(each_commission_record.get("transactionChargeAmount"))
            commission_structure_data["transactionGstAmount(₹)"].append(each_commission_record.get("transactionGstAmount"))
            commission_structure_data["transactionTotalAmount(₹)"].append(each_commission_record.get("transactionTotalAmount"))
            commission_structure_data["aggregatorChargeAmount(₹)"].append(each_commission_record.get("aggregatorChargeAmount"))
            commission_structure_data["aggregatorGstAmount(₹)"].append(each_commission_record.get("aggregatorGstAmount"))
            commission_structure_data["aggregatorTotalAmount(₹)"].append(each_commission_record.get("aggregatorTotalAmount"))
            commission_structure_data["companyChargeAmount(₹)"].append(each_commission_record.get("companyChargeAmount"))
            commission_structure_data["companyGstAmount(₹)"].append(each_commission_record.get("companyGstAmount"))
            commission_structure_data["companyTotalAmount(₹)"].append(each_commission_record.get("companyTotalAmount"))
            commission_structure_data["companyCommissionAmount(₹)"].append(each_commission_record.get("companyCommissionAmount"))
            commission_structure_data["totalVolumeAmount(₹)"].append(each_commission_record.get("totalVolumeAmount"))
            commission_structure_data["transactionsCount(₹)"].append(each_commission_record.get("transactionsCount"))
           
            # lengths = [len(value) for value in commission_structure_data.values()]
    
            # If the lengths are not all the same, print the iteration and lengths
            # if len(set(lengths)) == 1:
                # print(f"**********************************Inconsistent lengths found at iteration {each_record.transactionId}. Lengths: {lengths}")
            # print(commission_structure_data,"payin_transacion_reports")
        # Create DataFrame
        df = pd.DataFrame(commission_structure_data)

        # Define file path
        base_dir = os.path.join(app.config['SITE_ROOT'], "media/commissionStructures", "subpaymentmodewise")
        if not os.path.exists(base_dir):
            os.makedirs(base_dir)

        relative_temp_excel_file_name = os.path.join("media/commissionStructures", "subpaymentmodewise", fileName)
        os.makedirs(base_dir, exist_ok=True)
        full_file_name = os.path.join(app.config['SITE_ROOT'], relative_temp_excel_file_name)

        # Save DataFrame to Excel
        df.to_excel(full_file_name, index=False)

        # Send the file as a downloadable attachment
        return send_file(
            full_file_name,
            mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            download_name=fileName,
            as_attachment=True
        )
    except Exception as e:
        app.logger.error(traceback.format_exc())
        return relative_temp_excel_file_name

@admin.route("/admin_download_merchant_wise_payin_payout_excel_report",methods=["GET"])
@adminid_access_token_required
def admin_download_merchant_wise_payin_payout_excel_report():
    data_status = {"responseStatus":0,"result":""}
    date_format = "%d-%m-%Y"

    merchantsList=[]
    usersDataList=[]
    fileMerchantName=""
    try:
        permissionsList = check_permissions(session.get("adminId"),"merchantWiseTransactionPermissions")
        if "view" in permissionsList:
            merchantId = request.args.get("merchantId","")
            startDate = request.args.get("startDate", "")
            endDate = request.args.get("endDate", "")

            try:
                if startDate:
                    startDate = datetime.datetime.strptime(startDate, date_format)  # Use YYYY-MM-DD format
                    startDate = startDate.replace(hour=0, minute=0, second=0, microsecond=0)
                else:
                    startDate = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)

                if endDate:
                    endDate = datetime.datetime.strptime(endDate, date_format)
                    endDate = endDate.replace(hour=23, minute=59, second=59, microsecond=999999)
                else:
                    endDate = datetime.datetime.now().replace(hour=23, minute=59, second=59, microsecond=999999)
            except Exception as ve:
                app.logger.error("Date parsing error: %s", ve)
                startDate = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
                endDate = datetime.datetime.now().replace(hour=23, minute=59, second=59, microsecond=999999)

            start_date_str = startDate.strftime("%d-%m-%Y")+"_"
            end_date_str = endDate.strftime("%d-%m-%Y")+"_"


            filters = Q(status__nin=[2])
            # print("(((((((((((((((((((search_element)))))))))))))))))))",search_element)
            if merchantId:
                filters &= Q(id__in=[merchantId])

            user_queryset = (
                Users.objects(filters)
                .only("id", "fullName", "phoneNumber", "walletBalance", "payoutBalance")
                .order_by("_id")
            )

            user_queryset = list(user_queryset)

            for each_merchant in user_queryset:
                
                # merchantDict = fetching_user_details(each_merchant)
                merchantDict = {
                    "id": str(each_merchant.id),
                    "fullName": str(each_merchant.fullName),
                    "phoneNumber": str(each_merchant.phoneNumber),
                }
                merchantsList.append(merchantDict)

            # if merchantId:
            #     user_queryset = user_queryset.filter()
            snoCount=0
            for each_user in user_queryset:
                snoCount+=1
                payOutSuccessTotalAmount = 0
                payInSuccessTotalAmount = 0
                payoutOpeningBalance = None
                payoutClosingBalance = None

                currentPayinBalance = round(each_user.walletBalance,2)
                currentPayoutBalance = round(each_user.payoutBalance,2)
            
                wallet_transaction_queryset = WalletTransactions.objects(userId=each_user.id,status=1,createdOn__gte=startDate,createdOn__lte=endDate,creditType="Credit").order_by("_id").sum("grandTotal")
                payInSuccessTotalAmount = round(wallet_transaction_queryset,2)

                overall_payouts_queryset = FundTransfers.objects(transferType="Debit",status__in=[1,2],userId=each_user.id,createdOn__gte=startDate,createdOn__lte=endDate).order_by("_id").sum("grandTotal")
                payOutSuccessTotalAmount = round(overall_payouts_queryset,2)

                first_fund_transfer_transaction_queryset = FundTransfers.objects(userId=each_user.id,status__in=[1,2],createdOn__gte=startDate,createdOn__lte=endDate).order_by("createdOn").first()
                if first_fund_transfer_transaction_queryset:
                    payoutOpeningBalance = round(first_fund_transfer_transaction_queryset.previousBalance,2)
                else:
                    payoutOpeningBalance = currentPayoutBalance

                last_fund_transfer_transaction_queryset = FundTransfers.objects(userId=each_user.id,status__in=[1,2],createdOn__gte=startDate,createdOn__lte=endDate).order_by("-createdOn").first()
                if last_fund_transfer_transaction_queryset:
                    payoutClosingBalance = round(last_fund_transfer_transaction_queryset.currentBalance,2)
                else:
                    payoutClosingBalance = currentPayoutBalance
                    
                userDataDict = {
                    "userId": str(each_user.id),
                    "merchantName": str(each_user.fullName),
                    "phoneNumber": str(each_user.phoneNumber),
                    "payOutSuccessTotalAmount": payOutSuccessTotalAmount,
                    "payInSuccessTotalAmount": payInSuccessTotalAmount,
                    "payoutOpeningBalance": payoutOpeningBalance,
                    "payoutClosingBalance": payoutClosingBalance,
                    "currentPayinBalance": currentPayinBalance,
                    "currentPayoutBalance": currentPayoutBalance,
                    "snoCount": snoCount,
                }
                usersDataList.append(userDataDict)
            fileName = f"{start_date_str}{end_date_str}merchantwise_payin_payout_data.xlsx"
                
            reportData = admin_download_merchant_wise_payin_payout_excel_reports_data(usersDataList,fileName)
            return reportData
        else:
          data_status["result"] ="The staff member does not have permission to download merchant wise payin payout data."
          return data_status
    except Exception as e:
        app.logger.error(traceback.format_exc())
        data_status["result"] = "Unable to download Merchant Wise Payin Payout data!!"
        return data_status


def admin_download_merchant_wise_payin_payout_excel_reports_data(usersDataList,fileName):
    relative_temp_excel_file_name = ""
    try:
        merchant_wise_payin_payout_data = {
            # "userId" : [],
            "snoCount" : [],
            "merchantName" : [],
            "payInSuccessTotalAmount(₹)" : [],
            "currentPayinBalance(₹)" : [],
            "payoutOpeningBalance(₹)" : [],
            "payoutClosingBalance(₹)" : [],
            "payOutSuccessTotalAmount(₹)" : [],
            "currentPayoutBalance(₹)" : [],
        }
        for each_merchant_wise_record in usersDataList:
            print("each_merchant_wise_record",each_merchant_wise_record)
            merchant_wise_payin_payout_data["snoCount"].append(each_merchant_wise_record.get("snoCount"))
            # merchant_wise_payin_payout_data["apiId"].append(each_merchant_wise_record.get("apiId"))
            name_number = str(each_merchant_wise_record.get("merchantName"))+ " - " + str(each_merchant_wise_record.get("phoneNumber"))
            merchant_wise_payin_payout_data["merchantName"].append(name_number)
            merchant_wise_payin_payout_data["payOutSuccessTotalAmount(₹)"].append(each_merchant_wise_record.get("payOutSuccessTotalAmount"))
            merchant_wise_payin_payout_data["payInSuccessTotalAmount(₹)"].append(each_merchant_wise_record.get("payInSuccessTotalAmount"))
            merchant_wise_payin_payout_data["payoutOpeningBalance(₹)"].append(each_merchant_wise_record.get("payoutOpeningBalance"))
            merchant_wise_payin_payout_data["payoutClosingBalance(₹)"].append(each_merchant_wise_record.get("payoutClosingBalance"))
            merchant_wise_payin_payout_data["currentPayinBalance(₹)"].append(each_merchant_wise_record.get("currentPayinBalance"))
            merchant_wise_payin_payout_data["currentPayoutBalance(₹)"].append(each_merchant_wise_record.get("currentPayoutBalance"))
           
            # lengths = [len(value) for value in merchant_wise_payin_payout_data.values()]
    
            # If the lengths are not all the same, print the iteration and lengths
            # if len(set(lengths)) == 1:
                # print(f"**********************************Inconsistent lengths found at iteration {each_record.transactionId}. Lengths: {lengths}")
            # print(merchant_wise_payin_payout_data,"payin_transacion_reports")
        # Create DataFrame
        df = pd.DataFrame(merchant_wise_payin_payout_data)

        # Define file path
        base_dir = os.path.join(app.config['SITE_ROOT'], "media/merchantwisepayinpayout", "merchantwisepayinpayout")
        if not os.path.exists(base_dir):
            os.makedirs(base_dir)

        relative_temp_excel_file_name = os.path.join("media/merchantwisepayinpayout", "merchantwisepayinpayout", fileName)
        os.makedirs(base_dir, exist_ok=True)
        full_file_name = os.path.join(app.config['SITE_ROOT'], relative_temp_excel_file_name)

        # Save DataFrame to Excel
        df.to_excel(full_file_name, index=False)

        # Send the file as a downloadable attachment
        return send_file(
            full_file_name,
            mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            download_name=fileName,
            as_attachment=True
        )
    except Exception as e:
        app.logger.error(traceback.format_exc())
        return relative_temp_excel_file_name



#################################################################### downloads####################################################################



@admin.route("/dashboard1",methods=["POST","GET"])
@adminid_access_token_required
def dashboard1():
    try:
        if not session.get("adminId"):
            return redirect("admin_login")
        adminId = session.get("adminId")
        # if not check_latitude_and_longitude(accessToken, adminId):
        #   return redirect("admin_login")
        adminDict = {}
        commissionsDict = {}
        payInTop10MerchantsList = []
        payoutsTop10MerchantsList = []
        payoutsList = []
        payinsList = []
        adminDict = {}
        totalWalletBalance = 0
        merchants_count = 0
        totalPayInBalance = 0
        payinTotalchargeAmount = 0
        payinTotaltdsAmount = 0
        payinTotalgstAmount = 0
        totalPayinAmount = 0
        payoutTotalchargeAmount = 0
        payoutTotaltdsAmount = 0
        payoutTotalgstAmount = 0
        totalPayoutAmount = 0
        todayTotalPayinAmount = 0
        todayTotalPayoutAmount = 0
        yesterdayTotalPayinAmount = 0
        yesterdayTotalPayoutAmount = 0
        approved_count = 0
        total_merchants_count = 0
        rejected_count = 0
        pending_count = 0
        submitted_count = 0
        payoutTotalPgchargeAmount = 0
        payoutTotalPggstAmount = 0
        totalPgPayoutAmount = 0
        currentMonthPayoutPGCharges = 0
        currentMonthPayoutCommissionAmount = 0
        currentMonthPayoutPgGstAmount = 0
        currentMonthpgtotalAmount = 0
        currentMonthPayoutChargesAmount = 0


        previousMonthPayoutCommissionAmount = 0
        previousMonthPayoutCharges = 0
        previousMonthPGCharges = 0
        previousMonthoPayoutPgGstAmount = 0

        pgAdditionalChargeAmount = 0 
        pgCurrentMonthAdditionalChargeAmount = 0
        pgPreviousMonthAdditionalChargeAmount = 0
        
        todayTotalPayinSuccessCount = 0
        todayTotalPayinCount = 0
        todayTotalPayinSucceessRatio = 0

        todayTotalPayoutSuccessCount = 0
        todayTotalPayoutCount = 0
        todayTotalPayoutSucceessRatio = 0


        
        yesterdayTotalPayinSuccessCount = 0
        yesterdayTotalPayinCount = 0
        yesterdayTotalPayinSucceessRatio = 0

        yesterdayTotalPayoutSuccessCount = 0
        yesterdayTotalPayoutCount = 0
        yesterdayTotalPayoutSucceessRatio = 0

        currentMonthTotalPayinSuccessCount = 0
        currentMonthTotalPayinCount = 0
        currentMonthTotalPayinSucceessRatio = 0

        previousMonthTotalPayinSuccessCount = 0
        previousMonthPayinCount = 0
        previousMonthPayinSucceessRatio = 0
        
        currentMonthTotalPayoutSuccessCount = 0
        currentMonthTotalPayoutCount = 0
        currentMonthTotalPayoutSucceessRatio = 0

        previousMonthTotalPayoutSuccessCount = 0
        previousMonthPayoutCount = 0
        previousMonthPayoutSucceessRatio = 0

        yesterdayTotalPayinSuccessCount = 0
        yesterdayTotalPayinCount = 0
        yesterdayTotalPayinSucceessRatio = 0

        yesterdayTotalPayoutSuccessCount = 0
        yesterdayTotalPayoutCount = 0
        yesterdayTotalPayoutSucceessRatio = 0

        totalPayinSuccessCount = 0
        totalPayinCount = 0
        totalPayinSucceessRatio = 0

        totalPayoutSuccessCount = 0
        totalPayoutCount = 0
        totalPayoutSucceessRatio = 0



        admin_queryset = SuperAdmin.objects(id=adminId,status__in=[1]).first()

        todayStartDateTime = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
        todayEndDateTime = todayStartDateTime.replace(hour=23, minute=59, second=59, microsecond=59)
        # print(todayStartDateTime,"((((((((todayStartDateTime))))))))")
        # print(todayEndDateTime,"((((((((todayEndDateTime))))))))")

        # Today Payin & Payout Amounts
        todayTotalPayinAmount = WalletTransactions.objects(createdOn__gte=todayStartDateTime,createdOn__lte=todayEndDateTime,creditType="Credit",status=1,userType="user").sum('amount')
        
        todayTotalPayinSuccessCount=WalletTransactions.objects(createdOn__gte=todayStartDateTime,createdOn__lte=todayEndDateTime,creditType="Credit",status=1,userType="user").count()
        todayTotalPayinCount=WalletTransactions.objects(createdOn__gte=todayStartDateTime,createdOn__lte=todayEndDateTime,creditType="Credit",status__ne=5,userType="user").count()

        if todayTotalPayinSuccessCount>0 and todayTotalPayinCount>0:
            todayTotalPayinSucceessRatio=float(todayTotalPayinSuccessCount*100) / float(todayTotalPayinCount)

        todayTotalPayoutAmount = FundTransfers.objects(createdOn__gte=todayStartDateTime,createdOn__lte=todayEndDateTime,transferType__nin=["Credit"],status=1,userType__ne='admin').sum('amount')
        todayTotalPayoutSuccessCount = FundTransfers.objects(createdOn__gte=todayStartDateTime,createdOn__lte=todayEndDateTime,transferType__nin=["Credit"],status=1,userType__ne='admin').count()
        todayTotalPayoutCount = FundTransfers.objects(createdOn__gte=todayStartDateTime,createdOn__lte=todayEndDateTime,transferType__nin=["Credit"],userType__ne='admin').count()

        if todayTotalPayoutSuccessCount>0 and todayTotalPayoutCount>0:
            todayTotalPayoutSucceessRatio=float(todayTotalPayoutSuccessCount*100)/ float(todayTotalPayoutCount)

        # Yesterday Payin & Payout Amounts
        yesterdayStartDate = todayStartDateTime - datetime.timedelta(days=1)
        yesterdayEndDate = yesterdayStartDate.replace(hour=23, minute=59, second=59, microsecond=999999)

        # print("Yesterday Start:", yesterdayStartDate)
        # print("Yesterday End:", yesterdayEndDate)

        yesterdayTotalPayinAmount = WalletTransactions.objects(createdOn__gte=yesterdayStartDate,createdOn__lte=yesterdayEndDate,creditType="Credit",status=1,userType="user").sum('amount')
        yesterdayPayinSuccessCount=WalletTransactions.objects(createdOn__gte=yesterdayStartDate,createdOn__lte=yesterdayEndDate,creditType="Credit",status=1,userType="user").count()
        yesterdayTotalPayinCount=WalletTransactions.objects(createdOn__gte=yesterdayStartDate,createdOn__lte=yesterdayEndDate,creditType="Credit",status__ne=5,userType="user").count()
        if yesterdayPayinSuccessCount>0 and yesterdayTotalPayinCount>0:
            yesterdayTotalPayinSucceessRatio=float(yesterdayPayinSuccessCount*100)/ float(yesterdayTotalPayinCount)

        yesterdayTotalPayoutAmount = FundTransfers.objects(createdOn__gte=yesterdayStartDate,createdOn__lte=yesterdayEndDate,transferType__nin=["Credit"],status=1,userType__ne='admin').sum('amount')

        yesterdayTotalPayoutSuccessCount = FundTransfers.objects(createdOn__gte=yesterdayStartDate,createdOn__lte=yesterdayEndDate,transferType__nin=["Credit"],status=1,userType__ne='admin').count()
        yesterdayTotalPayoutCount = FundTransfers.objects(createdOn__gte=yesterdayStartDate,createdOn__lte=yesterdayEndDate,transferType__nin=["Credit"],userType__ne='admin').count()

        if yesterdayTotalPayoutSuccessCount>0 and yesterdayTotalPayoutCount>0:
            yesterdayTotalPayoutSucceessRatio=float(yesterdayTotalPayoutSuccessCount*100)/ float(yesterdayTotalPayoutCount)


        #totalWalletBalance = Users.objects(status__in=[1]).sum('walletBalance')

        #merchants_count = Users.objects(status__in=[1]).count()

        if yesterdayTotalPayinAmount == todayTotalPayinAmount:
            todayPayinGrowth = 0
        elif yesterdayTotalPayinAmount == 0:
            todayPayinGrowth = 100
        else:
            todayPayinGrowth = ((todayTotalPayinAmount-yesterdayTotalPayinAmount)/yesterdayTotalPayinAmount)*100

        if yesterdayTotalPayoutAmount == todayTotalPayoutAmount:
            todayPayoutGrowth = 0
        elif yesterdayTotalPayinAmount == 0:
            todayPayoutGrowth = 100
        else:
            todayPayoutGrowth = ((todayTotalPayoutAmount-yesterdayTotalPayoutAmount)/yesterdayTotalPayoutAmount)*100


        totalPayInBalance = WalletTransactions.objects(creditType="Credit",status=1,userType="user").sum('amount')


        totalPayinSuccessCount=WalletTransactions.objects(creditType="Credit",status=1,userType="user").count()
        totalPayinCount=WalletTransactions.objects(creditType="Credit",status__ne=5,userType="user").count()
        print(totalPayinSuccessCount,"totalPayinSuccessCount")
        print(totalPayinCount,"totalPayinCount")
        if totalPayinSuccessCount>0 and totalPayinCount>0:
            totalPayinSucceessRatio=float(totalPayinSuccessCount*100) / float(totalPayinCount)


        totalPayOutBalance = FundTransfers.objects(transferType__nin=["Credit"],status=1,userType__ne='admin').sum('amount')

        totalPayoutSuccessCount = FundTransfers.objects(transferType__nin=["Credit"],status=1,userType__ne='admin').count()
        totalPayoutCount = FundTransfers.objects(transferType__nin=["Credit"],userType__ne='admin').count()

        if totalPayoutSuccessCount>0 and totalPayoutCount>0:
            totalPayoutSucceessRatio=float(totalPayoutSuccessCount*100)/ float(totalPayoutCount)

        


        # Get the first and last day of the current month
        today = datetime.datetime.today()
        first_day_of_current_month = today.replace(day=1,hour=0, minute=0, second=0, microsecond=0)

        last_day_of_previous_month = first_day_of_current_month - datetime.timedelta(days=1)
        last_day_of_previous_month = last_day_of_previous_month.replace(hour=23, minute=59, second=59, microsecond=59)

        first_day_of_previous_month=last_day_of_previous_month.replace(day=1,hour=0, minute=0, second=0, microsecond=0)

        # Get the last day of the current month
        last_day_of_current_month = first_day_of_current_month + timedelta(days=calendar.monthrange(today.year, today.month)[1] - 1)
        last_day_of_current_month = last_day_of_current_month.replace(hour=23, minute=59, second=59, microsecond=999999)


        # Payout Current Month and Current Year
        totalCurrentMonthPayoutBalance = 0

        totalCurrentMonthPayoutBalance = FundTransfers.objects(createdOn__gte=first_day_of_current_month,createdOn__lte=today,status=1,transferType__nin=["Credit","Refund"],userType__ne='admin').sum("amount")


        currentMonthTotalPayoutSuccessCount = FundTransfers.objects(createdOn__gte=first_day_of_current_month,createdOn__lte=today,transferType__nin=["Credit","Refund"],status=1,userType__ne='admin').count()
        currentMonthTotalPayoutCount = FundTransfers.objects(createdOn__gte=first_day_of_current_month,createdOn__lte=today,transferType__nin=["Credit","Refund"],userType__ne='admin').count()

        if currentMonthTotalPayoutSuccessCount>0 and currentMonthTotalPayoutCount>0:
            currentMonthTotalPayoutSucceessRatio=float(currentMonthTotalPayoutSuccessCount*100)/ float(currentMonthTotalPayoutCount)


        totalPreviousMonthPayoutBalance = 0
        totalPreviousMonthPayoutBalance = FundTransfers.objects(createdOn__gte=first_day_of_previous_month,createdOn__lte=last_day_of_previous_month,status=1,transferType__nin=["Credit","Refund"],userType__ne='admin').sum("amount")


        previousMonthTotalPayoutSuccessCount = FundTransfers.objects(createdOn__gte=first_day_of_previous_month,createdOn__lte=last_day_of_previous_month,transferType__nin=["Credit","Refund"],status=1,userType__ne='admin').count()
        previousMonthTotalPayoutCount = FundTransfers.objects(createdOn__gte=first_day_of_previous_month,createdOn__lte=last_day_of_previous_month,transferType__nin=["Credit","Refund"],userType__ne='admin').count()

        if previousMonthTotalPayoutSuccessCount>0 and previousMonthTotalPayoutCount>0:
            previousMonthTotalPayoutSucceessRatio=float(previousMonthTotalPayoutSuccessCount*100)/ float(previousMonthTotalPayoutCount)


        # Payout Increase or Decrease Growth

        if totalPreviousMonthPayoutBalance > 0:
            payoutGrowth = (totalCurrentMonthPayoutBalance - totalPreviousMonthPayoutBalance)*100/totalPreviousMonthPayoutBalance
        else:
            payoutGrowth = 100




        # Payin Current Month and Current Year

        totalCurrentMonthPayinBalance = 0
        totalCurrentMonthPayinBalance = WalletTransactions.objects(createdOn__gte=first_day_of_current_month,createdOn__lte=today,status=1,creditType="Credit",userType="user").sum("amount")


        currentMonthTotalPayinSuccessCount=WalletTransactions.objects(createdOn__gte=first_day_of_current_month,createdOn__lte=today,creditType="Credit",status=1,userType="user").count()
        currentMonthTotalPayinCount=WalletTransactions.objects(createdOn__gte=first_day_of_current_month,createdOn__lte=today,creditType="Credit",status__ne=5,userType="user").count()
        if currentMonthTotalPayinSuccessCount>0 and yesterdayTotalPayinCount>0:
            currentMonthTotalPayinSucceessRatio=float(currentMonthTotalPayinSuccessCount*100)/ float(currentMonthTotalPayinCount)



        totalPreviousMonthPayinBalance = 0
        totalPreviousMonthPayinBalance = WalletTransactions.objects(createdOn__gte=first_day_of_previous_month,createdOn__lte=last_day_of_previous_month,status=1,creditType="Credit",userType="user").sum("amount")

        previousMonthTotalPayinSuccessCount=WalletTransactions.objects(createdOn__gte=first_day_of_current_month,createdOn__lte=today,creditType="Credit",status=1,userType="user").count()
        previousMonthTotalPayinCount=WalletTransactions.objects(createdOn__gte=first_day_of_current_month,createdOn__lte=today,creditType="Credit",status__ne=5,userType="user").count()
        if previousMonthTotalPayinSuccessCount>0 and previousMonthTotalPayinCount>0:
            previousMonthTotalPayinSucceessRatio=float(previousMonthTotalPayinSuccessCount*100)/ float(previousMonthTotalPayinCount)

        # Payout Increase or Decrease Growth

        if totalPreviousMonthPayinBalance > 0:
            payinGrowth = (totalCurrentMonthPayinBalance - totalPreviousMonthPayinBalance)*100/totalPreviousMonthPayinBalance
        else:
            payinGrowth = 100
    
        payOutSuccessRatio=0
        payoutsList = []
        payoutDataPipeline = [
            {
                "$match": {
                        "transferType": {"$nin": ["Credit", "Refund"]},
                        # "transactionAPIId": str(each_payout.id),
                        "userType": {"$ne": 'admin'}
                    }
                },
         # Step 1: Group by apiId and status in `funds`
            {
                "$group": {
                    "_id": {
                        "apiId": "$transactionAPIId",
                        "status": "$status"
                    },
                    "count": { "$sum": 1 }
                }
            },

            # Step 2: Regroup by apiId to get total and success counts
            {
                "$group": {
                    "_id": "$_id.apiId",
                    "totalCount": { "$sum": "$count" },
                    "successCount": {
                        "$sum": {
                            "$cond": [
                                { "$eq": ["$_id.status", 1] }, "$count", 0
                            ]
                        }
                    }
                }
            },

            # Step 3: Add successRatio field
            {
                "$project": {
                    "totalCount": 1,
                    "successCount": 1,
                    "successRatio": {
                        "$cond": [
                            { "$gt": ["$totalCount", 0] },
                            {"$round" :[{"$multiply":[{ "$divide": ["$successCount", "$totalCount"] },100]},
                                    2
                                ]},
                            0
                        ]
                    }
                }
            },

            # Step 4: Lookup latest balance from `balances` collection
            {
                "$lookup": {
                    "from": "admin_payout_balances",
                    "let": { "apiId": "$_id" },
                    "pipeline": [
                        { "$match": { "$expr": { "$eq": ["$apiTransactionId", "$$apiId"] } } },
                        { "$sort": { "createdOn": -1 } },
                        { "$limit": 1 },
                        { "$project": { "currentBalance": 1, "_id": 0 } }
                    ],
                    "as": "latestBalance"
                }
            },
            # Step 5: Lookup API name from `apis`
            {
                "$lookup": {
                    "from": "transaction_a_p_i",
                    "localField": "_id",
                    "foreignField": "_id",
                    "as": "apiInfo"
                }
            },

            # Step 5: Optional — project `latest_amount` safely from the joined balance
            {
                "$project": {
                    "apiId": "$_id",
                    "apiName": { "$arrayElemAt": ["$apiInfo.apiName", 0] },
                    "successRatio": 1,
                    "currentBalance": { "$arrayElemAt": ["$latestBalance.currentBalance", 0] }
                }
            }
        ]
        
        payoutsList = list(FundTransfers.objects.aggregate(*payoutDataPipeline))
        # print("payoutsList",payoutsList)

        # Payin Balance
        payinsList = []
        payInSuccessRatio=0
            ############################################################ payin success ratio pipeline ############################################################
        payinDataPipeline = [
                {
                    "$match": {
                            "creditType": {"$in": ["Credit"]},
                            "userType": {"$eq": 'user'},
                            "status": { "$in": [0, 1] }
                        }
                    },
            # Step 1: Group by apiId and status in `funds`
                {
                "$group": {
                    "_id": "$paymentGatewayId",                 
                    "totalCount": { "$sum": 1 },     
                    "successCount": {
                    "$sum": {
                        "$cond": [
                        { "$eq": ["$status", 1] },  
                        1,                          
                        0                           
                        ]
                    }
                    },
                    "totalAmount": {
                    "$sum": {
                        "$cond": [
                        { "$eq": ["$status", 1] },  
                        "$amount",                  
                        0                           
                        ]
                    }
                    }
                }
                },

                # Step 2: Add successRatio field
                {
                    "$project": {
                        "totalCount": 1,
                        "successCount": 1,
                        "totalAmount": 1,
                        "successRatio": {
                            "$cond": [
                                { "$gt": ["$totalCount", 0] },
                                {"$round" :[{"$multiply":[{ "$divide": ["$successCount", "$totalCount"] },100]},
                                        2
                                    ]},
                                0
                            ]
                        }
                    }
                },
                # Step 5: Lookup API name from `apis`
                {
                    "$lookup": {
                        "from": "transaction_a_p_i",
                        "localField": "_id",
                        "foreignField": "_id",
                        "as": "apiInfo"
                    }
                },
                # Step 5: Optional — project `latest_amount` safely from the joined balance
                {
                    "$project": {
                        "apiId": "$_id",
                        "apiName": { "$arrayElemAt": ["$apiInfo.apiName", 0] },
                        "successRatio": 1,
                        "currentBalance": "$totalAmount"
                    }
                }
            ]

        payinsList = list(WalletTransactions.objects.aggregate(*payinDataPipeline)) ### payin Volumes 
        # print("payinsList",payinsList)
            ############################################################ payin success ratio pipeline ############################################################
        
        # payin monthwise report

        current_year = datetime.datetime.now().year

        # Define the list of all months (1 to 12)
        all_months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

        # Aggregation pipeline
        monthwisePayinPipeline = [
            # Match transactions for the current year
            {
                "$match": {
                    "creditType": "Credit",
                    "status": 1,
                    "userType":"user",
                    "createdOn": {
                        "$gte": datetime.datetime(current_year, 1, 1),  # Start of the current year
                        "$lt": datetime.datetime(current_year + 1, 1, 1)  # Start of the next year
                    }
                }
            },
            # Add a field to extract the month from the transaction date
            {
                "$project": {
                    "paymentGatewayId": 1,
                    "amount": 1,
                    "month": {"$month": "$createdOn"}
                }
            },
            # Group by user_id and month, summing the amounts per month
            {
                "$group": {
                    "_id": {"paymentGatewayId": "$paymentGatewayId", "month": "$month"},
                    "total_amount": {"$sum": "$amount"},
                    "transaction_count": {"$sum": 1}
                }
            },
            # Group by user_id and collect monthly totals into a list
            {
                "$group": {
                    "_id": "$_id.paymentGatewayId",
                    "monthly_totals": {
                        "$push": {
                            "month": "$_id.month", 
                            "total_amount": "$total_amount",
                            "transaction_count": "$transaction_count"
                        }
                    }
                }
            },
            # Project each user and ensure every month (1-12) is in the list with a default total amount of 0 if not present
            {
                "$project": {
                    "paymentGatewayId": "$_id",
                    "monthly_totals": {
                        "$map": {
                            "input": all_months,
                            "as": "month",
                            "in": {
                                "$let": {
                                    "vars": {
                                        "month_data": {
                                            "$arrayElemAt": [
                                                {
                                                    "$filter": {
                                                        "input": "$monthly_totals",
                                                        "as": "item",
                                                        "cond": {"$eq": ["$$item.month", "$$month"]}
                                                    }
                                                },
                                                0
                                            ]
                                        }
                                    },
                                    "in": {
                                        "$cond": {
                                            "if": {"$ifNull": ["$$month_data", False]},
                                            "then": "$$month_data",
                                            "else": {
                                                "month": "$$month",
                                                "total_amount": 0,
                                                "transaction_count": 0
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            },
            # Optionally, sort the results by user_id
            {
                "$sort": {"paymentGatewayId": 1}
            }
        ]


    #     monthwisePayinPipeline = [
    #     # Match transactions for the current year
    #     {
    #         "$match": {
    #             "createdOn": {
    #                 "$gte": datetime.datetime(current_year, 1, 1),  # Start of the current year
    #                 "$lt": datetime.datetime(current_year + 1, 1, 1)  # Start of the next year
    #             }
    #         }
    #     },
    #     # Add a field to extract the month from the transaction date
    #     {
    #         "$project": {
    #             "paymentGatewayId": 1,
    #             "amount": 1,
    #             "month": {"$month": "$createdOn"}
    #         }
    #     },
    #     # Group by user_id and month, summing the amounts and counting the transactions per month
    #     {
    #         "$group": {
    #             "_id": {"paymentGatewayId": "$paymentGatewayId", "month": "$month"},
    #             "total_amount": {"$sum": "$amount"},
    #             "transaction_count": {"$sum": 1}  # Count each transaction
    #         }
    #     },
    #     # Group by user_id and collect monthly totals and counts into a list
    #     {
    #         "$group": {
    #             "_id": "$_id.paymentGatewayId",
    #             "monthly_data": {
    #                 "$push": {
    #                     "month": "$_id.month",
    #                     "total_amount": "$total_amount",
    #                     "transaction_count": "$transaction_count"
    #                 }
    #             }
    #         }
    #     },
    #     # Add missing months with 0 total_amount and transaction_count
    #     {
    #         "$project": {
    #             "monthly_data": {
    #                 "$map": {
    #                     "input": all_months,
    #                     "as": "m",
    #                     "in": {
    #                         "$let": {
    #                             "vars": {
    #                                 "found": {
    #                                     "$filter": {
    #                                         "input": "$monthly_data",
    #                                         "as": "md",
    #                                         "cond": {"$eq": ["$$md.month", "$$m"]}
    #                                     }
    #                                 }
    #                             },
    #                             "in": {
    #                                 "$ifNull": [
    #                                     {"$arrayElemAt": ["$$found", 0]},
    #                                     {"month": "$$m", "total_amount": 0, "transaction_count": 0}
    #                                 ]
    #                             }
    #                         }
    #                     }
    #                 }
    #             }
    #         }
    #     },
    #     # Optionally, sort the results by user_id
    #     {
    #         "$sort": {"_id": 1}
    #     }
    # ]

        # current_year = datetime.datetime.now().year
        monthwisePayinGraphData = []
        # # Aggregation pipeline
        # monthwisePayinPipeline = [
        #     # Match transactions for the current year
        #     {
        #         "$match": {
        #             "creditType": "Credit",
        #             "status": 1,
        #             "userType":"user",
        #             "createdOn": {
        #                 "$gte": datetime(current_year, 1, 1),  # Start of the current year
        #                 "$lt": datetime(current_year + 1, 1, 1)  # Start of the next year
        #             }
        #         }
        #     },
        #     # Add a field to extract the month from the transaction date
        #     {
        #         "$project": {
        #             "user_id": 1,
        #             "amount": 1,
        #             "month": {"$month": "$createdOn"}
        #         }
        #     },
        #     # Group by user_id and month
        #     {
        #         "$group": {
        #             "_id": {"paymentGatewayId": "$paymentGatewayId", "month": "$month"},
        #             "total_amount": {"$sum": "$amount"},
        #             "transaction_count": {"$sum": 1}  # Count the number of transactions
        #         }
        #     },
        #     # Optionally, sort the results by user_id and month
        #     {
        #         "$sort": {"_id.paymentGatewayId": 1, "_id.month": 1}
        #     }
        # ]

        # Execute aggregation
        results = list(WalletTransactions.objects.aggregate(*monthwisePayinPipeline))
        # Print the results
        for result in results:
            apiName=""
            # print(f"PgId: {result['paymentGatewayId']}, Monthly Totals: {result['monthly_totals']}")
            # pass
            if result['paymentGatewayId']:
                apiId=result['paymentGatewayId']
                apiName_queryset = TransactionAPI.objects(id=apiId).first()
                if apiName_queryset:
                    apiName=apiName_queryset.apiName
            dataList = [i.get("total_amount") for i in result['monthly_totals']]
            monthwisePayinDict = {
                "label": apiName,
                "data": dataList
            }
            monthwisePayinGraphData.append(monthwisePayinDict)

        monthwisePayoutPipeline = [
            # Match transactions for the current year
            {
                "$match": {
                    "userType": {"$nin":["admin"]},
                    "transferType": {"$nin":["Credit","Refund"]},
                    "status": 1,
                    "createdOn": {
                        "$gte": datetime.datetime(current_year, 1, 1),  # Start of the current year
                        "$lt": datetime.datetime(current_year + 1, 1, 1)  # Start of the next year
                    }
                }
            },
            # Add a field to extract the month from the transaction date
            {
                "$project": {
                    "transactionAPIId": 1,
                    "amount": 1,
                    "month": {"$month": "$createdOn"}
                }
            },
            # Group by user_id and month, summing the amounts per month
            {
                "$group": {
                    "_id": {"transactionAPIId": "$transactionAPIId", "month": "$month"},
                    "total_amount": {"$sum": "$amount"},
                    "transaction_count": {"$sum": 1}
                }
            },
            # Group by user_id and collect monthly totals into a list
            {
                "$group": {
                    "_id": "$_id.transactionAPIId",
                    "monthly_totals": {
                        "$push": {
                            "month": "$_id.month", 
                            "total_amount": "$total_amount",
                            "transaction_count": "$transaction_count"
                        }
                    }
                }
            },
            # Project each user and ensure every month (1-12) is in the list with a default total amount of 0 if not present
            {
                "$project": {
                    "transactionAPIId": "$_id",
                    "monthly_totals": {
                        "$map": {
                            "input": all_months,
                            "as": "month",
                            "in": {
                                "$let": {
                                    "vars": {
                                        "month_data": {
                                            "$arrayElemAt": [
                                                {
                                                    "$filter": {
                                                        "input": "$monthly_totals",
                                                        "as": "item",
                                                        "cond": {"$eq": ["$$item.month", "$$month"]}
                                                    }
                                                },
                                                0
                                            ]
                                        }
                                    },
                                    "in": {
                                        "$cond": {
                                            "if": {"$ifNull": ["$$month_data", False]},
                                            "then": "$$month_data",
                                            "else": {
                                                "month": "$$month",
                                                "total_amount": 0,
                                                "transaction_count": 0
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            },
            # Optionally, sort the results by user_id
            {
                "$sort": {"transactionAPIId": 1}
            }
        ]
        
        monthwisePayoutGraphData = []
        results = list(FundTransfers.objects.aggregate(*monthwisePayoutPipeline))
        # Print the results
        for result in results:
            apiName=""
            # print(f"PgId: {result['paymentGatewayId']}, Monthly Totals: {result['monthly_totals']}")
            # pass
            if result['transactionAPIId']:
                apiId=result['transactionAPIId']
                apiName_queryset = TransactionAPI.objects(id=apiId).first()
                if apiName_queryset:
                    apiName=apiName_queryset.apiName
            dataList = [i.get("total_amount") for i in result['monthly_totals']]
            monthwisePayoutDict = {
                "label": apiName,
                "data": dataList
            }
            monthwisePayoutGraphData.append(monthwisePayoutDict)


        # Filter for successful PayIn transactions for the current month
        pipeline = [
            {"$lookup": {
                "from": "users",
                "localField": "userId",
                "foreignField": "_id",
                "as": "userDetails"
            }},
            {"$match": {
                "creditType": "Credit",
                "status": 1,
                "userType":"user",
                "createdOn": {
                    "$gte": first_day_of_current_month,
                    "$lte": last_day_of_current_month
                }
            }},
            {"$unwind": "$userDetails"},  # Unwind the array returned by $lookup
            {"$group": {"_id": "$userId", "totalAmount": {"$sum": "$amount"}}},
            {"$sort": {"totalAmount": -1}},
            {"$limit": 10}
        ]

        # Execute the aggregation pipeline
        payins_top_10_merchants = list(WalletTransactions.objects.aggregate(*pipeline))
        print("===============payin len", len(payins_top_10_merchants))
        print("payins_top_10_merchants",payins_top_10_merchants)
        payInTop10MerchantsList = []

        for each_merchant in payins_top_10_merchants:
            totalMerchantPreviousPayinBalance=0
            payinMerchantGrowth=0
            merchant_queryset = Users.objects(id=each_merchant.get("_id")).first()
            if merchant_queryset:
                first_chars = re.findall(r'\b\w', merchant_queryset.fullName)

                imageString = ''.join(first_chars)

                totalMerchantPreviousPayinBalance = WalletTransactions.objects(userId=str(merchant_queryset.id),createdOn__gte=first_day_of_previous_month,createdOn__lte=last_day_of_previous_month,status=1,creditType="Credit",userType="user").sum("amount")

                if totalMerchantPreviousPayinBalance > 0:
                    payinMerchantGrowth = (float(each_merchant.get("totalAmount")) - totalMerchantPreviousPayinBalance) * 100 / totalMerchantPreviousPayinBalance
                else:
                    payinMerchantGrowth = 100

                payInDict = {
                "merchantId":str(merchant_queryset.id),
                "merchantName":merchant_queryset.fullName,
                "phoneNumber":merchant_queryset.phoneNumber,
                "imageString":imageString,
                "payinMerchantGrowth":round(float(payinMerchantGrowth),2),
                "totalMerchantAmount":formatINR("{:.2f}".format(float(each_merchant.get("totalAmount")))),
                "totalMerchantPreviousPayinBalance":formatINR("{:.2f}".format(float(totalMerchantPreviousPayinBalance)))
                }
                payInTop10MerchantsList.append(payInDict)

        # Filter for successful Payout transactions for the current month
        payout_pipeline = [
            {"$match": {
                "transferType": "Debit",
                "userType": {"$ne":"admin"},
                "status": 1,
                "createdOn": {
                    "$gte": first_day_of_current_month,
                    "$lte": last_day_of_current_month
                }
            }},  # Filtering
            {"$group": {"_id": "$userId", "totalAmount": {"$sum": "$amount"}}},  # Grouping and summing amounts
            {"$sort": {"totalAmount": -1}},  # Sorting by total amount in descending order
            {"$limit": 10}  # Limiting to top 10
        ]

        # Execute the aggregation payout_pipeline
        payouts_top_10_merchants = list(FundTransfers.objects.aggregate(*payout_pipeline))
        print("===============payout top len", len(payouts_top_10_merchants))
        payoutsTop10MerchantsList = []
        for each_payout_merchant in payouts_top_10_merchants:
            payoutMerchantGrowth=0
            totalMerchantPreviousPayoutBalance=0
            payout_merchant_queryset = Users.objects(id=each_payout_merchant.get("_id")).first()
            if payout_merchant_queryset:
                first_chars = re.findall(r'\b\w', payout_merchant_queryset.fullName)

                imageString = ''.join(first_chars)

                totalMerchantPreviousPayoutBalance = FundTransfers.objects(userId=str(merchant_queryset.id),createdOn__gte=first_day_of_previous_month,createdOn__lte=last_day_of_previous_month,status=1,transferType__nin=["Credit","Refund"],userType__ne='admin').sum("amount")

                if totalMerchantPreviousPayoutBalance > 0:
                    payoutMerchantGrowth = (float(each_payout_merchant.get("totalAmount")) - totalMerchantPreviousPayoutBalance) * 100 / totalMerchantPreviousPayoutBalance
                else:
                    payoutMerchantGrowth = 100

                payOutDict = {
                "merchantId":str(payout_merchant_queryset.id),
                "merchantName":payout_merchant_queryset.fullName,
                "phoneNumber":payout_merchant_queryset.phoneNumber,
                "imageString":imageString,
                "payoutMerchantGrowth":round(float(payoutMerchantGrowth),2),
                "totalMerchantAmount":formatINR("{:.2f}".format(float(each_payout_merchant.get("totalAmount")))),
                "totalMerchantPreviousPayoutBalance":formatINR("{:.2f}".format(float(totalMerchantPreviousPayoutBalance)))
                }
                payoutsTop10MerchantsList.append(payOutDict)

        # Commissions For Payin And Payout Calculations
        # payinTotalchargeAmount = WalletTransactions.objects(status=1).sum('commissionCharges.chargeAmount')
        # payinTotaltdsAmount = WalletTransactions.objects(status=1).sum('commissionCharges.tdsAmount')
        # payinTotalgstAmount = WalletTransactions.objects(status=1).sum('commissionCharges.gstAmount')

        # Commissions For Payin And Payout Calculations

        # comm_pipeline_payin = [
        #         {
        #             '$project': {
        #                 'chargeAmount': '$commissionCharges.chargeAmount',
        #                 'tdsAmount': '$commissionCharges.tdsAmount',
        #                 'gstAmount': '$commissionCharges.gstAmount'
        #             }
        #         },
        #         {
        #             '$group': {
        #                 '_id': None,
        #                 'payinTotalchargeAmount': {'$sum': '$chargeAmount'},
        #                 'payinTotaltdsAmount': {'$sum': '$tdsAmount'},
        #                 'payinTotalgstAmount': {'$sum': '$gstAmount'}
        #             }
        #         }
        #     ]
        # result = WalletTransactions.objects(status=1).aggregate(comm_pipeline_payin)

        # if result:
        #     payinTotalchargeAmount = result[0]['payinTotalchargeAmount']
        #     payinTotaltdsAmount = result[0]['payinTotaltdsAmount']
        #     payinTotalgstAmount = result[0]['payinTotalgstAmount']

        # totalPayinAmount  = payinTotalchargeAmount + payinTotaltdsAmount + payinTotalgstAmount

        ################################## Payout ############################################################

        pipeline = [
            {"$match": {"status": 1,"fundTransferType":{"$in":["Instant","bulk"]}}},  # Match documents with status=1
            {
                "$group": {
                    "_id": None,  # We don't need to group by any field
                    "totalChargeAmount": {"$sum": "$commissionCharges.chargeAmount"},
                    "totalGstAmount": {"$sum": "$commissionCharges.gstAmount"},
                    "totalPgChargeAmount": {"$sum": "$aggregatorCharges.chargeAmount"},
                    "totalPgGstAmount": {"$sum": "$aggregatorCharges.gstAmount"}
                }
            }
        ]

        result = list(FundTransfers.objects.aggregate(*pipeline))

        payoutTotalchargeAmount = result[0]["totalChargeAmount"]
        payoutTotalgstAmount = result[0]["totalGstAmount"]
        payoutTotalPgchargeAmount = result[0]["totalPgChargeAmount"]
        payoutTotalPggstAmount = result[0]["totalPgGstAmount"]


        # payoutTotalchargeAmount = FundTransfers.objects(fundTransferType__in=["Instant","bulk"],status=1).sum('commissionCharges.chargeAmount')
        # payoutTotaltdsAmount = FundTransfers.objects(status=1).sum('commissionCharges.tdsAmount')
        # payoutTotalgstAmount = FundTransfers.objects(fundTransferType__in=["Instant","bulk"],status=1).sum('commissionCharges.gstAmount')

        totalPayoutAmount  = payoutTotalchargeAmount + payoutTotaltdsAmount + payoutTotalgstAmount


        # payoutTotalPgchargeAmount = FundTransfers.objects(fundTransferType__in=["Instant","bulk"],status=1).sum('aggregatorCharges.chargeAmount')
        # payoutTotalPggstAmount = FundTransfers.objects(fundTransferType__in=["Instant","bulk"],status=1).sum('aggregatorCharges.gstAmount')
        totalPgPayoutAmount  = payoutTotalPgchargeAmount + payoutTotalPggstAmount

        pgAdditionalChargeAmount = PgSettlements.objects(status=1).sum('additionalChargeAmount')

        ######################################################################################################


        ####################################          Bene Charges    #################################################################
        beneficiaryTypeQueryset =  FundTransfers.objects(fundTransferType__in=["beneficiary"],status=1).all()
        beneficiaryTotalChargesAmount = FundTransfers.objects(fundTransferType__in=["beneficiary"],status=1).sum('grandTotal')
        beneficiaryGstAmount = FundTransfers.objects(fundTransferType__in=["beneficiary"],status=1).sum('commissionCharges.gstAmount')
        beneficiaryTransactionsCount = FundTransfers.objects(fundTransferType__in=["beneficiary"],status=1).count()

        ######################################################################################################


        #####################################          Bene Currrent Charges    #################################################################
        beneficiaryCurrentMonthTypeQueryset =  FundTransfers.objects(fundTransferType__in=["beneficiary"],createdOn__gte=first_day_of_current_month,createdOn__lte=today,status=1).all()
        beneficiaryCurrentMonthTotalChargesAmount = FundTransfers.objects(fundTransferType__in=["beneficiary"],createdOn__gte=first_day_of_current_month,createdOn__lte=today,status=1).sum('grandTotal')
        beneficiaryCurrentMonthGstAmount = FundTransfers.objects(fundTransferType__in=["beneficiary"],createdOn__gte=first_day_of_current_month,createdOn__lte=today,status=1).sum('commissionCharges.gstAmount')
        beneficiaryCurrentMonthTransactionsCount = FundTransfers.objects(fundTransferType__in=["beneficiary"],createdOn__gte=first_day_of_current_month,createdOn__lte=today,status=1).count()

        ######################################################################################################

        
        #####################################          Bene Previous Charges    #################################################################
        beneficiaryPreviousTypeQueryset =  FundTransfers.objects(fundTransferType__in=["beneficiary"],createdOn__gte=first_day_of_previous_month,createdOn__lte=last_day_of_previous_month,status=1).all()
        beneficiaryPreviousTotalChargesAmount = FundTransfers.objects(fundTransferType__in=["beneficiary"],createdOn__gte=first_day_of_previous_month,createdOn__lte=last_day_of_previous_month,status=1).sum('grandTotal')
        beneficiaryPreviousGstAmount = FundTransfers.objects(fundTransferType__in=["beneficiary"],createdOn__gte=first_day_of_previous_month,createdOn__lte=last_day_of_previous_month,status=1).sum('commissionCharges.gstAmount')
        beneficiaryPreviousTransactionsCount = FundTransfers.objects(fundTransferType__in=["beneficiary"],createdOn__gte=first_day_of_previous_month,createdOn__lte=last_day_of_previous_month,status=1).count()

        ######################################################################################################



        #################################################### Bene Data Pipeline###############################################
        # beneficiaryTotalChargesAmount = 0
        # beneficiaryGstAmount = 0
        # beneficiaryTransactionsCount = 0
        # beneficiaryCurrentMonthTotalChargesAmount = 0
        # beneficiaryCurrentMonthGstAmount = 0
        # beneficiaryCurrentMonthTransactionsCount = 0
        # beneficiaryPreviousTotalChargesAmount = 0
        # beneficiaryPreviousGstAmount = 0
        # beneficiaryPreviousTransactionsCount = 0

        # beneficiary_data_pipeline = [
        #     # Step 1: Filter documents by beneficiary type and status
        #     {
        #         "$match": {
        #             "fundTransferType": "beneficiary",  # Filter by 'beneficiary' type
        #             "status": 1               # Filter by 'status' = 1 (active beneficiaries)
        #         }
        #     },
            
        #     # Step 2: Group by date range and perform aggregation (total charges, GST, and transaction count)
        #     {
        #         "$group": {
        #             "_id": None,  # No grouping (will aggregate for all records)
        #             "totalCharges": { "$sum": "$grandTotal" },  # Sum of grandTotal (total charges)
        #             "totalGst": { "$sum": "$commissionCharges.gstAmount" },           # Sum of commissionCharges.gstAmount (GST)
        #             "totalTransactions": { "$sum": 1 }          # Count of total transactions
        #         }
        #     },

        #     # Optional: Add calculations for current month and previous month using date filters
        #     # Current month filter (from first day to today)
        #     {
        #         "$facet": {
        #             "total": [
        #                 {
        #                     "$match": {
        #                         "fundTransferType": "beneficiary",
        #                         "status": 1
        #                     }
        #                 },
        #                 {
        #                     "$group": {
        #                         "_id": None,
        #                         "totalCharges": { "$sum": "$grandTotal" },
        #                         "totalGst": { "$sum": "$commissionCharges.gstAmount" },
        #                         "totalTransactions": { "$sum": 1 }
        #                     }
        #                 }
        #             ],
        #             "currentMonth": [
        #                 {
        #                     "$match": {
        #                         "fundTransferType": "beneficiary",
        #                         "status": 1,
        #                         "createdOn": { "$gte": first_day_of_current_month, "$lte": today }  # Current month range
        #                     }
        #                 },
        #                 {
        #                     "$group": {
        #                         "_id": None,
        #                         "totalCharges": { "$sum": "$grandTotal" },
        #                         "totalGst": { "$sum": "$commissionCharges.gstAmount" },
        #                         "totalTransactions": { "$sum": 1 }
        #                     }
        #                 }
        #             ],
        #             "previousMonth": [
        #                 {
        #                     "$match": {
        #                         "fundTransferType": "beneficiary",
        #                         "status": 1,
        #                         "createdOn": { "$gte": first_day_of_previous_month, "$lte": last_day_of_previous_month }  # Previous month range
        #                     }
        #                 },
        #                 {
        #                     "$group": {
        #                         "_id": None,
        #                         "totalCharges": { "$sum": "$grandTotal" },
        #                         "totalGst": { "$sum": "$commissionCharges.gstAmount" },
        #                         "totalTransactions": { "$sum": 1 }
        #                     }
        #                 }
        #             ]
        #         }
        #     },

        #     # Step 3: Project the results to make them more readable
        #     {
        #     "$project": {
        #         "totalCharges": { "$ifNull": [{ "$arrayElemAt": ["$total.totalCharges", 0] }, 0] },
        #         "totalGst": { "$ifNull": [{ "$arrayElemAt": ["$total.totalGst", 0] }, 0] },
        #         "totalTransactions": { "$ifNull": [{ "$arrayElemAt": ["$total.totalTransactions", 0] }, 0] },
        #         "currentMonthTotalCharges": { "$ifNull": [{ "$arrayElemAt": ["$currentMonth.totalCharges", 0] }, 0] },
        #         "currentMonthTotalGst": { "$ifNull": [{ "$arrayElemAt": ["$currentMonth.totalGst", 0] }, 0] },
        #         "currentMonthTotalTransactions": { "$ifNull": [{ "$arrayElemAt": ["$currentMonth.totalTransactions", 0] }, 0] },
        #         "previousMonthTotalCharges": { "$ifNull": [{ "$arrayElemAt": ["$previousMonth.totalCharges", 0] }, 0] },
        #         "previousMonthTotalGst": { "$ifNull": [{ "$arrayElemAt": ["$previousMonth.totalGst", 0] }, 0] },
        #         "previousMonthTotalTransactions": { "$ifNull": [{ "$arrayElemAt": ["$previousMonth.totalTransactions", 0] }, 0] }
        #     }
        #     }
        # ]

        # # Run the aggregation
        # beneficiary_data_aggregator_results = list(FundTransfers.objects.aggregate(*beneficiary_data_pipeline))
        # print("((((((((beneficiary_data_aggregator_results))))))))",beneficiary_data_aggregator_results )
        
        # # Extract the results
        # for each_beneficiary_data_result in beneficiary_data_aggregator_results:
        #     beneficiaryTotalChargesAmount = each_beneficiary_data_result['totalCharges']
        #     beneficiaryGstAmount = each_beneficiary_data_result['totalGst']
        #     beneficiaryTransactionsCount = each_beneficiary_data_result['totalTransactions']
        #     beneficiaryCurrentMonthTotalChargesAmount = each_beneficiary_data_result['currentMonthTotalCharges']
        #     beneficiaryCurrentMonthGstAmount = each_beneficiary_data_result['currentMonthTotalGst']
        #     beneficiaryCurrentMonthTransactionsCount = each_beneficiary_data_result['currentMonthTotalTransactions']
        #     beneficiaryPreviousTotalChargesAmount = each_beneficiary_data_result['previousMonthTotalCharges']
        #     beneficiaryPreviousGstAmount = each_beneficiary_data_result['previousMonthTotalGst']
        #     beneficiaryPreviousTransactionsCount = each_beneficiary_data_result['previousMonthTotalTransactions']


        ######################################################################################################


        ################################## Current Month For Payout Commissions ############################################################

        # current_month_payout_queryset = FundTransfers.objects(fundTransferType__in=["Instant","bulk"],createdOn__gte=first_day_of_current_month,createdOn__lte=today,status=1)
        # currentMonthPayoutCommissionAmount = current_month_payout_queryset.filter().sum('aggregatorCharges.commissionAmount') #
        # currentMonthPayoutCommissionAmount=round(currentMonthPayoutCommissionAmount,2) ####1

        # currentMonthPayoutChargesAmount = current_month_payout_queryset.filter().sum('commissionCharges.chargeAmount')
        # currentMonthPayoutChargesAmount=round(currentMonthPayoutChargesAmount,2) ####2

        # currentMonthPayoutPGCharges = current_month_payout_queryset.filter().sum('aggregatorCharges.chargeAmount')3
        # currentMonthPayoutPgGstAmount = current_month_payout_queryset.filter().sum('aggregatorCharges.gstAmount')4
        # currentMonthPayoutPgGstAmount=round(float(currentMonthPayoutPgGstAmount),2) 
        # currentMonthpgtotalAmount = round(float(currentMonthPayoutPGCharges + currentMonthPayoutPgGstAmount),2)   #### 5



        ##########pipeline
        current_month_payout_comm_pipeline = [
            {"$match": {"status": 1,"fundTransferType":{"$in":["Instant","bulk"]},
            'status': 1,
            'createdOn': {
                        "$gte": first_day_of_current_month,
                        "$lte": today,
                    }
            }},  # Match documents with status=1
            
            {
                "$group": {
                    "_id": None,  # We don't need to group by any field
                    "currentMonthPayoutCommissionAmount": {"$sum": "$overallCommissionAmount"},
                    "currentMonthPayoutChargesAmount": {"$sum": "$commissionCharges.chargeAmount"},
                    "currentMonthPayoutChargesGstAmount": {"$sum": "$commissionCharges.gstAmount"},
                    "currentMonthPayoutPGCharges": {"$sum": "$aggregatorCharges.chargeAmount"},
                    "currentMonthPayoutPgGstAmount": {"$sum": "$aggregatorCharges.gstAmount"}
                }
            }
        ]
        current_month_payout_commissions_result = list(FundTransfers.objects.aggregate(current_month_payout_comm_pipeline))
        # print("current_month_payout_commissions_result",current_month_payout_commissions_result)

        if current_month_payout_commissions_result:
            currentMonthPayoutCommissionAmount= round(float(current_month_payout_commissions_result[0]["currentMonthPayoutCommissionAmount"]),2)
            currentMonthPayoutChargesGstAmount= round(float(current_month_payout_commissions_result[0]["currentMonthPayoutChargesGstAmount"]),2)
            currentMonthPayoutChargesAmount= round(float(current_month_payout_commissions_result[0]["currentMonthPayoutChargesAmount"]),2)
            currentMonthPayoutPGCharges= round(float(current_month_payout_commissions_result[0]["currentMonthPayoutPGCharges"]),2)
            currentMonthPayoutPgGstAmount= round(float(current_month_payout_commissions_result[0]["currentMonthPayoutPgGstAmount"]),2)
            currentMonthpgtotalAmount = round(float(currentMonthPayoutPGCharges + currentMonthPayoutPgGstAmount),2) 
            currentMonthPayoutChargesAmount = round(float(currentMonthPayoutChargesAmount + currentMonthPayoutChargesGstAmount),2) 


        pgCurrentMonthAdditionalChargeAmount = PgSettlements.objects(createdOn__gte=first_day_of_current_month,createdOn__lte=today,status=1).sum('additionalChargeAmount')





        ########################################################################################################################################

        ############################################################### Previous Month For Payout Commissions ####################################################################
        

        # payouts_all_queryset = FundTransfers.objects(createdOn__gte=first_day_of_previous_month,createdOn__lte=last_day_of_previous_month,status=1)
        # previous_month_payout_queryset = payouts_all_queryset.filter(fundTransferType__in=["Instant","bulk"])
        # previousMonthPayoutCommissionAmount = previous_month_payout_queryset.filter().sum('commissionCharges.commissionAmount')
        # previousMonthPayoutCommissionAmount=round(previousMonthPayoutCommissionAmount,2) ####
        # previousMonthPayoutCharges = previous_month_payout_queryset.filter().sum('commissionCharges.chargeAmount')

        # previousMonthPGCharges = previous_month_payout_queryset.filter().sum('aggregatorCharges.chargeAmount')
        # previousMonthoPayoutPgGstAmount = previous_month_payout_queryset.filter().sum('aggregatorCharges.gstAmount')
        # previousMonthoPayoutPgGstAmount=round(float(previousMonthoPayoutPgGstAmount),2)


        ##########pipeline
        previous_month_payout_comm_pipeline = [
            {"$match": {"status": 1,"fundTransferType":{"$in":["Instant","bulk"]},
            'status': 1,
            'createdOn': {
                        "$gte": first_day_of_previous_month,
                        "$lte": last_day_of_previous_month,
                    }
            }},  # Match documents with status=1
            
            {
                "$group": {
                    "_id": None,  # We don't need to group by any field
                    "previousMonthPayoutCommissionAmount": {"$sum": "$overallCommissionAmount"},
                    "previousMonthPayoutCharges": {"$sum": "$commissionCharges.chargeAmount"},
                    "previousMonthPayoutChargesGst": {"$sum": "$commissionCharges.gstAmount"},
                    "previousMonthPGCharges": {"$sum": "$aggregatorCharges.chargeAmount"},
                    "previousMonthoPayoutPgGstAmount": {"$sum": "$aggregatorCharges.gstAmount"}
                }
            }
        ]
        previous_month_payout_commissions_result = list(FundTransfers.objects.aggregate(previous_month_payout_comm_pipeline))
        # print("previous_month_payout_commissions_result",previous_month_payout_commissions_result)

        if previous_month_payout_commissions_result:
            previousMonthPayoutCommissionAmount= round(float(previous_month_payout_commissions_result[0]["previousMonthPayoutCommissionAmount"]),2)
            previousMonthPayoutChargesGst= round(float(previous_month_payout_commissions_result[0]["previousMonthPayoutChargesGst"]),2)
            previousMonthPayoutCharges= round(float(previous_month_payout_commissions_result[0]["previousMonthPayoutCharges"]),2)
            previousMonthPGCharges= round(float(previous_month_payout_commissions_result[0]["previousMonthPGCharges"]),2)
            previousMonthoPayoutPgGstAmount= round(float(previous_month_payout_commissions_result[0]["previousMonthoPayoutPgGstAmount"]),2)
            previousMonthPGCharges = round(float(previousMonthPGCharges + previousMonthoPayoutPgGstAmount),2) 
            previousMonthPayoutCharges = round(float(previousMonthPayoutCharges + previousMonthPayoutChargesGst),2) 


        pgPreviousMonthAdditionalChargeAmount = PgSettlements.objects(createdOn__gte=first_day_of_previous_month,createdOn__lte=last_day_of_previous_month,status=1).sum('additionalChargeAmount')
        ##########################################################################################################################################################################

        
        total_merchants_count = Users.objects(status__nin=[2,6]).count()

        users_kyc_queryset = UserKYC.objects(status__in=[0,1]).order_by("-id")
        for each_user_kyc in users_kyc_queryset:
            kycStatusList = []
            kycStatusList = [
            each_user_kyc.panStatus,
            each_user_kyc.aadharStatus,
            each_user_kyc.bankStatus,
            each_user_kyc.videoVerificationStatus,
            each_user_kyc.agreementVerificationStatus
            ]
            if each_user_kyc.userId.entityTypeId!=None and each_user_kyc.userId.entityTypeId.isIndividual==False:
                kycStatusList.append(each_user_kyc.shopVideoStatus)
                kycStatusList.append(each_user_kyc.businessStatus)
                if each_user_kyc.documentsList==[]:
                    kycStatusList.append('Pending')
                else:
                    for each_document in each_user_kyc.documentsList:
                        kycStatusList.append(each_document.get('documentStatus'))

                if each_user_kyc.shopImagesList==[]:
                    kycStatusList.append('Pending')
                else:
                    for each_simg in each_user_kyc.shopImagesList:
                        kycStatusList.append(each_simg.get('shopImageStatus'))

            if "Rejected" in kycStatusList:
                rejected_count += 1
            elif "Pending" in kycStatusList or "" in kycStatusList or  None in kycStatusList: ########## new code for count adding "" or none as pending
                pending_count += 1
            elif "Submitted" in kycStatusList:
                submitted_count += 1
            else:
                approved_count += 1

        # print(rejected_count,"(((((((((((rejected_count)))))))))))")
        # print(pending_count,"(((((((((((pending_count)))))))))))")
        # print(submitted_count,"(((((((((((submitted_count)))))))))))")
        # print(approved_count,"(((((((((((approved_count)))))))))))")
        # rejected_count = rejected_count
        # pending_count = pending_count
        # submitted_count=submitted_count
        approved_count=approved_count
        overPGCharges= 0
        overallTransactionChargesDatewise=0
        overPgGstAmount=0
        overallTransactionChargesDatewise=0
        overallTransactionGstAmountDatewise=0
        
        cwCommissionAmount=0 ####
        pgtotalAmount=0  ####
        totalTransactionAmount=0  ####
        agentCommissionAmount=0  ####

        currentMonthcwCommissionAmount = 0 
        currentMonthpgtotalAmount=0
        currentMonthTotalTransactionAmount = 0
        currentMonthAgentCommissionAmount = 0
        
        previousMonthcwCommissionAmount = 0 
        previousMonthpgtotalAmount=0
        previousMonthTotalTransactionAmount = 0
        previousMonthAgentCommissionAmount = 0

        ####### Overall #######
        transferType_query_val = "Credit"
        status_query_val = 1
        cw_commission_pipeline = pipeline = [
            {
                '$match': {
                    'transferType': transferType_query_val,  # Match documents with the specified type
                    'status': status_query_val,  # Match documents with the specified status
                }
            },
            {
                '$group': {
                    '_id': None,  # Group everything into one result
                    'cwCommissionAmount': {'$sum': '$commissionAmount'},  # Sum the field 'your_field'
                    'overPGCharges': {'$sum': '$aggregatorCommissionAmount'}, ## not in html
                    'overPgGstAmount': {'$sum': '$aggregatorCommissionCharges.gstAmount'},
                    'overallTransactionChargesDatewise': {'$sum': '$transactionCommissionCharges.chargeAmount'}, ## not in html## not in html
                    'overallTransactionGstAmountDatewise': {'$sum': '$transactionCommissionCharges.gstAmount'},
                }
            },
            {
            '$project': {
                'cwCommissionAmount': 1,
                'overPgGstAmount': 1,
                'overallTransactionGstAmountDatewise': 1,
                'pgtotalAmount': {'$add': ['$overPGCharges', '$overPgGstAmount']},  # Add the two sums together
                'totalTransactionAmount': {'$add': ['$overallTransactionChargesDatewise', '$overallTransactionGstAmountDatewise']}  # Add the two sums together
            }
            }
        ]

        over_all_cw_commission_result = list(CompanyCommissions.objects.aggregate(cw_commission_pipeline))
        # print("over_all_cw_commission_result",over_all_cw_commission_result)

        if over_all_cw_commission_result:
            cwCommissionAmount= round(float(over_all_cw_commission_result[0]["cwCommissionAmount"]),2)
            overPgGstAmount= round(float(over_all_cw_commission_result[0]["overPgGstAmount"]),2)
            overallTransactionGstAmountDatewise= round(float(over_all_cw_commission_result[0]["overallTransactionGstAmountDatewise"]),2)
            pgtotalAmount= round(float(over_all_cw_commission_result[0]["pgtotalAmount"]),2)
            totalTransactionAmount= round(float(over_all_cw_commission_result[0]["totalTransactionAmount"]),2)


        agentCommissionAmount = UserCommissions.objects(status=1).sum('parrentCommissionAmount')
        agentCommissionAmount = round(float(agentCommissionAmount),2) ####


        

        ####### Current Month #######
        current_month_cw_commission_pipeline = pipeline = [
            {
                '$match': {
                    'transferType': transferType_query_val,  # Match documents with the specified type
                    'status': status_query_val,  # Match documents with the specified status
                    'createdOn': {
                        "$gte": first_day_of_current_month,
                        "$lte": today,
                    }
                }
            },
            {
                '$group': {
                    '_id': None,  # Group everything into one result
                    'currentMonthcwCommissionAmount': {'$sum': '$commissionAmount'},  # Sum the field 'your_field'
                    'currentMonthoverPGCharges': {'$sum': '$aggregatorCommissionAmount'}, ## not in html
                    'currentMonthoverPgGstAmount': {'$sum': '$aggregatorCommissionCharges.gstAmount'},
                    'currentMonthOverallTransactionChargesDatewise': {'$sum': '$transactionCommissionCharges.chargeAmount'}, ## not in html## not in html
                    'currentMonthOverallTransactionGstAmountDatewise': {'$sum': '$transactionCommissionCharges.gstAmount'},
                }
            },
            {
            '$project': {
                'currentMonthcwCommissionAmount': 1,
                'currentMonthoverPgGstAmount': 1,
                'currentMonthOverallTransactionGstAmountDatewise': 1,
                'currentMonthpgtotalAmount': {'$add': ['$currentMonthoverPGCharges', '$currentMonthoverPgGstAmount']},  # Add the two sums together
                'currentMonthTotalTransactionAmount': {'$add': ['$currentMonthOverallTransactionChargesDatewise', '$currentMonthOverallTransactionGstAmountDatewise']}  # Add the two sums together
            }
            }
        ]

        current_month_over_all_cw_commission_result = list(CompanyCommissions.objects.aggregate(current_month_cw_commission_pipeline))
        # print("current_month_over_all_cw_commission_result",current_month_over_all_cw_commission_result)

        if current_month_over_all_cw_commission_result:
            currentMonthcwCommissionAmount= round(float(current_month_over_all_cw_commission_result[0]["currentMonthcwCommissionAmount"]),2)
            currentMonthoverPgGstAmount= round(float(current_month_over_all_cw_commission_result[0]["currentMonthoverPgGstAmount"]),2)
            currentMonthOverallTransactionGstAmountDatewise= round(float(current_month_over_all_cw_commission_result[0]["currentMonthOverallTransactionGstAmountDatewise"]),2)
            currentMonthpgtotalAmount= round(float(current_month_over_all_cw_commission_result[0]["currentMonthpgtotalAmount"]),2)
            currentMonthTotalTransactionAmount= round(float(current_month_over_all_cw_commission_result[0]["currentMonthTotalTransactionAmount"]),2)


        currentMonthAgentCommissionAmount = UserCommissions.objects(createdOn__gte=first_day_of_current_month,createdOn__lte=today,status=1).sum('parrentCommissionAmount')
        currentMonthAgentCommissionAmount = round(float(currentMonthAgentCommissionAmount),2) ####



        ####### Previous Month #######
        previous_month_cw_commission_pipeline  = [
            {
                '$match': {
                    'transferType': transferType_query_val,  # Match documents with the specified type
                    'status': status_query_val,  # Match documents with the specified status
                    'createdOn': {
                        "$gte": first_day_of_previous_month,
                        "$lte": last_day_of_previous_month,
                    }
                }
            },
            {
                '$group': {
                    '_id': None,  # Group everything into one result
                    'previousMonthcwCommissionAmount': {'$sum': '$commissionAmount'},  # Sum the field 'your_field'
                    'previousMonthoverPGCharges': {'$sum': '$aggregatorCommissionAmount'}, ## not in html
                    'previousMonthoverPgGstAmount': {'$sum': '$aggregatorCommissionCharges.gstAmount'},
                    'previousMonthOverallTransactionChargesDatewise': {'$sum': '$transactionCommissionCharges.chargeAmount'}, ## not in html## not in html
                    'previousMonthOverallTransactionGstAmountDatewise': {'$sum': '$transactionCommissionCharges.gstAmount'},
                }
            },
            {
            '$project': {
                'previousMonthcwCommissionAmount': 1,
                'previousMonthoverPgGstAmount': 1,
                'previousMonthOverallTransactionGstAmountDatewise': 1,
                'previousMonthpgtotalAmount': {'$add': ['$previousMonthoverPGCharges', '$previousMonthoverPgGstAmount']},  # Add the two sums together
                'previousMonthTotalTransactionAmount': {'$add': ['$previousMonthOverallTransactionChargesDatewise', '$previousMonthOverallTransactionGstAmountDatewise']}  # Add the two sums together
            }
            }
        ]

        previous_month_over_all_cw_commission_result = list(CompanyCommissions.objects.aggregate(previous_month_cw_commission_pipeline))
        # print("previous_month_over_all_cw_commission_result",previous_month_over_all_cw_commission_result)

        if previous_month_over_all_cw_commission_result:
            previousMonthcwCommissionAmount= round(float(previous_month_over_all_cw_commission_result[0]["previousMonthcwCommissionAmount"]),2)
            previousMonthoverPgGstAmount= round(float(previous_month_over_all_cw_commission_result[0]["previousMonthoverPgGstAmount"]),2)
            previousMonthOverallTransactionGstAmountDatewise= round(float(previous_month_over_all_cw_commission_result[0]["previousMonthOverallTransactionGstAmountDatewise"]),2)
            previousMonthpgtotalAmount= round(float(previous_month_over_all_cw_commission_result[0]["previousMonthpgtotalAmount"]),2)
            previousMonthTotalTransactionAmount= round(float(previous_month_over_all_cw_commission_result[0]["previousMonthTotalTransactionAmount"]),2)

        previousMonthAgentCommissionAmount = UserCommissions.objects(createdOn__gte=first_day_of_previous_month,createdOn__lte=last_day_of_previous_month,status=1).sum('parrentCommissionAmount')
        previousMonthAgentCommissionAmount = round(float(previousMonthAgentCommissionAmount),2) ####



        

        adminDict = {
        "userName":admin_queryset.userName,
        "merchantsCount":merchants_count,
        "payoutGrowth":round(payoutGrowth,2),
        "payinGrowth":round(payinGrowth,2),
        "payInSuccessRatio":round(payInSuccessRatio,2),
        "payOutSuccessRatio":round(payOutSuccessRatio,2),
        "totalPayOutBalance":formatINR("{:.2f}".format(float(totalPayOutBalance))),
        "totalPayInBalance":formatINR("{:.2f}".format(float(totalPayInBalance))),
        "totalWalletBalance":formatINR("{:.2f}".format(float(totalWalletBalance))),
        "totalCurrentMonthPayoutBalance":formatINR("{:.2f}".format(float(totalCurrentMonthPayoutBalance))),
        "totalPreviousMonthPayoutBalance":formatINR("{:.2f}".format(float(totalPreviousMonthPayoutBalance))),
        "totalPreviousMonthPayinBalance":formatINR("{:.2f}".format(float(totalPreviousMonthPayinBalance))),
        "totalCurrentMonthPayinBalance":formatINR("{:.2f}".format(float(totalCurrentMonthPayinBalance))),
        # "totalPayinCommissionsAmount":formatINR("{:.2f}".format(float(payinTotalchargeAmount))),
        # "totalPayinTdsAmount":formatINR("{:.2f}".format(float(payinTotaltdsAmount))),
        # "totalPayinGstAmount":formatINR("{:.2f}".format(float(payinTotalgstAmount))),
        "totalPayoutCommissionsAmount":formatINR("{:.2f}".format(float(payoutTotalchargeAmount))),
        "totalPayoutTdsAmount":formatINR("{:.2f}".format(float(payoutTotaltdsAmount))),
        "totalPayoutGstAmount":formatINR("{:.2f}".format(float(payoutTotalgstAmount))),
        "totalPayoutAmount":formatINR("{:.2f}".format(float(totalPayoutAmount))),
        "totalPayinAmount":formatINR("{:.2f}".format(float(totalPayinAmount))),
        "todayTotalPayinAmount":formatINR("{:.2f}".format(float(todayTotalPayinAmount))),
        "todayTotalPayoutAmount":formatINR("{:.2f}".format(float(todayTotalPayoutAmount))),
        "yesterdayTotalPayinAmount":formatINR("{:.2f}".format(float(yesterdayTotalPayinAmount))),
        "yesterdayTotalPayoutAmount":formatINR("{:.2f}".format(float(yesterdayTotalPayoutAmount))),
        "cwCommissionAmount":formatINR("{:.2f}".format(float(cwCommissionAmount))),
        "pgtotalAmount":formatINR("{:.2f}".format(float(pgtotalAmount))),
        "overallTransactionGstAmountDatewise":formatINR("{:.2f}".format(float(overallTransactionGstAmountDatewise))),
        "currentMonthTotalTransactionAmount":formatINR("{:.2f}".format(float(currentMonthTotalTransactionAmount))),
        # "companyCharges":formatINR("{:.2f}".format(float(companyCharges))),
        "agentCommissionAmount":formatINR("{:.2f}".format(float(agentCommissionAmount))),
        "currentMonthcwCommissionAmount":formatINR("{:.2f}".format(float(currentMonthcwCommissionAmount))),
        "currentMonthpgtotalAmount":formatINR("{:.2f}".format(float(currentMonthpgtotalAmount))),
        "totalTransactionAmount":formatINR("{:.2f}".format(float(totalTransactionAmount))),
        "currentMonthAgentCommissionAmount":formatINR("{:.2f}".format(float(currentMonthAgentCommissionAmount))),
        "previousMonthcwCommissionAmount":formatINR("{:.2f}".format(float(previousMonthcwCommissionAmount))),
        "previousMonthpgtotalAmount":formatINR("{:.2f}".format(float(previousMonthpgtotalAmount))),
        "previousMonthTotalTransactionAmount":formatINR("{:.2f}".format(float(previousMonthTotalTransactionAmount))),
        "previousMonthAgentCommissionAmount":formatINR("{:.2f}".format(float(previousMonthAgentCommissionAmount))),
        "payoutTotalPgchargeAmount":formatINR("{:.2f}".format(float(payoutTotalPgchargeAmount))),
        "payoutTotalPggstAmount":formatINR("{:.2f}".format(float(payoutTotalPggstAmount))),
        "overallPayinPgGstAmount":formatINR("{:.2f}".format(float(overPgGstAmount))),
        "currentMonthPayoutChargesAmount":formatINR("{:.2f}".format(float(currentMonthPayoutChargesAmount))),
        "previousMonthPayoutCommissionAmount":formatINR("{:.2f}".format(float(previousMonthPayoutCommissionAmount))),
        "previousMonthPayoutCharges":formatINR("{:.2f}".format(float(previousMonthPayoutCharges))),
        "previousMonthPGCharges":formatINR("{:.2f}".format(float(previousMonthPGCharges))),
        "previousMonthoPayoutPgGstAmount":formatINR("{:.2f}".format(float(previousMonthoPayoutPgGstAmount))),
        "currentMonthPayoutCommissionAmount":formatINR("{:.2f}".format(float(currentMonthPayoutCommissionAmount))),
        "currentMonthPayoutPGCharges":formatINR("{:.2f}".format(float(currentMonthPayoutPGCharges))),
        "currentMonthPayoutPgGstAmount":formatINR("{:.2f}".format(float(currentMonthPayoutPgGstAmount))),
        "approvedMerchantsCount":approved_count,
        "rejectedMerchantsCount":rejected_count,
        "pendingMerchantsCount":pending_count,
        "totalMerchantsCount":total_merchants_count,
        "beneficiaryTransactionsCount":beneficiaryTransactionsCount,
        "beneficiaryGstAmount":formatINR("{:.2f}".format(float(beneficiaryGstAmount))),
        "beneficiaryTotalChargesAmount":formatINR("{:.2f}".format(float(beneficiaryTotalChargesAmount))),

        "beneficiaryCurrentMonthTransactionsCount":beneficiaryCurrentMonthTransactionsCount,
        "beneficiaryCurrentMonthGstAmount":formatINR("{:.2f}".format(float(beneficiaryCurrentMonthGstAmount))),
        "beneficiaryCurrentMonthTotalChargesAmount":formatINR("{:.2f}".format(float(beneficiaryCurrentMonthTotalChargesAmount))),


        "beneficiaryTransactionsCount":beneficiaryTransactionsCount,
        "beneficiaryPreviousGstAmount":formatINR("{:.2f}".format(float(beneficiaryPreviousGstAmount))),
        "beneficiaryPreviousTransactionsCount":beneficiaryPreviousTransactionsCount,
        "beneficiaryPreviousTotalChargesAmount":formatINR("{:.2f}".format(float(beneficiaryPreviousTotalChargesAmount))),
        



        "pgAdditionalChargeAmount":formatINR("{:.2f}".format(float(pgAdditionalChargeAmount))),
        "pgCurrentMonthAdditionalChargeAmount":formatINR("{:.2f}".format(float(pgCurrentMonthAdditionalChargeAmount))),
        "pgPreviousMonthAdditionalChargeAmount":formatINR("{:.2f}".format(float(pgPreviousMonthAdditionalChargeAmount))),
        "todayPayinGrowth": round(todayPayinGrowth, 2),
        "todayPayoutGrowth": round(todayPayoutGrowth, 2),


        "todayTotalPayoutSucceessRatio": round(todayTotalPayoutSucceessRatio, 2),
        "yesterdayTotalPayoutSucceessRatio": round(yesterdayTotalPayoutSucceessRatio, 2),
        "totalPayoutSucceessRatio": round(totalPayoutSucceessRatio, 2),
        "previousMonthPayoutSucceessRatio": round(previousMonthTotalPayoutSucceessRatio, 2),
        "currentMonthTotalPayoutSucceessRatio": round(currentMonthTotalPayoutSucceessRatio, 2),

        "todayTotalPayinSucceessRatio": round(todayTotalPayinSucceessRatio, 2),
        "yesterdayTotalPayinSucceessRatio": round(yesterdayTotalPayinSucceessRatio, 2),
        "totalPayinSucceessRatio": round(totalPayinSucceessRatio, 2),
        "currentMonthTotalPayinSucceessRatio": round(currentMonthTotalPayinSucceessRatio, 2),
        "previousMonthPayinSucceessRatio": round(previousMonthTotalPayinSucceessRatio, 2),
        }
        return render_template(
            "super_admin_templates/dashboard1.html",
            adminDict=adminDict,
            payInTop10MerchantsList=payInTop10MerchantsList,
            payoutsTop10MerchantsList=payoutsTop10MerchantsList,
            payoutsList=payoutsList,
            payinsList=payinsList,
            monthwisePayinGraphData=monthwisePayinGraphData,
            monthwisePayoutGraphData=monthwisePayoutGraphData
            )
    except Exception as e:
        app.logger.error(traceback.format_exc())
        return redirect(url_for('admin.admin_login'))




@admin.route("/dashboard2",methods=["POST","GET"])
@adminid_access_token_required
def dashboard2():
    try:
        if not session.get("adminId"):
            return redirect("admin_login")
        adminId = session.get("adminId")
        # if not check_latitude_and_longitude(accessToken, adminId):
        # 	return redirect("admin_login")
        adminDict = {}
        commissionsDict = {}
        payInTop10MerchantsList = []
        payoutsTop10MerchantsList = []
        payoutsList = []
        payinsList = []
        adminDict = {}
        totalWalletBalance = 0
        merchants_count = 0
        totalPayInBalance = 0
        payinTotalchargeAmount = 0
        payinTotaltdsAmount = 0
        payinTotalgstAmount = 0
        totalPayinAmount = 0
        payoutTotalchargeAmount = 0
        payoutTotaltdsAmount = 0
        payoutTotalgstAmount = 0
        totalPayoutAmount = 0
        todayTotalPayinAmount = 0
        todayTotalPayoutAmount = 0
        yesterdayTotalPayinAmount = 0
        yesterdayTotalPayoutAmount = 0
        approved_count = 0
        total_merchants_count = 0
        rejected_count = 0
        pending_count = 0
        submitted_count = 0
        payoutTotalPgchargeAmount = 0
        payoutTotalPggstAmount = 0
        totalPgPayoutAmount = 0
        currentMonthPayoutPGCharges = 0
        currentMonthPayoutCommissionAmount = 0
        currentMonthPayoutPgGstAmount = 0
        currentMonthpgtotalAmount = 0
        currentMonthPayoutChargesAmount = 0


        previousMonthPayoutCommissionAmount = 0
        previousMonthPayoutCharges = 0
        previousMonthPGCharges = 0
        previousMonthoPayoutPgGstAmount = 0

        pgAdditionalChargeAmount = 0 
        pgCurrentMonthAdditionalChargeAmount = 0
        pgPreviousMonthAdditionalChargeAmount = 0

        admin_queryset = SuperAdmin.objects(id=adminId,status__in=[1]).first()

        todayStartDateTime = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
        todayEndDateTime = todayStartDateTime.replace(hour=23, minute=59, second=59, microsecond=59)
        # print(todayStartDateTime,"((((((((todayStartDateTime))))))))")
        # print(todayEndDateTime,"((((((((todayEndDateTime))))))))")

        # Today Payin & Payout Amounts
        todayTotalPayinAmount = WalletTransactions.objects(createdOn__gte=todayStartDateTime,createdOn__lte=todayEndDateTime,creditType="Credit",status=1,userType="user").sum('amount')
        todayTotalPayoutAmount = FundTransfers.objects(createdOn__gte=todayStartDateTime,createdOn__lte=todayEndDateTime,transferType__nin=["Credit"],status=1,userType__ne='admin').sum('amount')

        # Yesterday Payin & Payout Amounts
        yesterdayStartDate = todayStartDateTime - datetime.timedelta(days=1)
        yesterdayEndDate = yesterdayStartDate.replace(hour=23, minute=59, second=59, microsecond=999999)

        # print("Yesterday Start:", yesterdayStartDate)
        # print("Yesterday End:", yesterdayEndDate)

        yesterdayTotalPayinAmount = WalletTransactions.objects(createdOn__gte=yesterdayStartDate,createdOn__lte=yesterdayEndDate,creditType="Credit",status=1,userType="user").sum('amount')
        yesterdayTotalPayoutAmount = FundTransfers.objects(createdOn__gte=yesterdayStartDate,createdOn__lte=yesterdayEndDate,transferType__nin=["Credit"],status=1,userType__ne='admin').sum('amount')


        #totalWalletBalance = Users.objects(status__in=[1]).sum('walletBalance')

        #merchants_count = Users.objects(status__in=[1]).count()


        totalPayInBalance = WalletTransactions.objects(creditType="Credit",status=1,userType="user").sum('amount')

        totalPayOutBalance = FundTransfers.objects(transferType__nin=["Credit"],status=1,userType__ne='admin').sum('amount')


        # Get the first and last day of the current month
        today = datetime.datetime.today()
        first_day_of_current_month = today.replace(day=1,hour=0, minute=0, second=0, microsecond=0)

        last_day_of_previous_month = first_day_of_current_month - datetime.timedelta(days=1)
        last_day_of_previous_month = last_day_of_previous_month.replace(hour=23, minute=59, second=59, microsecond=59)

        first_day_of_previous_month=last_day_of_previous_month.replace(day=1,hour=0, minute=0, second=0, microsecond=0)

        # Get the last day of the current month
        last_day_of_current_month = first_day_of_current_month + timedelta(days=calendar.monthrange(today.year, today.month)[1] - 1)
        last_day_of_current_month = last_day_of_current_month.replace(hour=23, minute=59, second=59, microsecond=999999)


        # Payout Current Month and Current Year
        totalCurrentMonthPayoutBalance = 0

        totalCurrentMonthPayoutBalance = FundTransfers.objects(createdOn__gte=first_day_of_current_month,createdOn__lte=today,status=1,transferType__nin=["Credit","Refund"],userType__ne='admin').sum("amount")

        totalPreviousMonthPayoutBalance = 0
        totalPreviousMonthPayoutBalance = FundTransfers.objects(createdOn__gte=first_day_of_previous_month,createdOn__lte=last_day_of_previous_month,status=1,transferType__nin=["Credit","Refund"],userType__ne='admin').sum("amount")

        # Payout Increase or Decrease Growth

        if totalPreviousMonthPayoutBalance > 0:
            payoutGrowth = (totalCurrentMonthPayoutBalance - totalPreviousMonthPayoutBalance)*100/totalPreviousMonthPayoutBalance
        else:
            payoutGrowth = 100

        # Payin Current Month and Current Year
        totalCurrentMonthPayinBalance = 0
        totalCurrentMonthPayinBalance = WalletTransactions.objects(createdOn__gte=first_day_of_current_month,createdOn__lte=today,status=1,creditType="Credit",userType="user").sum("amount")

        totalPreviousMonthPayinBalance = 0
        totalPreviousMonthPayinBalance = WalletTransactions.objects(createdOn__gte=first_day_of_previous_month,createdOn__lte=last_day_of_previous_month,status=1,creditType="Credit",userType="user").sum("amount")

        # Payout Increase or Decrease Growth

        if totalPreviousMonthPayinBalance > 0:
            payinGrowth = (totalCurrentMonthPayinBalance - totalPreviousMonthPayinBalance)*100/totalPreviousMonthPayinBalance
        else:
            payinGrowth = 100
    
        payOutSuccessRatio=0
        payoutsList = []
        payoutDataPipeline = [
            {
                "$match": {
                        "transferType": {"$nin": ["Credit", "Refund"]},
                        # "transactionAPIId": str(each_payout.id),
                        "userType": {"$ne": 'admin'}
                    }
                },
         # Step 1: Group by apiId and status in `funds`
            {
                "$group": {
                    "_id": {
                        "apiId": "$transactionAPIId",
                        "status": "$status"
                    },
                    "count": { "$sum": 1 }
                }
            },

            # Step 2: Regroup by apiId to get total and success counts
            {
                "$group": {
                    "_id": "$_id.apiId",
                    "totalCount": { "$sum": "$count" },
                    "successCount": {
                        "$sum": {
                            "$cond": [
                                { "$eq": ["$_id.status", 1] }, "$count", 0
                            ]
                        }
                    }
                }
            },

            # Step 3: Add successRatio field
            {
                "$project": {
                    "totalCount": 1,
                    "successCount": 1,
                    "successRatio": {
                        "$cond": [
                            { "$gt": ["$totalCount", 0] },
                            {"$round" :[{"$multiply":[{ "$divide": ["$successCount", "$totalCount"] },100]},
                                    2
                                ]},
                            0
                        ]
                    }
                }
            },

            # Step 4: Lookup latest balance from `balances` collection
            {
                "$lookup": {
                    "from": "admin_payout_balances",
                    "let": { "apiId": "$_id" },
                    "pipeline": [
                        { "$match": { "$expr": { "$eq": ["$apiTransactionId", "$$apiId"] } } },
                        { "$sort": { "createdOn": -1 } },
                        { "$limit": 1 },
                        { "$project": { "currentBalance": 1, "_id": 0 } }
                    ],
                    "as": "latestBalance"
                }
            },
            # Step 5: Lookup API name from `apis`
            {
                "$lookup": {
                    "from": "transaction_a_p_i",
                    "localField": "_id",
                    "foreignField": "_id",
                    "as": "apiInfo"
                }
            },

            # Step 5: Optional — project `latest_amount` safely from the joined balance
            {
                "$project": {
                    "apiId": "$_id",
                    "apiName": { "$arrayElemAt": ["$apiInfo.apiName", 0] },
                    "successRatio": 1,
                    "currentBalance": { "$arrayElemAt": ["$latestBalance.currentBalance", 0] }
                }
            }
        ]
        
        payoutsList = list(FundTransfers.objects.aggregate(*payoutDataPipeline))
        # print("payoutsList",payoutsList)

        # Payin Balance
        payinsList = []
        payInSuccessRatio=0
            ############################################################ payin success ratio pipeline ############################################################
        payinDataPipeline = [
                {
                    "$match": {
                            "creditType": {"$in": ["Credit"]},
                            "userType": {"$eq": 'user'},
                            "status": { "$in": [0, 1] }
                        }
                    },
            # Step 1: Group by apiId and status in `funds`
                {
                "$group": {
                    "_id": "$paymentGatewayId",                 
                    "totalCount": { "$sum": 1 },     
                    "successCount": {
                    "$sum": {
                        "$cond": [
                        { "$eq": ["$status", 1] },  
                        1,                          
                        0                           
                        ]
                    }
                    },
                    "totalAmount": {
                    "$sum": {
                        "$cond": [
                        { "$eq": ["$status", 1] },  
                        "$amount",                  
                        0                           
                        ]
                    }
                    }
                }
                },

                # Step 2: Add successRatio field
                {
                    "$project": {
                        "totalCount": 1,
                        "successCount": 1,
                        "totalAmount": 1,
                        "successRatio": {
                            "$cond": [
                                { "$gt": ["$totalCount", 0] },
                                {"$round" :[{"$multiply":[{ "$divide": ["$successCount", "$totalCount"] },100]},
                                        2
                                    ]},
                                0
                            ]
                        }
                    }
                },
                # Step 5: Lookup API name from `apis`
                {
                    "$lookup": {
                        "from": "transaction_a_p_i",
                        "localField": "_id",
                        "foreignField": "_id",
                        "as": "apiInfo"
                    }
                },
                # Step 5: Optional — project `latest_amount` safely from the joined balance
                {
                    "$project": {
                        "apiId": "$_id",
                        "apiName": { "$arrayElemAt": ["$apiInfo.apiName", 0] },
                        "successRatio": 1,
                        "currentBalance": "$totalAmount"
                    }
                }
            ]

        payinsList = list(WalletTransactions.objects.aggregate(*payinDataPipeline)) ### payin Volumes 
        # print("payinsList",payinsList)
            ############################################################ payin success ratio pipeline ############################################################
        
        
        # Filter for successful PayIn transactions for the current month
        pipeline = [
            {"$lookup": {
                "from": "users",
                "localField": "userId",
                "foreignField": "_id",
                "as": "userDetails"
            }},
            {"$match": {
                "creditType": "Credit",
                "status": 1,
                "userType":"user",
                "createdOn": {
                    "$gte": first_day_of_current_month,
                    "$lte": last_day_of_current_month
                }
            }},
            {"$unwind": "$userDetails"},  # Unwind the array returned by $lookup
            {"$group": {"_id": "$userId", "totalAmount": {"$sum": "$amount"}}},
            {"$sort": {"totalAmount": -1}},
            {"$limit": 10}
        ]

        # Execute the aggregation pipeline
        payins_top_10_merchants = list(WalletTransactions.objects.aggregate(*pipeline))
        print("payins_top_10_merchants",payins_top_10_merchants)
        payInTop10MerchantsList = []

        for each_merchant in payins_top_10_merchants:
            merchant_queryset = Users.objects(id=each_merchant.get("_id")).first()
            if merchant_queryset:
                first_chars = re.findall(r'\b\w', merchant_queryset.fullName)

                imageString = ''.join(first_chars)

                payInDict = {
                "merchantId":str(merchant_queryset.id),
                "merchantName":merchant_queryset.fullName,
                "phoneNumber":merchant_queryset.phoneNumber,
                "imageString":imageString,
                "totalMerchantAmount":formatINR("{:.2f}".format(float(each_merchant.get("totalAmount"))))
                }
                payInTop10MerchantsList.append(payInDict)

        # Filter for successful Payout transactions for the current month
        payout_pipeline = [
            {"$match": {
                "transferType": "Debit",
                "userType": {"$ne":"admin"},
                "status": 1,
                "createdOn": {
                    "$gte": first_day_of_current_month,
                    "$lte": last_day_of_current_month
                }
            }},  # Filtering
            {"$group": {"_id": "$userId", "totalAmount": {"$sum": "$amount"}}},  # Grouping and summing amounts
            {"$sort": {"totalAmount": -1}},  # Sorting by total amount in descending order
            {"$limit": 10}  # Limiting to top 10
        ]

        # Execute the aggregation payout_pipeline
        payouts_top_10_merchants = list(FundTransfers.objects.aggregate(*payout_pipeline))
        payoutsTop10MerchantsList = []
        for each_payout_merchant in payouts_top_10_merchants:
            payout_merchant_queryset = Users.objects(id=each_payout_merchant.get("_id")).first()
            if payout_merchant_queryset:
                first_chars = re.findall(r'\b\w', payout_merchant_queryset.fullName)

                imageString = ''.join(first_chars)

                payOutDict = {
                "merchantId":str(payout_merchant_queryset.id),
                "merchantName":payout_merchant_queryset.fullName,
                "phoneNumber":payout_merchant_queryset.phoneNumber,
                "imageString":imageString,
                "totalMerchantAmount":formatINR("{:.2f}".format(float(each_payout_merchant.get("totalAmount"))))
                }
                payoutsTop10MerchantsList.append(payOutDict)

        # Commissions For Payin And Payout Calculations
        # payinTotalchargeAmount = WalletTransactions.objects(status=1).sum('commissionCharges.chargeAmount')
        # payinTotaltdsAmount = WalletTransactions.objects(status=1).sum('commissionCharges.tdsAmount')
        # payinTotalgstAmount = WalletTransactions.objects(status=1).sum('commissionCharges.gstAmount')

        # Commissions For Payin And Payout Calculations

        # comm_pipeline_payin = [
        #         {
        #             '$project': {
        #                 'chargeAmount': '$commissionCharges.chargeAmount',
        #                 'tdsAmount': '$commissionCharges.tdsAmount',
        #                 'gstAmount': '$commissionCharges.gstAmount'
        #             }
        #         },
        #         {
        #             '$group': {
        #                 '_id': None,
        #                 'payinTotalchargeAmount': {'$sum': '$chargeAmount'},
        #                 'payinTotaltdsAmount': {'$sum': '$tdsAmount'},
        #                 'payinTotalgstAmount': {'$sum': '$gstAmount'}
        #             }
        #         }
        #     ]
        # result = WalletTransactions.objects(status=1).aggregate(comm_pipeline_payin)

        # if result:
        #     payinTotalchargeAmount = result[0]['payinTotalchargeAmount']
        #     payinTotaltdsAmount = result[0]['payinTotaltdsAmount']
        #     payinTotalgstAmount = result[0]['payinTotalgstAmount']

        # totalPayinAmount  = payinTotalchargeAmount + payinTotaltdsAmount + payinTotalgstAmount

        ################################## Payout ############################################################

        pipeline = [
            {"$match": {"status": 1,"fundTransferType":{"$in":["Instant","bulk"]}}},  # Match documents with status=1
            {
                "$group": {
                    "_id": None,  # We don't need to group by any field
                    "totalChargeAmount": {"$sum": "$commissionCharges.chargeAmount"},
                    "totalGstAmount": {"$sum": "$commissionCharges.gstAmount"},
                    "totalPgChargeAmount": {"$sum": "$aggregatorCharges.chargeAmount"},
                    "totalPgGstAmount": {"$sum": "$aggregatorCharges.gstAmount"}
                }
            }
        ]

        result = list(FundTransfers.objects.aggregate(*pipeline))

        payoutTotalchargeAmount = result[0]["totalChargeAmount"]
        payoutTotalgstAmount = result[0]["totalGstAmount"]
        payoutTotalPgchargeAmount = result[0]["totalPgChargeAmount"]
        payoutTotalPggstAmount = result[0]["totalPgGstAmount"]


        # payoutTotalchargeAmount = FundTransfers.objects(fundTransferType__in=["Instant","bulk"],status=1).sum('commissionCharges.chargeAmount')
        # payoutTotaltdsAmount = FundTransfers.objects(status=1).sum('commissionCharges.tdsAmount')
        # payoutTotalgstAmount = FundTransfers.objects(fundTransferType__in=["Instant","bulk"],status=1).sum('commissionCharges.gstAmount')

        totalPayoutAmount  = payoutTotalchargeAmount + payoutTotaltdsAmount + payoutTotalgstAmount


        # payoutTotalPgchargeAmount = FundTransfers.objects(fundTransferType__in=["Instant","bulk"],status=1).sum('aggregatorCharges.chargeAmount')
        # payoutTotalPggstAmount = FundTransfers.objects(fundTransferType__in=["Instant","bulk"],status=1).sum('aggregatorCharges.gstAmount')
        totalPgPayoutAmount  = payoutTotalPgchargeAmount + payoutTotalPggstAmount

        pgAdditionalChargeAmount = PgSettlements.objects(status=1).sum('additionalChargeAmount')

        ######################################################################################################


        ####################################          Bene Charges    #################################################################
        beneficiaryTypeQueryset =  FundTransfers.objects(fundTransferType__in=["beneficiary"],status=1).all()
        beneficiaryTotalChargesAmount = FundTransfers.objects(fundTransferType__in=["beneficiary"],status=1).sum('grandTotal')
        beneficiaryGstAmount = FundTransfers.objects(fundTransferType__in=["beneficiary"],status=1).sum('commissionCharges.gstAmount')
        beneficiaryTransactionsCount = FundTransfers.objects(fundTransferType__in=["beneficiary"],status=1).count()

        ######################################################################################################


        #####################################          Bene Currrent Charges    #################################################################
        beneficiaryCurrentMonthTypeQueryset =  FundTransfers.objects(fundTransferType__in=["beneficiary"],createdOn__gte=first_day_of_current_month,createdOn__lte=today,status=1).all()
        beneficiaryCurrentMonthTotalChargesAmount = FundTransfers.objects(fundTransferType__in=["beneficiary"],createdOn__gte=first_day_of_current_month,createdOn__lte=today,status=1).sum('grandTotal')
        beneficiaryCurrentMonthGstAmount = FundTransfers.objects(fundTransferType__in=["beneficiary"],createdOn__gte=first_day_of_current_month,createdOn__lte=today,status=1).sum('commissionCharges.gstAmount')
        beneficiaryCurrentMonthTransactionsCount = FundTransfers.objects(fundTransferType__in=["beneficiary"],createdOn__gte=first_day_of_current_month,createdOn__lte=today,status=1).count()

        ######################################################################################################

        
        #####################################          Bene Previous Charges    #################################################################
        beneficiaryPreviousTypeQueryset =  FundTransfers.objects(fundTransferType__in=["beneficiary"],createdOn__gte=first_day_of_previous_month,createdOn__lte=last_day_of_previous_month,status=1).all()
        beneficiaryPreviousTotalChargesAmount = FundTransfers.objects(fundTransferType__in=["beneficiary"],createdOn__gte=first_day_of_previous_month,createdOn__lte=last_day_of_previous_month,status=1).sum('grandTotal')
        beneficiaryPreviousGstAmount = FundTransfers.objects(fundTransferType__in=["beneficiary"],createdOn__gte=first_day_of_previous_month,createdOn__lte=last_day_of_previous_month,status=1).sum('commissionCharges.gstAmount')
        beneficiaryPreviousTransactionsCount = FundTransfers.objects(fundTransferType__in=["beneficiary"],createdOn__gte=first_day_of_previous_month,createdOn__lte=last_day_of_previous_month,status=1).count()

        ######################################################################################################



        #################################################### Bene Data Pipeline###############################################
        # beneficiaryTotalChargesAmount = 0
        # beneficiaryGstAmount = 0
        # beneficiaryTransactionsCount = 0
        # beneficiaryCurrentMonthTotalChargesAmount = 0
        # beneficiaryCurrentMonthGstAmount = 0
        # beneficiaryCurrentMonthTransactionsCount = 0
        # beneficiaryPreviousTotalChargesAmount = 0
        # beneficiaryPreviousGstAmount = 0
        # beneficiaryPreviousTransactionsCount = 0

        # beneficiary_data_pipeline = [
        #     # Step 1: Filter documents by beneficiary type and status
        #     {
        #         "$match": {
        #             "fundTransferType": "beneficiary",  # Filter by 'beneficiary' type
        #             "status": 1               # Filter by 'status' = 1 (active beneficiaries)
        #         }
        #     },
            
        #     # Step 2: Group by date range and perform aggregation (total charges, GST, and transaction count)
        #     {
        #         "$group": {
        #             "_id": None,  # No grouping (will aggregate for all records)
        #             "totalCharges": { "$sum": "$grandTotal" },  # Sum of grandTotal (total charges)
        #             "totalGst": { "$sum": "$commissionCharges.gstAmount" },           # Sum of commissionCharges.gstAmount (GST)
        #             "totalTransactions": { "$sum": 1 }          # Count of total transactions
        #         }
        #     },

        #     # Optional: Add calculations for current month and previous month using date filters
        #     # Current month filter (from first day to today)
        #     {
        #         "$facet": {
        #             "total": [
        #                 {
        #                     "$match": {
        #                         "fundTransferType": "beneficiary",
        #                         "status": 1
        #                     }
        #                 },
        #                 {
        #                     "$group": {
        #                         "_id": None,
        #                         "totalCharges": { "$sum": "$grandTotal" },
        #                         "totalGst": { "$sum": "$commissionCharges.gstAmount" },
        #                         "totalTransactions": { "$sum": 1 }
        #                     }
        #                 }
        #             ],
        #             "currentMonth": [
        #                 {
        #                     "$match": {
        #                         "fundTransferType": "beneficiary",
        #                         "status": 1,
        #                         "createdOn": { "$gte": first_day_of_current_month, "$lte": today }  # Current month range
        #                     }
        #                 },
        #                 {
        #                     "$group": {
        #                         "_id": None,
        #                         "totalCharges": { "$sum": "$grandTotal" },
        #                         "totalGst": { "$sum": "$commissionCharges.gstAmount" },
        #                         "totalTransactions": { "$sum": 1 }
        #                     }
        #                 }
        #             ],
        #             "previousMonth": [
        #                 {
        #                     "$match": {
        #                         "fundTransferType": "beneficiary",
        #                         "status": 1,
        #                         "createdOn": { "$gte": first_day_of_previous_month, "$lte": last_day_of_previous_month }  # Previous month range
        #                     }
        #                 },
        #                 {
        #                     "$group": {
        #                         "_id": None,
        #                         "totalCharges": { "$sum": "$grandTotal" },
        #                         "totalGst": { "$sum": "$commissionCharges.gstAmount" },
        #                         "totalTransactions": { "$sum": 1 }
        #                     }
        #                 }
        #             ]
        #         }
        #     },

        #     # Step 3: Project the results to make them more readable
        #     {
        #     "$project": {
        #         "totalCharges": { "$ifNull": [{ "$arrayElemAt": ["$total.totalCharges", 0] }, 0] },
        #         "totalGst": { "$ifNull": [{ "$arrayElemAt": ["$total.totalGst", 0] }, 0] },
        #         "totalTransactions": { "$ifNull": [{ "$arrayElemAt": ["$total.totalTransactions", 0] }, 0] },
        #         "currentMonthTotalCharges": { "$ifNull": [{ "$arrayElemAt": ["$currentMonth.totalCharges", 0] }, 0] },
        #         "currentMonthTotalGst": { "$ifNull": [{ "$arrayElemAt": ["$currentMonth.totalGst", 0] }, 0] },
        #         "currentMonthTotalTransactions": { "$ifNull": [{ "$arrayElemAt": ["$currentMonth.totalTransactions", 0] }, 0] },
        #         "previousMonthTotalCharges": { "$ifNull": [{ "$arrayElemAt": ["$previousMonth.totalCharges", 0] }, 0] },
        #         "previousMonthTotalGst": { "$ifNull": [{ "$arrayElemAt": ["$previousMonth.totalGst", 0] }, 0] },
        #         "previousMonthTotalTransactions": { "$ifNull": [{ "$arrayElemAt": ["$previousMonth.totalTransactions", 0] }, 0] }
        #     }
        #     }
        # ]

        # # Run the aggregation
        # beneficiary_data_aggregator_results = list(FundTransfers.objects.aggregate(*beneficiary_data_pipeline))
        # print("((((((((beneficiary_data_aggregator_results))))))))",beneficiary_data_aggregator_results )
        
        # # Extract the results
        # for each_beneficiary_data_result in beneficiary_data_aggregator_results:
        #     beneficiaryTotalChargesAmount = each_beneficiary_data_result['totalCharges']
        #     beneficiaryGstAmount = each_beneficiary_data_result['totalGst']
        #     beneficiaryTransactionsCount = each_beneficiary_data_result['totalTransactions']
        #     beneficiaryCurrentMonthTotalChargesAmount = each_beneficiary_data_result['currentMonthTotalCharges']
        #     beneficiaryCurrentMonthGstAmount = each_beneficiary_data_result['currentMonthTotalGst']
        #     beneficiaryCurrentMonthTransactionsCount = each_beneficiary_data_result['currentMonthTotalTransactions']
        #     beneficiaryPreviousTotalChargesAmount = each_beneficiary_data_result['previousMonthTotalCharges']
        #     beneficiaryPreviousGstAmount = each_beneficiary_data_result['previousMonthTotalGst']
        #     beneficiaryPreviousTransactionsCount = each_beneficiary_data_result['previousMonthTotalTransactions']


        ######################################################################################################


        ################################## Current Month For Payout Commissions ############################################################

        # current_month_payout_queryset = FundTransfers.objects(fundTransferType__in=["Instant","bulk"],createdOn__gte=first_day_of_current_month,createdOn__lte=today,status=1)
        # currentMonthPayoutCommissionAmount = current_month_payout_queryset.filter().sum('aggregatorCharges.commissionAmount') #
        # currentMonthPayoutCommissionAmount=round(currentMonthPayoutCommissionAmount,2) ####1

        # currentMonthPayoutChargesAmount = current_month_payout_queryset.filter().sum('commissionCharges.chargeAmount')
        # currentMonthPayoutChargesAmount=round(currentMonthPayoutChargesAmount,2) ####2

        # currentMonthPayoutPGCharges = current_month_payout_queryset.filter().sum('aggregatorCharges.chargeAmount')3
        # currentMonthPayoutPgGstAmount = current_month_payout_queryset.filter().sum('aggregatorCharges.gstAmount')4
        # currentMonthPayoutPgGstAmount=round(float(currentMonthPayoutPgGstAmount),2) 
        # currentMonthpgtotalAmount = round(float(currentMonthPayoutPGCharges + currentMonthPayoutPgGstAmount),2)   #### 5



        ##########pipeline
        current_month_payout_comm_pipeline = [
            {"$match": {"status": 1,"fundTransferType":{"$in":["Instant","bulk"]},
            'status': 1,
            'createdOn': {
                        "$gte": first_day_of_current_month,
                        "$lte": today,
                    }
            }},  # Match documents with status=1
            
            {
                "$group": {
                    "_id": None,  # We don't need to group by any field
                    "currentMonthPayoutCommissionAmount": {"$sum": "$commissionCharges.commissionAmount"},
                    "currentMonthPayoutChargesAmount": {"$sum": "$commissionCharges.chargeAmount"},
                    "currentMonthPayoutPGCharges": {"$sum": "$aggregatorCharges.chargeAmount"},
                    "currentMonthPayoutPgGstAmount": {"$sum": "$aggregatorCharges.gstAmount"}
                }
            }
        ]
        current_month_payout_commissions_result = list(FundTransfers.objects.aggregate(current_month_payout_comm_pipeline))
        # print("current_month_payout_commissions_result",current_month_payout_commissions_result)

        if current_month_payout_commissions_result:
            currentMonthPayoutCommissionAmount= round(float(current_month_payout_commissions_result[0]["currentMonthPayoutCommissionAmount"]),2)
            currentMonthPayoutChargesAmount= round(float(current_month_payout_commissions_result[0]["currentMonthPayoutChargesAmount"]),2)
            currentMonthPayoutPGCharges= round(float(current_month_payout_commissions_result[0]["currentMonthPayoutPGCharges"]),2)
            currentMonthPayoutPgGstAmount= round(float(current_month_payout_commissions_result[0]["currentMonthPayoutPgGstAmount"]),2)
            currentMonthpgtotalAmount = round(float(currentMonthPayoutPGCharges + currentMonthPayoutPgGstAmount),2) 


        pgCurrentMonthAdditionalChargeAmount = PgSettlements.objects(createdOn__gte=first_day_of_current_month,createdOn__lte=today,status=1).sum('additionalChargeAmount')





        ########################################################################################################################################

        ############################################################### Previous Month For Payout Commissions ####################################################################
        

        # payouts_all_queryset = FundTransfers.objects(createdOn__gte=first_day_of_previous_month,createdOn__lte=last_day_of_previous_month,status=1)
        # previous_month_payout_queryset = payouts_all_queryset.filter(fundTransferType__in=["Instant","bulk"])
        # previousMonthPayoutCommissionAmount = previous_month_payout_queryset.filter().sum('commissionCharges.commissionAmount')
        # previousMonthPayoutCommissionAmount=round(previousMonthPayoutCommissionAmount,2) ####
        # previousMonthPayoutCharges = previous_month_payout_queryset.filter().sum('commissionCharges.chargeAmount')

        # previousMonthPGCharges = previous_month_payout_queryset.filter().sum('aggregatorCharges.chargeAmount')
        # previousMonthoPayoutPgGstAmount = previous_month_payout_queryset.filter().sum('aggregatorCharges.gstAmount')
        # previousMonthoPayoutPgGstAmount=round(float(previousMonthoPayoutPgGstAmount),2)


        ##########pipeline
        previous_month_payout_comm_pipeline = [
            {"$match": {"status": 1,"fundTransferType":{"$in":["Instant","bulk"]},
            'status': 1,
            'createdOn': {
                        "$gte": first_day_of_previous_month,
                        "$lte": last_day_of_previous_month,
                    }
            }},  # Match documents with status=1
            
            {
                "$group": {
                    "_id": None,  # We don't need to group by any field
                    "previousMonthPayoutCommissionAmount": {"$sum": "$commissionCharges.commissionAmount"},
                    "previousMonthPayoutCharges": {"$sum": "$commissionCharges.chargeAmount"},
                    "previousMonthPGCharges": {"$sum": "$aggregatorCharges.chargeAmount"},
                    "previousMonthoPayoutPgGstAmount": {"$sum": "$aggregatorCharges.gstAmount"}
                }
            }
        ]
        previous_month_payout_commissions_result = list(FundTransfers.objects.aggregate(previous_month_payout_comm_pipeline))
        # print("previous_month_payout_commissions_result",previous_month_payout_commissions_result)

        if previous_month_payout_commissions_result:
            previousMonthPayoutCommissionAmount= round(float(previous_month_payout_commissions_result[0]["previousMonthPayoutCommissionAmount"]),2)
            previousMonthPayoutCharges= round(float(previous_month_payout_commissions_result[0]["previousMonthPayoutCharges"]),2)
            previousMonthPGCharges= round(float(previous_month_payout_commissions_result[0]["previousMonthPGCharges"]),2)
            previousMonthoPayoutPgGstAmount= round(float(previous_month_payout_commissions_result[0]["previousMonthoPayoutPgGstAmount"]),2)


        pgPreviousMonthAdditionalChargeAmount = PgSettlements.objects(createdOn__gte=first_day_of_previous_month,createdOn__lte=last_day_of_previous_month,status=1).sum('additionalChargeAmount')
        ##########################################################################################################################################################################

        
        total_merchants_count = Users.objects(status__nin=[2,6]).count()

        users_kyc_queryset = UserKYC.objects(status__in=[0,1]).order_by("-id")
        for each_user_kyc in users_kyc_queryset:
            kycStatusList = []
            kycStatusList = [
            each_user_kyc.panStatus,
            each_user_kyc.aadharStatus,
            each_user_kyc.bankStatus,
            each_user_kyc.videoVerificationStatus,
            each_user_kyc.agreementVerificationStatus
            ]
            if each_user_kyc.userId.entityTypeId!=None and each_user_kyc.userId.entityTypeId.isIndividual==False:
                kycStatusList.append(each_user_kyc.shopVideoStatus)
                kycStatusList.append(each_user_kyc.businessStatus)
                if each_user_kyc.documentsList==[]:
                    kycStatusList.append('Pending')
                else:
                    for each_document in each_user_kyc.documentsList:
                        kycStatusList.append(each_document.get('documentStatus'))

                if each_user_kyc.shopImagesList==[]:
                    kycStatusList.append('Pending')
                else:
                    for each_simg in each_user_kyc.shopImagesList:
                        kycStatusList.append(each_simg.get('shopImageStatus'))

            if "Rejected" in kycStatusList:
                rejected_count += 1
            elif "Pending" in kycStatusList or "" in kycStatusList or  None in kycStatusList: ########## new code for count adding "" or none as pending
                pending_count += 1
            elif "Submitted" in kycStatusList:
                submitted_count += 1
            else:
                approved_count += 1

        # print(rejected_count,"(((((((((((rejected_count)))))))))))")
        # print(pending_count,"(((((((((((pending_count)))))))))))")
        # print(submitted_count,"(((((((((((submitted_count)))))))))))")
        # print(approved_count,"(((((((((((approved_count)))))))))))")
        # rejected_count = rejected_count
        # pending_count = pending_count
        # submitted_count=submitted_count
        approved_count=approved_count
        overPGCharges= 0
        overallTransactionChargesDatewise=0
        overPgGstAmount=0
        overallTransactionChargesDatewise=0
        overallTransactionGstAmountDatewise=0
        
        cwCommissionAmount=0 ####
        pgtotalAmount=0  ####
        totalTransactionAmount=0  ####
        agentCommissionAmount=0  ####

        currentMonthcwCommissionAmount = 0 
        currentMonthpgtotalAmount=0
        currentMonthTotalTransactionAmount = 0
        currentMonthAgentCommissionAmount = 0
        
        previousMonthcwCommissionAmount = 0 
        previousMonthpgtotalAmount=0
        previousMonthTotalTransactionAmount = 0
        previousMonthAgentCommissionAmount = 0

        ####### Overall #######
        transferType_query_val = "Credit"
        status_query_val = 1
        cw_commission_pipeline = pipeline = [
            {
                '$match': {
                    'transferType': transferType_query_val,  # Match documents with the specified type
                    'status': status_query_val,  # Match documents with the specified status
                }
            },
            {
                '$group': {
                    '_id': None,  # Group everything into one result
                    'cwCommissionAmount': {'$sum': '$commissionAmount'},  # Sum the field 'your_field'
                    'overPGCharges': {'$sum': '$aggregatorCommissionAmount'}, ## not in html
                    'overPgGstAmount': {'$sum': '$aggregatorCommissionCharges.gstAmount'},
                    'overallTransactionChargesDatewise': {'$sum': '$transactionCommissionCharges.chargeAmount'}, ## not in html## not in html
                    'overallTransactionGstAmountDatewise': {'$sum': '$transactionCommissionCharges.gstAmount'},
                }
            },
            {
            '$project': {
                'cwCommissionAmount': 1,
                'overPgGstAmount': 1,
                'overallTransactionGstAmountDatewise': 1,
                'pgtotalAmount': {'$add': ['$overPGCharges', '$overPgGstAmount']},  # Add the two sums together
                'totalTransactionAmount': {'$add': ['$overallTransactionChargesDatewise', '$overallTransactionGstAmountDatewise']}  # Add the two sums together
            }
            }
        ]

        over_all_cw_commission_result = list(CompanyCommissions.objects.aggregate(cw_commission_pipeline))
        # print("over_all_cw_commission_result",over_all_cw_commission_result)

        if over_all_cw_commission_result:
            cwCommissionAmount= round(float(over_all_cw_commission_result[0]["cwCommissionAmount"]),2)
            overPgGstAmount= round(float(over_all_cw_commission_result[0]["overPgGstAmount"]),2)
            overallTransactionGstAmountDatewise= round(float(over_all_cw_commission_result[0]["overallTransactionGstAmountDatewise"]),2)
            pgtotalAmount= round(float(over_all_cw_commission_result[0]["pgtotalAmount"]),2)
            totalTransactionAmount= round(float(over_all_cw_commission_result[0]["totalTransactionAmount"]),2)


        agentCommissionAmount = UserCommissions.objects(status=1).sum('parrentCommissionAmount')
        agentCommissionAmount = round(float(agentCommissionAmount),2) ####


        

        ####### Current Month #######
        current_month_cw_commission_pipeline = pipeline = [
            {
                '$match': {
                    'transferType': transferType_query_val,  # Match documents with the specified type
                    'status': status_query_val,  # Match documents with the specified status
                    'createdOn': {
                        "$gte": first_day_of_current_month,
                        "$lte": today,
                    }
                }
            },
            {
                '$group': {
                    '_id': None,  # Group everything into one result
                    'currentMonthcwCommissionAmount': {'$sum': '$commissionAmount'},  # Sum the field 'your_field'
                    'currentMonthoverPGCharges': {'$sum': '$aggregatorCommissionAmount'}, ## not in html
                    'currentMonthoverPgGstAmount': {'$sum': '$aggregatorCommissionCharges.gstAmount'},
                    'currentMonthOverallTransactionChargesDatewise': {'$sum': '$transactionCommissionCharges.chargeAmount'}, ## not in html## not in html
                    'currentMonthOverallTransactionGstAmountDatewise': {'$sum': '$transactionCommissionCharges.gstAmount'},
                }
            },
            {
            '$project': {
                'currentMonthcwCommissionAmount': 1,
                'currentMonthoverPgGstAmount': 1,
                'currentMonthOverallTransactionGstAmountDatewise': 1,
                'currentMonthpgtotalAmount': {'$add': ['$currentMonthoverPGCharges', '$currentMonthoverPgGstAmount']},  # Add the two sums together
                'currentMonthTotalTransactionAmount': {'$add': ['$currentMonthOverallTransactionChargesDatewise', '$currentMonthOverallTransactionGstAmountDatewise']}  # Add the two sums together
            }
            }
        ]

        current_month_over_all_cw_commission_result = list(CompanyCommissions.objects.aggregate(current_month_cw_commission_pipeline))
        # print("current_month_over_all_cw_commission_result",current_month_over_all_cw_commission_result)

        if current_month_over_all_cw_commission_result:
            currentMonthcwCommissionAmount= round(float(current_month_over_all_cw_commission_result[0]["currentMonthcwCommissionAmount"]),2)
            currentMonthoverPgGstAmount= round(float(current_month_over_all_cw_commission_result[0]["currentMonthoverPgGstAmount"]),2)
            currentMonthOverallTransactionGstAmountDatewise= round(float(current_month_over_all_cw_commission_result[0]["currentMonthOverallTransactionGstAmountDatewise"]),2)
            currentMonthpgtotalAmount= round(float(current_month_over_all_cw_commission_result[0]["currentMonthpgtotalAmount"]),2)
            currentMonthTotalTransactionAmount= round(float(current_month_over_all_cw_commission_result[0]["currentMonthTotalTransactionAmount"]),2)


        currentMonthAgentCommissionAmount = UserCommissions.objects(createdOn__gte=first_day_of_current_month,createdOn__lte=today,status=1).sum('parrentCommissionAmount')
        currentMonthAgentCommissionAmount = round(float(currentMonthAgentCommissionAmount),2) ####



        ####### Previous Month #######
        previous_month_cw_commission_pipeline  = [
            {
                '$match': {
                    'transferType': transferType_query_val,  # Match documents with the specified type
                    'status': status_query_val,  # Match documents with the specified status
                    'createdOn': {
                        "$gte": first_day_of_previous_month,
                        "$lte": last_day_of_previous_month,
                    }
                }
            },
            {
                '$group': {
                    '_id': None,  # Group everything into one result
                    'previousMonthcwCommissionAmount': {'$sum': '$commissionAmount'},  # Sum the field 'your_field'
                    'previousMonthoverPGCharges': {'$sum': '$aggregatorCommissionAmount'}, ## not in html
                    'previousMonthoverPgGstAmount': {'$sum': '$aggregatorCommissionCharges.gstAmount'},
                    'previousMonthOverallTransactionChargesDatewise': {'$sum': '$transactionCommissionCharges.chargeAmount'}, ## not in html## not in html
                    'previousMonthOverallTransactionGstAmountDatewise': {'$sum': '$transactionCommissionCharges.gstAmount'},
                }
            },
            {
            '$project': {
                'previousMonthcwCommissionAmount': 1,
                'previousMonthoverPgGstAmount': 1,
                'previousMonthOverallTransactionGstAmountDatewise': 1,
                'previousMonthpgtotalAmount': {'$add': ['$previousMonthoverPGCharges', '$previousMonthoverPgGstAmount']},  # Add the two sums together
                'previousMonthTotalTransactionAmount': {'$add': ['$previousMonthOverallTransactionChargesDatewise', '$previousMonthOverallTransactionGstAmountDatewise']}  # Add the two sums together
            }
            }
        ]

        previous_month_over_all_cw_commission_result = list(CompanyCommissions.objects.aggregate(previous_month_cw_commission_pipeline))
        # print("previous_month_over_all_cw_commission_result",previous_month_over_all_cw_commission_result)

        if previous_month_over_all_cw_commission_result:
            previousMonthcwCommissionAmount= round(float(previous_month_over_all_cw_commission_result[0]["previousMonthcwCommissionAmount"]),2)
            previousMonthoverPgGstAmount= round(float(previous_month_over_all_cw_commission_result[0]["previousMonthoverPgGstAmount"]),2)
            previousMonthOverallTransactionGstAmountDatewise= round(float(previous_month_over_all_cw_commission_result[0]["previousMonthOverallTransactionGstAmountDatewise"]),2)
            previousMonthpgtotalAmount= round(float(previous_month_over_all_cw_commission_result[0]["previousMonthpgtotalAmount"]),2)
            previousMonthTotalTransactionAmount= round(float(previous_month_over_all_cw_commission_result[0]["previousMonthTotalTransactionAmount"]),2)

        previousMonthAgentCommissionAmount = UserCommissions.objects(createdOn__gte=first_day_of_previous_month,createdOn__lte=last_day_of_previous_month,status=1).sum('parrentCommissionAmount')
        previousMonthAgentCommissionAmount = round(float(previousMonthAgentCommissionAmount),2) ####



        

        adminDict = {
        "userName":admin_queryset.userName,
        "merchantsCount":merchants_count,
        "payoutGrowth":round(payoutGrowth,2),
        "payinGrowth":round(payinGrowth,2),
        "payInSuccessRatio":round(payInSuccessRatio,2),
        "payOutSuccessRatio":round(payOutSuccessRatio,2),
        "totalPayOutBalance":formatINR("{:.2f}".format(float(totalPayOutBalance))),
        "totalPayInBalance":formatINR("{:.2f}".format(float(totalPayInBalance))),
        "totalWalletBalance":formatINR("{:.2f}".format(float(totalWalletBalance))),
        "totalCurrentMonthPayoutBalance":formatINR("{:.2f}".format(float(totalCurrentMonthPayoutBalance))),
        "totalPreviousMonthPayoutBalance":formatINR("{:.2f}".format(float(totalPreviousMonthPayoutBalance))),
        "totalPreviousMonthPayinBalance":formatINR("{:.2f}".format(float(totalPreviousMonthPayinBalance))),
        "totalCurrentMonthPayinBalance":formatINR("{:.2f}".format(float(totalCurrentMonthPayinBalance))),
        # "totalPayinCommissionsAmount":formatINR("{:.2f}".format(float(payinTotalchargeAmount))),
        # "totalPayinTdsAmount":formatINR("{:.2f}".format(float(payinTotaltdsAmount))),
        # "totalPayinGstAmount":formatINR("{:.2f}".format(float(payinTotalgstAmount))),
        "totalPayoutCommissionsAmount":formatINR("{:.2f}".format(float(payoutTotalchargeAmount))),
        "totalPayoutTdsAmount":formatINR("{:.2f}".format(float(payoutTotaltdsAmount))),
        "totalPayoutGstAmount":formatINR("{:.2f}".format(float(payoutTotalgstAmount))),
        "totalPayoutAmount":formatINR("{:.2f}".format(float(totalPayoutAmount))),
        "totalPayinAmount":formatINR("{:.2f}".format(float(totalPayinAmount))),
        "todayTotalPayinAmount":formatINR("{:.2f}".format(float(todayTotalPayinAmount))),
        "todayTotalPayoutAmount":formatINR("{:.2f}".format(float(todayTotalPayoutAmount))),
        "yesterdayTotalPayinAmount":formatINR("{:.2f}".format(float(yesterdayTotalPayinAmount))),
        "yesterdayTotalPayoutAmount":formatINR("{:.2f}".format(float(yesterdayTotalPayoutAmount))),
        "cwCommissionAmount":formatINR("{:.2f}".format(float(cwCommissionAmount))),
        "pgtotalAmount":formatINR("{:.2f}".format(float(pgtotalAmount))),
        "overallTransactionGstAmountDatewise":formatINR("{:.2f}".format(float(overallTransactionGstAmountDatewise))),
        "currentMonthTotalTransactionAmount":formatINR("{:.2f}".format(float(currentMonthTotalTransactionAmount))),
        # "companyCharges":formatINR("{:.2f}".format(float(companyCharges))),
        "agentCommissionAmount":formatINR("{:.2f}".format(float(agentCommissionAmount))),
        "currentMonthcwCommissionAmount":formatINR("{:.2f}".format(float(currentMonthcwCommissionAmount))),
        "currentMonthpgtotalAmount":formatINR("{:.2f}".format(float(currentMonthpgtotalAmount))),
        "totalTransactionAmount":formatINR("{:.2f}".format(float(totalTransactionAmount))),
        "currentMonthAgentCommissionAmount":formatINR("{:.2f}".format(float(currentMonthAgentCommissionAmount))),
        "previousMonthcwCommissionAmount":formatINR("{:.2f}".format(float(previousMonthcwCommissionAmount))),
        "previousMonthpgtotalAmount":formatINR("{:.2f}".format(float(previousMonthpgtotalAmount))),
        "previousMonthTotalTransactionAmount":formatINR("{:.2f}".format(float(previousMonthTotalTransactionAmount))),
        "previousMonthAgentCommissionAmount":formatINR("{:.2f}".format(float(previousMonthAgentCommissionAmount))),
        "payoutTotalPgchargeAmount":formatINR("{:.2f}".format(float(payoutTotalPgchargeAmount))),
        "payoutTotalPggstAmount":formatINR("{:.2f}".format(float(payoutTotalPggstAmount))),
        "overallPayinPgGstAmount":formatINR("{:.2f}".format(float(overPgGstAmount))),
        "currentMonthPayoutChargesAmount":formatINR("{:.2f}".format(float(currentMonthPayoutChargesAmount))),
        "previousMonthPayoutCommissionAmount":formatINR("{:.2f}".format(float(previousMonthPayoutCommissionAmount))),
        "previousMonthPayoutCharges":formatINR("{:.2f}".format(float(previousMonthPayoutCharges))),
        "previousMonthPGCharges":formatINR("{:.2f}".format(float(previousMonthPGCharges))),
        "previousMonthoPayoutPgGstAmount":formatINR("{:.2f}".format(float(previousMonthoPayoutPgGstAmount))),
        "currentMonthPayoutCommissionAmount":formatINR("{:.2f}".format(float(currentMonthPayoutCommissionAmount))),
        "currentMonthPayoutPGCharges":formatINR("{:.2f}".format(float(currentMonthPayoutPGCharges))),
        "currentMonthPayoutPgGstAmount":formatINR("{:.2f}".format(float(currentMonthPayoutPgGstAmount))),
        "approvedMerchantsCount":approved_count,
        "rejectedMerchantsCount":rejected_count,
        "pendingMerchantsCount":pending_count,
        "totalMerchantsCount":total_merchants_count,
        "beneficiaryTransactionsCount":beneficiaryTransactionsCount,
        "beneficiaryGstAmount":formatINR("{:.2f}".format(float(beneficiaryGstAmount))),
        "beneficiaryTotalChargesAmount":formatINR("{:.2f}".format(float(beneficiaryTotalChargesAmount))),

        "beneficiaryCurrentMonthTransactionsCount":beneficiaryCurrentMonthTransactionsCount,
        "beneficiaryCurrentMonthGstAmount":formatINR("{:.2f}".format(float(beneficiaryCurrentMonthGstAmount))),
        "beneficiaryCurrentMonthTotalChargesAmount":formatINR("{:.2f}".format(float(beneficiaryCurrentMonthTotalChargesAmount))),


        "beneficiaryTransactionsCount":beneficiaryTransactionsCount,
        "beneficiaryPreviousGstAmount":formatINR("{:.2f}".format(float(beneficiaryPreviousGstAmount))),
        "beneficiaryPreviousTransactionsCount":formatINR("{:.2f}".format(float(beneficiaryPreviousTransactionsCount))),



        "pgAdditionalChargeAmount":formatINR("{:.2f}".format(float(pgAdditionalChargeAmount))),
        "pgCurrentMonthAdditionalChargeAmount":formatINR("{:.2f}".format(float(pgCurrentMonthAdditionalChargeAmount))),
        "pgPreviousMonthAdditionalChargeAmount":formatINR("{:.2f}".format(float(pgPreviousMonthAdditionalChargeAmount))),
        }
        # print("(((((((((((((payInTop10MerchantsList)))))))))))))",payInTop10MerchantsList)
        # print("(((((((((((((payoutsTop10MerchantsList)))))))))))))",payoutsTop10MerchantsList)
        
        return render_template(
            "super_admin_templates/dashboard2.html",
            adminDict=adminDict,
            payInTop10MerchantsList=payInTop10MerchantsList,
            payoutsTop10MerchantsList=payoutsTop10MerchantsList,
            payoutsList=payoutsList,
            payinsList=payinsList,
            )
    except Exception as e:
        app.logger.error(traceback.format_exc())
        return redirect(url_for('admin.admin_login'))
