import io
import json
import os
import re
from datetime import datetime
import boto3
import pdfkit
import requests
from jinja2 import Template
from db.query import QueryExecution
from logger_module.package_logger import print_log
BILL_VALIDATION_HTML = """
Summary
Complete Data
{% for key, value in complete.items() %}
| {{ key }} |
{{ value }} |
{% endfor %}
"""
class KarzaIntegration:
KARZA_BASE_URL = os.getenv("KARZA_URL")
@classmethod
def electricity_bill_verification(cls, consumer_id, service_provider, district, reg_mobile_no="", consent="Y"):
karza_api_key = os.getenv("KARZA_ELEC_API_KEY")
url = f"{cls.KARZA_BASE_URL}/v2/elec"
headers = {
"content-type": "application/json",
"x-karza-key": karza_api_key
}
payload = {
"consumer_id": consumer_id,
"service_provider": service_provider,
"district": district,
"regMobileNo": reg_mobile_no,
"consent": consent
}
try:
response = requests.post(url, json=payload, headers=headers, timeout=60)
response.raise_for_status()
print_log(f"Karza electricity verification response: {response.json()}")
return response.json()
# return {'result': {'bill_no': '', 'bill_due_date': '18-03-2026', 'consumer_number': '020013159263', 'bill_amount': '1010', 'bill_issue_date': '', 'mobile_number': '99******79', 'amount_payable': '', 'total_amount': '', 'address': '', 'consumer_name': 'SANJAY MAHADEO KUDTARKAR.', 'email_address': '', 'bill_date': '26-02-2026'}, 'request_id': '83a8b684-e82e-42ac-8b51-a41730837a62', 'status-code': '101'}
# return {'result': {}, 'request_id': 'd42d84bb-f2c5-4f10-97a7-cca377391a98', 'status-code': '102'}
except Exception as ex:
print_log(f"Karza electricity verification failed: {str(ex)}")
return {"error": "Karza electricity verification failed", "message": str(ex)}
@classmethod
def save_utility_validation(cls, data, response):
try:
if response and response.get("result") and (response.get('status-code') == '101' or response.get('status-code') == 101):
QueryExecution.fetch_result(
"INSERT INTO utility_validation "
"(data, consumer_application_file_id, created_at, user_id, consumer_application_id) "
"VALUES (%s, %s, %s, %s, %s)",
(
json.dumps(response),0,
datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
107,
data.get('id', 0)
)
)
if response['result'].get('bill_amount'):
bill_amount_str = response['result'].get('bill_amount', '')
cleaned = re.sub(r'Rs\.', '', bill_amount_str)
if cleaned.startswith('-'):
monthly_bill = data.get('monthly_bill')
else:
monthly_bill = int(re.sub(r'[,\s]|\.\d+', '', cleaned.strip()))
else:
monthly_bill = data.get('monthly_bill')
cls.generate_bill_validation(data, response.get("result"))
return True, monthly_bill
else:
QueryExecution.fetch_result(
"INSERT INTO comments (application_id, comment, user_id, show_consumer, show_merchant, created_at, updated_at) "
"VALUES (%s, %s, %s, %s, %s, %s, %s)",
(
data.get('id'),
f"Incorrect e-bills details received via API and e-bill validation failed. Details - Consumer ID - {data.get('consumer_id')}, Service Provider - {data.get('service_provider')}",
107,
0,
0,
datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
datetime.now().strftime('%Y-%m-%d %H:%M:%S')
)
)
return False, 0
except Exception as ex:
print_log(f"Save utility validation failed: {str(ex)}")
return False, 0
@classmethod
def _array_flatten(cls, data, prefix=''):
"""Recursively flatten a nested dict into a single-level dict (PHP array_flatten equivalent)."""
result = {}
for key, value in data.items():
full_key = f"{prefix}{key}" if not prefix else f"{prefix}_{key}"
if isinstance(value, dict):
result.update(cls._array_flatten(value, full_key))
else:
result[full_key] = value
return result
@classmethod
def generate_bill_validation(cls, data, result):
try:
logo_url = os.getenv("LENDER_KMGCP_LOGO", "")
file_type = 'electricity_bill'
application_id = data.get('id')
flat_result = cls._array_flatten(result)
html_content = Template(BILL_VALIDATION_HTML).render(
logo_url=logo_url,
complete=flat_result
)
pdf_bytes = pdfkit.from_string(html_content, False, options={"quiet": ""})
s3 = boto3.client("s3", region_name=os.getenv("AWS_REGION_NAME"))
s3_key = f"{application_id}/{file_type}_validation_report.pdf"
s3.put_object(
Bucket=os.getenv("AWS_BUCKET"),
Key=s3_key,
Body=io.BytesIO(pdf_bytes),
ContentType="application/pdf"
)
QueryExecution.fetch_result(
"INSERT INTO consumer_application_files "
"(consumer_application_id, file_type, file_path, created_at, created_by) "
"VALUES (%s, %s, %s, %s, %s)",
(
application_id,
f"{file_type}_validation_report",
s3_key,
datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
107
)
)
print_log(f"Bill validation report uploaded: {s3_key}")
return True
except Exception as ex:
print_log(f"Generate bill validation failed: {str(ex)}")
return False