def index(mode, **kw): host = request.form.get('host') or request.form.get('helperURI') or request.host_url debug = request.args.get('debug') == '1' and True or False demo(request.args.get('demo'), request=request) setReference(host, debug) wizard = request.args.get('wizard', 'BillGateDUS120') #'StreetGateDUS210' locale = _validate('locale', request.args.get('locale')) country = kw.get('country') region = kw.get('region') user = kw.get('user') document = kw.get('document') exchange = _make_exchange(mode, locale, country, region, user, document) page = _make_page(wizard, locale, init_only=False) kw = _make_platform(wizard, locale, user, debug) kw['extra'] = { \ 'selected_action' : request.form.get('selected_action') or 'null', 'selected_item' : request.form.get('selected_item') or 'null', } forms = ('index', 'log',) keywords = _make_keywords() session['communication'] = exchange['communication'] session['session'] = exchange['sessionID'] session['security'] = exchange['securityID'] session['browser'] = kw['browser'] session['locale'] = locale session['wizard'] = wizard session['name'] = page and page.get_title(False) or '' kw.update({ \ 'title' : gettext('Helper Configurator Main Page'), 'host' : host, 'wizard' : wizard, 'locale' : locale, 'exchange' : exchange, 'keywords' : keywords, 'forms' : forms, 'page' : page, }) if IsDebug: print '$$$' print '%s: %s %s %s %s session:[%s]' % (getTime(), host, wizard, locale, exchange['clientName'], exchange['sessionID']) print '%s: %s %s communication:[%s]' % (getTime(), kw['browser'], kw['agent'], exchange['communication']) print '%s: %s demo:%s' % (getTime(), kw['platform'], demo()) return respond(template='index.html', debug=debug, **kw)
def log(mode, **kw): host = request.form.get('host') or request.form.get('helperURI') or request.host_url debug = request.args.get('debug') == '1' and True or False demo(request.args.get('demo'), request=request) setReference(host, debug) mode = request.form.get('helperCommunicationType', session.get('communication')) wizard = request.args.get('wizard', request.form.get('wizardID', session.get('wizard'))) locale = _validate('locale', request.form.get('currentLocale', session.get('locale'))) country = request.form.get('countryID', n_a) region = request.form.get('regionID', n_a) user = request.form.get('userID', n_a) exchange = _make_exchange(mode, locale, country, region, user=request.form.get('clientName', n_a)) exchange['wizard'] = wizard page = _make_page(wizard, locale, init_only=True) kw = _make_platform(wizard, locale, user, debug) kw['links']['close'] = re.sub(r'index|log(?i)', '', request.referrer or request.url) kw['extra'] = { \ 'log_headers' : getLogVisibleHeaders(), 'statistics_headers' : getStatisticsVisibleHeaders(), 'images' : getLogImages(), } forms = ('load', 'search',) keywords = _make_keywords() kw.update({ \ 'title' : gettext('Helper Configurator Order Log Page'), 'host' : host, 'wizard' : wizard, 'locale' : locale, 'exchange' : exchange, 'keywords' : keywords, 'forms' : forms, 'page' : page, }) return respond('log.html', debug, **kw)
def respond(template='', debug=None, **kw): locale = kw.get('locale', '') host = kw.get('host', '') exchange = kw.get('exchange', {}) keywords = kw.get('keywords', {}) page = kw.get('page', None) response = make_response(render_template(template, \ # ------------------ # Communication Mode # ------------------ authorized = kw['authorized'], external = exchange['communication'] == COMMUNICATIONS['external'], internal = exchange['communication'] == COMMUNICATIONS['internal'], exchange = exchange, language = get_locale(), # ------------- # Client System # ------------- agent = kw['agent'], platform = kw['platform'], locale = locale, host = host, os = kw['os'], browser = IsIE() and 'ie' or kw['browser'], version = request.args.get('_v', '') or kw['version'] or '', css = kw['css'], screen = kw['screen'], scale = kw['scale'], style = kw['style'], is_frame = kw['is_frame'], is_demo = demo(), # ----------------- # Page & Properties # ----------------- title = kw.get('title'), name = page and page.get_title() or gettext('Helper Configurator Main Page'), article = page and page.get_article() or '', image = page and page.get_image() or '', root = kw['root'], loader = '/loader?locale=%s%s' % (locale, debug and '&debug=1' or ''), referer = kw['referer'], base = page and page.get_base() or '', uri = page and page.get_uri() or {}, forms = kw['forms'], document = '', price = gettext(n_a), links = kw['links'], keywords = keywords, page = page, # ------------- # Extra entries # ------------- extra = kw.get('extra', None), )) #response.headers['content-length'] = str(len(response.data)+419) return response
def send(action, request, session, **kw): """ Get XML from **kw or build it from the WEB-form, and send request to the External WEB-Service. WEB-form parameters are Helper tags: products, parameters and other. From **kw(data) XML is ready. Arguments: action - 203|204|205|206 for External request - form (Helper tags) session - current session kw - data (XML). Returns: exchange_error, exchange_message - exchange error info dom - DOM object data - XML (response of WEB-Service). """ global BASE_URL, BASE_PATH, REFERENCE_PATH, HELPER_URL BASE_URL, BASE_PATH, REFERENCE_PATH, HELPER_URL = getReference() exchange_error = 0 exchange_message = '' response = None error = None data = None dom = None print_action(action, 'Exchange.Send') form = request.form _print_form(form) if kw and 'data' in kw and kw.get('data'): data = kw['data'] check = 1 else: check, data = setRequestXML(action == '205' and '204' or action, request, session, **kw) _print_item(check, 'ready') if not check: # ---------------------------------- # Request is not ready, data missing # ---------------------------------- pass else: _print_xml(data, 'XML Request') url = HELPER_URL _print_item(url, 'URL') # unicode -> utf8 if isinstance(data, unicode): data = data.encode(default_unicode, 'ignore') query = data.strip() # ----------------------- # Send request to Service # ----------------------- request = urllib2.Request( \ url=url, data=urlencode({'queryDocument':query}), headers={'Content-Type': 'application/x-www-form-urlencoded'} ) data = None try: response = urllib2.urlopen(request) data = response.read() except Exception, error: exchange_message = '%s [%s]' % (gettext('No connection!'), url) # ----------------------- # Server connection error # ----------------------- exchange_error = -1 if exchange_error and demo(): # -------------------------------------------------- # Only for demo purposes, web-service is unavailable # -------------------------------------------------- return (0, exchange_message, parseString(query), query,) elif data and XML_PREFIX in data: # -------------- # Response is OK # -------------- data = data.replace(data[0:data.find(XML_PREFIX)], '').strip() elif not exchange_error: # -------------------------------------------- # No XML Response (error from the application) # -------------------------------------------- exchange_error = -2 _print_xml(data, 'XML Response') try: # --------- # Parse DOM # --------- if not exchange_error and data: dom = parseString(data) except Exception, error: exchange_message = gettext('Not valid response!'), # --------------- # Unvalid XML DOM # --------------- exchange_error = -3
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, }
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, }
def loader(): if not request.form.get('wizardID'): return '' host = request.form.get('host') debug = request.args.get('debug') == '1' and True or False demo(request.form.get('demo'), request=request) setReference(host, debug) if IsDebug: start = datetime.datetime.now() print '--> Started at %s' % start.strftime('%H:%M:%S:%f') wizard = request.form.get('wizardID') or session.get('wizard') action = request.form.get('action') or '204' check = request.form.get('check') or '' communication = request.form.get('helperCommunicationType') or default_communication locale = request.form.get('currentUsedLocalization') or session.get('locale') exchange_error = 0 if IsDebug: print '--> action: [%s]' % action print '--> communication: [%s]' % communication print '--> demo: [%s]' % demo() print '--> host: [%s]' % host print '--> wizard: [%s]' % wizard response = {} if not (action and action in valid_action_types): return '' IsChecked = True if not isAuthorized(request.form.get('userID')): exchange_error = -4 exchange_message = gettext('Sorry, you are not authorized.') IsChecked = False if IsChecked and action in ('207','307') and demo() and not _check(wizard, check): exchange_error = -5 exchange_message = gettext('Sorry, the confirmation code is invalid.')+'<br>'+gettext('Please, try more.') IsChecked = False if action in ('301','302','303','304','305','307','308',): if IsChecked: # ------------------------------------------------------------------------------------- # Get Data from DB (XML:data, DOM:dom, parsed XML-Items:items or Log-page content:data) # ------------------------------------------------------------------------------------- response = respond_log(action) if not (response and response.get('data')): pass elif action in ('303','304','307',): requested_action = str(int(action)-100) # -------------------------------------------------- # Get XML (update tags for a new request to Service) # -------------------------------------------------- check, data = getRequestXML(requested_action, request, session, data=response.get('items'), dom=response.get('dom'), title=response.get('title'), page='log', url=host) # ---------------------------------------- # Send request to Service and get response # ---------------------------------------- response = respond_external(requested_action, data=data, id=response.get('id')) response['action'] = action # ------------------------------------------------------------- # Get Data Dictionary (!!!) from response to send to Controller # ------------------------------------------------------------- if action == '303': dom, data = receive(action, request, session, data=response.get('data')) response['data'] = data response['dom'] = None response['items'] = None else: # -------------------------------------- # Remove DOM from response to Controller # -------------------------------------- response['dom'] = None response['items'] = None elif communication == COMMUNICATIONS['external'] or not communication: if IsDebug: print '--> check: [%s] = %s' % (check, IsChecked) if action == '100': # ------------------- # Validate the action # ------------------- if not demo(): response = {'x1' : None, 'x2' : None, 'op' : None} else: response = _set_checker(wizard) elif action in ('203','204','205',): # --------------------------------------------------------------- # Send External request to Service and get response (calculation) # --------------------------------------------------------------- response = respond_external(action) elif action in ('207',) and IsChecked: # --------------------------------------------------------- # Send External request to Service and get response (order) # --------------------------------------------------------- response = respond_external(action) if response: response['data'] = '' elif communication == COMMUNICATIONS['internal']: if action == '100': # ------------------- # Validate the action # ------------------- response = {'x1' : None, 'x2' : None, 'op' : None} elif action in ('203','204','205','206',): # ------------------------------------------------- # Send Internal request to Service and get response # ------------------------------------------------- response = respond_internal(action) if not response: response = { \ 'action' : action, 'op' : '', # ------------------------------- # Not authorized or check invalid # ------------------------------- 'exchange_error' : exchange_error, 'exchange_message' : exchange_message, 'error_code' : '', 'error_description' : '', 'errors' : '', # ----------------- # Results (no data) # ----------------- 'price' : '', 'data' : '', } if IsDebug: finish = datetime.datetime.now() t = finish - start print '--> Finished at %s' % finish.strftime('%H:%M:%S:%f') print '--> Spent time: %s sec' % ((t.seconds*1000000+t.microseconds)/1000000) return jsonify(response)