def property_search(waterJsonString):
    try:
        water = json.loads(waterJsonString)
        mobilenumber = water[0]["mobilenumber"]
        if mobilenumber != None:

            access_token = superuser_login()["access_token"]
            request_data = {"RequestInfo": {"authToken": access_token}}

            url = config.URL_PROPERTY_SEARCH + "?tenantId=" + tenant_id + "&mobileNumber=" + mobilenumber
            response = requests.post(url, json=request_data).json()

            data = response
            if (len(data['Properties']) == 0):
                return config.NO_PROPERTY_MESSAGE
            else:
                for property in data['Properties']:
                    if (property["owners"][0]["name"]
                            == water[0]["applicantname"]) and (
                                property["owners"][0]["fatherOrHusbandName"]
                                == water[0]["guardianname"]):
                        return property['propertyId']

                        return config.NO_PROPERTY_MESSAGE
        else:
            return config.NO_MOBILE_NUMBER

    except Exception as ex:
        print("Exception occurred while searching the property", ex)
        return config.NO_PROPERTY_MESSAGE
예제 #2
0
def main():
    try:
        if connection is not None and cursor is not None:
            set_path = """set search_path to {}""".format(schema_name)
            cursor.execute(set_path)
            my_path = os.path.abspath(os.path.dirname(__file__))
            # print(my_path)
            # /home/walkingtree/Desktop/migration/water/sql/water-collection-query.sql
            path = os.path.join(my_path, "../sql/water-collection-query.sql")
            print(path)
            sql = open(path, mode='r', encoding='utf-8-sig').read()
            # print(sql)

            access_token = superuser_login()["access_token"]
            # property_id = "65af3a8d-ab1b-4cb8-9a81-ac56583abff6"
            # property_id = "c1578dac-7e8f-45a4-ab17-1d57a55f6a40"
            # egov micro qa property id
            continue_processing = True
            while continue_processing:
                cursor.execute(sql)
                data = cursor.fetchmany(int(batch_size))
                if not data:
                    print("No more data to process. Script exiting")
                    continue_processing = False
                    cursor.close()
                    connection.close()

                for row in data:
                    # print(rows)
                    json_data = row[0]
                    consumer_code = json_data["consumercode"]
                    start = time.time()
                    payments = Payments()
                    payments.prepare_payments(json_data, 'pb.amritsar')
                    request, response = payments.upload_water_collection(access_token)
                    print("Water connection created", json.dumps(response))
                    # time_taken = time.time() - start

    except Exception as ex:
        print("Exception occurred while pushing data to API.+ ")
        print(ex)
def main():
    try:
        if connection is not None and cursor is not None:
            set_path = """set search_path to {}""".format(schema_name)
            cursor.execute(set_path)
            my_path = os.path.abspath(os.path.dirname(__file__))
            # print(my_path)
            path = os.path.join(my_path, "../sql/water_search.sql")
            print(path)
            sql = open(path, mode='r', encoding='utf-8-sig').read()
            # print(sql)

            access_token = superuser_login()["access_token"]
            property_id = "65af3a8d-ab1b-4cb8-9a81-ac56583abff6"
            continue_processing = True
            while continue_processing:
                cursor.execute(sql)
                data = cursor.fetchmany(int(batch_size))
                if not data:
                    print("No more data to process. Script exiting")
                    continue_processing = False
                    cursor.close()
                    connection.close()

                for row in data:
                    # print(rows)
                    json_data = row[0]
                    consumer_code = json_data["consumercode"]
                    start = time.time()
                    water = WaterConnectionRequest()
                    water.prepare_water_connection(json_data, tenant_id,
                                                   property_id)
                    request, response = water.upload_water_connection(
                        access_token)
                    print("Water connection created", json.dumps(response))
                    time_taken = time.time() - start

    except Exception as ex:
        print("Exception occurred while pushing data to API.+ ")
        print(ex)
