def get_app_user_tuple_by_email(app_user_email):
    azzert('/' not in app_user_email, "app_user_email should not contain /")
    if ':' in app_user_email:
        human_user_email, app_id = app_user_email.split(':')
    else:
        human_user_email, app_id = app_user_email, APP_ID_ROGERTHAT
    return users.User(human_user_email), app_id
def call_rogerthat(api_key, method, params, json_rpc_id=None):
    # type: (unicode, unicode, dict, unicode) -> dict
    azzert(api_key, 'No API_KEY provided')
    request = {
        'id': json_rpc_id or guid(),
        'method': method,
        'params': params
    }
    run_hook('before_api_call', request)
    headers = {
        'Content-Type': 'application/json-rpc; charset=utf-8',
        'X-Nuntiuz-API-key': api_key
    }
    json_request = json.dumps(request)

    api_url = '%s/api/1' % get_plugin(NAMESPACE).configuration.rogerthat_server_url
    result = urlfetch.fetch(api_url, json_request, method=urlfetch.POST, headers=headers, deadline=600)
    if result.status_code != httplib.OK:
        raise RogerthatApiStatusCodeException(result.status_code)

    json_response = str(result.content)
    response = json.loads(json_response)
    run_hook('after_api_call', method, response)

    error = response['error']
    if error:
        if error['code'] != 1000:
            raise RogerthatApiException(error)
        else:
            raise RogerthatApiUnknownException(error)  # Unknown error (e.g. datastore timeout / transaction collision)

    return response['result']
Esempio n. 3
0
def invest(message_flow_run_id, member, steps, end_id, end_message_flow_id, parent_message_key, tag, result_key,
           flush_id, flush_message_flow_id, service_identity, user_details, flow_params, token):
    if flush_id == 'flush_kyc' or flush_id == 'flush_corporation':
        # KYC flow started from within the invest flow
        return kyc_part_1(message_flow_run_id, member, steps, end_id, end_message_flow_id, parent_message_key, tag,
                          result_key, flush_id, flush_message_flow_id, service_identity, user_details, flow_params)

    try:
        email = user_details[0].email
        app_id = user_details[0].app_id
        app_user = create_app_user_by_email(email, app_id)
        logging.info('User %s wants to invest', email)
        version = get_key_name_from_key_string(steps[0].message_flow_id)
        currency = get_step_value(steps, 'message_get_currency').replace('_cur', '')
        if version.startswith(BUY_TOKENS_FLOW_V3) or version.startswith(BUY_TOKENS_FLOW_V5):
            amount = float(get_step_value(steps, 'message_get_order_size_ITO').replace(',', '.'))
            token_count_float = get_token_count(currency, amount)
        else:
            token_count_float = float(get_step_value(steps, 'message_get_order_size_ITO'))
            amount = get_investment_amount(currency, token_count_float)
        username = get_iyo_username(app_user)
        agreement = _create_investment_agreement(amount, currency, token, token_count_float, username, version,
                                                 app_user, status=InvestmentAgreement.STATUS_CREATED)
        payment_info = []
        usd_within_uae_step = get_step(steps, 'message_usd_within_uae')
        if usd_within_uae_step and usd_within_uae_step.answer_id == 'button_yes':
            payment_info.append(PaymentInfo.UAE.value)
        agreement.payment_info.extend(payment_info)
        agreement.put()

        if version == BUY_TOKENS_FLOW_V3_PAUSED:
            return None

        utility_bill_step = get_step(steps, 'message_utility_bill')
        if utility_bill_step:
            azzert(utility_bill_step.answer_id == FormTO.POSITIVE)
            url = utility_bill_step.get_value()
            deferred.defer(save_utility_bill, url, TffProfile.create_key(get_iyo_username(user_details[0])))

        tag = {
            '__rt__.tag': INVEST_FLOW_TAG,
            'investment_id': agreement.id
        }
        flow_params = {
            'token': agreement.token,
            'amount': agreement.amount,
            'currency': agreement.currency
        }
        result = FlowCallbackResultTypeTO(flow=FLOW_CONFIRM_INVESTMENT,
                                          tag=json.dumps(tag).decode('utf-8'),
                                          force_language=None,
                                          flow_params=json.dumps(flow_params))
        return FlowMemberResultCallbackResultTO(type=TYPE_FLOW, value=result)
    except Exception as e:
        logging.exception(e)
        return create_error_message()
def send_action(action, user_id=None):
    """
    Args:
        action (dict): Action to send to the client. Should only contain 'type' and 'payload' keys.
         'type' should be a string, payload should be a dict
        user_id (unicode):
    """
    azzert('type' in action, 'Missing \'type\' on action')
    if 'payload' not in action:
        action['payload'] = None
    send_update('framework.action', action, user_id)
