HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux spn-python 5.15.0-89-generic #99-Ubuntu SMP Mon Oct 30 20:42:41 UTC 2023 x86_64
User: arjun (1000)
PHP: 8.1.2-1ubuntu2.20
Disabled: NONE
Upload Files
File: //home/arjun/projects/buyercall_forms/buyercall/buyercall/lib/util_dms.py
import logging
import datetime
import traceback
import xml.etree.ElementTree as ET

from buyercall.integrations.ams import AMS
from buyercall.integrations.ams_analytics import AMSAnalytics
from buyercall.integrations.neo import NEO
from buyercall.integrations.ams_prequalify import AMSPreQualify
from buyercall.blueprints.form_leads.models import ExternalFormFieldDefinition
from flask import current_app as app
from buyercall.lib.util_crypto import AESCipher


log = logging.getLogger(__name__)


def append_error(current_message, error_message):
    if len(current_message) > 0:
        current_message = current_message + ' ' + error_message
    else:
        current_message = current_message + error_message

    return current_message


def decrypt_value(text):
    crypto_key = app.config['CRYPTO_SECRET_KEY']
    cipher = AESCipher(crypto_key)

    if text is not None:
        try:
            return cipher.decrypt(text)
        except TypeError:
            #log.error('Error decrypting field value: ' + str(text))
            return text
        except ValueError:
            #log.error('Error decrypting field value: ' + str(text))
            return text
    else:
        return text


def set_string_value(value):
    if value and len(value) > 0:
        return value
    else:
        return ''


def ams_client(partnership_account_id, provider_type,request_id):
    from buyercall.blueprints.partnership.models import ExternalApiServiceProvidersPartnershipAccountTie, \
        ExternalApiServiceProviders

    # Get the encryption key to decrypt credentials
    encrypt_key = app.config['CRYPTO_SECRET_KEY']

    # Retrieve the AMS Evolution profile for the partnership account
    partner_service_provider_profile = ExternalApiServiceProvidersPartnershipAccountTie\
        .query\
        .join(ExternalApiServiceProviders)\
        .filter(ExternalApiServiceProviders.name == provider_type)\
        .filter(ExternalApiServiceProvidersPartnershipAccountTie.partnership_account_id == partnership_account_id)\
        .first()

    if partner_service_provider_profile:
        url = partner_service_provider_profile.url
        from buyercall.blueprints.sysadmin.models import RequestLog
        update_data = {
                "current_url": url,
                'path_info': url
                }
        RequestLog().update_record(request_id, update_data)
        # Decrypt the credentials
        cipher = AESCipher(encrypt_key)
        decrypted_username = cipher.decrypt(partner_service_provider_profile.username)
        decrypted_password = cipher.decrypt(partner_service_provider_profile.password)
        decrypted_secret = cipher.decrypt(partner_service_provider_profile.secret)
        decrypted_client_id = cipher.decrypt(partner_service_provider_profile.client_id)

        client = AMS(decrypted_username, decrypted_password, decrypted_client_id, decrypted_secret, url,request_id)

    return client

def ams_analytics_client(partnership_account_id, provider_type):
    from buyercall.blueprints.partnership.models import ExternalApiServiceProvidersPartnershipAccountTie, \
        ExternalApiServiceProviders

    # Get the encryption key to decrypt credentials
    encrypt_key = app.config['CRYPTO_SECRET_KEY']

    # Retrieve the AMS Evolution profile for the partnership account
    partner_service_provider_profile = ExternalApiServiceProvidersPartnershipAccountTie\
        .query\
        .join(ExternalApiServiceProviders)\
        .filter(ExternalApiServiceProviders.name == provider_type)\
        .filter(ExternalApiServiceProvidersPartnershipAccountTie.partnership_account_id == partnership_account_id)\
        .first()

    if partner_service_provider_profile:
        url = partner_service_provider_profile.url
        client_id = partner_service_provider_profile.client_id

        # Decrypt the credentials
        # cipher = AESCipher(encrypt_key)
        # decrypted_client_id = cipher.decrypt(partner_service_provider_profile.client_id)

        client = AMSAnalytics(client_id, url)

    return client



def ams_prequalify_client(partnership_account_id, provider_type):
    from buyercall.blueprints.partnership.models import ExternalApiServiceProvidersPartnershipAccountTie, \
        ExternalApiServiceProviders
    # Get the encryption key to decrypt credentials
    encrypt_key = app.config['CRYPTO_SECRET_KEY']
    # Retrieve the AMS Evolution profile for the partnership account
    partner_service_provider_profile = ExternalApiServiceProvidersPartnershipAccountTie\
        .query\
        .join(ExternalApiServiceProviders)\
        .filter(ExternalApiServiceProviders.name == provider_type)\
        .filter(ExternalApiServiceProvidersPartnershipAccountTie.partnership_account_id == partnership_account_id)\
        .first()
    if partner_service_provider_profile:
        url = partner_service_provider_profile.url
        client_id = partner_service_provider_profile.client_id
        # Decrypt the credentials
        # cipher = AESCipher(encrypt_key)
        # decrypted_client_id = cipher.decrypt(partner_service_provider_profile.client_id)
        client = AMSPreQualify(url, client_id)
    return client