예제 #4
0
from common import superuser_login, cleanup_property

properties = (('PT-1012-622468', 'pb.testing'), )

if __name__ == "__main__":
    login = superuser_login()
    auth_token = login["access_token"]

    cleanup_property(auth_token, properties)
예제 #5
0
        return api_call(auth_token,
                        "egov-common-masters/businessDetails/_create",
                        {"tenantId": tenant_id}, "BusinessDetails", [data])


def data_rainmaker_tl(tenant_id, auth_token, modules, locale):
    return api_call(auth_token, "egov-common-masters/businessCategory/_create",
                    {
                        "tenantId": tenant_id,
                        "modules": modules,
                        "locale": locale
                    })


if __name__ == "__main__":
    auth_token = superuser_login()["access_token"]
    tenant_id = "pb.zirakpur"
    # print(search_bank("pb.zirakpur", auth_token))Cash-Cash In Transit
    # print(search_bank_branches(tenant_id, auth_token, 'AXIS'))
    # upsert_bank(tenant_id, auth_token, 'AXIS', 'AXIS BANK')
    # print(upsert_bankbranches(tenant_id, auth_token, 'AXIS', 'AXIS_BANK', 'zirakpur', 'Punjab', '9876543212', 'deep'))
    # print(upsert_account_code_purposes(tenant_id,auth_token, 'Cheque In Hand'))
    # print(upsert_account_code_purposes(tenant_id,auth_token, 'Demand Draft In Hand'))
    # print(upsert_account_code_purposes(tenant_id,auth_token, 'Online'))
    # print(upsert_account_code_purposes(tenant_id,auth_token, 'Cash In Hand'))
    # print(upsert_chart_of_accounts(tenant_id, auth_token, "1", "Income", "I", None, None))
    # print(upsert_chart_of_accounts(tenant_id,auth_token,'4501003','Cash-Cash ',"A","Cash In Hand","4501001"))
    # print(search_chart_of_accounts(tenant_id,auth_token,'4'))
    # print(upsert_chart_of_accounts(tenant_id, auth_token, '4', 'Assets', "A",None, None))
    # print(upsert_chart_of_accounts(tenant_id,auth_token,'450','Cash and Bank balance',"A",None,"4"))
    # print(upsert_chart_of_accounts(tenant_id,auth_token,'45010','Cash-Cash',"A",None,"450"))
def main():
    auth_token = superuser_login()["access_token"]
    update_user_password(auth_token, "pb.testing", "ptemp03", "ptemp03")
예제 #7
0
def main():
    auth_token = superuser_login()["access_token"]

    download_revenue_boundary(auth_token, "REVENUE")
예제 #8
0
def main():
    auth_token = superuser_login()["access_token"]
    for tenant in tenants:
        create_and_update_billing_slab(auth_token, tenant)
