Ejemplo n.º 1
0
def _order(dom):
    number = getDOMItemValue(dom, 'documentNumber')
    date = getDOMItemValue(dom, 'documentDate')

    if IsDebug:
        print '--> Number: [%s]' % number
        print '--> Date: [%s]' % date

    return { 'number' : number, 'date' : date, }
Ejemplo n.º 2
0
def respond_external(action, **kw):
    exchange_error = 0
    exchange_message = ''
    error_code = ''
    error_description = ''
    errors = ''
    response = {}
    dom = None
    data = ''
    total = ''
    price = ''
    currency = ''
    document = ''
    order_number = ''
    order_date = ''

    print_action(action, 'Respond.External')

    locale = request.form.get('currentUsedLocalization') or ''
    wizard = request.form.get('wizardID') or ''

    try:
        # -------------------------------------
        # Get DOM and XML response from Service
        # -------------------------------------
        exchange_error, exchange_message, dom, data = send(action, request, session, **kw)

        if demo():
            exchange_error, exchange_message, total, currency = _demo_price(action)
            order_number, order_date = _demo_order(action)
        elif exchange_error:
            total = 0.0
        elif dom is not None:
            total = float(getDOMItemValue(dom, 'total') or '0')
            currency = CURRENCIES.get(getDOMItemValue(dom, 'currency'), gettext('undefined'))
            error_code = getDOMItemValue(dom, 'errorCode').strip()
            error_description = getDOMItemValue(dom, 'errorDescription')

            if action == '207':
                order = _order(dom)
                order_number = order.get('number', '')
                order_date = order.get('date', '')
        elif data:
            x = request.form.get('price')
            total = x and float(x.split()[0])*1.288726 or 0
    except:
        msg = '--> Send error!'
        print_to(errorlog, [msg, data], request=request)
        # ----------------------
        # Service Exchange Error
        # ----------------------
        if IsDeepDebug:
            print msg
        raise

    #print_to(errorlog, ['>>> Data:', data])

    IsValid = data and True or False

    if exchange_message and exchange_message == exchange_error:
        exchange_message = ''
    if error_description and error_description == error_code:
        error_description = ''

    # -----------------
    # Response is valid
    # -----------------

    if IsValid:
        errors = getDOMErrors(dom) or ''

        if IsDeepDebug:
            print errors

        if currency in ('undefined', n_a, '') or not total:
            if not exchange_message:
                if action == '203' and error_code in ('', '0',):
                    pass
                else:
                    exchange_message = gettext('Calculation is not performed.')
            IsValid = False

        total = IsValid and '%.2f' % total or ''
        price = IsValid and '%s %s' % (total, currency) or ''

        if IsDebug:
            print '--> Total: %s' % price

        document = order_number and ('# %s %s %s' % (order_number, gettext('at'), order_date)) or ''

    # -------------------------------------------
    # Make parameters and Register response in DB
    # -------------------------------------------

    attrs = { \
        'locale'            : locale,
        'selected_item'     : kw.get('id') or request.form.get('selected_item'),
        'title'             : request.form.get('title') or '',
        'document'          : document or action,
        'total'             : total,
        'currency'          : currency,
        'countryID'         : getCountryID(getDOMItemValue(dom, 'countryID'), locale),
        'regionID'          : getRegionID(getDOMItemValue(dom, 'regionID'), locale),
        'userID'            : getUserID(getDOMItemValue(dom, 'userID'), locale),
        'userName'          : getClient(getDOMItemValue(dom, 'userName'), locale),
        'wizardID'          : wizard,
        'wizardName'        : request.form.get('wizardName') or '',
        'custom_code'       : request.form.get('custom_code') or '',
        'option_update'     : request.form.get('option_update') or '',
        'option_cost'       : request.form.get('option_cost') or '',
        'data'              : data, #getDOMTagStrippedValue(dom, 'parameters'),
    }

    #print_to(errorlog, ['>>> Total:', total])

    if IsValid and action in ('203','204','205','207',): # and dom
        response = register(action, dom, attrs)

        if IsDeepDebug:
            print '>>> DB Response:%s' % response

    order = action == '205' and response.get('custom_code') or document

    return { \
        'action'            : action,
        'op'                : '',
        # --------------
        # Service Errors
        # --------------
        'exchange_error'    : exchange_error, 
        'exchange_message'  : exchange_message,
        'error_code'        : error_code,
        'error_description' : error_description,
        'errors'            : errors,
        # ---
        # IDs
        # ---
        'countryID'         : getDOMItemValue(dom, 'countryID') or '',
        'regionID'          : getDOMItemValue(dom, 'regionID') or '',
        'userID'            : attrs['userID'],
        # --------------
        # Client Details
        # --------------
        'country_name'      : getDOMItemValue(dom, 'countryName') or getCountry(getDOMItemValue(dom, 'countryID'), locale),
        'region_name'       : getDOMItemValue(dom, 'regionName') or getRegion(getDOMItemValue(dom, 'regionID'), locale),
        'client_name'       : attrs['userName'],
        # ----------
        # Order Info
        # ----------
        'document_number'   : order_number,
        'document_date'     : order_date,
        'order'             : order,
        # -------
        # DB Data
        # -------
        'total_log_rows'    : getLogTotal({'userID' : attrs['userID'], 'wizardID' : wizard}),
        'custom_code'       : response.get('custom_code', ''),
        'next_custom_code'  : response.get('next_custom_code', ''),
        'option_update'     : response.get('option_update', ''),
        'option_cost'       : response.get('option_cost', ''),
        'title'             : response.get('title', ''),
        # ------------------------------
        # Results (Price & XML-Response)
        # ------------------------------
        'price'             : price,
        'data'              : data,
    }
