Example #1
0
def recharge_failed(api_key,
                    msisdn,
                    ref=None,
                    startDate=None,
                    endDate=str(now()),
                    recharge_limit=1,
                    project=None,
                    prodType='airtime'):
    # a. obtain history of recharges for the given msisdn
    if endDate != None and startDate != None:
        df_rec = msisdn_history(api_key,
                                msisdn,
                                startDate=startDate,
                                prodType=prodType)
    else:
        df_rec = msisdn_history(api_key, msisdn, prodType=prodType)

    if str(df_rec) != 'None':
        print('prodType: ', prodType, '\t MSISDN:', msisdn, '\t HISTORY: ',
              len(df_rec))
        # b. obtain successful and failed recharges
        if project != None:
            s_rec = df_rec[
                df_rec['reference'].str.contains(project)
                & df_rec['status'].str.contains(
                    'SUCCESS'
                )]  # records of successful recharges in the given project
            f_rec = df_rec[
                df_rec['reference'].str.contains(project)
                & df_rec['status'].str.contains(
                    'FAILED'
                )]  # records of FAILED recharges in the given project
        else:
            s_rec = df_rec[df_rec['status'].str.contains(
                'SUCCESS')]  # records of successful recharges
            f_rec = df_rec[df_rec['status'].str.contains(
                'FAILED')]  # records of failed recharges

        if len(s_rec) < recharge_limit and len(f_rec) > 0 and len(f_rec) <= 1:
            # recharge msisdn
            if f_rec.loc[0, 'productType'] == 'AIRTIME':
                recharge = airtime(api_key,
                                   msisdn,
                                   network=f_rec.loc[0, 'network']['name'],
                                   amount=f_rec.loc[0, 'price'],
                                   ref=concat(f_rec.loc[0, 'reference'],
                                              '_FINALTRIAL'))

                return recharge
            else:
                recharge = buyProd(api_key,
                                   msisdn,
                                   network=f_rec.loc[0, 'network']['name'],
                                   prodID=f_rec.loc[0, 'product']['id'],
                                   ref=concat(f_rec.loc[0, 'reference'],
                                              '_FINALTRIAL'))
                return recharge

    else:
        return None
Example #2
0
def simcontact(msisdn):
    msisdn = str(msisdn)
    #print('\nMSISDN: %s'%msisdn)

    if is_number(msisdn):
        msisdn = str(int(float(msisdn)))
        #print('\nMSISDN: %s'%msisdn)

    if len(msisdn) == 11 and '.' in msisdn and msisdn.index('.') == 9:
        idx = msisdn.index('.')
        sub_1 = msisdn[0:9]
        msisdn = msisdn[-1] + sub_1

    contact = remove_specialchar(msisdn)  # remove special characters
    # format contact
    if contact[0] == '0' and len(contact) == 10:
        return concat('+27', contact[1:len(contact)])

    elif contact[0:2] == '27' and len(contact[2:len(contact)]) == 9:
        return concat('+', contact)

    elif len(contact) == 9 and contact[0] != '0':
        return concat('+27', contact)

    else:
        return concat(msisdn,
                      ' is not recognised as a South African mobile number.')
Example #3
0
def recharge_data(api_key, reference):
    # form query string
    string = concat(
        '{ adhocRecharges(first: 1, reference: \"', reference,
        '\") { edges { node {id msisdn network { name } productType product { label } price status succeededAt created failureType reference} } } }'
    )
    data = api_query(string, api_key)['data']['adhocRecharges']['edges']

    if len(data) != 0:
        data = data[0]['node']
        data['network'] = data['network']['name']

    return data
Example #4
0
def recharge_count(contact,
                   api_key,
                   prodType='airtime',
                   status='success',
                   r_idx=100,
                   startDate='',
                   endDate=''):

    # create query string
    if startDate == '' or endDate == '':
        q_string = concat(
            '{ adhocRecharges( first: ', r_idx, ', msisdn: \"',
            simcontact(contact), '\", productType: \"', prodType.upper(),
            '\", status: \"', status.upper(),
            '\") { edges { node {id msisdn network { name } productType product { label } price status succeededAt created failureType reference} } } }'
        )

    else:
        # format startDate and endDate
        fmt = '%Y-%m-%dT%H:%M:%S'
        startDate = format_date_time(str(startDate), fmt)
        endDate = format_date_time(str(endDate), fmt)
        q_string = concat(
            '{ adhocRecharges( first: ', r_idx, ', msisdn: \"',
            simcontact(contact), '\", productType: \"', prodType.upper(),
            '\", status: \"', status.upper(), '\", created_Gte:\"', startDate,
            '\" created_Lt:\"', endDate,
            '\") { edges { node {id msisdn network { name } productType product { label } price status succeededAt created reference } } } }'
        )

    # prequest the 1st 100 recharges fot the msisdn
    q_res = api_query(q_string, api_key)  # perform api_query
    #print(q_res)
    #count number of successful recharges
    recharges = str(q_res).count(simcontact(contact))

    return recharges