class AmsLeadXml(object):
    def __init__(self, elt=None):
        self.root = elt if elt is not None else ET.Element('DealPushVoV1')
        self.root.set("xmlns:xsd", "http://www.w3.org/2001/XMLSchema")
        self.root.set("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")

        self.buyer = ET.Element('Buyer')
        self.co_buyer = ET.Element('CoBuyer')
        self.integration = ET.Element('IntegrationMapping')
        self.vehicle = ET.Element('Vehicle')
        self.cash_down = ET.Element('CashDown')
        self.deal_number = ET.Element('DealNumber')  # Leave blank
        self.deal_type = ET.Element('DealType')  # Leave blank
        self.lender_dms_id = ET.Element('LenderDmsID')  # Leave blank
        self.sales_person_dms_id_1 = ET.Element('SalesPerson1DmsID')  # Leave blank
        self.sales_person_dms_id_2 = ET.Element('SalesPerson2DmsID')  # Leave blank

        # Append buyer and buyer defaults to root
        contact_type = ET.SubElement(self.buyer, 'ContactType')
        contact_type.text = 'Prospect'
        contact_sub_type = ET.SubElement(self.buyer, 'ContactSubType')
        contact_sub_type.text = 'Private'
        company_name = ET.SubElement(self.buyer, 'CompanyName')
        country_code = ET.SubElement(self.buyer, 'CountryCode')
        country_code.text = 'US'
        entity_type = ET.SubElement(self.buyer, 'EntityType')
        entity_type.text = 'Person'
        status_type = ET.SubElement(self.buyer, 'StatusType')
        status_type.text = 'Unknown'
        opt_in_email = ET.SubElement(self.buyer, 'OptInEmail')
        opt_in_email.set('xsi:nil', 'true')
        opt_in_phone = ET.SubElement(self.buyer, 'OptInPhone')
        opt_in_phone.set('xsi:nil', 'true')
        opt_in_print = ET.SubElement(self.buyer, 'OptInPrint')
        opt_in_print.set('xsi:nil', 'true')
        opt_in_text = ET.SubElement(self.buyer, 'OptInText')
        opt_in_text.set('xsi:nil', 'true')

        # Append co-buyer and co-buyer defaults to root
        co_applicant_contact_type = ET.SubElement(self.co_buyer, 'ContactType')
        co_applicant_contact_type.text = 'Prospect'
        co_applicant_contact_sub_type = ET.SubElement(self.co_buyer, 'ContactSubType')
        co_applicant_contact_sub_type.text = 'Private'
        co_applicant_company_name = ET.SubElement(self.co_buyer, 'CompanyName')
        co_applicant_country_code = ET.SubElement(self.co_buyer, 'CountryCode')
        co_applicant_country_code.text = 'US'
        co_applicant_entity_type = ET.SubElement(self.co_buyer, 'EntityType')
        co_applicant_entity_type.text = 'Person'
        co_applicant_status_type = ET.SubElement(self.co_buyer, 'StatusType')
        co_applicant_status_type.text = 'Unknown'
        co_applicant_opt_in_email = ET.SubElement(self.co_buyer, 'OptInEmail')
        co_applicant_opt_in_email.set('xsi:nil', 'true')
        co_applicant_opt_in_phone = ET.SubElement(self.co_buyer, 'OptInPhone')
        co_applicant_opt_in_phone.set('xsi:nil', 'true')
        co_applicant_opt_in_print = ET.SubElement(self.co_buyer, 'OptInPrint')
        co_applicant_opt_in_print.set('xsi:nil', 'true')
        co_applicant_opt_in_text = ET.SubElement(self.co_buyer, 'OptInText')
        co_applicant_opt_in_text.set('xsi:nil', 'true')

        # Append integration and integration defaults to root
        dms_store = ET.SubElement(self.integration, 'DMSStore')
        dms_branch = ET.SubElement(self.integration, 'DMSBranch')
        #dsi_address_id = ET.SubElement(self.integration, 'DSiAddressId')
        #dsi_entity_id = ET.SubElement(self.integration, 'DSiEntityId')
        #dsi_event_id = ET.SubElement(self.integration, 'DSiEventId')
        dsi_activity_id = ET.SubElement(self.integration, 'DSiActivityId')
        dsi_activity_id.set('xsi:nil', 'true')
        dsi_vehicle_id = ET.SubElement(self.integration, 'DSiVehicleId')
        dsi_vehicle_id.set('xsi:nil', 'true')
        #dsi_quoted_id = ET.SubElement(self.integration, 'DSiQuoteId')
        dsi_inventory_id = ET.SubElement(self.integration, 'DSiInventory')
        dsi_inventory_id.set('xsi:nil', 'true')
        dsi_wl_account_id = ET.SubElement(self.integration, 'DSiWLAccountId')
        dsi_wl_account_id.set('xsi:nil', 'true')
        dsi_address = ET.SubElement(self.integration, 'DMSIPAddress')
        dsi_address.text = 'https://buyercall.com'
        dms_name = ET.SubElement(self.integration, 'DMSName')
        dms_name.text = 'BuyerCall'
        dms_version = ET.SubElement(self.integration, 'DMSVersion')
        dms_version.text = '1'

        # Append vehicle and vehicle defaults to root
        odometer = ET.SubElement(self.vehicle, 'Odometer')
        odometer.text = '0'
        msrp = ET.SubElement(self.vehicle, 'MSRP')
        msrp.text = '0.0000'
        vehicle_type = ET.SubElement(self.vehicle, 'VehicleType')
        #next_service_date = ET.SubElement(self.vehicle, 'NextServiceDate')
        #last_sold_date = ET.SubElement(self.vehicle, 'LastSoldDate')
        warranty_expire_date = ET.SubElement(self.vehicle, 'ExtWarrantyExpireDate')
        warranty_expire_date.set('xsi:nil', 'true')
        warranty_miles = ET.SubElement(self.vehicle, 'ExtWarrantyMiles')
        warranty_miles.set('xsi:nil', 'true')
        service_contract_expire = ET.SubElement(self.vehicle, 'SrvcContractExpireDate')
        service_contract_expire.set('xsi:nil', 'true')
        service_maintenance_miles = ET.SubElement(self.vehicle, 'SrvcMaintMiles')
        service_maintenance_miles.set('xsi:nil', 'true')
        certified_number = ET.SubElement(self.vehicle, 'CertifiedNumber')
        price = ET.SubElement(self.vehicle, 'Price')
        price.text = '0.0000'

        self.root.append(self.buyer)
        self.root.append(self.integration)
        self.root.append(self.vehicle)
        self.root.append(self.deal_number)
        self.root.append(self.deal_type)
        self.root.append(self.lender_dms_id)
        self.root.append(self.cash_down)
        #self.root.append(self.sales_person_dms_id_1)
        #self.root.append(self.sales_person_dms_id_2)

    def __str__(self):
        return ET.tostring(self.root, encoding="unicode" )

    # Buyer fields
    def address_1(self, text):
        elt = ET.Element(
            'Address1'
        )
        elt.text = text
        self.buyer.append(elt)
        return elt

    def address_2(self, text):
        elt = ET.Element(
            'Address2'
        )
        elt.text = text
        self.buyer.append(elt)
        return elt

    def birthday(self, text):
        elt = ET.Element(
            'Birthday'
        )
        elt.text = text
        self.buyer.append(elt)
        return elt

    def mobile_phone(self, text):
        elt = ET.Element(
            'CellPhone'
        )
        elt.text = text
        self.buyer.append(elt)
        return elt

    def city(self, text):
        elt = ET.Element(
            'City'
        )
        elt.text = text
        self.buyer.append(elt)
        return elt

    def drivers_license(self, text):
        elt = ET.Element(
            'DriversLicense'
        )
        elt.text = text
        self.buyer.append(elt)
        return elt

    def email(self, text):
        elt = ET.Element(
            'Email1'
        )
        elt.text = text
        self.buyer.append(elt)
        return elt

    def firstname(self, text):
        elt = ET.Element(
            'FirstName'
        )
        elt.text = text
        self.buyer.append(elt)
        return elt

    def phonenumber(self, text):
        elt = ET.Element(
            'HomePhone'
        )
        elt.text = text
        self.buyer.append(elt)
        return elt

    def lastname(self, text):
        elt = ET.Element(
            'LastName'
        )
        elt.text = text
        self.buyer.append(elt)
        return elt

    def middlename(self, text):
        elt = ET.Element(
            'MiddleName'
        )
        elt.text = text
        self.buyer.append(elt)
        return elt

    def state(self, text):
        elt = ET.Element(
            'State'
        )
        elt.text = text
        self.buyer.append(elt)
        return elt

    def work_phone(self, text):
        elt = ET.Element(
            'WorkPhone'
        )
        elt.text = text
        self.buyer.append(elt)
        return elt

    def zip(self, text):
        elt = ET.Element(
            'Zip'
        )
        elt.text = text
        self.buyer.append(elt)
        return elt

    def ssn(self, text):
        elt = ET.Element(
            'SSN'
        )
        elt.text = text
        self.buyer.append(elt)
        return elt

    # Co-buyer fields
    def co_applicant_address_1(self, text):
        elt = ET.Element(
            'Address1'
        )
        elt.text = text
        self.co_buyer.append(elt)

        if self.co_buyer not in self.root:
            self.root.append(self.co_buyer)

        return elt

    def co_applicant_address_2(self, text):
        elt = ET.Element(
            'Address2'
        )
        elt.text = text
        self.co_buyer.append(elt)

        if self.co_buyer not in self.root:
            self.root.append(self.co_buyer)

        return elt

    def co_applicant_birthday(self, text):
        elt = ET.Element(
            'Birthday'
        )
        elt.text = text
        self.co_buyer.append(elt)

        if self.co_buyer not in self.root:
            self.root.append(self.co_buyer)

        return elt

    def co_applicant_mobile_phone(self, text):
        elt = ET.Element(
            'CellPhone'
        )
        elt.text = text
        self.co_buyer.append(elt)

        if self.co_buyer not in self.root:
            self.root.append(self.co_buyer)

        return elt

    def co_applicant_city(self, text):
        elt = ET.Element(
            'City'
        )
        elt.text = text
        self.co_buyer.append(elt)

        if self.co_buyer not in self.root:
            self.root.append(self.co_buyer)

        return elt

    def co_applicant_driver_license(self, text):
        elt = ET.Element(
            'DriversLicense'
        )
        elt.text = text
        self.co_buyer.append(elt)

        if self.co_buyer not in self.root:
            self.root.append(self.co_buyer)

        return elt

    def co_applicant_email(self, text):
        elt = ET.Element(
            'Email1'
        )
        elt.text = text
        self.co_buyer.append(elt)

        if self.co_buyer not in self.root:
            self.root.append(self.co_buyer)

        return elt

    def co_applicant_firstname(self, text):
        elt = ET.Element(
            'FirstName'
        )
        elt.text = text
        self.co_buyer.append(elt)

        if self.co_buyer not in self.root:
            self.root.append(self.co_buyer)

        return elt

    def co_applicant_phonenumber(self, text):
        elt = ET.Element(
            'HomePhone'
        )
        elt.text = text
        self.co_buyer.append(elt)

        if self.co_buyer not in self.root:
            self.root.append(self.co_buyer)

        return elt

    def co_applicant_lastname(self, text):
        elt = ET.Element(
            'LastName'
        )
        elt.text = text
        self.co_buyer.append(elt)

        if self.co_buyer not in self.root:
            self.root.append(self.co_buyer)

        return elt

    def co_applicant_middlename(self, text):
        elt = ET.Element(
            'MiddleName'
        )
        elt.text = text
        self.co_buyer.append(elt)

        if self.co_buyer not in self.root:
            self.root.append(self.co_buyer)

        return elt

    def co_applicant_state(self, text):
        elt = ET.Element(
            'State'
        )
        elt.text = text
        self.co_buyer.append(elt)

        if self.co_buyer not in self.root:
            self.root.append(self.co_buyer)

        return elt

    def co_applicant_work_phone(self, text):
        elt = ET.Element(
            'WorkPhone'
        )
        elt.text = text
        self.co_buyer.append(elt)

        if self.co_buyer not in self.root:
            self.root.append(self.co_buyer)

        return elt

    def co_applicant_zip(self, text):
        elt = ET.Element(
            'Zip'
        )
        elt.text = text
        self.co_buyer.append(elt)

        if self.co_buyer not in self.root:
            self.root.append(self.co_buyer)

        return elt

    def co_applicant_ssn(self, text):
        elt = ET.Element(
            'SSN'
        )
        elt.text = text
        self.co_buyer.append(elt)

        if self.co_buyer not in self.root:
            self.root.append(self.co_buyer)

        return elt

    # Integration fields
    def dealer_lot_id(self, text):
        elt = ET.Element(
            'DSiSiteId'
        )
        elt.text = text
        self.integration.append(elt)

        return elt

    def client_id(self, text):
        elt = ET.Element(
            'DMSDealer'
        )
        elt.text = text
        self.integration.append(elt)

        return elt

    def username(self, text):
        elt = ET.Element(
            'DMSUsername'
        )
        elt.text = text
        self.integration.append(elt)

        return elt

    def password(self, text):
        elt = ET.Element(
            'DMSPassword'
        )
        elt.text = text
        self.integration.append(elt)

        return elt

    # Vehicle fields
    def vehicle_make(self, text):
        elt = ET.Element(
            'Make'
        )
        elt.text = text
        self.vehicle.append(elt)
        return elt

    def vehicle_model(self, text):
        elt = ET.Element(
            'Model'
        )
        elt.text = text
        self.vehicle.append(elt)
        return elt

    def vehicle_year(self, text):
        elt = ET.Element(
            'Year'
        )
        elt.text = text
        self.vehicle.append(elt)
        return elt

    def vin(self, text):
        elt = ET.Element(
            'VIN'
        )
        elt.text = text
        self.vehicle.append(elt)
        return elt

    def stock_number(self, text):
        elt = ET.Element(
            'StockNumber'
        )
        elt.text = text
        self.vehicle.append(elt)
        return elt

    # Cash Down
    def down_payment_amount(self, text):
        self.cash_down.text = text
        return self.cash_down

    # Sales Person
    def representative(self, text):
        self.sales_person_dms_id_1.text = text

        if self.sales_person_dms_id_1 not in self.root:
            self.root.append(self.sales_person_dms_id_1)

        return self.sales_person_dms_id_1