def create_boundary_new(auth_token, config_function, boundary_type):
    current_boundary_type = boundary_type
    config_function()

    tenant_id = config.TENANT_ID
    # boundary_datas = get_mdms_boundary_data(auth_token, tenant_id)
    #
    # for boundary_datas in boundary_datas:
    #     if boundary_datas["hierarchyType"]["code"] == boundary_type:
    #         boundary_datas = boundary_datas["boundary"]["children"]
    #         break

    dfs = open_excel_file(config.SHEET)
    locality = get_sheet(dfs, config.SHEET_LOCALITY)

    index_zone_name = get_column_index(locality, config.COLUMN_ZONE_NAME) or 1
    index_zone_code = get_column_index(locality, config.COLUMN_ZONE_CODE) or 2
    index_ward_name = get_column_index(locality, config.COLUMN_WARD_NAME) or 3
    index_ward_code = get_column_index(locality, config.COLUMN_WARD_CODE) or 4
    index_locality_name = get_column_index(locality,
                                           config.COLUMN_LOCALITY_NAME) or 5
    index_locality_code = get_column_index(locality,
                                           config.COLUMN_LOCALITY_CODE) or 6
    index_area_name = get_column_index(locality,
                                       config.COLUMN_LOCALITY_AREA) or 7

    zone_to_code_map = {}
    zone_code_map = {}
    ward_code_map = {}
    ward_to_code_map = {}
    locality_data = []
    ward_data = {}
    zone_ward_map = {}
    for _, row in locality.iterrows():
        zone_to_code_map[
            row[index_zone_name].strip()] = row[index_zone_code].strip()
        zone_to_code_map[
            row[index_zone_code].strip()] = row[index_zone_name].strip()
        zone_code_map[
            row[index_zone_code].strip()] = row[index_zone_name].strip()
        ward_to_code_map[
            row[index_ward_name].strip()] = row[index_ward_code].strip()
        ward_to_code_map[
            row[index_ward_code].strip()] = row[index_ward_name].strip()
        ward_code_map[
            row[index_ward_code].strip()] = row[index_ward_name].strip()

        zone_ward_map[row[index_zone_code].strip()] = zone_ward_map.get(
            row[index_zone_code].strip(), set())
        zone_ward_map[row[index_zone_code].strip()].add(
            row[index_ward_code].strip())

        if row[index_ward_name] not in ward_data:
            ward_data[row[index_ward_name]] = []
            ward_data[row[index_ward_name]].append({
                "id":
                str(uuid.uuid4()),
                "boundaryNum":
                1,
                "name":
                row[index_ward_name].strip(),
                "localname":
                row[index_ward_name].strip(),
                "longitude":
                None,
                "latitude":
                None,
                "label":
                "Block",
                "code":
                row[index_ward_code].strip(),
                "zone":
                row[index_zone_code].strip(),
                "children": []
            })

        area = "" if current_boundary_type == "ADMIN" else row[
            index_area_name].strip().upper().replace(" ", "").replace("-", "")
        area_code = area.replace("AREA", "A")

        if current_boundary_type == "REVENUE" and area not in ("AREA1",
                                                               "AREA2",
                                                               "AREA3"):
            raise InvalidArgumentException("Area type is not valid - " + area)

        if area_code:
            area_code = " - " + area_code

        locality_data.append({
            "id":
            str(uuid.uuid4()),
            "boundaryNum":
            1,
            "name":
            row[index_locality_name].strip() + " - " +
            ward_to_code_map[row[index_ward_name].strip()] + area_code,
            "localname":
            row[index_locality_name].strip() + " - " +
            ward_to_code_map[row[index_ward_name].strip()] + area_code,
            "longitude":
            None,
            "latitude":
            None,
            "label":
            "Locality",
            "code":
            row[index_locality_code].strip(),
            "ward":
            row[index_ward_code].strip(),
            "area":
            area,
            "children": []
        })
    ward_list = []
    zone_ward_len = 0
    for code, zone_ward in zone_ward_map.items():
        for ward in zone_ward:
            ward_list.append(ward)
        zone_ward_len = zone_ward_len + len(zone_ward)

    zone_data = []
    for zones in zone_code_map:
        name = zone_code_map[zones]
        zone_data.append({
            "id": str(uuid.uuid4()),
            "boundaryNum": 1,
            "name": name.strip(),
            "localname": name.strip(),
            "longitude": None,
            "latitude": None,
            "label": "Zone",
            "code": zones.strip(),
            "children": []
        })

    # for boundary_data in boundary_datas:
    #     for ward in boundary_data["children"]:
    #         for revloc in ward["children"]:
    #             for locality in locality_data:
    #                 if locality['code'] == revloc['code']:
    #                     # locality['id']=None
    #                     locality['id'] = revloc['id']

    ward_loc_data = []
    for id, wards_data in ward_data.items():
        for wards in wards_data:
            for locality in locality_data:
                if locality["ward"] == wards["code"]:
                    wards["children"].append(locality)
            ward_loc_data.append(wards)

    # for boundary_data in boundary_datas:
    #     for zones in zone_data:
    #         if zones['code'] == boundary_data['code']:
    #             zones['id'] = boundary_data['id']
    #     for ward in boundary_data["children"]:
    #         for loc_ward in ward_loc_data:
    #             if loc_ward["code"] == ward["code"]:
    #                 loc_ward["id"] = ward["id"]

    for ward_loc in ward_loc_data:
        for loc in ward_loc["children"]:
            if loc["ward"]:
                loc.pop("ward")

    for zone in zone_data:
        for ward_loc in ward_loc_data:
            if zone["code"] == ward_loc["zone"]:
                zone["children"].append(ward_loc)

    for zones in zone_data:
        for wards in zones["children"]:
            if wards['zone']:
                wards.pop('zone')

    import json
    # current_boundary_type = "ADMIN"

    new_boundary_data = {
        "hierarchyType": {
            "code": current_boundary_type,
            "name": current_boundary_type
        },
        "boundary": {
            "id": 1,
            "boundaryNum": 1,
            "name": config.CITY_NAME,
            "localname": config.CITY_NAME,
            "longitude": None,
            "latitude": None,
            "label": "City",
            "code": config.TENANT_ID,
            "children": zone_data
        }
    }

    final_data = {
        "tenantId": config.TENANT_ID,
        "moduleName": "egov-location",
        "TenantBoundary": [new_boundary_data]
    }

    data = json.dumps(final_data, indent=2)

    auth_token = superuser_login()["access_token"]
    errors = validate_boundary_data(auth_token, final_data, boundary_type,
                                    config.BOUNDARY_DUPLICATE_CHECK,
                                    config.BOUNDARY_USED_CHECK)

    # validate for one block is in multiple zones
    freq = {}
    for item in ward_list:
        if (item in freq):
            freq[item] += 1
        else:
            freq[item] = 1

    for key, value in freq.items():
        if value > 1:
            errors.append(
                "\nBlock : \"{}\"  is in multiple zones ".format(key))

    if len(errors) > 0:
        print("error list")
        for error in errors:
            print(error)
        return

    print(data)

    import os
    response = os.getenv(
        "ASSUME_YES",
        None) or input("Do you want to append the data in repo (y/[n])?")

    if response.lower() == "y":

        boundary_path = config.MDMS_LOCATION / config.CITY_NAME.lower(
        ) / "egov-location"
        os.makedirs(boundary_path, exist_ok=True)

        if os.path.isfile(boundary_path / "boundary-data.json"):
            with open(boundary_path / "boundary-data.json") as f:
                existing_boundary_data = json.load(f)

            if len(existing_boundary_data["TenantBoundary"]) == 0:
                # should never happen but just in case
                existing_boundary_data["TenantBoundary"].append(
                    new_boundary_data)
                print("Boundary added")
            elif len(existing_boundary_data["TenantBoundary"]) == 1:
                if existing_boundary_data["TenantBoundary"][0][
                        "hierarchyType"]["code"] == current_boundary_type:
                    existing_boundary_data["TenantBoundary"][
                        0] = new_boundary_data
                    print("Boundary already exists. Overwriting")
                else:
                    existing_boundary_data["TenantBoundary"].append(
                        new_boundary_data)
                    print("Boundary file exists. Adding new data")
            elif len(existing_boundary_data["TenantBoundary"]) == 2:
                if existing_boundary_data["TenantBoundary"][0][
                        "hierarchyType"]["code"] == current_boundary_type:
                    existing_boundary_data["TenantBoundary"][
                        0] = new_boundary_data
                else:
                    existing_boundary_data["TenantBoundary"][
                        1] = new_boundary_data
                print("Boundary already exists. Overwriting")
                print("File Path : ", boundary_path, "boundary-data.json")

        else:
            # the file doesn't exists already, so we can safely generate current boundary
            print("Boundary didn't exist. Creating one")
            print("File Path : ", boundary_path + "boundary-data.json")
            existing_boundary_data = final_data

        with open(boundary_path / "boundary-data.json", "w") as f:
            json.dump(existing_boundary_data, f, indent=2)