Esempio n. 5
0
def on_trans_committed(func, *args, **kwargs):
    """
    Executes func when the transaction the function is run in has completed.

    Args:
        func: Function to execute
        *args: Positional arguments for func
        **kwargs: Keyword arguments for func

    Notes:
        Does not return the function's return value.
    """
    azzert(db.is_in_transaction())
    post_transaction_actions.append(True, func, *args, **kwargs)
def upsert_user(user_id, name=None, email=None, phone=None):
    # type: (unicode, unicode, unicode, unicode) -> User
    azzert(user_id, u'Expected username to not be empty')
    client = get_intercom_client()
    try:
        user = client.users.find(user_id=user_id)
        logging.debug('Found intercom user with user_id %s', user_id)
        return update_user_if_necessary(user, user_id, name, email, phone)
    except ResourceNotFound:
        logging.debug('No intercom user found with user_id %s, trying to find user with email %s', user_id, email)
        if email:
            try:
                # try again by searching on email
                user = client.users.find(email=email)
                logging.debug('Found user with email %s', email)
                return update_user_if_necessary(user, user_id, name, email, phone)
            except ResourceNotFound:
                return create_user(user_id, name, email, phone)
        else:
            return create_user(user_id, name, email, phone)
def create_app_user_by_email(human_user_email, app_id):
    azzert('/' not in human_user_email, "human_user_email should not contain /")
    azzert(':' not in human_user_email, "human_user_email should not contain :")
    azzert(app_id, "app_id should not be empty")
    if app_id != APP_ID_ROGERTHAT:
        return users.User(u"%s:%s" % (human_user_email, app_id))
    return users.User(human_user_email)
def _create_token_value_agreement_if_needed(profile_key):
    profile = profile_key.get()  # type: TffProfile
    investments = [
        i for i in InvestmentAgreement.list_by_user(profile.app_user)
        if PaymentInfo.HAS_MULTIPLIED_TOKENS not in i.payment_info
        and i.creation_time <= FF_ENDED_TIMESTAMP
    ]
    statuses = [
        InvestmentAgreement.STATUS_PAID, InvestmentAgreement.STATUS_SIGNED
    ]
    canceled_or_started_investments = [
        i for i in investments if i.status not in statuses
    ]
    to_put, token_count = multiply_tokens_for_agreements(
        canceled_or_started_investments)
    azzert(token_count == 0, 'Expected token_count to be 0')
    logging.info('Updated %s agreements for user %s', len(to_put),
                 profile.username)
    if to_put:
        ndb.put_multi(to_put)
    has_document = any(d.type == DocumentType.TOKEN_VALUE_ADDENDUM.value
                       for d in Document.list_by_username(profile.username))
    if any(i.status in statuses for i in investments) and not has_document:
        create_token_value_agreement(profile.username)
Esempio n. 9
0
def create_itft_amendment_1_pdf(app_user):
    from plugins.tff_backend.bizz.investor import get_total_token_count
    agreements = InvestmentAgreement.list_by_status_and_user(app_user, (InvestmentAgreement.STATUS_PAID,
                                                                        InvestmentAgreement.STATUS_SIGNED))
    azzert(agreements)
    agreements.sort(key=lambda a: a.sign_time)
    purchase_amounts = ''
    sign_dates = ''
    for i, agreement in enumerate(agreements):
        if i:
            purchase_amounts += '<br>'
            sign_dates += '<br>'
        purchase_amounts += '%s %s' % (agreement.amount, agreement.currency)
        sign_dates += _get_effective_date(agreement.sign_time)

    old_count = get_total_token_count(app_user, agreements)[TOKEN_ITFT]
    new_count = old_count * 100.0
    purchase_amount_in_usd = old_count * 5.0

    fmt = lambda x: '{:.2f}'.format(x)
    template_variables = {
        'logo_path': 'assets/logo.jpg',
        'agreement': _get_effective_date,
        'full_name': agreements[0].name,
        'purchase_amounts': purchase_amounts,
        'sign_dates': sign_dates,
        'old_count': fmt(old_count),
        'new_count': fmt(new_count),
        'purchase_amount_in_usd': fmt(purchase_amount_in_usd),
        'title': 'iTFT Purchase Agreement - Amendment I<br>iTFT Token Price & Volume Adjustment'
    }

    md = JINJA_ENVIRONMENT.get_template('itft_amendment_1.md').render(template_variables)
    markdown_to_html = markdown.markdown(md, extensions=['markdown.extensions.tables'])
    template_variables['markdown_to_html'] = markdown_to_html.replace('<th', '<td')
    return _render_pdf_from_html('token_itft.html', template_variables)
Esempio n. 10
0
def on_trans_rollbacked(func, *args, **kwargs):
    azzert(db.is_in_transaction())
    post_transaction_actions.append(False, func, *args, **kwargs)
Esempio n. 11
0
 def set_current_transaction_guid(self, transaction_guid):
     azzert(transaction_guid not in self.transaction_guids)
     self.transaction_guids.append(transaction_guid)
     self.items[transaction_guid] = list()