def _get_reward_data(self, conn, id_coupon, coupon_type): reward = {} if coupon_type == COUPON_REWARD_TYPE.COUPON_CURRENCY: credit_value = db_utils.select_dict( conn, 'store_credit', 'id_coupon', where={'id_coupon': id_coupon}).values()[0] reward['credit'] = { 'currency': credit_value['currency'], 'amount': credit_value['amount'], } else: gift_values = db_utils.select( conn, 'coupon_gift', columns=('id_sale', 'quantity'), where={'id_coupon': id_coupon}) if gift_values: reward['gifts'] = [{'item_id': gift[0], 'quantity': gift[1]} for gift in gift_values] results = db_utils.select( conn, 'coupon_give_away', where={'id_coupon': id_coupon}) if results: reward['max_selection'] = results[0]['max_selection'] or 0 else: discount_value = db_utils.select_dict( conn, 'coupon_discount', 'id_coupon', where={'id_coupon': id_coupon}).values()[0] reward['discount'] = { 'type': COUPON_DISCOUNT_APPLIES.toReverseDict()[ discount_value['discount_type']], 'discount': discount_value['discount'], } return reward
def save_vessel_data(conn, mmsi, lat, lon, detail_html): soup = BeautifulSoup(detail_html) if soup.find(name='td'): time = soup.find(name='p').text nav_status = soup.find(name='td', text='Navigation Status').find_next().text heading = soup.find(name='td', text='True Heading').find_next().text speed = soup.find(name='td', text='Speed Over Ground').find_next().text else: info = soup.find(name='p').text.split('\n') time = info[0] nav_status = '' m = re.match( r'.* (?P<speed>\d+(\.\d+)?) heading (?P<heading>\d+(\.\d+)?) .*', info[1]) if m: heading = m.groupdict()['heading'] speed = m.groupdict()['speed'] else: heading = None speed = None vessels = db_utils.select(conn, "vessel", columns=("id", ), where={'mmsi': mmsi}, limit=1) if len(vessels) > 0: id_vessel = vessels[0][0] else: vessel_values = { 'mmsi': mmsi, } id_vessel = db_utils.insert(conn, "vessel", values=vessel_values, returning='id')[0] pos_values = { 'id_vessel': id_vessel, 'location': '', 'longitude': lon, 'latitude': lat, 'heading': format_number(heading), 'speed': format_number(speed), 'time': format_text(time), 'status': nav_status, } existings = db_utils.select(conn, "vessel_position", columns=("id", ), where={'id_vessel': id_vessel, 'time': format_text(time)}, limit=1) if len(existings) == 0: print "inserting: ", pos_values db_utils.insert(conn, "vessel_position", values=pos_values) else: print "existing: ", pos_values
def valid_check(self, conn, req, **kwargs): data = decrypt_json_resp(req.stream, settings.SERVER_APIKEY_URI_MAP[self.service], settings.PRIVATE_KEY_PATH) logging.info("payment_ajax_request: %s", data) data = ujson.loads(data) try: cookie = ujson.loads(data['cookie']) trans = get_trans_by_id(conn, cookie['internal_trans']) assert len(trans) == 1, "No trans for cookie %s" % cookie trans = trans[0] assert data['cookie'] == trans['cookie'], ( "invalid cookie: %s expected: %s" % (cookie, trans['cookie'])) id_card = CCAddResource().add_card(conn, { 'id_user': trans['id_user'], 'pan': data.get('pan'), 'cvc': data.get('cvc'), 'expiration_date': data.get('expiration_date'), 'repeat': data.get('repeat'), }) card = db_utils.select(conn, 'credit_card', where={'id': id_card, 'valid': True})[0] return trans, card except AssertionError, e: logging.error("pm_ajax_invalid_request, param : %s " "error: %s", data, e, exc_info=True) raise UserError(ErrorCode.PMA_INVALID_REQ[0], ErrorCode.PMA_INVALID_REQ[1])
def push_order_confirming_event(conn, id_order, id_brand): id_user, confirmation_time = db_utils.select(conn, "orders", columns=("id_user", "confirmation_time"), where={'id': id_order})[0] user_info = get_user_info(conn, id_user) month, day = confirmation_time.strftime('%b|%d').split('|') params = { 'email': user_info['fo_user_email'], 'service_email': settings.SERVICE_EMAIL, 'id_brand': id_brand, 'id_order': id_order, 'fo_user_name': user_info['fo_user_name'], 'order_created_month': month, 'order_created_day': day, } from models.order import get_order_items items = [ item for item in get_order_items(conn, id_order) if item['brand_id'] == int(id_brand) ] order_xml = render_content('order_details.xml', **to_unicode({'order_items': items})) _xslt = order_xslt(order_xml) params['order_xslt'] = _xslt _push_specific_event('USR_ORDER_CONFIRMING', **params)
def valid_check(self, conn, req, **kwargs): req._params.update(kwargs) logging.info("payment_auto_request: %s", req._params) try: cookie = req.get_param('cookie') cookie = ujson.loads(cookie) trans = get_trans_by_id(conn, cookie['internal_trans']) assert len(trans) == 1, "No trans for cookie %s" % cookie trans = trans[0] assert req.get_param('cookie') == trans['cookie'], ( "invalid cookie: %s expected: %s" % (cookie, trans['cookie'])) id_card = req.get_param('id_card') card = db_utils.select(conn, 'credit_card', where={'id': id_card, 'valid': True}) assert len(card) == 1, "No valid card %s" % id_card return trans[0], card[0] except AssertionError, e: logging.error("pm_ajax_invalid_request, param : %s " "error: %s", data, e, exc_info=True) raise UserError(ErrorCode.PM_AUTO_INVALID_REQ[0], ErrorCode.PM_AUTO_INVALID_REQ[1])
def add_card(self, conn, data): # validation for param in ['id_user', 'pan', 'cvc', 'expiration_date']: if not data.get(param): raise ValidationError('Missing param %s' % param) id_user = data['id_user'] cardholder_name = data.get('cardholder_name', '') pan = data['pan'] cvc = data['cvc'] expire = data['expiration_date'] repeat = data.get('repeat') if not is_valid_cc_num(pan): raise ValidationError('Invalid param pan') if not is_valid_cvc(cvc): raise ValidationError('Invalid param cvc') try: datetime.strptime(expire, '%m%y') except: raise ValidationError('Invalid param expiration_date') results = db_utils.select(conn, 'credit_card', where={ 'id_user': id_user, 'cc_num': mask_cc_num(pan), 'expiration_date': expire, 'valid': True, }) if results: raise ValidationError('Duplicated Card') values = { 'id_user': id_user, 'cardholder_name': cardholder_name, 'cc_num': mask_cc_num(pan), 'expiration_date': expire, 'repeat': bool(repeat), 'valid': False, } id_card = db_utils.insert(conn, 'credit_card', values=values, returning='id')[0] cli = Paybox() token = cli.register_card(id_card, id_user, pan, cvc, expire, repeat=bool(repeat)) db_utils.update(conn, 'credit_card', values={ 'paybox_token': token, 'valid': True }, where={'id': id_card}) return id_card
def up_order_log(conn, id_order, sellers): for id_brand, shops in sellers.iteritems(): for id_shop in shops: status = get_order_status(conn, id_order, id_brand, [id_shop]) where = { 'id_order': id_order, 'id_brand': id_brand, 'id_shop': id_shop } log = select(conn, 'orders_log', where=where) if log: log = log[0] else: continue v = None if status == ORDER_STATUS.PENDING: if log['pending_date'] is None: v = {'pending_date': datetime.utcnow().date()} elif status == ORDER_STATUS.AWAITING_PAYMENT: if log['waiting_payment_date'] is None: v = {'waiting_payment_date': datetime.utcnow().date()} elif status == ORDER_STATUS.AWAITING_SHIPPING: if log['waiting_shipping_date'] is None: v = {'waiting_shipping_date': datetime.utcnow().date()} elif status == ORDER_STATUS.COMPLETED: if log['completed_date'] is None: v = {'completed_date': datetime.utcnow().date()} if v is not None: where = { 'id_order': id_order, 'id_brand': id_brand, 'id_shop': id_shop } update(conn, 'orders_log', values=v, where=where)
def verify(self, conn, email, raw_password): if not email or not raw_password: raise ValidationError('ERR_LOGIN') result = db_utils.select(conn, "users", columns=("id", "password", "salt", "hash_iteration_count", "hash_algorithm"), where={'email': email.lower()}, limit=1) if not result or len(result) == 0: raise ValidationError('ERR_LOGIN') users_id, password, salt, hash_iteration_count, hash_algorithm = result[ 0] auth_token = get_preimage(hash_algorithm, hash_iteration_count, salt, raw_password) if password != get_authenticator(hash_algorithm, auth_token): raise ValidationError('ERR_LOGIN') if (hash_algorithm != settings.DEFAULT_PASSWORD_HASH_ALGORITHM or hash_iteration_count < settings.HASH_MIN_ITERATIONS): auth_token = self.auth_update(conn, users_id, raw_password) return users_id, auth_token
def _on_post(self, req, resp, conn, **kwargs): ticket_id = req.get_param('ticket_id') priority = req.get_param('priority') escalation = req.get_param('escalation') update_values = {} if priority: if priority.isdigit() and int( priority) not in TICKET_PRIORITY.toDict().values(): raise ValidationError('INVALID_PARAM_PRIORITY') update_values.update({'priority': priority}) if escalation: escalation = req.get_param('escalation') in ('True', 'true') update_values.update({'escalation': escalation}) if escalation: update_values.update({'escalation_time': datetime.utcnow()}) rows = db_utils.select(self.conn, 'ticket', columns=('id', ), where={'id': ticket_id}, limit=1) if not rows or len(rows) == 0: raise ValidationError('INVALID_PARAM_TICKET_ID') db_utils.update(conn, "ticket", values=update_values, where={'id': ticket_id}) return {"res": RESP_RESULT.S, "err": ""}
def _coupon_redeemed(conn, id_coupon, id_order, id_invoice): results = db_utils.select(conn, 'coupon_redeemed', where={ 'id_coupon': id_coupon, 'id_order': id_order, }) if not results: return update_values = { 'id_invoice': id_invoice, 'order_status': ORDER_STATUS_FOR_COUPON.PAID, } if len(results) == 1 and results[0]['id_invoice'] is None: db_utils.update(conn, 'coupon_redeemed', values=update_values, where={'id': results[0]['id']}) else: values = { 'id_coupon': results[0]['id_coupon'], 'id_user': results[0]['id_user'], 'id_order': results[0]['id_order'], 'redeemed_time': results[0]['redeemed_item'], 'account_address': results[0]['account_address'], 'account_phone': results[0]['account_phone'], 'user_agent': results[0]['user_agent'], } values.update(update_values) db_utils.insert(conn, 'coupon_redeemed', values=values)
def get_coupon_user_data(conn, id_coupon): id_users = db_utils.select(conn, 'coupon_given_to', columns=('id_user', ), where={'id_coupon': id_coupon}) if id_users: id_users = [v[0] for v in id_users] return id_users
def get_coupon_shop_data(conn, id_coupon): id_shops = db_utils.select(conn, 'coupon_accepted_at', columns=('id_shop', ), where={'id_coupon': id_coupon}) if id_shops: id_shops = [id_shop[0] for id_shop in id_shops] return id_shops
def _on_get(self, req, resp, conn, **kwargs): where = self._get_req_range(req) r = select(self.conn, 'visitors_log', where=where) visitors = [] for visitor in r: visitors.append(dict(visitor)) data = {'number': len(visitors), 'visitors': visitors} return {'GET_R': data}
def _query_portname(self, conn, locode): results = db_utils.select(conn, "port", columns=("name", ), where={'locode': locode}, limit=1) if len(results) > 0: return results[0][0] else: return None
def handle_titles(self, req, resp, conn): dep_val = req.get_param('dep') or '' cur_val = req.get_param('val') or '' result = db_utils.select(conn, "title", columns=("title", "title"), where={'locale': dep_val}) field = field_utils.SelectFieldType("Title", cur_val, result) return field.toDict()
def handle_countries(self, req, resp, conn): dep_val = req.get_param('dep') or '' cur_val = req.get_param('val') or '' result = db_utils.select(conn, "country", columns=("printable_name", "iso"), order=("printable_name", )) field = field_utils.SelectFieldType("Country", cur_val, result) return field.toDict()
def _check_param_db_existing(self, fname, table, fields=None): if not fields: fields = ("id", ) fvalue = self.request.get_param(fname) result = db_utils.select(self.conn, table, columns=fields, where={'id': fvalue}) if len(result) == 0: raise ValidationError('INVALID_PARAM_%s' % fname.upper()) return result[0]
def _filter_by_id(self, conn, id_type, id_value, id_coupons): results = db_utils.select( conn, 'coupon_condition', columns=('id_coupon',), where={'id_value': id_value, 'id_type': id_type}) results = [v[0] for v in results] if results: results = list(set(id_coupons).intersection(results)) results.sort(key=lambda o:id_coupons.index(o)) return results else: return id_coupons
def charge(self, conn, id_trans, card_token): trans = db_utils.select(conn, "transactions", columns=['amount_due', 'currency', 'iv_numbers'], where={'id': id_trans})[0] stripe.api_key = settings.STRIPE_SECRET_API_KEY resp = stripe.Charge.create( amount=int(trans[0] * 100), currency=trans[1], source=card_token, description="Charge for invoice num: %s" % trans[2], ) return resp
def _on_get(self, req, resp, conn, **kwargs): id_user = req.get_param('id_user') if not id_user: raise ValidationError('INVALID_REQUEST') results = db_utils.select(conn, "vessel_arrival_notif", columns=("imo", "mmsi"), where={ 'id_user': id_user, 'done': False }) return {'objects': results, 'res': RESP_RESULT.S}
def get_email(self, req, conn, users_id=None): email = req.get_param('email') if email is None or not is_valid_email(email): raise ValidationError('ERR_EMAIL') result = db_utils.select(conn, "users", columns=("id", ), where={'email': email.lower()}, limit=1) if result and (users_id is None or str(users_id) != str(result[0][0])): raise ValidationError('EXISTING_EMAIL') return email.lower()
def api_key_verify(conn, email, api_key): result = db_utils.select(conn, "users", columns=("id", "salt", "hash_iteration_count"), where={'email': email.lower()}, limit=1) if len(result) == 0: raise ValidationError('ERR_EMAIL') users_id, salt, hash_count = result[0] if api_key != get_api_key(email, salt, hash_count): raise ValidationError('ERR_API_KEY') return users_id
def get_chosen_gifts(conn, id_coupon, chosen_gifts): gift_values = db_utils.select(conn, 'coupon_gift', columns=('id_sale', 'quantity'), where={'id_coupon': id_coupon}) gifts_available = [(gift['id_sale'], gift['quantity']) for gift in gift_values] results = db_utils.select(conn, 'coupon_give_away', where={'id_coupon': id_coupon}) if results: max_selection = results[0]['max_selection'] or 0 if max_selection: params = { 'max_selection': max_selection, 'gifts_available': gifts_available } if not chosen_gifts: raise UserError( ErrorCode.COUPON_ERR_GIFTS_NEED_SELECT_GIFTS[0], params) if len(chosen_gifts) > max_selection: raise UserError( ErrorCode.COUPON_ERR_GIFTS_EXCEED_MAX_SELECTION[0], params) if not set(dict(chosen_gifts).keys()).issubset( dict(gifts_available).keys()): raise UserError(ErrorCode.COUPON_ERR_GIFTS_INVALID_ITEM[0], params) for id_sale, quantity in chosen_gifts: if dict(gifts_available)[id_sale] < quantity: raise UserError( ErrorCode.COUPON_ERR_GIFTS_INVALID_QUANTITY[0], params) else: chosen_gifts = gifts_available else: chosen_gifts = gifts_available return chosen_gifts
def coupon_update(self, req, resp, conn): id_brand = req.get_param('id_issuer') if not id_brand: raise ValidationError('COUPON_ERR_INVALID_ID_BRAND') id_coupon = req.get_param('id_coupon') coupons = db_utils.select( conn, 'coupons', where={'id': id_coupon}) if not coupons: raise ValidationError('COUPON_ERR_INVALID_ID_COUPON') if coupons[0]['id_brand'] != int(id_brand): raise ValidationError('COUPON_ERR_INVALID_COUPON_FOR_BRAND') return self.coupon_create(req, resp, conn, id_coupon=id_coupon)
def _check_ticket(self, id_ticket): if not id_ticket: raise ValidationError('INVALID_REQUEST') rows = db_utils.select(self.conn, 'ticket', columns=('fo_author', 'fo_recipient'), where={'id': id_ticket}, limit=1) if not rows or len(rows) == 0: raise ValidationError('INVALID_REQUEST') fo_author, fo_recipient = rows[0] if int(self.users_id) not in (fo_author, fo_recipient): raise ValidationError('INVALID_REQUEST')
def handle_provinces(self, req, resp, conn): dep_val = req.get_param('dep') or '' cur_val = req.get_param('val') or '' if dep_val in settings.SUPPORTED_MAJOR_COUNTRIES: result = db_utils.select(conn, "province", columns=("name", "code"), where={'country_code': dep_val}, order=("name", )) else: result = [] field = field_utils.SelectFieldType("Province", cur_val, result) return field.toDict()
def _item_changed(self, conn, users_id, columns, table, item_id, item_data): if item_id.isdigit() and int(item_id) == 0: return True result = db_utils.select(conn, table, columns=columns, where={'id': item_id}, limit=1) if len(result) == 0: return True for i, c in enumerate(columns): if str(item_data.get(c)) != str(result[0][i]): return True return False
def get_user_profile(conn, user_id): user_profile = {} columns = [ 'locale', 'title', 'first_name', 'last_name', 'gender', 'birthday', 'users_id', 'is_business_account', 'company_name', 'company_position', 'company_tax_id' ] results = select(conn, 'users_profile', where={'users_id': user_id}, columns=columns) if results: user_profile = dict(zip(columns, results[0])) user_profile.update({'email': get_user_email(conn, user_id)}) return user_profile
def _on_get(self, req, resp, conn, **kwargs): id_user = req.get_param('id_user') if not id_user: raise ValidationError('Missing param id_user') results = db_utils.select(conn, 'credit_card', where={ 'id_user': id_user, 'valid': True }) cc_list = [{ 'id_card': one['id'], 'pan': one['cc_num'], 'expiration_date': one['expiration_date'], } for one in results] return {"res": RESP_RESULT.S, "err": "", "data": cc_list}
def send_container_arrival_notif(container, last_pod): logging.info("Sending container arrival notif for %s" % container) with db_utils.get_conn() as conn: msg = "Container(%s) is arriving in %s" % (container, last_pod) notifs = db_utils.select(conn, "container_arrival_notif", columns=("id", "email"), where={'container': container, 'done': False}) for _id, _email in notifs: send_html_email(_email, msg, msg) db_utils.update(conn, "container_arrival_notif", values={'done': True}, where={'id': _id}) conn.commit()