Added the script for recurring templates

This commit is contained in:
ashutosh.nehete 2025-11-06 09:21:46 +05:30
parent e64ef287a6
commit 17def2526a
2 changed files with 184 additions and 0 deletions

View File

@ -0,0 +1,32 @@
{
"SMPT": {
"SMPTSERVER": "smtp.gmail.com",
"PORT": 587,
"SENDER_EMAIL": "marcoioitsoft@gmail.com",
"SENDER_PASSWORD": "qrtq wfuj hwpp fhqr",
"RECIPIENT_EMAILS": "ashutosh.nehete@marcoaiot.com,umesh@marcoaiot.com"
},
"API": {
"BASE_URL": "http://localhost:5032/api",
"USERNAME": "admin@marcoaiot.com",
"PASSWORD": "User@123",
"TENANTID": "b3466e83-7e11-464c-b93a-daf047838b26"
},
"WEB": {
"BASE_URL": "https://stageapp.marcoaiot.com"
},
"MONGODB": {
"MONGO_CONNECTION_STRING": "mongodb://localhost:27017",
"DATABASE_NAME": "MarcoBMS_Caches",
"COLLECTION_NAME": "ProjectReportMail"
},
"UNIQUE_IDENTIFIER": {
"PROJECT_IDS": "2618eb89-2823-11f0-9d9e-bc241163f504"
},
"MYSQL": {
"DB_HOST": "147.93.98.152",
"DB_USER": "devuser",
"DB_PASSWORD": "AppUser@123$",
"DB_NAME": "MarcoBMSOFW"
}
}

View File

@ -0,0 +1,152 @@
import json
import requests
import mysql.connector
import logging
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def login_api():
"""Authenticate and get JWT token from login API."""
payload = {"username": API_USERNAME, "password": API_PASSWORD}
headers = {"Content-Type": "application/json"}
try:
response = requests.post(f"{BASE_URL}/auth/login", json=payload, headers=headers)
response.raise_for_status()
data = response.json().get("data", {})
jwt = data.get("token")
if jwt:
logging.info("API login successful.")
return jwt
else:
logging.error("JWT token not found in login response.")
return None
except requests.RequestException as e:
logging.error(f"Login API error: {e}")
return None
def select_tenant(jwt):
"""Select tenant and retrieve a new JWT token."""
headers = {"Authorization": f"Bearer {jwt}", "Content-Type": "application/json"}
try:
response = requests.post(f"{BASE_URL}/auth/select-tenant/{API_TENANT}", headers=headers)
response.raise_for_status()
data = response.json().get("data", {})
jwt = data.get("token")
if jwt:
logging.info("Tenant selected successfully.")
return jwt
else:
logging.error("JWT token not found in tenant selection response.")
return None
except requests.RequestException as e:
logging.error(f"Select tenant error: {e}")
return None
def get_recurring_templates(cursor):
"""Retrieve recurring payment templates that need processing."""
try:
val = ("da462422-13b2-45cc-a175-910a225f6fc8",)
query = """
SELECT Id
FROM RecurringPayments
WHERE StatusId = %s
AND (LatestPRGeneratedAt IS NULL OR DATE(LatestPRGeneratedAt) <> CURDATE())
"""
cursor.execute(query, val)
result = cursor.fetchall()
id_list = [row[0] for row in result]
logging.info(f"Found {len(id_list)} recurring templates to process.")
return id_list
except mysql.connector.Error as e:
logging.error(f"MySQL query error: {e}")
return []
def convert_recurring_templates(jwt, recurring_template_ids):
"""Convert each recurring template to a payment request via API."""
if not recurring_template_ids:
logging.info("No recurring templates to process.")
return
payload = {"recurringTemplateIds": recurring_template_ids}
headers = {"Authorization": f"Bearer {jwt}", "Content-Type": "application/json"}
try:
response = requests.post(
f"{BASE_URL}/expense/recurring-payment/convert/payment-request",
json=payload, headers=headers
)
response.raise_for_status()
message = response.json().get("message", "Conversion successful.")
logging.info(f"Conversion response: {message}")
except requests.HTTPError as http_err:
status_code = http_err.response.status_code
try:
error_message = http_err.response.json().get("message", http_err.response.text)
except Exception:
error_message = http_err.response.text
logging.error(f"HTTP error {status_code}: {error_message}")
except requests.RequestException as e:
logging.error(f"Request error: {e}")
except Exception as e:
logging.error(f"Unexpected error during conversion: {e}")
# --- Main execution logic ---
if __name__ == "__main__":
import sys
# Load configuration
GLOBAL_CONFIG_PATH = "config.json"
try:
with open(GLOBAL_CONFIG_PATH, "r", encoding="utf-8") as f:
config = json.load(f)
logging.info("Configuration loaded successfully.")
except Exception as e:
logging.critical(f"Failed to load config: {e}")
sys.exit(1)
# Extract config parameters
API_CONFIG = config.get("API", {})
BASE_URL = API_CONFIG.get("BASE_URL")
API_USERNAME = API_CONFIG.get("USERNAME")
API_PASSWORD = API_CONFIG.get("PASSWORD")
API_TENANT = API_CONFIG.get("TENANTID")
# Initialize database connection
MYSQL_CONFIG = config.get("MYSQL", {})
try:
mydb = mysql.connector.connect(
host=MYSQL_CONFIG.get("DB_HOST"),
user=MYSQL_CONFIG.get("DB_USER"),
password=MYSQL_CONFIG.get("DB_PASSWORD"),
database=MYSQL_CONFIG.get("DB_NAME")
)
# Create cursor
mycursor = mydb.cursor()
logging.info("Database connection established.")
except mysql.connector.Error as e:
logging.critical(f"Database connection error: {e}")
sys.exit(1)
# Authenticate and get JWT token
token = login_api()
if not token:
logging.critical("Login failed, aborting.")
sys.exit(1)
# Select tenant, get tenant-specific token
jwt_token = select_tenant(token)
if not jwt_token:
logging.critical("Tenant selection failed, aborting.")
sys.exit(1)
# Fetch recurring payment templates to process
recurring_ids = get_recurring_templates(mycursor)
# Close DB resources
mycursor.close()
mydb.close()
logging.info("Database connection closed.")
# Process the templates
convert_recurring_templates(jwt_token, recurring_ids)