######################## Firebase Initialize ############################ import firebase_admin from firebase_admin import db, credentials, storage from firebase_admin import firestore import stripe import json import traceback import requests from stripe.http_client import RequestsClient # Configure Stripe with a custom HTTP client class CustomHTTPClient(stripe.http_client.HTTPClient): def request(self, method, url, headers, post_data=None): resp = requests.request( method, url, headers=headers, data=post_data, timeout=80 ) return resp.content, resp.status_code, resp.headers try: # Check if any Firebase apps already exist and delete them if firebase_admin._apps: for app_name in list(firebase_admin._apps.keys()): if app_name == "default_app" or app_name == "default_app_2": firebase_admin.delete_app(firebase_admin.get_app(app_name)) # Firebase database and storage URLs database_url = "https://farmbase-b2f7e-31c0c.firebaseio.com/" database_url_2 = "https://farmbase-b2f7e-60c5a.firebaseio.com" storage_url = "farmbase-b2f7e.appspot.com" # Firebase credentials cred = credentials.Certificate("servicekey.json") # Initialize the first app default_app = firebase_admin.initialize_app( cred, {"databaseURL": database_url, "storageBucket": storage_url} ) # Initialize the second app default_app_2 = firebase_admin.initialize_app( cred, {"databaseURL": database_url_2, "storageBucket": storage_url}, name="second_app", ) print("Firebase initialization successful") except Exception as e: print(f"Error initializing Firebase: {str(e)}") exit(1) ############################################### Stripe Get Products ############################################### def get_product(plan_name): with open("stripe_config.json") as config_file: config = json.load(config_file) stripe_secret_key = config["stripe_secret_key_live"] """ Retrieve product metadata based on the plan name. Args: plan_name (str): The name of the plan to search for. Returns: dict: Product metadata if found, None otherwise. """ try: url = "https://api.stripe.com/v1/products" headers = {"Authorization": f"Bearer {stripe_secret_key}"} response = requests.get(url, headers=headers) products = response.json() print(products) #products = stripe.Product.list(limit=100) products_list = products["data"] for product in products_list: print(plan_name) if plan_name.lower() in product["name"].lower(): return product["metadata"] return None except stripe.error.StripeError as e: print(f"Stripe error: {str(e)}") return None try: # Load Stripe configuration with open("stripe_config.json") as config_file: config = json.load(config_file) stripe_secret_key = config["stripe_secret_key_live"] stripe.api_key = stripe_secret_key #stripe.http_client = stripe.http_client.RequestsClient(verify_ssl_certs=True) stripe.http_client = RequestsClient() print("Stripe configuration loaded successfully") except Exception as e: print(f"Error setting up Stripe: {str(e)}") exit(1) def process_field(UID, FieldID): """ Process a field based on its subscription status and visit limits. Args: UID (str): User ID FieldID (str): Field ID Returns: dict: A dictionary containing 'process_field' and 'update_counter' flags """ result = {"process_field": False, "update_counter": False} try: # Get Field Data str_ref_field = f"/PaidMonitoredFields/PMF/{UID}/{FieldID}" print(str_ref_field) # Check if subscribed or not by checking Subscription == True subscribe = db.reference(f"{str_ref_field}/Subscription").get() print("subscription", subscribe) if subscribe: print(f"{FieldID} - Subscribed Field") # Get My Profile Data str_ref_myprofile = f"/{UID}/MyProfile" db_app2 = db.reference(str_ref_myprofile, app=default_app_2) myprofile_data = db_app2.get() total_satellite_visits = myprofile_data.get("TotalSatelliteVisits", 1) print(f"Total Satellite Visits till Now: {total_satellite_visits}") # Get Plan Details sub_plan = myprofile_data.get("SubPlan") plan_details = get_product(sub_plan) plan_schedule_type = myprofile_data.get("SubScheduleType") # Calculate satellite visits limit satellite_visits_limit_multiplier = ( 73 if plan_schedule_type.lower() == "yearly" else 6 ) plan_satellite_visits_limit = ( int(plan_details.get("totalFarms", 0)) * satellite_visits_limit_multiplier ) print(f"Total Satellite visits Allowed: {plan_satellite_visits_limit}") within_limits = total_satellite_visits < plan_satellite_visits_limit result["total_satellite_visits"] = total_satellite_visits if within_limits: print("Within limits - process field") result["process_field"] = True result["update_counter"] = True else: print("Not processing, satellite visits exceeds limits") else: print("Pag Field - Process field") result["process_field"] = True except: print(traceback.format_exc()) # print(f"Error in process_field: {str(e)}") return result ### How to Use # import process_field_flag # UID = "CFv7IjeJR8ZKFWSXb95qzgvymCv1" # FieldID = "1726644367354" # process_field_flag.process_field(UID, FieldID) ## need to add following to update the TotalSatelliteVisits # # Update TotalSatelliteVisits # str_ref_satellite_visits = "/" + UID + "/MyProfile/TotalSatelliteVisits" # db_app2 = db.reference(f"{str_ref_satellite_visits}", app=default_app_2) # db_app2.set(total_satellite_visits + 1)