def main():
    auth_token = superuser_login()["access_token"]
    create_boundary_new(auth_token, load_new_revenue_boundary_config,
                        "REVENUE")
def main():
    try:
        if connection is not None and cursor is not None:
            set_path = """set search_path to {}""".format(schema_name)
            cursor.execute(set_path)
            my_path = os.path.abspath(os.path.dirname(__file__))
            # print(my_path)
            path = os.path.join(my_path, "../sql/water_search.sql")
            print(path)
            sql = open(path, mode='r', encoding='utf-8-sig').read()
            # print(sql)

            ws_access_token = ws_user_login()["access_token"]
            print("access token:", ws_access_token)

            # property_id = "65af3a8d-ab1b-4cb8-9a81-ac56583abff6"
            # property_id = "c1578dac-7e8f-45a4-ab17-1d57a55f6a40"
            # egov micro qa property id
            # property_id = "601a9410-a873-4bc5-bd7c-37d3864f3beb"
            # punjab qa property id
            property_id = "0af72ed5-0df3-41de-8749-7275fbfacfe2"

            continue_processing = True
            while continue_processing:
                cursor.execute(sql)
                data = cursor.fetchmany(int(batch_size))
                if not data:
                    print("No more data to process. Script exiting")
                    continue_processing = False
                    cursor.close()
                    connection.close()

                for row in data:
                    # print(rows)
                    json_data = row[0]
                    consumer_code = json_data["consumercode"]
                    start = time.time()
                    water = WaterConnectionRequest()
                    print("ERP Water data", json.dumps(json_data))
                    water.prepare_water_connection(json_data, tenant_id,
                                                   property_id)
                    request, response = water.upload_water_connection(
                        ws_access_token)
                    print("Water connection created", json.dumps(response))
                    # time_taken = time.time() - start

                    if "WaterConnection" in response:
                        super_access_token = superuser_login()["access_token"]
                        print("super_access_token: ", super_access_token)
                        application_number = response["WaterConnection"][0][
                            "applicationNo"]
                        ack_no = water.property.get("acknowldgementNumber")
                        print("ack_no: ", ack_no)
                        owner_uuid = water.property.get("owners")[0]["uuid"]
                        print("UUID: ", owner_uuid)
                        wd = WaterDemand()
                        demands = wd.prepare_demand(json_data, tenant_id,
                                                    application_number,
                                                    owner_uuid)
                        wd_request, wd_response = wd.create_demand(
                            super_access_token, demands)
                        print(wd_request, wd_response)
                        print("Demand request", json.dumps(wd_request))
                        print("Demand created", json.dumps(wd_response))
                        # penalty_request, penalty_response = wd.generate_penalty(super_access_token, tenant_id, applicationNo)
                        # print("Penalty Generated", json.dumps(penalty_response))
                        bill_request, bill_response = wd.generate_bill(
                            super_access_token, tenant_id, application_number)
                        print("Bill Generated", json.dumps(bill_response))
                        print("A Water with unique identifier:", consumer_code,
                              "is migrated successfully with applicationNo:",
                              application_number)

    except Exception as ex:
        print("Exception occurred while pushing data to API.+ ")
        print(ex)