Ejemplo n.º 3
0
def respond_internal(action, **kw):
    exchange_error = 0
    exchange_message = ''
    error_code = ''
    error_description = ''
    response = {}
    dom = None
    data = ''
    currency = ''
    order_number = ''
    order_date = ''

    print_action(action, 'Respond.Internal')

    op = request.form.get('op') or kw.get('op')

    if IsDebug:
        print '--> op: [%s]' % op

    if not op:
        pass

    elif op == 'get':
        # --------------------------------------------------------------
        # Generate and Send XML to Service (from WEB-form to JavaScript)
        # --------------------------------------------------------------
        data = getXml(action, request, session)
        errors = []

    elif op == 'set':
        # -----------------------------------------------
        # Receive XML from Service (loaded by JavaScript)
        # -----------------------------------------------
        dom, data = receive(action, request, session, **kw)

        if demo():
            exchange_error, exchange_message, total, currency = _demo_price(action)
            order_number, order_date = _demo_order(action)
        else:
            total = float(getDOMItemValue(dom, 'total'))
            currency = CURRENCIES.get(getDOMItemValue(dom, 'currency'), gettext('undefined'))
            error_code = getDOMItemValue(dom, 'errorCode').strip()
            error_description = getDOMItemValue(dom, 'errorDescription')

        errors = getDOMErrors(dom) or ''

        if IsDebug:
            print '--> Total: %s %s' % (total, currency)

        total = '%.2f' % total or ''
        price = '%s %s' % (total, currency) or ''

    return { \
        'action'            : action,
        'op'                : op,
        # --------------
        # Service Errors
        # --------------
        'exchange_error'    : exchange_error, 
        'exchange_message'  : exchange_message,
        'error_code'        : error_code,
        'error_description' : error_description,
        'errors'            : errors,
        # ---
        # IDs
        # ---
        'countryID'         : getDOMItemValue(dom, 'countryID') or '',
        'regionID'          : getDOMItemValue(dom, 'regionID') or '',
        'userID'            : getUserID(getDOMItemValue(dom, 'userID')),
        # --------------
        # Client Details
        # --------------
        'country_name'      : getDOMItemValue(dom, 'countryName') or getCountry(getDOMItemValue(dom, 'countryID')),
        'region_name'       : getDOMItemValue(dom, 'regionName') or getRegion(getDOMItemValue(dom, 'regionID')),
        'client_name'       : getClient(getDOMItemValue(dom, 'userName')),
        # ------------------------------
        # Results (Price & XML-Response)
        # ------------------------------
        'price'             : price,
        'data'              : data,
    }