def neo_client(partnership_account_id, provider_type,request_id):
    from buyercall.blueprints.partnership.models import ExternalApiServiceProvidersPartnershipAccountTie, \
        ExternalApiServiceProviders

    # Get the encryption key to decrypt credentials
    encrypt_key = app.config['CRYPTO_SECRET_KEY']

    # Retrieve the AMS Evolution profile for the partnership account
    partner_service_provider_profile = ExternalApiServiceProvidersPartnershipAccountTie\
        .query\
        .join(ExternalApiServiceProviders)\
        .filter(ExternalApiServiceProviders.name == provider_type)\
        .filter(ExternalApiServiceProvidersPartnershipAccountTie.partnership_account_id == partnership_account_id)\
        .first()

    if partner_service_provider_profile:
        url = partner_service_provider_profile.url

        # Decrypt the credentials
        cipher = AESCipher(encrypt_key)
        decrypted_secret = cipher.decrypt(partner_service_provider_profile.secret)
        client = NEO(decrypted_secret, url,request_id)
    return client


class NeoLead(object):
    lead_fields = []
    field_definition_list = []

    application = {}
    applicant = {}
    applicant_residences = {}
    applicant_employers = {}
    co_applicant = None
    co_applicant_residences = None
    co_applicant_employers = None

    dealer_lot_id = None
    location = None
    representative = None

    first_name = None
    last_name = None
    birthday = None
    ssn = None
    email = None
    cell_phone = None
    home_phone = None
    work_phone = None
    marital_status = None
    gender = None
    number_of_dependents = None

    address_1 = None
    previous_address_1 = None
    address_2 = None
    previous_address_2 = None
    state = None
    previous_state = None
    city = None
    previous_city = None
    zip = None
    rent_or_own = None
    address_start_date = None
    address_monthly_cost = None
    previous_zip = None

    co_application_first_name = None
    co_application_last_name = None
    co_application_birthday = None
    co_application_marital_status = None
    co_application_gender = None
    co_application_number_of_dependents = None

    co_application_address_1 = None
    co_application_previous_address_1 = None
    co_application_address_2 = None
    co_application_previous_address_2 = None
    co_application_state = None
    co_application_previous_state = None
    co_application_city = None
    co_application_previous_city = None
    co_application_zip = None
    co_application_previous_zip = None

    employer = None
    previous_employer = None
    employer_address_1 = None
    previous_employer_address_1 = None
    employer_address_2 = None
    previous_employer_address_2 = None
    employer_city = None
    previous_employer_city = None
    employer_state = None
    previous_employer_state = None
    employer_zip = None
    previous_employer_zip = None
    employment_title = None
    job_type = None
    previous_employment_title = None
    previous_job_type = None
    income = None
    previous_income = None
    pay_period = None
    previous_pay_period = None
    next_paydate = None
    previous_next_paydate = None
    employment_start_date = None
    previous_start_date = None
    end_date = None
    previous_end_date = None

    co_application_employer = None
    co_application_previous_employer = None
    co_application_employer_address_1 = None
    co_application_previous_employer_address_1 = None
    co_application_employer_address_2 = None
    co_application_previous_employer_address_2 = None
    co_application_employer_city = None
    co_application_previous_employer_city = None
    co_application_employer_state = None
    co_application_previous_employer_state = None
    co_application_employer_zip = None
    co_application_previous_employer_zip = None
    co_application_employment_title = None
    co_application_previous_employment_title = None
    co_application_income = None
    co_application_previous_income = None
    co_application_pay_period = None
    co_application_previous_pay_period = None
    co_application_job_type = None
    co_application_next_paydate = None
    co_applicant_employment_start_date = None
    co_application_end_date = None
    co_application_previous_job_type = None
    co_application_previous_next_paydate = None
    co_application_previous_start_date = None
    co_application_previous_end_date = None

    def __init__(self, lead_fields, field_definition_list, neo_id=None):
        if neo_id:
            self.application['neo_id'] = neo_id
        self.application['type'] = 'Online'
        self.application['status'] = 'Fresh'
        self.application['advertising_source'] = 'BuyerCall'
        self.application['referral_source'] = 'BuyerCall'
        self.application['joint-income'] = ''
        self.lead_fields = lead_fields
        self.field_definition_list = field_definition_list

    def process_lead(self):
        error_message = ''
        result = True

        try:
            for field in self.lead_fields:
                field_list = ExternalFormFieldDefinition.get_all_related_fields(field.field_id,
                                                                                self.field_definition_list)
                field_value = decrypt_value(field.field_value)

                # Buyer fields
                if 'firstname' in field_list:
                    if len(field_value) > 0:
                        self.first_name = field_value
                if 'lastname' in field_list:
                    if len(field_value) > 0:
                        self.last_name = field_value
                if 'gender' in field_list:
                    if len(field_value) > 0:
                        self.gender = field_value
                if 'marital_status' in field_list:
                    if len(field_value) > 0:
                        self.marital_status = field_value
                if 'birthday' in field_list:
                    if len(field_value) > 0:
                        try:
                            field_value = field_value.replace('/', '-')
                            final_field_value = datetime.datetime.strptime(field_value, '%m-%d-%Y').strftime('%Y-%m-%d')
                            self.birthday = final_field_value
                        except:
                            error_message = append_error(error_message, 'Invalid Application Birthday ' + str(
                                field_value) + ', must be in YYYY-mm-dd format.')
                        if not self.birthday:
                            self.birthday = set_string_value(field_value)
                if 'ssn' in field_list:
                    if len(field_value) > 0:
                        clean_field_value = field_value.replace('-', '')

                        if len(clean_field_value) == 9:
                            section_one = clean_field_value[0:3]
                            section_two = clean_field_value[3:5]
                            section_three = clean_field_value[5:9]
                            field_value = '{0}-{1}-{2}'.format(section_one, section_two, section_three)
                        self.ssn = field_value
                if 'email' in field_list:
                    if len(field_value) > 0:
                        self.email = field_value
                if 'phonenumber' in field_list:
                    if len(field_value) > 0:
                        self.home_phone = field_value
                if 'mobile_phone' in field_list:
                    if len(field_value) > 0:
                        self.cell_phone = field_value
                if 'work_phone' in field_list:
                    if len(field_value) > 0:
                        self.work_phone = field_value

                if 'number_of_dependents' in field_list:
                    if len(field_value) > 0:
                        self.number_of_dependents = field_value

                # Buyer current address
                if 'address_1' in field_list:
                    if len(field_value) > 0:
                        self.address_1 = field_value
                if 'address_2' in field_list:
                    if len(field_value) > 0:
                        self.address_2 = field_value
                if 'city' in field_list:
                    if len(field_value) > 0:
                        self.city = field_value
                if 'state' in field_list:
                    if len(field_value) > 0:
                        self.state = field_value
                if 'zip' in field_list:
                    if len(field_value) > 0:
                        self.zip = field_value
                if 'rent_or_own' in field_list:
                    if len(field_value) > 0:
                        self.rent_or_own = field_value
                if 'address_start_date' in field_list:
                    if len(field_value) > 0:
                        self.address_start_date = field_value
                if 'address_monthly_cost' in field_list:
                    if len(field_value) > 0:
                        self.address_monthly_cost = field_value

                # Buyer previous address
                if 'previous_address_1' in field_list:
                    if len(field_value) > 0:
                        self.previous_address_1 = field_value
                if 'previous_address_2' in field_list:
                    if len(field_value) > 0:
                        self.previous_address_2 = field_value
                if 'previous_city' in field_list:
                    if len(field_value) > 0:
                        self.previous_city = field_value
                if 'previous_state' in field_list:
                    if len(field_value) > 0:
                        self.previous_state = field_value
                if 'previous_zip' in field_list:
                    if len(field_value) > 0:
                        self.previous_zip = field_value

                # Buyer employer
                if 'employer' in field_list:
                    if len(field_value) > 0:
                        self.employer = field_value
                if 'previous_employer' in field_list:
                    if len(field_value) > 0:
                        self.previous_employer = field_value
                if 'employer_address_1' in field_list:
                    if len(field_value) > 0:
                        self.employer_address_1 = field_value
                if 'previous_employer_address_1' in field_list:
                    if len(field_value) > 0:
                        self.previous_employer_address_1 = field_value
                if 'employer_address_2' in field_list:
                    if len(field_value) > 0:
                        self.employer_address_2 = field_value
                if 'previous_employer_address_2' in field_list:
                    if len(field_value) > 0:
                        self.previous_employer_address_2 = field_value
                if 'employer_city' in field_list:
                    if len(field_value) > 0:
                        self.employer_city = field_value
                if 'previous_employer_city' in field_list:
                    if len(field_value) > 0:
                        self.previous_employer_city = field_value
                if 'employer_state' in field_list:
                    if len(field_value) > 0:
                        self.employer_state = field_value
                if 'previous_employer_state' in field_list:
                    if len(field_value) > 0:
                        self.previous_employer_state = field_value
                if 'employer_zip' in field_list:
                    if len(field_value) > 0:
                        self.employer_zip = field_value
                if 'previous_employer_zip' in field_list:
                    if len(field_value) > 0:
                        self.previous_employer_zip = field_value
                if 'employment_title' in field_list:
                    if len(field_value) > 0:
                        self.employment_title = field_value
                if 'previous_employment_title' in field_list:
                    if len(field_value) > 0:
                        self.previous_employment_title = field_value
                if 'income' in field_list:
                    if len(field_value) > 0:
                        self.income = field_value
                if 'previous_income' in field_list:
                    if len(field_value) > 0:
                        self.previous_income = field_value
                if 'pay_period' in field_list:
                    if len(field_value) > 0:
                        self.pay_period = field_value
                if 'previous_pay_period' in field_list:
                    if len(field_value) > 0:
                        self.previous_pay_period = field_value
                if 'employment_start_date' in field_list:
                    if len(field_value) > 0:
                        self.employment_start_date = field_value

                # Co-applicant fields
                if 'co_applicant_firstname' in field_list:
                    if len(field_value) > 0:
                        self.co_application_first_name = field_value
                if 'co_applicant_lastname' in field_list:
                    if len(field_value) > 0:
                        self.co_application_last_name = field_value
                if 'co_applicant_birthday' in field_list:
                    if len(field_value) > 0:
                        try:
                            field_value = field_value.replace('/', '-')
                            final_field_value = datetime.datetime.strptime(field_value, '%m-%d-%Y').strftime('%Y-%m-%d')
                            self.co_application_birthday = final_field_value
                        except:
                            error_message = append_error(error_message, 'Invalid Co-Applicant Birthday ' + str(
                                field_value) + ', must be in YYYY-mm-dd format.')
                        if not self.co_application_birthday:
                            self.co_application_birthday = set_string_value(field_value)
                if 'co_applicant_number_of_dependents' in field_list:
                    if len(field_value) > 0:
                        self.co_application_number_of_dependents = field_value
                if 'co_applicant_marital_status' in field_list:
                    if len(field_value) > 0:
                        self.co_application_marital_status = field_value

                # Current co-applicant address
                if 'co_applicant_address_1' in field_list:
                    if len(field_value) > 0:
                        self.co_application_address_1 = field_value
                if 'co_applicant_address_2' in field_list:
                    if len(field_value) > 0:
                        self.co_application_address_2 = field_value
                if 'co_applicant_city' in field_list:
                    if len(field_value) > 0:
                        self.co_application_city = field_value
                if 'co_applicant_state' in field_list:
                    if len(field_value) > 0:
                        self.co_application_state = field_value
                if 'co_applicant_zip' in field_list:
                    if len(field_value) > 0:
                        self.co_application_zip = field_value

                # Previous co-applicant address
                if 'co_applicant_previous_address_1' in field_list:
                    if len(field_value) > 0:
                        self.co_application_previous_address_1 = field_value
                if 'co_applicant_previous_address_2' in field_list:
                    if len(field_value) > 0:
                        self.co_application_previous_address_2 = field_value
                if 'co_applicant_previous_city' in field_list:
                    if len(field_value) > 0:
                        self.co_application_previous_city = field_value
                if 'co_applicant_previous_state' in field_list:
                    if len(field_value) > 0:
                        self.co_application_previous_state = field_value
                if 'co_applicant_previous_zip' in field_list:
                    if len(field_value) > 0:
                        self.co_application_previous_zip = field_value

                # Co-applicant employer
                if 'co_applicant_employer' in field_list:
                    if len(field_value) > 0:
                        self.co_application_employer = field_value
                if 'co_applicant_previous_employer' in field_list:
                    if len(field_value) > 0:
                        self.co_application_previous_employer = field_value
                if 'co_applicant_employer_address_1' in field_list:
                    if len(field_value) > 0:
                        self.co_application_employer_address_1 = field_value
                if 'co_applicant_previous_employer_address_1' in field_list:
                    if len(field_value) > 0:
                        self.co_application_previous_employer_address_1 = field_value
                if 'co_applicant_employer_address_2' in field_list:
                    if len(field_value) > 0:
                        self.co_application_employer_address_2 = field_value
                if 'co_applicant_previous_employer_address_2' in field_list:
                    if len(field_value) > 0:
                        self.co_application_previous_employer_address_2 = field_value
                if 'co_applicant_employer_city' in field_list:
                    if len(field_value) > 0:
                        self.co_application_employer_city = field_value
                if 'co_applicant_previous_employer_city' in field_list:
                    if len(field_value) > 0:
                        self.co_application_previous_employer_city = field_value
                if 'co_applicant_employer_state' in field_list:
                    if len(field_value) > 0:
                        self.co_application_employer_state = field_value
                if 'co_applicant_previous_employer_state' in field_list:
                    if len(field_value) > 0:
                        self.co_application_previous_employer_state = field_value
                if 'co_applicant_employer_zip' in field_list:
                    if len(field_value) > 0:
                        self.co_application_employer_zip = field_value
                if 'co_applicant_previous_employer_zip' in field_list:
                    if len(field_value) > 0:
                        self.co_application_previous_employer_zip = field_value
                if 'co_applicant_employment_title' in field_list:
                    if len(field_value) > 0:
                        self.co_application_employment_title = field_value
                if 'co_applicant_previous_employment_title' in field_list:
                    if len(field_value) > 0:
                        self.co_application_previous_employment_title = field_value
                if 'co_applicant_income' in field_list:
                    if len(field_value) > 0:
                        self.co_application_income = field_value
                if 'co_applicant_previous_income' in field_list:
                    if len(field_value) > 0:
                        self.co_application_previous_income = field_value
                if 'co_applicant_pay_period' in field_list:
                    if len(field_value) > 0:
                        self.co_application_pay_period = field_value
                if 'co_applicant_previous_pay_period' in field_list:
                    if len(field_value) > 0:
                        self.co_application_previous_pay_period = field_value
                if 'co_applicant_employment_start_date' in field_list:
                    if len(field_value) > 0:
                        self.co_applicant_employment_start_date = field_value

                # Location / Dealer Lot ID
                if 'location' in field_list:
                    if len(field_value) > 0:
                        self.location = field_value

                if 'dealer_lot_id' in field_list:
                    if len(field_value) > 0:
                        self.dealer_lot_id = field_value

                # Sales person
                if 'representative' in field_list:
                    if len(field_value) > 0:
                        self.representative = field_value

            if self.address_1 is not None and self.address_2 is not None:
                self.address_1 = self.address_1 + ' ' + self.address_2
            if self.previous_address_1 is not None and self.previous_address_2 is not None:
                self.previous_address_1 = self.previous_address_1 + ' ' + self.previous_address_2

            if self.co_application_address_1 is not None and self.co_application_address_2 is not None:
                self.co_application_address_1 = self.co_application_address_1 + ' ' + self.co_application_address_2
            if self.co_application_previous_address_1 is not None and self.co_application_previous_address_2 is not None:
                self.co_application_previous_address_1 = self.co_application_previous_address_1 + ' ' \
                                                         + self.co_application_previous_address_2

            if self.employer_address_1 is not None and self.employer_address_2 is not None:
                self.employer_address_1 = self.employer_address_1 + ' ' + self.employer_address_2
            if self.previous_employer_address_1 is not None and self.previous_employer_address_2 is not None:
                self.previous_employer_address_1 = self.previous_employer_address_1 + ' ' \
                                                   + self.previous_employer_address_2

            if self.co_application_employer_address_1 is not None \
                    and self.co_application_employer_address_2 is not None:
                self.co_application_employer_address_1 = self.co_application_employer_address_1 + ' ' \
                                                         + self.co_application_employer_address_2
            if self.co_application_previous_employer_address_1 is not None \
                    and self.co_application_previous_employer_address_2 is not None:
                self.co_application_previous_employer_address_1 = self.co_application_previous_employer_address_1 \
                                                                  + ' ' \
                                                                  + self.co_application_previous_employer_address_2
        except:
            error_message = append_error(error_message, 'Error processing lead.')
            result = False

        return result, error_message

    def set_applicant(self):
        self.applicant['first_name'] = set_string_value(self.first_name)
        self.applicant['last_name'] = set_string_value(self.last_name)
        self.applicant['date_of_birth'] = self.birthday
        self.applicant['ssn'] = self.ssn
        self.applicant['email_address'] = self.email
        self.applicant['cell_phone_number'] = self.cell_phone
        self.applicant['home_phone_number'] = self.home_phone
        self.applicant['work_phone_number'] = self.work_phone
        self.applicant['gender'] = set_string_value(self.gender)
        self.applicant['marital_status'] = set_string_value(self.marital_status)
        self.applicant['dependents_number'] = self.number_of_dependents

    def set_applicant_residences(self):
        self.applicant_residences = []
        current_residence = {}
        previous_residence = {}

        current_residence['street'] = set_string_value(self.address_1)
        current_residence['city'] = set_string_value(self.city)
        current_residence['state'] = set_string_value(self.state)
        current_residence['zip'] = set_string_value(self.zip)
        current_residence['residence_type'] = set_string_value(self.rent_or_own)
        current_residence['start_date'] = set_string_value(self.address_start_date)
        current_residence['payment'] = self.address_monthly_cost
        current_residence['current'] = True
        self.applicant_residences.append(current_residence)

        if self.previous_address_1:
            previous_residence['street'] = set_string_value(self.previous_address_1)
            previous_residence['city'] = set_string_value(self.previous_city)
            previous_residence['state'] = set_string_value(self.previous_state)
            previous_residence['zip'] = set_string_value(self.previous_zip)
            previous_residence['current'] = False
            self.applicant_residences.append(previous_residence)

    def set_applicant_employers(self):
        self.applicant_employers = []
        current_employer_obj = {}
        previous_employer_obj = {}

        current_employer_obj['employer'] = set_string_value(self.employer)
        current_employer_obj['position'] = set_string_value(self.employment_title)
        current_employer_obj['job_type'] = set_string_value(self.job_type)
        current_employer_obj['monthly_net_income'] = self.income
        current_employer_obj['pay_period'] = self.pay_period
        current_employer_obj['next_paydate'] = self.next_paydate
        current_employer_obj['start_date'] = self.employment_start_date
        current_employer_obj['end_date'] = self.end_date
        current_employer_obj['street'] = set_string_value(self.employer_address_1)
        current_employer_obj['city'] = set_string_value(self.employer_city)
        current_employer_obj['state'] = set_string_value(self.employer_state)
        current_employer_obj['zip'] = set_string_value(self.employer_zip)
        current_employer_obj['current'] = True
        self.applicant_employers.append(current_employer_obj)

        if self.previous_employer:
            previous_employer_obj['previous_employer'] = set_string_value(self.previous_employer)
            previous_employer_obj['position'] = set_string_value(self.previous_employment_title)
            previous_employer_obj['job_type'] = set_string_value(self.previous_job_type)
            previous_employer_obj['monthly_net_income'] = self.previous_income
            previous_employer_obj['pay_period'] = self.previous_pay_period
            previous_employer_obj['next_paydate'] = self.previous_next_paydate
            previous_employer_obj['start_date'] = self.previous_start_date
            previous_employer_obj['end_date'] = self.previous_end_date
            previous_employer_obj['previous_street'] = set_string_value(self.previous_employer_address_1)
            previous_employer_obj['previous_city'] = set_string_value(self.previous_employer_city)
            previous_employer_obj['previous_state'] = set_string_value(self.previous_employer_state)
            previous_employer_obj['previous_zip'] = set_string_value(self.previous_employer_zip)
            previous_employer_obj['current'] = False
            self.applicant_employers.append(previous_employer_obj)

    def set_co_applicant(self):
        if self.co_application_first_name is not None and self.co_application_last_name is not None:
            self.co_applicant = {}
            self.co_applicant_employers = []
            self.co_applicant_residences = []
            self.co_applicant['first_name'] = set_string_value(self.co_application_first_name)
            self.co_applicant['last_name'] = set_string_value(self.co_application_last_name)
            self.co_applicant['date_of_birth'] = self.co_application_birthday
            self.co_applicant['gender'] = set_string_value(self.co_application_gender)
            self.co_applicant['marital_status'] = set_string_value(self.co_application_marital_status)
            self.co_applicant['dependents_number'] = self.co_application_number_of_dependents

    def set_co_applicant_residences(self):
        self.co_applicant_residences = []
        current_residence = {}
        previous_residence = {}

        current_residence['street'] = set_string_value(self.co_application_address_1)
        current_residence['city'] = set_string_value(self.co_application_city)
        current_residence['state'] = set_string_value(self.co_application_state)
        current_residence['zip'] = set_string_value(self.co_application_zip)
        current_residence['current'] = True
        self.co_applicant_residences.append(current_residence)

        previous_residence['street'] = set_string_value(self.co_application_previous_address_1)
        previous_residence['city'] = set_string_value(self.co_application_previous_city)
        previous_residence['state'] = set_string_value(self.co_application_previous_state)
        previous_residence['zip'] = set_string_value(self.co_application_previous_zip)
        previous_residence['current'] = False
        self.co_applicant_residences.append(previous_residence)

    def set_co_applicant_employers(self):
        self.co_applicant_employers = []
        current_employer_obj = {}
        previous_employer_obj = {}

        current_employer_obj['employer'] = set_string_value(self.co_application_employer)
        current_employer_obj['position'] = set_string_value(self.co_application_employment_title)
        current_employer_obj['job_type'] = set_string_value(self.co_application_job_type)
        current_employer_obj['monthly_net_income'] = self.co_application_income
        current_employer_obj['pay_period'] = self.co_application_pay_period
        current_employer_obj['next_paydate'] = self.co_application_next_paydate
        current_employer_obj['start_date'] = self.co_applicant_employment_start_date
        current_employer_obj['end_date'] = self.co_application_end_date
        current_employer_obj['street'] = set_string_value(self.co_application_employer_address_1)
        current_employer_obj['city'] = set_string_value(self.co_application_employer_city)
        current_employer_obj['state'] = set_string_value(self.co_application_employer_state)
        current_employer_obj['zip'] = set_string_value(self.co_application_employer_zip)
        current_employer_obj['current'] = True
        self.co_applicant_employers.append(current_employer_obj)

        previous_employer_obj['previous_employer'] = set_string_value(self.co_application_previous_employer)
        previous_employer_obj['position'] = set_string_value(self.co_application_previous_employment_title)
        previous_employer_obj['job_type'] = set_string_value(self.co_application_previous_job_type)
        previous_employer_obj['monthly_net_income'] = self.co_application_previous_income
        previous_employer_obj['pay_period'] = self.co_application_previous_pay_period
        previous_employer_obj['next_paydate'] = self.co_application_previous_next_paydate
        previous_employer_obj['start_Date'] = self.co_application_previous_start_date
        previous_employer_obj['end_date'] = self.co_application_previous_end_date
        previous_employer_obj['previous_street'] = set_string_value(self.co_application_previous_employer_address_1)
        previous_employer_obj['previous_city'] = set_string_value(self.co_application_previous_employer_city)
        previous_employer_obj['previous_state'] = set_string_value(self.co_application_previous_employer_state)
        previous_employer_obj['previous_zip'] = set_string_value(self.co_application_previous_employer_zip)
        previous_employer_obj['current'] = False
        self.co_applicant_employers.append(previous_employer_obj)

    def build_lead_object(self):
        result = True
        error_message = ''

        try:
            self.application['car_lot'] = ''
            if self.location:
                self.application['car_lot'] = self.location
            elif self.dealer_lot_id:
                self.application['car_lot'] = self.dealer_lot_id
            self.application['salesperson'] = self.representative

            self.set_applicant()
            self.set_applicant_residences()
            self.applicant['residences'] = self.applicant_residences
            self.set_applicant_employers()
            self.applicant['employments'] = self.applicant_employers
            self.application['applicant'] = self.applicant

            self.set_co_applicant()
            if self.co_applicant is not None:
                self.set_co_applicant_residences()
                self.co_applicant['residences'] = self.co_applicant_residences
                self.set_co_applicant_employers()
                self.co_applicant['employments'] = self.co_applicant_employers
                self.application['coapplicant'] = self.co_applicant
        except:
            error_message = 'Error building lead JSON.'
            log.error('Error building lead JSON. Error: {}'.format(traceback.format_exc()))
            result = False

        return result, error_message

    def get_lead_object(self):
        # start creating request-log
        from buyercall.blueprints.sysadmin.utilities.request_log_task_call import LogRequestTaskTrigger
        from flask import request
        # LogRequestTaskTrigger().log_request_task_trigger(
        #                     request, "ams-2000")
        # end creating request-log
        return self.application