Example #5
0
def products(api_key, network, prodType='DATA', idx=100):
    # 2. api query
    if network.lower() == 'mtn':
        network = network.upper()
    else:
        network = network.title()

    string = concat(
        '{  products(first:', idx, 'productType: \"', prodType.upper(),
        '\" network_Name:\"', network,
        '\"){edges{node{ network{id name} id productType label price bundleSize bundleSizeInMb}} }}'
    )
    df_resp = simdict_to_DataFrame(
        api_query(string, api_key)['data']['products']['edges']).sort_values(
            by=['price', 'bundleSize'])
    return df_resp
Example #6
0
def buyProd(api_key, msisdn, network, prodID, ref=None):
    if ref == None:
        ref = str(uuid())

    if msisdn != 'nan' and network != 'nan':
        # a. Determine the network ID for a given network name
        try:
            mno_id = sim_control_networks(api_key)[
                network.lower()]  #retrieve network ID
        except:
            mno_id = 'TmV0d29ya05vZGU6MTM='
        # b. form query_string and query simcontrol API
        string = concat('mutation { rechargeSim(msisdn: \"',
                        simcontact(msisdn), '\", networkId: \"', mno_id,
                        '\", productId:\"', prodID, '\", reference: \"', ref,
                        '\") { rechargeId message}}')
        recharge = api_query(string, api_key)  # perform api_query
        # c. request recharge data
        data_recharge = [recharge_data(reference=ref, api_key=api_key)
                         ]  # get metadata data of recharge

        print(data_recharge)
        return pd.DataFrame(data_recharge)
Example #7
0
def msisdn_history(api_key,
                   msisdn,
                   prodType='airtime',
                   status=None,
                   r_idx=100,
                   startDate=None,
                   endDate=str(now())):
    try:
        # a. create query string with and without time period filter
        if startDate != None and endDate != None:
            # a(i). form query string with time period filter
            date = sim_dateformat(
                startDate=startDate, endDate=endDate,
                fmt='%Y-%m-%dT%H:%M:%S')  # format startDate and endDate
            if status != None:
                q_string = concat(
                    '{ adhocRecharges( first: ', r_idx, ', msisdn: \"',
                    simcontact(msisdn),
                    '\", productType: \"', prodType.upper(), '\", status: \"',
                    status.upper(), '\", created_Gte:\"', date['startDate'],
                    '\" created_Lt:\"', date['endDate'],
                    '\") { edges { node {id msisdn network { name } productType product { label id} price status succeededAt created reference } } } }'
                )
            else:
                q_string = concat(
                    '{ adhocRecharges( first: ', r_idx, ', msisdn: \"',
                    simcontact(msisdn), '\", productType: \"',
                    prodType.upper(), '\", created_Gte:\"', date['startDate'],
                    '\" created_Lt:\"', date['endDate'],
                    '\") { edges { node {id msisdn network { name } productType product { label id} price status succeededAt created reference } } } }'
                )

        else:
            # a(ii). query string without time period filter
            if status != None:
                q_string = concat(
                    '{ adhocRecharges( first: ', r_idx, ', msisdn: \"',
                    simcontact(msisdn), '\", productType: \"',
                    prodType.upper(), '\", status: \"', status.upper(),
                    '\") { edges { node {id msisdn network { name } productType product { label id} price status succeededAt created failureType reference} } } }'
                )
            else:
                q_string = concat(
                    '{ adhocRecharges( first: ', r_idx, ', msisdn: \"',
                    simcontact(msisdn), '\", productType: \"',
                    prodType.upper(),
                    '\") { edges { node {id msisdn network { name } productType product { label id} price status succeededAt created failureType reference} } } }'
                )

        # b. obtain msisdn recharge history
        r_hist = simdict_to_DataFrame(
            api_query(q_string, api_key)['data']['adhocRecharges']
            ['edges'])  # perform api_query

        if len(r_hist) < 1 or len(list(r_hist)) < 1:
            r_hist = []

    except Exception as err:
        print(str(err))

        r_hist = None

    return r_hist