def main():
    auth_token = superuser_login()["access_token"]
    from config import load_new_admin_boundary_config
    create_boundary_new(auth_token, load_new_admin_boundary_config, "ADMIN")
def main():
    connection = psycopg2.connect(
        "dbname={} user={} password={} host={}".format(dbname, dbuser,
                                                       dbpassword, host))
    cursor = connection.cursor()
    postgresql_select_Query = """
        select row_to_json(pd) from pt_legacy_data as pd where  
        pd.new_propertyid is not null
        and pd.receipt_status is NULL
        and "Session" = '2019-2020'
        and batchname = '{}'
        limit 10
    """.format(batch)

    auth_token = superuser_login()["access_token"]

    continue_processing = True

    while continue_processing:
        cursor.execute(postgresql_select_Query)
        data = cursor.fetchmany(10)

        # continue_processing = False
        if not data:
            print("No more data to process. Script exiting")
            continue_processing = False
            cursor.close()
            connection.close()

        print("found data for {}".format(len(data)))

        for row in data:
            json_data = row[0]
            uuid = json_data["uuid"]

            print("processing uuid - {}".format(uuid))
            new_propertyid = json_data["new_propertyid"]

            session = json_data["Session"].replace("-20", "-")

            owner = json_data["Owner"].split('/')[0].strip()

            amount = {
                "PT_ADHOC_REBATE": 0,
                "PT_ADVANCE_CARRYFORWARD": 0,
                "PT_OWNER_EXEMPTION": 0,
                "PT_TIME_REBATE": -round(float(json_data["Rebate"])),
                "PT_UNIT_USAGE_EXEMPTION":
                -round(float(json_data["ExemptionAmt"])),
                "PT_ADHOC_PENALTY": 0,
                "PT_TAX": round(float(json_data["GrossTax"])),
                "PT_FIRE_CESS": round(float(json_data["FireCharges"])),
                "PT_CANCER_CESS": 0,
                "PT_TIME_PENALTY": round(float(json_data["Penalty"])),
                "PT_TIME_INTEREST": round(float(json_data["InterestAmt"]))
            }

            amount = {
                "PT_ADHOC_REBATE": 0,
                "PT_ADVANCE_CARRYFORWARD": 0,
                "PT_OWNER_EXEMPTION": 0,
                "PT_TIME_REBATE": 0,
                "PT_UNIT_USAGE_EXEMPTION": 0,
                "PT_ADHOC_PENALTY": 0,
                "PT_TAX": float(json_data["TaxAmt"]),
                "PT_FIRE_CESS": 0,
                "PT_CANCER_CESS": 0,
                "PT_TIME_PENALTY": 0,
                "PT_TIME_INTEREST": 0
            }

            g8_book_no = json_data["G8BookNo"]

            g8_receipt_no = json_data["G8ReceiptNo"]

            if g8_receipt_no and g8_book_no:
                old_g8_receiptno = g8_book_no + '/' + g8_receipt_no
            elif g8_receipt_no:
                old_g8_receiptno = g8_receipt_no
            else:
                old_g8_receiptno = json_data["AcknowledgementNo"]

            payment_date = json_data["PaymentDate"]

            tax_amt = float(json_data["TaxAmt"])

            payment_mode = "Cash"  # json_data["PaymentMode"]

            try:
                start_time = time.time()
                receipt_request, receipt_response = create_manual_receipt_collection(
                    auth_token, tenant, new_propertyid,
                    session, owner, amount, old_g8_receiptno,
                    to_epoch(payment_date), tax_amt, payment_mode)
                time_taken_receipt = time.time() - start_time

                if "Receipt" in receipt_response:
                    print("receipt creation successfull")
                    update_db_record(
                        uuid,
                        receipt_number=receipt_response["Receipt"][0]["Bill"]
                        [0]["billDetails"][0]["receiptNumber"],
                        receipt_status="COMPLETED",
                        time_taken_receipt=time_taken_receipt,
                        receipt_response=json.dumps(receipt_response),
                        receipt_request=json.dumps(receipt_request))
                else:
                    print("receipt create failed with error")
                    # Some error has occurred
                    update_db_record(
                        uuid,
                        receipt_status="ERROR",
                        receipt_response=json.dumps(receipt_response),
                        receipt_request=json.dumps(receipt_request))

                    pass
            except Exception as ex:
                import traceback
                traceback.print_exc()
                update_db_record(uuid,
                                 receipt_status="EXCEPTION",
                                 receipt_response=str(ex))