class AmsPreQualifyLead(object):
    lead_fields = []
    field_definition_list = []

    application = {}

    firstName = None
    lastName = None
    cellPhone = None
    suffix = None
    email = None
    address = None 
    city = None
    stateAbbreviation = None
    zipCode = None
    monthlyIncome = None
    
    utmSource = None
    utmMedium = None
    utmCampaign = None
    utm_content = None
    

    def __init__(self, lead_fields, field_definition_list, ams_prequalify_id=None):
        self.lead_fields = lead_fields
        self.field_definition_list = field_definition_list

    def process_lead(self):
        error_message = ''
        result = True

        try:
            for field in self.lead_fields:
                field_list = ExternalFormFieldDefinition.get_all_related_fields(field.field_id,
                                                                                self.field_definition_list)
                field_value = decrypt_value(field.field_value)

                # Buyer fields
                if 'firstname' in field_list:
                    if len(field_value) > 0:
                        self.firstName = field_value
                if 'lastname' in field_list:
                    if len(field_value) > 0:
                        self.lastName = field_value
                if 'phonenumber' in field_list:
                    if len(field_value) > 0:
                        self.cellPhone = field_value
                if 'suffix' in field_list:
                    if len(field_value) > 0:
                        self.suffix = field_value
                if 'email' in field_list:
                    if len(field_value) > 0:
                        self.email = field_value
                if 'address_1' in field_list:
                    if len(field_value) > 0:
                        self.address = field_value
                if 'city' in field_list:
                    if len(field_value) > 0:
                        self.city = field_value
                if 'state' in field_list:
                    if len(field_value) > 0:
                        self.stateAbbreviation = field_value
                if 'zip' in field_list:
                    if len(field_value) > 0:
                        self.zipCode = field_value 
                if 'zip' in field_list:
                    if len(field_value) > 0:
                        self.zipCode = field_value  
                if 'income' in field_list:
                    if len(field_value) > 0:
                        self.monthlyIncome = field_value
                if 'ad_campaign' in field_list:
                    if len(field_value) > 0:
                        self.utmCampaign = field_value
                if 'ad_content' in field_list:
                    if len(field_value) > 0:
                        self.utm_content = field_value
                if 'ad_medium' in field_list:
                    if len(field_value) > 0:
                        self.utmMedium = field_value
                if 'ad_source' in field_list:
                    if len(field_value) > 0:
                        self.utmSource = field_value

        except:
            error_message = append_error(error_message, 'Error processing lead.')
            result = False
        return result, error_message

    
    def build_lead_object(self):
        result = True
        error_message = ''
        self.application = {}
        
        try:
            # Extracting customer data
            self.application['firstName'] = self.firstName
            self.application['lastName'] = self.lastName
            self.application['cellPhone'] = self.cellPhone
            self.application['suffix'] = self.suffix
            self.application['email'] = self.email
            self.application['address'] = self.address
            self.application['city'] = self.city
            self.application['stateAbbreviation'] = self.stateAbbreviation
            self.application['zipCode'] = self.zipCode 
            self.application['monthlyIncome'] = self.monthlyIncome

        except Exception as e:
            error_message = f"Error building lead JSON: {str(e)}"
            result = False
        return result, error_message 

    def get_lead_object(self):
        return self.application



