def getLogItem(action, request, session): """ Get Log item from DB by selected log item's ID. Arguments: action - 302|303|304|307 request - form (selected_item) session - current session Returns: exchange_error, exchange_message - exchange error info id - parsed ID of selected_item data - XML (Order.data) """ form = request.form print_action(action, 'DBase.GetLogItem') exchange_message = '' exchange_error = 0 order = None id = form.get('selected_item', None) if IsDebug: print '>>> Selected LogItem ID: [%s]' % id if id: order = Order.get_by_id(id) else: exchange_message = '%s: <id>' % gettext('Missing argument') exchange_error = -10 return (exchange_error, exchange_message, id, order)
def getStatictics(action, request, session): """ Get Price items from DB by selected log item's ID. Arguments: action - 305 request - form (selected_item) session - current session Returns: exchange_error, exchange_message - exchange error info id - parsed ID of selected_item data - XML (Order.data) """ form = request.form print_action(action, 'DBase.GetLogStatistics') exchange_message = '' exchange_error = 0 response = None order = None id = form.get('selected_item', None) if IsDebug: print '>>> Selected LogItem ID: [%s]' % id if id: order = Order.get_by_id(id) else: exchange_message = '%s: <id>' % gettext('Missing argument') exchange_error = -10 total, order_id, data, query = statistics(DEFAULT_LOG_MODE, order=order) items = [] headers = get_statistics_headers() line_in_page = 0 for row in data: x = dict(zip(headers[0], row)) line_in_page += 1 x['root'] = '%s' % request.script_root x['num'] = line_in_page x['cdate'] = cdate(x['reg_date'], fmt=LOCAL_EASY_TIMESTAMP) for n, column in enumerate(headers[1]): x['%s_title' % column['id']] = column['title'] items.append([x['id'], [ column.has_key('value') and (column['value'] % x) or x[column['id']] for n, column in enumerate(headers[1]) if column.get('visible') ] ]) return (exchange_error, exchange_message, id, total, items)
def getLogTotal(attrs, force=None): """ Get Log rows count filtered by optional user, module, order type. Arguments: attrs - attributes (userID, wizardID, otype) Filter by (attrs): userID - user ID wizardID- wizard ID otype - order type (Config.valid_order_types) Returns: total - page items count """ print_db_state() userID = attrs.get('userID', None) user = userID and User.query.filter_by(userID=userID).first() if IsDebug and userID: print '>>> User[%s]: %s' % (userID, user and user.userID == userID and 'OK' or 'invalid!') wizardID = attrs.get('wizardID', None) module = wizardID and Module.query.filter_by(wizardID=wizardID).first() if IsDebug and wizardID: print '>>> Module[%s]: %s' % (wizardID, module and module.wizardID == wizardID and 'OK' or 'invalid!') otype = int(attrs.get('otype', 0)) if IsDebug and otype in valid_order_types: print '>>> Order type[%s]: %s' % (otype, valid_order_names[otype]) query = Order.query if user: query = query.filter_by(user=user) if module: query = query.filter_by(module=module) if otype: query = query.filter_by(otype=otype) if user and module or force: total = query.count() else: total = 0 print_action(total, 'DBase.getLogTotal') return total
def receive(action, request, session, **kw): """ Receive XML from **kw (DB) or requested WEB-form, parse DOM and XML-Items and return its to the caller. From **kw(data) or requested WEB-form XML is ready. Arguments: action - 203|204|205|206 for Internal, 303 for Log request - form.data (XML, Internal) session - current session kw - data (XML, DB). Returns: dom - DOM object data - Data Dictionary (XML-Items). """ error = None dom = None print_action(action, 'Exchange.Receive') form = request.form _print_form(form) data = kw.get('data') or form.get('data') or '' # unicode -> utf8 if isinstance(data, unicode): data = data.encode(default_unicode, 'ignore') data = data.strip() if data and data.startswith(CDATA): data = data[9:-3] try: dom = parseString(data) except Exception, error: msg = '--> Invalid XML content!' # --------------- # Unvalid XML DOM # --------------- print_to(errorlog, [msg, data], request=request) #traceback.print_exc(file=open(errorlog, 'a')) raise
def removeLogItem(action, request, session): """ Remove Log item from DB by selected log item's ID. Arguments: action - 308 request - form (selected_item) session - current session Returns: exchange_error, exchange_message - exchange error info """ form = request.form print_action(action, 'DBase.RemoveLogItem') exchange_message = '' exchange_error = 0 IsDone = False id = form.get('selected_item', None) if id: order =get_order(id) if order and order.otype not in (ORDER_STANDARD, ORDER_DONE): _delete(order) _commit(True) IsDone = True else: exchange_message = 'Error %s: <%s>' % (gettext('Missing argument'), id) exchange_error = -10 if IsDebug: if IsDone and not exchange_error: print '>>> Removed LogItem ID: [%s]' % id elif exchange_error: print '>>> [%s] %s' % (exchange_error, exchange_message) else: print '>>> [%s] %s' % (id, gettext('Cannot be removed')) return getLogPage(action, request, session)
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 setRequestXML(action, request, session): """ Generate XML from the WEB-form. Get XML-Items and DOM from **kw (WEB-form), generate XML and return it to the caller. Arguments: action - 203|204|207 for Internal/External request - form.data (product/parameters/options) session - current session. Returns: data - XML (String). """ form = request.form print_action(action, 'Exchange.setRequestXML') level0 = ' '*6 level1 = ' '*8 level2 = ' '*10 helperXMLVersion = form.get('helperXMLVersion', None) or '1' if helperXMLVersion == '2': # ------------- # XML VERSION 2 # ------------- products = [] for key in 'abcde': option = form.get('options[%s]' % key, None) if not option: break if IsDebug: print '--> option[%s]:%s' % (key, option) is_default = key == 'a' and True or False product = { 'option' : option, 'default' : is_default and ' default="1"' or '', 'content' : '' } check, parameters, options = setRequestContent(form, level2, (PARAMETER_XML_TEMPLATE, OPTION_XML_TEMPLATE,), key, is_default) #product['parameters'] = parameters.strip() and level1 + (PARAMETERS_XML_V2_TEMPLATE % parameters).strip() or '' #product['options'] = options.strip() and level1 + (OPTIONS_XML_V2_TEMPLATE % options).strip() or '' product['content'] = \ (options.strip() and EOL+level1+(OPTIONS_XML_V2_TEMPLATE % options).strip() or '') + \ (parameters.strip() and EOL+level1+(PARAMETERS_XML_V2_TEMPLATE % parameters).strip() or '') if product['content']: product['content'] += EOL+level0 products.append(level0 + (PRODUCT_XML_V2_TEMPLATE % product).strip()) content = CONTENT_XML_V2_TEMPLATE % EOL.join(products) else: # ----------------------- # XML VERSION 1 (DEFAULT) # ----------------------- check, parameters, products = setRequestContent(form, level1, (PARAMETER_XML_TEMPLATE, PRODUCT_XML_TEMPLATE,)) if form.get('defaultConstruct', None) and form.get('defaultConstructCount', None): products = CONSTRUCT_XML_TEMPLATE % {'indent':level1, 'code':form['defaultConstruct'], 'value':form['defaultConstructCount'], 'n_a':n_a} + \ EOL + products content = CONTENT_XML_V1_TEMPLATE % { 'products' : (PRODUCTS_XML_V1_TEMPLATE % products).strip(), 'parameters' : (PARAMETERS_XML_V1_TEMPLATE % parameters).strip(), } attrs = _create_request_attrs(action, request, session, content=content, version=helperXMLVersion) return check, (REQUEST_XML_TEMPLATE % attrs).strip()
def getRequestXML(action, request, session, data=None, dom=None, title=None, page=None, url=None): """ Generate XML from DB. Get XML-Items and DOM from **kw (DB), generate XML and return it to the caller. Arguments: action - 303|304|307 for Log request - form.data session - current session kw - Data (Data Dictionary made by receive) and DOM-object. Returns: data - XML (String). """ if not data or not dom: return '' print_action(action, 'Exchange.getRequestXML') form = request.form level0 = ' '*6 level1 = ' '*8 level2 = ' '*10 helperXMLVersion = form.get('helperXMLVersion', None) or '1' # unicode -> utf8 if title and not isinstance(title, unicode): title = title.decode(default_unicode, 'ignore') content = '' if helperXMLVersion == '1': # ------------- # XML VERSION 1 # ------------- products = '' for x in data['products']: x['indent'] = level1 x['code'] = x['id'] x['price'] = n_a if x['unit'] == n_a: x['unit'] = '' products += (products and EOL or '')+(PRODUCT_XML_TEMPLATE % x) parameters = '' for x in data['parameters']: x['indent'] = level1 x['cis'] = x['id'] if x['parent']: x['parent'] = ' parent="%s"' % x['parent'] x['price'] = n_a if x['unit'] == n_a: x['unit'] = '' parameters += (parameters and EOL or '')+(PARAMETER_XML_TEMPLATE % x) content = CONTENT_XML_V1_TEMPLATE % { 'products' : (PRODUCTS_XML_V1_TEMPLATE % products).strip(), 'parameters' : (PARAMETERS_XML_V1_TEMPLATE % parameters).strip(), } check = (products or parameters) and 1 or 0 else: # ----------------------- # XML VERSION 2 and other # ----------------------- content = \ re.sub(r'\n\s+<parameter\s+id="\w{8,}?-\w{4,}?-\w{4,}?-\w{4,}?-\w{12,}?".*?\/(parameter)?>', r'', re.sub(r'\s+(article|title)=".*?"', '', re.sub(r'price=".*?"', 'price="%s"' % n_a, getDOMTagValue(dom, 'products')))) check = 1 _print_xml(content, 'XML Content') attrs = _create_request_attrs(action, request, session, content=content, version=helperXMLVersion, title=title, page=page, url=url) #, url=HELPER_URL return check, (REQUEST_XML_TEMPLATE % attrs).strip() # data
def respond_log(action): exchange_error = 0 exchange_message = '' page = None current_page, pages, per_page, has_prev, has_next, total, id = (0, 0, 0, False, False, 0, None) iter_pages = [] order = None data = None dom = None items = None title = '' print_action(action, 'Respond.Log') locale = request.form.get('currentUsedLocalization') or '' try: # ---------------- # Get Data from DB # ---------------- if not action: pass elif action == '301': exchange_error, exchange_message, page, data = getLogPage(action, request, session) elif action == '305': exchange_error, exchange_message, id, total, data = getStatictics(action, request, session) elif action == '308': exchange_error, exchange_message, page, data = removeLogItem(action, request, session) else: #if action in ('302','303','304','307',): exchange_error, exchange_message, id, order = getLogItem(action, request, session) except: msg = '--> Database error!' # ------------- # DB Log failed # -------------- print_to(errorlog, msg, request=request) raise if not (action and action in valid_action_types): pass elif action in ('301','308',): # -------------------- # Get Log-page content # -------------------- if page: current_page, pages, per_page, has_prev, has_next, total = page.get_page_params() iter_pages = page.iter_pages() if IsDebug: print '--> LogPage[%s]: items:[%s] %s-%s-%s-%s iter:%s' % ( \ current_page, len(data), pages, per_page, has_prev, has_next, iter_pages) elif action in ('302',): # ------------------------------ # DOM and XML-Items (Dictionary) # ------------------------------ dom, data = receive(action, request, session, data=order.data) #, products_sorted=True if IsDebug: print '--> LogPageItem[%s]: Data %s, Products %s, Parameters %s' % ( \ id, len(order.data), len(data['products']), len(data['parameters'])) elif action in ('303','304','307',): # --------- # Clean XML # --------- data = order.data #_data(coding='encode') # ------------------------------ # DOM and XML-Items (Dictionary) # ------------------------------ dom, items = receive(action, request, session, data=data) title = order.title if IsDebug: print '--> Loaded LogPageItem[%s]: Data %s, Products %s, Parameters %s' % ( \ id, len(order.data), len(items['products']), len(items['parameters'])) elif action in ('305',): if IsDebug: print '--> LogStatictics[%s]: Data %s' % ( \ id, data and len(data), ) if exchange_error: if IsDebug: print '--> ExchangeError[%s]: %s' % (exchange_error, exchange_message) return { \ 'action' : action, 'op' : '', # -------------- # Service Errors # -------------- 'exchange_error' : exchange_error, 'exchange_message' : exchange_message, # ----------------------------- # Results (Log page parameters) # ----------------------------- 'id' : id, 'rows_on_page' : len(data), 'total' : total, 'page' : current_page, 'pages' : pages, 'per_page' : per_page, 'has_prev' : has_prev, 'has_next' : has_next, 'iter_pages' : iter_pages, # -------------------------- # Results (Log page content) # -------------------------- 'custom_code' : order and order.code or '', 'title' : title, 'price' : '', 'data' : data, 'dom' : dom, 'items' : items, }
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 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
def getLogPage(action, request, session): """ Get Log page from DB by selected number filtered by requested userID and wizardID. Arguments: action - 301 request - form (page, per_page, userID, wizardID) session - current session Filter by (attrs): userID - user ID wizardID- wizard ID otype - order type (Config.valid_order_types) context - search context Returns: exchange_error, exchange_message - exchange error info data - Pagination object from DB models items - page column items """ print_db_state() form = request.form print_action(action, 'DBase.GetLogPage') exchange_message = '' exchange_error = 0 data = None page = int(form.get('page', 0)) or 1 per_page = int(form.get('per_page', 0)) or DEFAULT_PER_PAGE sort = form.get('sort') or '' userID = form.get('userID', None) user = userID and User.query.filter_by(userID=userID).first() if IsDebug and userID: print '>>> User[%s]: %s' % (userID, user and user.userID == userID and 'OK' or 'invalid!') wizardID = form.get('wizardID', None) module = wizardID and Module.query.filter_by(wizardID=wizardID).first() if IsDebug and wizardID: print '>>> Module[%s]: %s' % (wizardID, module and module.wizardID == wizardID and 'OK' or 'invalid!') otype = int(form.get('otype', -1)) if IsDebug and otype in valid_order_types: print '>>> Order type[%s]: %s' % (otype, valid_order_names[otype]) context = form.get('search_context', None) if IsDebug and context: print '>>> Search context: [%s]' % context data = log(DEFAULT_LOG_MODE, page, per_page, user=user, module=module, otype=otype, context=context, check=IsDBCheck, sort=sort) items = [] headers = get_log_headers() line_in_page = 0 #(page-1) * per_page for row in data.items: x = dict(zip(headers[0], row)) line_in_page += 1 s = x['document'] or '' if s and s.startswith('#'): x['document'] = s[1:].strip() x['root'] = '%s' % request.script_root x['image'] = '%s-16.png' % ( \ x['rating'] == RATING_UP and 'up' or x['rating'] == RATING_DOWN and 'down' or x['rating'] == RATING_EQUAL and 'equal' or 'undef') x['num'] = line_in_page x['cdate'] = cdate(x['reg_date'], fmt=LOCAL_EASY_TIMESTAMP) x['price'], x['currency'] = x['current_price'].split() x['code'] = x['otype'] == ORDER_DONE and x['document'] or x['code'] x['updatable'] = x['option_update'] and 'updatable' or x['option_cost'] and 'cost' or 'fixed' for n, column in enumerate(headers[1]): x['%s_title' % column['id']] = column['title'] items.append([x['id'], [ column.has_key('value') and (column['value'] % x) or x[column['id']] for n, column in enumerate(headers[1]) if column.get('visible') ] ]) return (exchange_error, exchange_message, data, items)