예제 #14
0
def main():
    city = config.CITY_NAME

    sheets = config.BASE_PPATH / "employees"
    sheet_name = sheets / (city.lower() + ".csv")
    tenant_id = "pb." + city.lower()

    auth_token = superuser_login()["access_token"]
    start_row = 1

    with open(sheet_name) as csvfile:
        readCSV = csv.reader(csvfile, delimiter=',')
        current_row = 0
        for row in readCSV:
            current_row += 1

            if current_row < start_row:
                continue

            headers = {'Content-Type': 'application/json'}

            details = []
            roles = []
            is_primary = True

            departments = row[6]
            role_codes = row[10]
            role_names = row[11]
            designation = row[7]
            password = row[9]
            username = row[8]
            mobile_number = row[2]
            name = row[0]

            existing_employees = get_employees_by_id(auth_token, username, tenant_id)

            roles_needed = set(map(str.strip, role_codes.split("|")))

            if existing_employees:
                # This employee already exists
                existing_mobilenumber = existing_employees[0]['mobileNumber']
                roles_currently = set(map(lambda role: role['code'], existing_employees[0]['roles']))
                ask_for_role_update = False

                if existing_mobilenumber != mobile_number:
                    print(
                        "The employee {} already exist with mobile number {}. You have specified a different mobile number {}".format(
                            username, existing_mobilenumber, mobile_number))
                    ask_for_role_update = True
                else:
                    print("Employee", username, tenant_id, name, mobile_number, "already exists - ",
                          len(existing_employees))

                if roles_needed.issubset(roles_currently):
                    print("The employee already has all required roles. Nothing needed")
                else:
                    if ask_for_role_update:
                        username_update = input(
                            "Would you like to add " + role_codes + " to " + username + "[Use n for skip]? ")
                        if username_update.lower() == "n":
                            print("Skipping adding required roles to user - {}".format(username))
                            continue
                    else:
                        print("Adding required roles to user - {}".format(username))
                    add_role_to_user(auth_token, username, tenant_id, roles_needed - roles_currently)
                continue

            existing_employees = get_employees_by_phone(auth_token, mobile_number, tenant_id)

            if existing_employees:
                info = map(lambda emp: "(username={}, mob={}, name={}, roles={}".format(
                    emp["userName"],
                    emp["mobileNumber"],
                    emp["name"],
                    "|".join(map(lambda role: role["code"], emp["roles"])))
                           , existing_employees)
                print("{} Employee(s) with mobile number {} already exists".format(len(existing_employees),
                                                                                   mobile_number), list(info))
                if len(existing_employees) > 1:
                    username_update = input(
                        "Which user would you like to update with " + role_codes + " [Use n for skip]? ")
                else:
                    username_update = input(
                        "Will you like to add the " + role_codes + " to user {} [Yn]? ".format(
                            existing_employees[0]["userName"]))
                    if username_update.strip().lower() == "n":
                        print("Skipping the user creation for {}".format(username))
                        continue
                    else:
                        username_update = existing_employees[0]["userName"]

                if username_update.strip().lower() == "n":
                    print("Skipping the user creation for {}".format(username))
                    continue
                else:
                    employee_found = list(filter(lambda emp: emp["userName"] == username_update, existing_employees))
                    if not employee_found:
                        print("Cannot find employee with username - " + username_update)
                    else:
                        roles_currently = set(map(lambda role: role['code'], employee_found[0]['roles']))
                        add_role_to_user(auth_token, username_update, tenant_id, roles_needed - roles_currently)
                continue

            for department in departments.split("|"):
                {
                    "fromDate": 0,
                    "toDate": None,
                    "department": department.strip(),
                    "isCurrentAssignment": True,
                    "designation": designation.strip(),
                    "reportingTo": "",
                    "isHod": True
                }
                is_primary = False

            for role, role_name in zip(role_codes.split("|"), role_names.split("|")):
                roles.append({"code": role, "name": role_name, "tenantId": tenant_id})

            post_data = {
                "RequestInfo": {
                    "authToken": "{{access_token}}"
                },
                "Employees": [
                    {
                        "user": {
                            "name": name,
                            "userName": username,
                            "fatherOrHusbandName": "F",
                            "mobileNumber": mobile_number,
                            "gender": "",
                            "dob": 0,
                            "roles": [
                            ],
                            "tenantId": tenant_id
                        },
                        "dateOfAppointment": 0,
                        "employeeType": "PERMANENT",
                        "employeeStatus": "EMPLOYED",
                        "jurisdictions": [
                            {
                                "hierarchy": "ADMIN",
                                "boundary": tenant_id,
                                "boundaryType": "City",
                                "tenantId": tenant_id
                            }
                        ],
                        "active": True,
                        "assignments": [

                        ],
                        "serviceHistory": [

                        ],
                        "education": [
                        ],
                        "tests": [
                        ],
                        "tenantId": tenant_id
                    }
                ]
            }
            post_response = requests.post(url=config.HOST + '/egov-hrms/employees/_create', headers=headers,
                                          json=post_data)
            print("==================================================")
            print(post_data)
            print("--------")
            print(post_response.json())
            print("==================================================")
            print("\n\n")