class AmsAnalyticsLead(object):
    lead_fields = []
    field_definition_list = []
    
    customers = []

    customer_data = {}
    applicant_residences = []
    applicant_employers = []
    applicant_income_and_debt = {}
    applicant_utm_paramenters = {}
    applicant_user = {}
 

    application = {}
    ams_analytics_id = None

    mappingId = 0
    isPrimary = True
    apartmentNumber = None
    # isCurrent

    firstName = None
    lastName = None
    middleName = None
    dateOfBirth = None
    cellPhone = None
    email = None
    homePhone = None
    suffix = None
    ssn = None
    driverLicenseNumber = None
    driverLicenseStateId = None
    driverLicenseState = None
    maritalStatusId = None
    maritalStatus = None
    numberOfDependents = None
    housingStatusId = None
    housingStatus = None

    address = None
    address2 = None
    city = None
    stateId = None
    state = None
    zip = None
    county = None
    township = None
    mortgageHolderOrLandlord = None
    landlordPhone = None
    monthlyMortgageOrRentPmt = None
    apartmentNumber = None
    startDate = None

    employerName = None
    occupation = None
    hourlyPay = None
    incomeTypeId = None
    incomeType = None
    hoursWorked = None
    employerStartDate = None
    monthlyGrossIncome = None
    payPeriodId = None
    payPeriod = None

    chapter = None
    dischargeDate = None
    downPayment = None

    co_applicant_firstName = None
    co_applicant_lastName = None
    co_applicant_middleName = None
    co_applicant_dateOfBirth = None
    co_applicant_cellPhone = None
    co_applicant_email = None
    co_applicant_homePhone = None
    co_applicant_suffix = None
    co_applicant_ssn = None
    co_applicant_driverLicenseNumber = None
    co_applicant_driverLicenseStateId = None
    co_applicant_driverLicenseState = None
    co_applicant_maritalStatusId = None
    co_applicant_maritalStatus = None
    co_applicant_numberOfDependents = None
    co_applicant_housingStatusId = None
    co_applicant_housingStatus = None

    co_applicant_address = None
    co_applicant_address2 = None
    co_applicant_city = None
    co_applicant_stateId = None
    co_applicant_state = None
    co_applicant_zip = None
    co_applicant_county = None
    co_applicant_township = None
    co_applicant_mortgageHolderOrLandlord = None
    co_applicant_landlordPhone = None
    co_applicant_monthlyMortgageOrRentPmt = None
    co_applicant_apartmentNumber = None
    co_applicant_startDate = None

    co_applicant_employerName = None
    co_applicant_occupation = None
    co_applicant_hourlyPay = None
    co_applicant_incomeTypeId = None
    co_applicant_incomeType = None
    co_applicant_hoursWorked = None
    co_applicant_employerStartDate = None
    co_applicant_monthlyGrossIncome = None
    co_applicant_payPeriodId = None
    co_applicant_payPeriod = None

    co_applicant_chapter = None
    co_applicant_dischargeDate = None
    co_applicant_downPayment = None


    utmSource = None
    utmMedium = None
    utmCampaign = None
    utm_content = None

    def __init__(self, lead_fields, field_definition_list, ams_analytics_id=None):
        
        self.lead_fields = lead_fields
        self.field_definition_list = field_definition_list

    def process_lead(self):
        error_message = ''
        result = True

        try:
            for field in self.lead_fields:
                field_list = ExternalFormFieldDefinition.get_all_related_fields(field.field_id,
                                                                                self.field_definition_list)
                field_value = decrypt_value(field.field_value)
                
                if 'firstname' in field_list:
                    if len(field_value) > 0:
                        self.firstName = field_value
                if 'lastname' in field_list:
                    if len(field_value) > 0:
                        self.lastName = field_value
                if 'middlename' in field_list:
                    if len(field_value) > 0:
                        self.middleName = field_value
                if 'birthday' in field_list:
                    if len(field_value) > 0:
                        self.dateOfBirth = field_value
                        
                if 'phonenumber' in field_list:
                    if len(field_value) > 0:
                        self.cellPhone = field_value
                
                if 'homephone' in field.field_id:
                    if len(field_value) > 0:
                        self.homePhone = field_value

                if 'address_1' in field_list:
                    if len(field_value) > 0:
                        self.address = field_value

                if 'address_2' in field_list:
                    if len(field_value) > 0:
                        self.address2 = field_value

                if 'city' in field_list:
                    if len(field_value) > 0:
                        self.city = field_value

                if 'state' in field_list:
                    if len(field_value) > 0:
                        self.state = field_value

                if 'zip' in field_list:
                    if len(field_value) > 0:
                        self.zip = field_value

                if 'country' in field.field_id:
                    if len(field_value) > 0:
                        self.county = field_value

                if 'township' in field_list:
                    if len(field_value) > 0:
                        self.township = field_value


                if 'monthlymortagerent' in field.field_id:
                    if len(field_value) > 0:
                        self.monthlyMortgageOrRentPmt = field_value



                if 'employer' in field_list:
                    if len(field_value) > 0:
                        self.employerName = field_value

                if 'employment_title' in field_list:
                    if len(field_value) > 0:
                        self.occupation = field_value

                if 'hours_worked' in field_list:
                    if len(field_value) > 0:
                        self.hoursWorked = field_value

                if 'income_type_0' in field_list:
                    if len(field_value) > 0:
                        self.incomeType = field_value


                if 'employment_start_date' in field_list:
                    if len(field_value) > 0:
                        self.employerStartDate = field_value


                if 'total_income' in field_list:
                    if len(field_value) > 0:
                        self.monthlyGrossIncome = field_value


                if 'pay_period' in field_list:
                    if len(field_value) > 0:
                        self.payPeriod = field_value


                if 'email' in field_list:
                    if len(field_value) > 0:
                        self.email = field_value


                if 'bankruptcy_declaration' in field_list:
                    if len(field_value) > 0:
                        self.everFiledBankruptcy = field_value


                if 'repossession_declaration' in field_list:
                    if len(field_value) > 0:
                        self.everHadVehicleRepossession = field_value


                if 'bankruptcy_chapter' in field_list:
                    if len(field_value) > 0:
                        self.chapter = field_value


                if 'bankruptcy_discharge_date' in field_list:
                    if len(field_value) > 0:
                        self.dischargeDate = field_value


                if 'down_payment_amount' in field_list:
                    if len(field_value) > 0:
                        self.downPayment = field_value

                if 'suffix' in field.field_id:
                    if len(field_value) > 0:
                        self.suffix = field_value

                if 'driver_license' in field_list:
                    if len(field_value) > 0:
                        self.driverLicenseNumber = field_value

                if 'driver_license_state' in field_list:
                    if len(field_value) > 0:
                        self.driverLicenseState = field_value

                if 'marital_status' in field_list:
                    if len(field_value) > 0:
                        self.maritalStatus = field_value

                if 'number_of_dependents' in field_list:
                    if len(field_value) > 0:
                        self.numberOfDependents = field_value

                if 'housing_status' in field.field_id:
                    if len(field_value) > 0:
                        self.housingStatus = field_value

                if 'address_start_date' in field_list:
                    if len(field_value) > 0:
                        self.startDate = field_value

                if 'landlord_phone' in field_list:
                    if len(field_value) > 0:
                        self.landlordPhone = field_value


                if 'landlord_name' in field_list:
                    if len(field_value) > 0:
                        self.mortgageHolderOrLandlord = field_value

                if 'hourlypay' in field.field_id:
                    if len(field_value) > 0:
                        self.hourlyPay = field_value

                if 'ssn' in field_list:
                    if len(field_value) > 0:
                        self.ssn = field_value

                if 'ad_campaign' in field.field_id:
                    if len(field_value) > 0:
                        self.utmCampaign = field_value
                if 'ad_content' in field.field_id:
                    if len(field_value) > 0:
                        self.utm_content = field_value

                if 'ad_medium' in field.field_id:
                    if len(field_value) > 0:
                        self.utmMedium = field_value


                if 'ad_source' in field.field_id:
                    if len(field_value) > 0:
                        self.utmSource = field_value
                
                
                
                
                if 'co_applicant_firstname' in field_list:
                    if len(field_value) > 0:
                        self.co_applicant_firstName = field_value
                if 'co_applicant_lastname' in field_list:
                    if len(field_value) > 0:
                        self.co_applicant_lastName = field_value
                if 'co_applicant_middlename' in field_list:
                    if len(field_value) > 0:
                        self.co_applicant_middleName = field_value
                if 'co_applicant_birthday' in field_list:
                    if len(field_value) > 0:
                        self.co_applicant_dateOfBirth = field_value
                        

                if 'co_applicant_phonenumber' in field_list:
                    if len(field_value) > 0:
                        self.co_applicant_cellPhone = field_value

                if 'co_applicant_address_1' in field_list:
                    if len(field_value) > 0:
                        self.co_applicant_address = field_value

                if 'co_applicant_address_2' in field_list:
                    if len(field_value) > 0:
                        self.co_applicant_address2 = field_value

                if 'co_applicant_city' in field_list:
                    if len(field_value) > 0:
                        self.co_applicant_city = field_value

                if 'co_applicant_state' in field_list:
                    if len(field_value) > 0:
                        self.co_applicant_state = field_value

                if 'co_applicant_zip' in field_list:
                    if len(field_value) > 0:
                        self.co_applicant_zip = field_value

                if 'co_applicant_country' in field_list:
                    if len(field_value) > 0:
                        self.co_applicant_county = field_value

                if 'co_applicant_township' in field_list:
                    if len(field_value) > 0:
                        self.co_applicant_township = field_value


                if 'co_applicant_monthlymortagerent' in field.field_id:
                    if len(field_value) > 0:
                        self.co_applicant_monthlyMortgageOrRentPmt = field_value



                if 'co_applicant_employer' in field_list:
                    if len(field_value) > 0:
                        self.co_applicant_employerName = field_value

                if 'co_applicant_employment_title' in field_list:
                    if len(field_value) > 0:
                        self.co_applicant_occupation = field_value

                if 'co_applicant_hours_worked' in field_list:
                    if len(field_value) > 0:
                        self.co_applicant_hoursWorked = field_value

                if 'co_applicant_income_type_0' in field.field_id:
                    if len(field_value) > 0:
                        self.co_applicant_incomeType = field_value


                if 'co_applicant_employment_start_date' in field_list:
                    if len(field_value) > 0:
                        self.co_applicant_employerStartDate = field_value


                if 'co_applicant_total_income' in field.field_id:
                    if len(field_value) > 0:
                        self.co_applicant_monthlyGrossIncome = field_value


                if 'co_applicant_pay_period' in field_list:
                    if len(field_value) > 0:
                        self.co_applicant_payPeriod = field_value


                if 'co_applicant_email' in field_list:
                    if len(field_value) > 0:
                        self.co_applicant_email = field_value


                if 'co_applicant_bankruptcy_declaration' in field_list:
                    if len(field_value) > 0:
                        self.co_applicant_everFiledBankruptcy = field_value


                if 'co_applicant_repossession_declaration' in field_list:
                    if len(field_value) > 0:
                        self.co_applicant_everHadVehicleRepossession = field_value


                if 'co_applicant_bankruptcy_chapter' in field_list:
                    if len(field_value) > 0:
                        self.co_applicant_chapter = field_value


                if 'co_applicant_bankruptcy_discharge_date' in field_list:
                    if len(field_value) > 0:
                        self.co_applicant_dischargeDate = field_value


                if 'co_applicant_down_payment_amount' in field_list:
                    if len(field_value) > 0:
                        self.co_applicant_downPayment = field_value

                if 'co_applicant_suffix' in field.field_id:
                    if len(field_value) > 0:
                        self.co_applicant_suffix = field_value

                if 'co_applicant_driver_license' in field_list:
                    if len(field_value) > 0:
                        self.co_applicant_driverLicenseNumber = field_value

                if 'co_applicant_driver_license_state' in field_list:
                    if len(field_value) > 0:
                        self.co_applicant_driverLicenseState = field_value

                if 'co_applicant_marital_status' in field_list:
                    if len(field_value) > 0:
                        self.co_applicant_maritalStatus = field_value

                if 'co_applicant_number_of_dependents' in field_list:
                    if len(field_value) > 0:
                        self.co_applicant_numberOfDependents = field_value

                if 'co_applicant_housing_status' in field.field_id:
                    if len(field_value) > 0:
                        self.co_applicant_housingStatus = field_value

                if 'co_applicant_address_start_date' in field_list:
                    if len(field_value) > 0:
                        self.co_applicant_startDate = field_value

                if 'co_applicant_landlord_phone' in field_list:
                    if len(field_value) > 0:
                        self.co_applicant_landlordPhone = field_value


                if 'co_applicant_landlord_name' in field_list:
                    if len(field_value) > 0:
                        self.co_applicant_mortgageHolderOrLandlord = field_value

                if 'co_applicant_hourlypay' in field.field_id:
                    if len(field_value) > 0:
                        self.co_applicant_hourlyPay = field_value

                if 'co_applicant_ssn' in field_list:
                    if len(field_value) > 0:
                        self.co_applicant_ssn = field_value
                
                if 'co_applicant_homephone' in field.field_id:
                    if len(field_value) > 0:
                        self.co_applicant_homePhone = field_value
                
                
                
        except:
            error_message = append_error(error_message, 'Error processing lead.')
            result = False

        return result, error_message

    def get_list_data(self):
        result = True

        client = AMSAnalytics(client_id=None, url=None)
        status_code, response_data = client.get_lists()
        
        if status_code == 200:
            for category in response_data:
                if category['name'] == 'MaritalStatuses' and self.maritalStatus:
                    for item in category['items']:
                        if item['name'] == self.maritalStatus:
                            self.maritalStatusId = item['id']
                        elif item['name'] == self.co_applicant_maritalStatus:
                            self.co_applicant_maritalStatusId = item['id']
                
                elif category['name'] == 'States' and self.state:
                    for item in category['items']:
                        if item['description'] == self.state:
                            self.stateId = item['id']
                        elif item['description'] == self.co_applicant_state:
                            self.co_applicant_stateId = item['id']
                        if item['description'] == self.driverLicenseState:
                            self.driverLicenseStateId = item['id']
                        elif item['description'] == self.co_applicant_driverLicenseState:
                            self.co_applicant_driverLicenseStateId= item['id']

                elif category['name'] == 'HousingStatuses' and self.housingStatus:
                    for item in category['items']:
                        if item['description'] == self.housingStatus:
                            self.housingStatusId = item['id']
                        elif item['description'] == self.co_applicant_housingStatus:
                            self.co_applicant_housingStatusId = item['id']

                elif category['name'] == 'IncomePeriods' and self.payPeriod:
                    for item in category['items']:
                        if item['name'] == self.payPeriod:
                            self.payPeriodId = item['id']
                        elif item['name'] == self.co_applicant_payPeriod:
                            self.co_applicant_payPeriodId = item['id']

                elif category['name'] == 'IncomeTypes' and self.incomeType:
                    for item in category['items']:
                        if item['name'] == self.incomeType:
                            self.incomeTypeId = item['id']
                        elif item['name'] == self.co_applicant_incomeType:
                            self.co_applicant_incomeTypeId = item['id']
            message = "Successfull"
        else:
            result = False
            message = "Failed to retrieve list data"
        return result, message

    def set_applicant(self):
        self.customer_data = {}

        self.customer_data['mappingId'] = self.mappingId
        self.customer_data['isPrimary'] = self.isPrimary
        self.customer_data['firstName'] = self.firstName
        self.customer_data['lastName'] = self.lastName
        self.customer_data['middleName'] = self.middleName
        self.customer_data['dateOfBirth'] = self.dateOfBirth
        self.customer_data['cellPhone'] = self.cellPhone
        self.customer_data['email'] = self.email
        self.customer_data['isPrimaryAddressSameAsPrimaryCustomer'] = False
        self.customer_data['homePhone'] = self.homePhone
        self.customer_data['suffix'] = self.suffix
        self.customer_data['ssn'] = self.ssn
        self.customer_data['driverLicenseNumber'] = self.driverLicenseNumber
        self.customer_data['driverLicenseStateId'] = self.driverLicenseStateId
        self.customer_data['maritalStatusId'] = self.maritalStatusId
        self.customer_data['numberOfDependents'] = self.numberOfDependents
        self.customer_data['housingStatusId'] = self.housingStatusId
    
    def co_set_applicant(self):
        self.customer_data = {}

        self.customer_data['mappingId'] = self.mappingId
        self.customer_data['isPrimary'] = self.isPrimary
        self.customer_data['firstName'] = self.co_applicant_firstName
        self.customer_data['lastName'] = self.co_applicant_lastName
        self.customer_data['middleName'] = self.co_applicant_middleName
        self.customer_data['dateOfBirth'] = self.co_applicant_dateOfBirth
        self.customer_data['cellPhone'] = self.co_applicant_cellPhone
        self.customer_data['email'] = self.co_applicant_email
        self.customer_data['isPrimaryAddressSameAsPrimaryCustomer'] = False
        self.customer_data['homePhone'] = self.co_applicant_homePhone
        self.customer_data['suffix'] = self.co_applicant_suffix
        self.customer_data['ssn'] = self.co_applicant_ssn
        self.customer_data['driverLicenseNumber'] = self.co_applicant_driverLicenseNumber
        self.customer_data['driverLicenseStateId'] = self.co_applicant_driverLicenseStateId
        self.customer_data['maritalStatusId'] = self.co_applicant_maritalStatusId
        self.customer_data['numberOfDependents'] = self.co_applicant_numberOfDependents
        self.customer_data['housingStatusId'] = self.co_applicant_housingStatusId

 
    def set_addresses(self):
        self.applicant_addresses = []
        current_residence = {}

        current_residence['mappingId'] = 0
        current_residence['isPrimary'] = True
        current_residence['address'] = set_string_value(self.address)
        current_residence['address2'] = set_string_value(self.address2)
        current_residence['stateId'] = set_string_value(self.stateId)
        current_residence['city'] = set_string_value(self.city)
        current_residence['county'] = set_string_value(self.county)
        current_residence['zip'] = set_string_value(self.zip)
        current_residence['township'] = set_string_value(self.township)
        current_residence['mortgageHolderOrLandlord'] = set_string_value(self.mortgageHolderOrLandlord)
        current_residence['landlordPhone'] = set_string_value(self.landlordPhone)
        current_residence['monthlyMortgageOrRentPmt'] = set_string_value(self.monthlyMortgageOrRentPmt)
        current_residence['apartmentNumber'] = set_string_value(self.apartmentNumber)
        current_residence['startDate'] = self.startDate
        self.applicant_addresses.append(current_residence)

    def co_set_addresses(self):
        self.applicant_addresses = []
        current_residence = {}

        current_residence['mappingId'] = 0
        current_residence['isPrimary'] = True
        current_residence['address'] = set_string_value(self.co_applicant_address)
        current_residence['address2'] = set_string_value(self.co_applicant_address2)
        current_residence['stateId'] = set_string_value(self.co_applicant_stateId)
        current_residence['city'] = set_string_value(self.co_applicant_city)
        current_residence['county'] = set_string_value(self.co_applicant_county)
        current_residence['zip'] = set_string_value(self.co_applicant_zip)
        current_residence['township'] = set_string_value(self.co_applicant_township)
        current_residence['mortgageHolderOrLandlord'] = set_string_value(self.co_applicant_mortgageHolderOrLandlord)
        current_residence['landlordPhone'] = set_string_value(self.co_applicant_landlordPhone)
        current_residence['monthlyMortgageOrRentPmt'] = self.co_applicant_monthlyMortgageOrRentPmt
        current_residence['apartmentNumber'] = set_string_value(self.co_applicant_apartmentNumber)
        current_residence['startDate'] = self.co_applicant_startDate
        self.applicant_addresses.append(current_residence)
        

    def set_employments(self):
        self.applicant_employers = []
        current_employer_obj = {}

        current_employer_obj['mappingId'] = 0
        current_employer_obj['isPrimary'] = True
        current_employer_obj['isCurrent'] = True
        current_employer_obj['employerName'] =  set_string_value(self.employerName)
        current_employer_obj['occupation'] = set_string_value(self.occupation)
        current_employer_obj['hourlyPay'] = self.hourlyPay
        current_employer_obj['incomeTypeId'] = self.incomeTypeId
        current_employer_obj['hoursWorked'] = self.hoursWorked
        current_employer_obj['employerStartDate'] =  self.employerStartDate
        current_employer_obj['monthlyGrossIncome'] = self.monthlyGrossIncome
        current_employer_obj['payPeriodId'] = self.payPeriodId
        
        self.applicant_employers.append(current_employer_obj)

    def co_set_employments(self):
        self.applicant_employers = []
        current_employer_obj = {}

        current_employer_obj['mappingId'] = 0
        current_employer_obj['isPrimary'] = True
        current_employer_obj['isCurrent'] = True
        current_employer_obj['employerName'] = set_string_value(self.co_applicant_employerName)
        current_employer_obj['occupation'] = set_string_value(self.co_applicant_occupation)
        current_employer_obj['hourlyPay'] = self.co_applicant_hourlyPay
        current_employer_obj['incomeTypeId'] = self.co_applicant_incomeTypeId ########
        current_employer_obj['hoursWorked'] = self.co_applicant_hoursWorked
        current_employer_obj['employerStartDate'] = self.co_applicant_employerStartDate
        current_employer_obj['monthlyGrossIncome'] = self.co_applicant_monthlyGrossIncome
        current_employer_obj['payPeriodId'] = self.co_applicant_payPeriodId #######
        
        self.applicant_employers.append(current_employer_obj)

    def set_income_and_debt(self):
        self.applicant_income_and_debt = {}
        
        self.applicant_income_and_debt['everFiledBankruptcy'] = True
        self.applicant_income_and_debt['everHadVehicleRepossession'] = True
        self.applicant_income_and_debt['chapter'] = self.chapter
        self.applicant_income_and_debt['dischargeDate'] = self.dischargeDate
        self.applicant_income_and_debt['downPayment'] = self.downPayment

    def co_set_income_and_debt(self):
        self.applicant_income_and_debt = {}
        
        self.applicant_income_and_debt['everFiledBankruptcy'] = True
        self.applicant_income_and_debt['everHadVehicleRepossession'] = True
        self.applicant_income_and_debt['chapter'] = self.co_applicant_chapter
        self.applicant_income_and_debt['dischargeDate'] = self.co_applicant_dischargeDate
        self.applicant_income_and_debt['downPayment'] = self.co_applicant_downPayment

    def set_utm_paramenters(self):
        self.applicant_utm_paramenters = {}
    
        self.applicant_utm_paramenters['utmSource'] = self.utmSource
        self.applicant_utm_paramenters['utmMedium'] = self.utmMedium
        self.applicant_utm_paramenters['utmCampaign'] = self.utmCampaign
        self.applicant_utm_paramenters['utm_content'] = self.utm_content
    

    def build_lead_object(self):
        result = True
        error_message = ''
        customers = [] 
    
        try:
            for i in range(2):  # Loop exactly two times
                # Extracting customer data
                if i == 0:
                    self.set_applicant()
                    
                    # Setting addresses
                    self.set_addresses()
                    self.customer_data['addresses'] =  self.applicant_addresses 
                    
                    # Setting employments
                    self.set_employments()
                    self.customer_data['employments'] =  self.applicant_employers 
                

                    # Setting income and debt
                    self.set_income_and_debt()
                    self.customer_data['incomeAndDebt'] =  self.applicant_income_and_debt

                    self.customer_data['otherIncomeAndDebt'] = []
                    self.customer_data['otherIncomes'] = []
                    self.customer_data['previousCarCredit'] = [{}]
                    customers.append(self.customer_data)
                elif i == 1 and self.co_applicant_firstName :
                    self.co_set_applicant()
                    
                    # Setting addresses
                    self.co_set_addresses()
                    self.customer_data['addresses'] =  self.applicant_addresses 
                    
                    
                    # Setting employments
                    self.co_set_employments()
                    self.customer_data['employments'] =  self.applicant_employers 
                    

                    # Setting income and debt
                    self.co_set_income_and_debt()
                    self.customer_data['incomeAndDebt'] =  self.applicant_income_and_debt
                    
                    

                    self.customer_data['otherIncomeAndDebt'] = []
                    self.customer_data['otherIncomes'] = []
                    self.customer_data['previousCarCredit'] = [{}]
                    customers.append(self.customer_data)
                
            self.application['customFields'] = []
            self.set_utm_paramenters()
            self.application['utmParameters'] = self.applicant_utm_paramenters
            self.application['customers'] = customers
            # Error handling
        except Exception as e:
            error_message = f"Error building lead JSON: {str(e)}"
            result = False

        return result, error_message    

    def get_lead_object(self):
        return self.application