Beispiel #1
0
 def trans():
     logging.debug('Storing order in the database')
     order = NodeOrder(key=order_key,
                       app_user=app_user,
                       tos_iyo_see_id=None,
                       billing_info=billing_info,
                       shipping_info=shipping_info,
                       order_time=now(),
                       status=NodeOrderStatus.APPROVED
                       if can_host else NodeOrderStatus.WAITING_APPROVAL,
                       socket=socket)
     order.put()
     if can_host:
         logging.info(
             'User has invested more than %s tokens, immediately creating node order PDF.',
             REQUIRED_TOKEN_COUNT_TO_HOST)
         deferred.defer(_create_node_order_pdf,
                        order_key.id(),
                        _transactional=True)
     else:
         logging.info(
             'User has not invested more than %s tokens, an admin needs to approve this order manually.',
             REQUIRED_TOKEN_COUNT_TO_HOST)
         deferred.defer(_inform_support_of_new_node_order,
                        order_key.id(),
                        _transactional=True)
     deferred.defer(set_hoster_status_in_user_data,
                    order.app_user,
                    False,
                    _transactional=True)
     if updated_user_data:
         deferred.defer(put_user_data,
                        app_user,
                        updated_user_data,
                        _transactional=True)
Beispiel #2
0
def order_node(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):
    order_key = NodeOrder.create_key()
    deferred.defer(_order_node, order_key, user_details[0].email,
                   user_details[0].app_id, steps)
Beispiel #3
0
def _order_node_iyo_see(app_user,
                        node_order_id,
                        pdf_url,
                        pdf_size,
                        create_quotation=True):
    iyo_username = get_iyo_username(app_user)
    doc_id = u'Zero-Node order %s' % NodeOrder.create_human_readable_id(
        node_order_id)
    category = u'Terms and conditions'
    content_type = u'application/pdf'
    description = u'Terms and conditions for ordering a Zero-Node'
    create_see_document(doc_id, category, description, iyo_username, pdf_url,
                        content_type)
    attachment_name = u' - '.join([doc_id, category])

    def trans():
        order = get_node_order(node_order_id)
        order.tos_iyo_see_id = doc_id
        order.put()
        if create_quotation:
            deferred.defer(_create_quotation,
                           app_user,
                           node_order_id,
                           pdf_url,
                           attachment_name,
                           pdf_size,
                           _transactional=True)

    ndb.transaction(trans)
Beispiel #4
0
def _order_node_iyo_see(app_user, node_order_id, pdf_url):
    iyo_username = get_iyo_username(app_user)
    organization_id = get_iyo_organization_id()

    iyo_see_doc = IYOSeeDocumentView(username=iyo_username,
                                     globalid=organization_id,
                                     uniqueid=u'Zero-Node order %s' % NodeOrder.create_human_readable_id(node_order_id),
                                     version=1,
                                     category=u'Terms and conditions',
                                     link=pdf_url,
                                     content_type=u'application/pdf',
                                     markdown_short_description=u'Terms and conditions for ordering a Zero-Node',
                                     markdown_full_description=u'Terms and conditions for ordering a Zero-Node')
    logging.debug('Creating IYO SEE document: %s', iyo_see_doc)
    iyo_see_doc = create_see_document(iyo_username, iyo_see_doc)

    attachment_name = u' - '.join([iyo_see_doc.uniqueid, iyo_see_doc.category])

    def trans():
        order = get_node_order(node_order_id)
        order.tos_iyo_see_id = iyo_see_doc.uniqueid
        order.put()
        deferred.defer(_create_quotation, app_user, node_order_id, pdf_url, attachment_name,
                       _transactional=True)

    ndb.transaction(trans)
Beispiel #5
0
def _create_node_order_pdf(node_order_id):
    node_order = get_node_order(node_order_id)
    user_email, app_id = get_app_user_tuple(node_order.app_user)
    logging.debug('Creating Hosting agreement')
    pdf_name = NodeOrder.filename(node_order_id)
    pdf_contents = create_hosting_agreement_pdf(node_order.billing_info.name, node_order.billing_info.address)
    pdf_url = upload_to_gcs(pdf_name, pdf_contents, 'application/pdf')
    deferred.defer(_order_node_iyo_see, node_order.app_user, node_order_id, pdf_url)
    deferred.defer(update_hoster_progress, user_email.email(), app_id, HosterSteps.FLOW_ADDRESS)
Beispiel #6
0
def set_hoster_status_in_user_data(app_user, can_order=None):
    # type: (users.User, bool) -> None
    if not isinstance(can_order, bool):
        can_order = all(o.status == NodeOrderStatus.CANCELED
                        for o in NodeOrder.list_by_user(app_user))
    user_data = {'hoster': {'can_order': can_order}}
    api_key = get_rogerthat_api_key()
    email, app_id = get_app_user_tuple(app_user)
    current_user_data = system.get_user_data(api_key, email.email(), app_id,
                                             ['hoster'])
    if current_user_data != user_data:
        system.put_user_data(api_key, email.email(), app_id, user_data)