def main():
    continue_processing = True
    access_token = superuser_login()["access_token"]
    import time

    while continue_processing:
        cursor.execute(postgresql_select_Query)
        data = cursor.fetchmany(int(batch_size))

        # continue_processing = False
        if not data:
            print("No more data to process. Script exiting")
            continue_processing = False
            cursor.close()
            connection.close()

        for row in data:
            json_data = row[0]
            uuid = json_data["uuid"]
            print('Processing {}'.format(uuid))
            try:
                p = IkonProperty()
                p.process_record(json_data, tenant, city)
                pd = p.property_details[0]
                # pd.financial_year = "2018-19"
                # p.tenant_id = tenant
                # for o in pd.owners:
                #     o.mobile_number = default_phone
                # pd.citizen_info.mobile_number = default_phone
                pd.source = "LEGACY_RECORD"
                # p.address.locality = {
                #     "code": default_locality,
                #     "area": "AREA1"
                # }
                p.additional_details = {}

                start = time.time()
                req, res = p.upload_property(access_token)
                time_taken = time.time() - start

                if "Properties" in res:
                    pt_id = res["Properties"][0]["propertyId"]
                    ack_no = res["Properties"][0]["acknowldgementNumber"]
                    calc = res["Properties"][0]["propertyDetails"][0]["calculation"]
                    total_amount = calc["totalAmount"]
                    tax_amount = calc["taxAmount"]
                    # upload_status = "COMPLETED"
                    print("Record updloaded successfully", pt_id)
                    update_db_record(uuid, upload_status="COMPLETED",
                                     upload_response=json.dumps(res),
                                     new_tax=tax_amount,
                                     new_total=total_amount,
                                     new_propertyid=pt_id,
                                     new_assessmentnumber=ack_no,
                                     req_json=json.dumps(req),
                                     time_taken=time_taken)
                else:
                    # Some error has occurred
                    print("Error occured while uploading data")
                    print(json.dumps(req, indent=1))
                    print(json.dumps(res, indent=1))
                    update_db_record(uuid, upload_status="ERROR",
                                     upload_response=json.dumps(res),
                                     req_json=json.dumps(req))
            except Exception as ex:
                import traceback
                traceback.print_exc()
                update_db_record(uuid, upload_status="EXCEPTION", upload_response=str(ex))

            if dry_run:
                print("Dry run only, exiting now")
                exit(0)