import pymysql import sys import json import random import threading import logging from sqlalchemy import func from concurrent.futures import ThreadPoolExecutor, as_completed from datetime import datetime from typing import List, Dict, Union, Any from stripe_payment_processor import StripePaymentProcessor from config import Config from app import create_app, db from models import Payments, PaymentBatch, SinglePayments, PaymentPlans from splynx import Splynx, SPLYNX_URL, SPLYNX_KEY, SPLYNX_SECRET from services import ( log_script_start, log_script_completion, log_batch_created, log_payment_intent_followup ) if __name__ == "__main__": app = create_app() with app.app_context(): # Find customer_ids that appear more than once duplicate_customer_ids = db.session.query( Payments.Stripe_Customer_ID ).group_by( Payments.Stripe_Customer_ID ).having( func.count(Payments.Stripe_Customer_ID) > 1 ).all() # Get the actual duplicate records duplicate_records = db.session.query(Payments).filter( Payments.Stripe_Customer_ID.in_([row[0] for row in duplicate_customer_ids]) ).order_by(Payments.Stripe_Customer_ID).all() i = 0 has_charge = 0 for a in duplicate_records: i += 1 #print(a.Stripe_Customer_ID) if a.Stripe_Charge_ID != None: has_charge += 1 print(i, i/2, has_charge, has_charge/2) ranked_duplicates = db.session.query( Payments.id, func.row_number().over( partition_by=Payments.Stripe_Customer_ID, order_by=Payments.id ).label('rn') ).filter( Payments.Stripe_Customer_ID.in_([row[0] for row in duplicate_customer_ids]) ).subquery() # Get only the first record (rn = 1) for each customer_id first_duplicates = db.session.query(Payments).join( ranked_duplicates, Payments.id == ranked_duplicates.c.id ).filter(ranked_duplicates.c.rn == 1).order_by(Payments.Stripe_Customer_ID).all() i = 0 has_charge = 0 for a in first_duplicates: i += 1 #print(a.id, a.Splynx_ID) print(a.Stripe_Charge_ID) if a.Stripe_Charge_ID != None: has_charge += 1 print(i, has_charge)