Beispiel #7
0
def search_node_orders(query=None, page_size=20, cursor=None):
    # type: (unicode, int, unicode) -> tuple[list[NodeOrder], search.Cursor, bool]
    options = search.QueryOptions(limit=page_size,
                                  cursor=search.Cursor(cursor),
                                  ids_only=True,
                                  sort_options=search.SortOptions(
                                      expressions=[SortExpression(expression='order_time',
                                                                  direction=SortExpression.DESCENDING)]))
    search_results = NODE_ORDER_INDEX.search(search.Query(query, options=options))  # type: search.SearchResults
    results = search_results.results  # type: list[search.ScoredDocument]
    node_orders = ndb.get_multi([NodeOrder.create_key(long(result.doc_id)) for result in results])
    return node_orders, search_results.cursor, search_results.cursor is not None
Beispiel #8
0
def create_node_order(data):
    # type: (CreateNodeOrderTO) -> NodeOrder
    if data.status not in (NodeOrderStatus.SIGNED, NodeOrderStatus.SENT,
                           NodeOrderStatus.ARRIVED, NodeOrderStatus.PAID):
        data.sign_time = MISSING
    if data.status not in (NodeOrderStatus.SENT, NodeOrderStatus.ARRIVED):
        data.send_time = MISSING
    app_user = users.User(data.app_user)
    order_count = NodeOrder.list_by_so(data.odoo_sale_order_id).count()
    if order_count > 0:
        raise OrderAlreadyExistsException(data.odoo_sale_order_id)
    try:
        nodes = get_nodes_from_odoo(data.odoo_sale_order_id)
    except (IndexError, TypeError):
        logging.warn('Could not get nodes from odoo for order id %s' %
                     data.odoo_sale_order_id,
                     exc_info=True)
        raise HttpBadRequestException('cannot_find_so_x',
                                      {'id': data.odoo_sale_order_id})
    if not nodes:
        raise HttpBadRequestException('no_serial_number_configured_yet',
                                      {'sale_order': data.odoo_sale_order_id})
    prefix, doc_content_base64 = data.document.split(',')
    content_type = prefix.split(';')[0].replace('data:', '')
    if content_type != 'application/pdf':
        raise InvalidContentTypeException(content_type, ['application/pdf'])

    doc_content = base64.b64decode(doc_content_base64)
    order_key = NodeOrder.create_key()
    pdf_name = NodeOrder.filename(order_key.id())
    pdf_url = upload_to_gcs(pdf_name, doc_content, content_type)
    order = NodeOrder(key=order_key,
                      app_user=app_user,
                      **data.to_dict(exclude=['document', 'app_user']))
    order.put()
    iyo_username = get_iyo_username(app_user)
    email, app_id = get_app_user_tuple(app_user)
    deferred.defer(add_nodes_to_profile, iyo_username, nodes)
    deferred.defer(set_hoster_status_in_user_data, order.app_user, False)
    deferred.defer(add_user_to_role,
                   UserDetailsTO(email=email.email(), app_id=app_id),
                   RogerthatRoles.HOSTERS)
    deferred.defer(tag_intercom_users, IntercomTags.HOSTER, [iyo_username])
    deferred.defer(_order_node_iyo_see,
                   order.app_user,
                   order.id,
                   pdf_url,
                   len(doc_content),
                   create_quotation=False)
    return order
def _get_node_orders():
    return NodeOrder.query()
Beispiel #10
0
def _move_node_order_pdf_to_gcs(node_order_key):
    node_order = get_node_order_details(node_order_key.id())
    if not node_order.see_document:
        return
    original_url = node_order.see_document.versions[0].link
    _move_pdf(NodeOrder.filename(node_order.id), original_url)
Beispiel #11
0
def _get_orders(status):
    return NodeOrder.list_by_status(status)
Beispiel #12
0
def get_node_order(order_id):
    # type: (int) -> NodeOrder
    order = NodeOrder.get_by_id(order_id)
    if not order:
        raise HttpNotFoundException('order_not_found')
    return order
Beispiel #13
0
def _get_node_orders():
    return NodeOrder.list_check_online()
Beispiel #14
0
def get_node_id_for_user(app_user):
    for order in NodeOrder.list_by_user(app_user):
        if order.status in (NodeOrderStatus.SENT, NodeOrderStatus.ARRIVED):
            node_id = get_node_id_from_odoo(order.odoo_sale_order_id)
            if node_id:
                return node_id