Ejemplo n.º 4
0
def register(action, dom, attrs):
    """
        Register XML-response in DB. Get items form DOM and clear XML. 
        Valid actions: 203|204|205|207.

        Arguments:
            dom     - DOM object
            attrs   - Dictionary (requested items: action, data (XML), selected_item, custom_code and another...)

        Returns:
            data    - Dictionary (next_custom_code)
    """
    print_db_state()

    IsError = False

    print_action(action, 'DBase.Register')

    # ----
    # User
    # ----
    userID = get_item(dom, attrs, 'userID')
    user = userID and User.query.filter_by(userID=userID).first()
    if not user:
        user = User(userID, title=get_item(dom, attrs, 'userName'), email=getDOMItemValue(dom, 'orderEmail'))
        _add(user)

    # ------
    # Module
    # ------
    wizardID = get_item(dom, attrs, 'wizardID')
    module = wizardID and Module.query.filter_by(wizardID=wizardID).first()
    if not module:
        module = Module(wizardID, title=re.sub(r'\s+', ' ', re.sub(r'<.*?>', '', get_item(dom, attrs, 'wizardName'))))
        m = re.search(r'.*(DUS-[\d-]*)', module.wizardName)
        if m:
            module.DUS = m.group(1)
        _add(module)

    # ------------------
    # Parameters & Items
    # ------------------
    for n, x in enumerate(getDOMParameters(dom, False)):
        parameter = Parameter.query.filter_by(CIS=x['id']).first()
        if not parameter:
            parameter = Parameter(x['id'], valid_parameter_names.get(x['type'].upper()), unit=x['unit'])
            _add(parameter)

        item = Item.query.filter_by(parameter=parameter, module=module).first()
        if not item:
            item = Item(parameter, module)
            _add(item)

    # ---------------------
    # Order & Prices & Data
    # ---------------------
    if action not in valid_action_types:
        IsError = True
        otype = -1

    id = get_item(dom, attrs, 'selected_item')
    code = get_item(dom, attrs, 'custom_code')

    IsAddOrder = False
    IsUpdateOrder = False
    custom_code = ''
    order = None

    if IsError:
        pass

    # ----------------------------------------------
    # Get Order item from DB and update or add a new
    # ----------------------------------------------
    elif action == '203':
        if not id:
            otype = ORDER_STANDARD
            order = Order.query.filter_by(user=user, module=module, otype=otype).first()
        else:
            order = get_order(id, None)
            custom_code = order and order.code
            otype = -1
    elif action == '204':
        otype = ORDER_CUSTOM
        order = get_order(id, code, user=user, module=module)
    elif action == '205':
        otype = ORDER_CUSTOM
        #order = get_order(None, code, user=user, module=module)
    elif action == '207':
        otype = ORDER_DONE
    else:
        otype = -1

    if IsDebug:
        print '>>> Order: %s %s %s' % (order, str(code), str(id))

    if otype in valid_order_types:
        price_columns = get_columns(dom, attrs, model_price_columns)

        if not attrs.get('title'):
            attrs['title'] = gettext(valid_order_names[otype])

        if not order:
            order = Order(user, module, otype, get_columns(dom, attrs, model_order_columns))

            #if otype == ORDER_DONE:
            #    order.code = Order.generate_custom_code(user, module, otype=ORDER_DONE)
            #elif otype == ORDER_CUSTOM:
            #    order.code = get_item(dom, attrs, 'custom_code') or \
            #        Order.generate_custom_code(user, module, otype=otype)

            IsAddOrder = True
        else:
            if action in ('203','207'):
                pass
            elif action == '204':
                if order.option_update:
                    order.data = order._data(get_item(dom, attrs, 'data'))
                    IsUpdateOrder = True
            elif action == '205':
                order.set_attrs(get_columns(dom, attrs, model_order_columns))
                IsUpdateOrder = True

        current_price = Order.generate_current_price(int(float(price_columns['total']) * 100), \
            price_columns['currency'])

        if IsAddOrder:
            last_price = ''
            order.current_price = current_price
        else:
            last_price = order.current_price
            if order.otype in (ORDER_STANDARD, ORDER_CUSTOM,):
                order.current_price = current_price
                order.rating = order.current_price < last_price and RATING_DOWN or \
                               order.current_price > last_price and RATING_UP or \
                               RATING_EQUAL
            else:
                order.rating = current_price > last_price and RATING_DOWN or \
                               current_price < last_price and RATING_UP or \
                               RATING_EQUAL

        if IsDebug:
            print '>>> Current price: %s %s %s' % (last_price, order.current_price, order.rating)

        if order and IsAddOrder:
            _add(order)

        if order and (IsAddOrder or (order.option_cost and last_price != current_price)):
            _add(Price(order, price_columns))

    # ----------
    # Save to DB
    # ----------
    _commit(IsUpdateOrder and True or False)

    # ---------------------
    # Get data for response
    # ---------------------
    data = {}
    next_custom_code = Order.generate_custom_code(user, module)

    if action in ('203','204','205',):
        if order:
            data['title'] = order.title
            data['custom_code'] = order.code or custom_code
            data['next_custom_code'] = order.option_update and order.code or next_custom_code
            data['option_update'] = order.option_update
            data['option_cost'] = order.option_cost
        else:
            data['next_custom_code'] = next_custom_code
            data['custom_code'] = custom_code

    return data
Ejemplo n.º 5
0
def get_item(dom, attrs, id):
    return attrs.get(id) or id not in RESTRITED_ATTRS and getDOMItemValue(dom, id)