Beispiel #15
0
def _order_node(order_key, user_email, app_id, steps):
    logging.info('Receiving order of Zero-Node')
    app_user = create_app_user_by_email(user_email, app_id)

    overview_step = get_step(steps, 'message_overview')
    if overview_step and overview_step.answer_id == u"button_use":
        api_key = get_rogerthat_api_key()
        user_data_keys = [
            'name', 'email', 'phone', 'billing_address', 'address',
            'shipping_name', 'shipping_email', 'shipping_phone',
            'shipping_address'
        ]
        user_data = system.get_user_data(api_key, user_email, app_id,
                                         user_data_keys)
        billing_info = ContactInfo(name=user_data['name'],
                                   email=user_data['email'],
                                   phone=user_data['phone'],
                                   address=user_data['billing_address']
                                   or user_data['address'])

        if user_data['shipping_name']:
            shipping_info = ContactInfo(name=user_data['shipping_name'],
                                        email=user_data['shipping_email'],
                                        phone=user_data['shipping_phone'],
                                        address=user_data['shipping_address'])
        else:
            shipping_info = billing_info

        updated_user_data = None
    else:
        name = get_step_value(steps, 'message_name')
        email = get_step_value(steps, 'message_email')
        phone = get_step_value(steps, 'message_phone')
        billing_address = get_step_value(steps, 'message_billing_address')
        updated_user_data = {
            'name': name,
            'email': email,
            'phone': phone,
            'billing_address': billing_address,
        }

        billing_info = ContactInfo(name=name,
                                   email=email,
                                   phone=phone,
                                   address=billing_address)

        same_shipping_info_step = get_step(steps,
                                           'message_choose_shipping_info')
        if same_shipping_info_step and same_shipping_info_step.answer_id == u"button_yes":
            shipping_info = billing_info
        else:
            shipping_name = get_step_value(steps, 'message_shipping_name')
            shipping_email = get_step_value(steps, 'message_shipping_email')
            shipping_phone = get_step_value(steps, 'message_shipping_phone')
            shipping_address = get_step_value(steps,
                                              'message_shipping_address')
            updated_user_data.update({
                'shipping_name': shipping_name,
                'shipping_email': shipping_email,
                'shipping_phone': shipping_phone,
                'shipping_address': shipping_address,
            })

            shipping_info = ContactInfo(name=shipping_name,
                                        email=shipping_email,
                                        phone=shipping_phone,
                                        address=shipping_address)
    socket_step = get_step(steps, 'message_socket')
    socket = socket_step and socket_step.answer_id.replace('button_', '')

    # Only one node is allowed per user, and one per location
    if NodeOrder.has_order_for_user_or_location(
            app_user, billing_info.address) and not DEBUG:
        logging.info('User already has a node order, sending abort message')
        msg = u'Dear ThreeFold Member, we sadly cannot grant your request to host an additional ThreeFold Node:' \
              u' We are currently only allowing one Node to be hosted per ThreeFold Member and location.' \
              u' This will allow us to build a bigger base and a more diverse Grid.'
        subject = u'Your ThreeFold Node request'
        send_message_and_email(app_user, msg, subject)
        return

    # Check if user has invested >= 120 tokens
    paid_orders = InvestmentAgreement.list_by_status_and_user(
        app_user, InvestmentAgreement.STATUS_PAID)
    total_tokens = sum([o.token_count_float for o in paid_orders])
    can_host = total_tokens >= REQUIRED_TOKEN_COUNT_TO_HOST

    def trans():
        logging.debug('Storing order in the database')
        order = NodeOrder(key=order_key,
                          app_user=app_user,
                          tos_iyo_see_id=None,
                          billing_info=billing_info,
                          shipping_info=shipping_info,
                          order_time=now(),
                          status=NodeOrderStatus.APPROVED
                          if can_host else NodeOrderStatus.WAITING_APPROVAL,
                          socket=socket)
        order.put()
        if can_host:
            logging.info(
                'User has invested more than %s tokens, immediately creating node order PDF.',
                REQUIRED_TOKEN_COUNT_TO_HOST)
            deferred.defer(_create_node_order_pdf,
                           order_key.id(),
                           _transactional=True)
        else:
            logging.info(
                'User has not invested more than %s tokens, an admin needs to approve this order manually.',
                REQUIRED_TOKEN_COUNT_TO_HOST)
            deferred.defer(_inform_support_of_new_node_order,
                           order_key.id(),
                           _transactional=True)
        deferred.defer(set_hoster_status_in_user_data,
                       order.app_user,
                       False,
                       _transactional=True)
        if updated_user_data:
            deferred.defer(put_user_data,
                           app_user,
                           updated_user_data,
                           _transactional=True)

    ndb.transaction(trans)
Beispiel #16
0
def get_nodes_for_user(app_user):
    nodes = []
    for order in NodeOrder.list_by_user(app_user):
        if order.status in (NodeOrderStatus.SENT, NodeOrderStatus.ARRIVED):
            nodes.extend(get_nodes_from_odoo(order.odoo_sale_order_id))
    return nodes