def _valid_check(self, conn): if self.request.get_param('receiver_email') != settings.SELLER_EMAIL: logging.error('paypal_valid_err: wrong receiver email %s', self.request.query_string, exc_info=True) raise UserError(ErrorCode.PP_ERR_RECEIVER_EMAIL[0], ErrorCode.PP_ERR_RECEIVER_EMAIL[1]) trans = get_trans_by_id(conn, self.id_trans) if len(trans) == 0: logging.error('paypal_valid_err: trans(%s) not exist %s', self.id_trans, self.request.query_string, exc_info=True) raise UserError(ErrorCode.PP_ERR_NO_TRANS[0], ErrorCode.PP_ERR_NO_TRANS[1]) trans = trans[0] amount_due = float(trans['amount_due']) mc_gross = float(self.request.get_param('mc_gross')) if amount_due != mc_gross: logging.error( 'paypal_valid_err: mc_gross %s is not same ' 'as expected amount due: %s for request: %s', mc_gross, amount_due, self.request.query_string, exc_info=True) raise UserError(ErrorCode.PP_ERR_MC_GROSS[0], ErrorCode.PP_ERR_MC_GROSS[1]) return trans
def shipment_delete(self, req, resp, conn): id_shipment = self.request.get_param('shipment') id_shop = self.request.get_param('shop') id_brand = self.request.get_param('brand') try: shipment = get_shipment_by_id(conn, id_shipment) if not shipment: raise UserError(E_C.ERR_ENOENT[0], E_C.ERR_ENOENT[1]) if int(shipment['status']) == SHIPMENT_STATUS.DELIVER: raise UserError(E_C.ERR_EPERM[0], E_C.ERR_EPERM[1]) if int(shipment['id_brand']) != int(id_brand): raise UserError(E_C.ERR_EPERM[0], E_C.ERR_EPERM[1]) if int(shipment['id_shop']) != int(id_shop): raise UserError(E_C.ERR_EPERM[0], E_C.ERR_EPERM[1]) # update shipment status to deleted values = { 'status': SHIPMENT_STATUS.DELETED, 'update_time': datetime.datetime.utcnow() } update_shipment(conn, id_shipment, values, shipment=shipment) return {'res': SUCCESS, 'id_shipment': id_shipment} except UserError, e: conn.rollback() logging.error('SPM_CREATE_ERR_%s, order: %s', str(e), id_shipment, exc_info=True) return {'res': FAILURE, 'err': e.desc}
def valid_check(self, conn, data): try: assert 'processor' in data, "Miss processor in request" proc = int(data['processor']) if proc == PAYMENT_TYPES.PAYPAL: required_fields = ['cookie', 'url_notify', 'url_return', 'url_cancel'] elif proc == PAYMENT_TYPES.PAYBOX: required_fields = ['cookie', 'url_success', 'url_failure', 'url_cancel', 'url_waiting', 'url_return'] elif proc == PAYMENT_TYPES.STRIPE: required_fields = ['cookie', 'url_success', 'url_failure'] for field in required_fields: assert field in data, "Miss %s in request" % field 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'])) return trans except AssertionError, e: logging.error("pm_form_invalid_request, param : %s " "error: %s", data, e, exc_info=True) raise UserError(ErrorCode.PMF_INVALID_REQ[0], ErrorCode.PMF_INVALID_REQ[1])
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 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 _on_post(self, req, resp, conn, **kwargs): try: self._request_verify() id_shipment = self.request._params.get('shipment') id_carrier = self.request._params.get('carrier') id_service = self.request._params.get('service') supported_services = get_shipping_supported_services( self.conn, id_shipment) supported_services = dict(supported_services) if (id_carrier not in supported_services or id_service not in supported_services.get( id_carrier, [])): raise UserError( E_C.SP_INVALID_SERVICE[0], E_C.SP_INVALID_SERVICE[1] % (id_shipment, id_carrier, id_service)) fee, fee_with_free = self._get_shipping_fee( id_shipment, id_carrier, id_service) fee_for_free = None if fee_with_free: fee_for_free = fee_with_free - fee conf_shipping_service(self.conn, id_shipment, id_service, fee, fee_for_free) return SUCCESS except UserError, e: conn.rollback() logging.error("%s" % str(e), exc_info=True) return {FAILURE: e.code}
def shipment_update(self, req, resp, conn): id_shipment = self.request.get_param('shipment') id_shop = self.request.get_param('shop') id_brand = self.request.get_param('brand') try: shipment = get_shipment_by_id(conn, id_shipment) self.shipment_check(shipment) cur_status = shipment['status'] new_status = self.request.get_param('status') shipment_confirmed = (cur_status == SHIPMENT_STATUS.CONFIRMING and new_status not in (SHIPMENT_STATUS.DELETED, SHIPMENT_STATUS.CONFIRMING)) if int(shipment['status']) == SHIPMENT_STATUS.DELIVER: self._update_delivered_shipment(conn) else: content = self.request.get_param('content') if content: content = ujson.loads(content) self.content_check(conn, content, id_shop, id_brand, id_shipment) self.content_update(conn, id_shipment, content) # update status, shipping fee, handling fee self._update_shipment(conn) order_status = get_order_status(conn, shipment['id_order'], id_brand) order_need_confirm = _order_need_confirmation( conn, shipment['id_order'], id_brand) if shipment_confirmed: params = stock_req_params(conn, id_shipment) success, errmsg = decrease_stock(params) if not success: raise UserError(E_C.OUT_OF_STOCK[0], out_of_stock_errmsg(errmsg)) if shipment_confirmed and not order_need_confirm: try: push_order_confirmed_event(conn, shipment['id_order'], id_brand) except Exception, e: logging.error( 'confirmed_event_err: %s, ' 'order_id: %s, ' 'brand: %s', e, order_id, brand, exc_info=True) return { 'res': SUCCESS, 'id_shipment': id_shipment, 'id_order': shipment['id_order'], 'order_status': order_status }
def shipment_check(self, shipment): if not shipment: raise UserError(E_C.ERR_ENOENT[0], E_C.ERR_ENOENT[1]) cur_status = shipment['status'] new_status = self.request.get_param('status') if (cur_status == SHIPMENT_STATUS.DELIVER and cur_status != int(new_status)): logging.error( "Some one trying to change shipment %s " "status from %s to %s", shipment['id'], cur_status, new_status, exc_info=True) raise UserError(E_C.ERR_EPERM[0], E_C.ERR_EPERM[1])
def _valid_check(self, conn): trans = get_trans_by_id(conn, self.id_trans) if len(trans) == 0: logging.error('stripe_valid_err: trans(%s) not exist %s', self.id_trans, self.request.query_string, exc_info=True) raise UserError(ErrorCode.PM_ERR_INVALID_REQ[0], ErrorCode.PM_ERR_INVALID_REQ[1]) return trans[0]
def _request_verify(self): id_shipment = self.request._params.get('shipment') id_carrier = self.request._params.get('carrier') id_service = self.request._params.get('service') try: assert id_shipment is not None, 'shipment' assert id_carrier is not None, 'carrier' assert id_service is not None, 'service' except AssertionError, e: raise UserError(E_C.SP_MISS_PARAMS[0], E_C.SP_MISS_PARAMS[1] % e)
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 get(self): if self.id_weight_type is None or self.id_shop is None: raise UserError(E_C.SSF_MISS_PARAM[0], E_C.SSF_MISS_PARAM[1] % self.id_sale) sale = CachedSale(self.id_sale).sale supported_services = self._get_supported_service() id_address = self._get_sale_address(sale, self.id_shop) weight_unit = SHIPPING_WEIGHT_UNIT dest = ujson.dumps(get_user_dest_addr(self.conn, self.id_user)) weight = self._get_sale_weight(sale) return remote_xml_shipping_fee(supported_services, weight, weight_unit, dest, id_address)
def _get_supported_service(self): supported_services = self._get_sale_supported_services() if self.id_carrier is not None and self.id_service is not None: services = supported_services.get(self.id_carrier, []) if self.id_service not in services: raise UserError( E_C.SSF_NOT_SUPPORT_SERVICE[0], E_C.SSF_NOT_SUPPORT_SERVICE[1] % (self.id_sale, self.id_carrier, self.id_service)) else: supported_services = {self.id_carrier: [self.id_service]} return supported_services.items()
def _get_supported_service(self): supported_services = dict( get_shipping_supported_services(self.conn, self.id_shipment)) if (self.id_carrier is not None and self.id_service is not None): services = supported_services.get(self.id_carrier, []) if self.id_service not in services: raise UserError( E_C.SPSF_NOT_SUPPORT_SERVICE[0], E_C.SPSF_NOT_SUPPORT_SERVICE[1] % (self.id_shipment, self.id_carrier, self.id_service)) else: supported_services = {self.id_carrier: [self.id_service]} return supported_services.items()
def valid_check(self, conn, id_trans, id_processor, url_success, url_failure): try: assert id_trans is not None, "Miss transaction in request" assert id_processor is not None, "Miss processor in request" assert url_success is not None, "Miss success URL in request" assert url_failure is not None, "Miss failure URL in request" trans = get_trans_by_id(conn, id_trans) assert len(trans) == 1, "Transaction not exist" return trans[0] except AssertionError, e: logging.error("pm_form_req_err: %s", e, exc_info=True) raise UserError(ErrorCode.PM_ERR_INVALID_REQ[0], ErrorCode.PM_ERR_INVALID_REQ[1])
def fin_trans_notify(self, trans, data): cookie = ujson.loads(trans['cookie']) fin_internal_trans = cookie['internal_trans'] url = settings.FIN_PAYMENT_NOTIFY_URL.get(self.payment_type) % { 'id_trans': fin_internal_trans } if isinstance(data, (dict, list)): data = urllib.urlencode(data) req = urllib2.Request(url, data=data) resp = urllib2.urlopen(req) resp_code = resp.getcode() if resp_code != httplib.OK: logging.error( '%s_trans_failure for %s got status: %s', PAYMENT_TYPES.toReverseDict()[self.payment_type].lower(), fin_internal_trans, resp_code) raise UserError(*self._fin_handled_err_code())
def get_user_dest_addr(conn, id_user, id_addr=None): """ @param conn: database connection @param user_id: user's id. @param addr_id: id of users_address @return: {'address': ..., 'address2': ..., 'city': ..., 'country': ..., 'province': ..., 'postalcode': ...} """ user_address = get_user_address(conn, id_user, id_addr) if not user_address: raise UserError(E_C.UR_NO_ADDR[0], E_C.UR_NO_ADDR[1] % (id_user, id_addr)) return user_address[0]
def valid_check(self, conn, id_order, id_invoices): try: assert id_order is not None, "Miss order in request" assert id_invoices is not None, "Miss invoices in request" id_invoices = ujson.loads(id_invoices) oi = get_invoice_by_order(conn, id_order) id_oi = [item['id'] for item in oi] ex_invoices = set(id_invoices) - set(id_oi) assert len(ex_invoices) == 0, ("invoices %s not belongs " "to order %s" % (ex_invoices, id_order)) except (AssertionError, TypeError, ValueError), e: logging.error("pm_init_req_err: %s", e, exc_info=True) raise UserError(ErrorCode.PM_ERR_INVALID_REQ[0], ErrorCode.PM_ERR_INVALID_REQ[1])
class ShippingConfResource(BaseJsonResource): login_required = {'get': False, 'post': True} def _request_verify(self): id_shipment = self.request._params.get('shipment') id_carrier = self.request._params.get('carrier') id_service = self.request._params.get('service') try: assert id_shipment is not None, 'shipment' assert id_carrier is not None, 'carrier' assert id_service is not None, 'service' except AssertionError, e: raise UserError(E_C.SP_MISS_PARAMS[0], E_C.SP_MISS_PARAMS[1] % e) if not user_accessable_shipment(self.conn, id_shipment, self.users_id): raise UserError( E_C.SP_PRIORITY_ERROR[0], E_C.SP_PRIORITY_ERROR[1] % (self.users_id, id_shipment))
def _on_get(self, req, resp, conn, **kwargs): try: id_sale = self.request._params.get('sale') id_shipment = self.request._params.get('shipment') id_carrier = self.request._params.get('carrier') id_service = self.request._params.get('service') if not id_sale and not id_shipment: raise UserError(E_C.SF_MISS_PARAMS[0], E_C.SF_MISS_PARAMS[1]) if id_sale: id_weight_type = self.request._params.get('weight_type') id_shop = self.request._params.get('shop') return SaleShippingFees(conn, self.users_id, id_sale, id_weight_type, id_shop, id_carrier, id_service).get() else: return ShipmentShippingFees(conn, self.users_id, id_shipment, id_carrier, id_service).get() except UserError, e: conn.rollback() logging.error("%s" % str(e)) return {'error': e.code}
def get_user_sel_phone_num(conn, id_user, id_phone=None): phones = get_user_phone_num(conn, id_user, id_phone) if not phones: raise UserError(E_C.UR_NO_PHONE[0], E_C.UR_NO_PHONE[1] % (id_user, id_phone)) return phones[0]
def content_check(self, conn, content, id_shop, id_brand, id_shipment=None): if isinstance(content, str): content = ujson.loads(content) items_id = [] for item in content: id_order_item = item.get('id_order_item') quantity = int(item.get('quantity')) items_id.append(id_order_item) assert id_order_item is not None, 'id_order_item' assert quantity is not None, 'quantity' orig_packing_quantity = shipping_list_item_packing_quantity( conn, id_shipment, id_order_item) if orig_packing_quantity is None: orig_packing_quantity = 0 if quantity > orig_packing_quantity: item_quantity = order_item_quantity(conn, id_order_item) cur_packing = order_item_packing_quantity(conn, id_order_item) added_packing = quantity - orig_packing_quantity left_packing = item_quantity - cur_packing if added_packing > left_packing: logging.error( "shipment_err: " "invalid shipping list quantity %s " "for order item:%s with shipment %s", quantity, id_order_item, id_shipment, exc_info=True) raise UserError(E_C.ERR_EINVAL[0], E_C.ERR_EINVAL[1]) # check items shop/brand is consistence with operator's shop/brand from models.order import get_order_items_by_id items = get_order_items_by_id(conn, items_id) items_shop = [] items_brand = [] for item in items: items_shop.append(item['id_shop']) items_brand.append(item['id_brand']) try: assert {int(id_shop)} == set(items_shop), ("items shop %s is not " "consistence with " "operators shop %s" % (items_shop, id_shop)) assert {int(id_brand) } == set(items_brand), ("items brand %s is not " "consistence with " "operators brand %s" % (items_brand, id_brand)) except AssertionError, e: logging.error('spm_content_check_err:%s', e, exc_info=True) raise UserError(E_C.ERR_EPERM[0], E_C.ERR_EPERM[1])
def _valid_check(self, conn): resp_code = self.request.get_param('RespCode') amount = float(self.request.get_param('Amt')) / 100 order_id = self.request.get_param('Ref') auth = self.request.get_param('Auth') # for a rejected transaction, this parameter is not sent back. if not auth: logging.error( 'paybox_valid_err: rejected transaction for ' 'request %s', self.request.query_string, exc_info=True) raise UserError(ErrorCode.PB_ERR_REJECTED_TRANS[0], ErrorCode.PB_ERR_REJECTED_TRANS[1]) # authorization number is alphanumeric. if not re.match(r'^[a-zA-Z0-9]+$', auth): logging.error( 'paybox_valid_err: wrong authorization number %s for' ' request %s', auth, self.request.query_string, exc_info=True) raise UserError(ErrorCode.PB_ERR_WRONG_AUTH[0], ErrorCode.PB_ERR_WRONG_AUTH[1]) # TODO: check ip address ip_addr = get_client_ip(self.request) logging.info('Paybox IPN request address %s for request %s', ip_addr, self.request.query_string) trans = get_trans_by_id(conn, self.id_trans) if len(trans) == 0: logging.error('paybox_valid_err: trans(%s) not exist %s', self.id_trans, self.request.query_string, exc_info=True) raise UserError(ErrorCode.PB_ERR_NO_TRANS[0], ErrorCode.PB_ERR_NO_TRANS[1]) trans = trans[0] amount_due = float(trans['amount_due']) if amount_due != amount: logging.error( 'paybox_valid_err: paybox amount %s is not same ' 'as expected amount due: %s for request: %s', amount, amount_due, self.request.query_string, exc_info=True) raise UserError(ErrorCode.PB_ERR_WRONG_AMOUNT[0], ErrorCode.PB_ERR_WRONG_AMOUNT[1]) if int(order_id) != int(trans['id_order']): logging.error( 'paybox_valid_err: order_id %s is not same as ' 'expected order_id %s for request: %s', order_id, trans['id_order'], self.request.query_string, exc_info=True) raise UserError(ErrorCode.PB_ERR_WRONG_ORDER[0], ErrorCode.PB_ERR_WRONG_ORDER[1]) return trans
def create_order(conn, users_id, telephone_id, order_items, upc_shop=None, shipaddr=None, billaddr=None, user_info=None, chosen_gifts=None): order_id = _create_order(conn, users_id) _create_order_shipment_detail(conn, order_id, shipaddr, billaddr, telephone_id) sellers = defaultdict(set) id_sales = [] for item in order_items: sale = CachedSale(item['id_sale']).sale item_id = _create_order_item( conn, sale, item['id_variant'], sale.brand.id, upc_shop=upc_shop, barcode=item.get('barcode', None), id_shop=item['id_shop'], id_type=item.get('id_type', None), id_price_type=item.get('id_price_type', None), id_weight_type=item.get('id_weight_type', None)) # populate id_order_item into order params, it will be # used when create shipping list. item['id_order_item'] = item_id id_sales.append(sale.id) _create_order_details(conn, order_id, item_id, item['quantity']) sellers[sale.brand.id].add(item['id_shop']) gevent.spawn(gen_bought_history, users_id, id_sales) _log_order(conn, users_id, order_id, sellers) if upc_shop is None: wwwOrderShipments(conn, order_id, order_items, shipaddr, users_id).create() else: posOrderShipments(conn, order_id, order_items, None, users_id).create() up_order_log(conn, order_id, sellers) if not _order_need_confirmation(conn, order_id): params = [] shipments = get_shipments_by_order(conn, order_id) for s in shipments: params += stock_req_params(conn, s['id']) success, errmsg = decrease_stock(params) if not success: raise UserError(E_C.OUT_OF_STOCK[0], out_of_stock_errmsg(errmsg)) for brand, shops in sellers.iteritems(): try: if _order_need_confirmation(conn, order_id, brand): push_order_confirming_event(conn, order_id, brand) except Exception, e: logging.error( 'confirming_event_err: %s, ' 'order_id: %s, ' 'brand: %s', e, order_id, brand, exc_info=True)
def _order_check(self, conn): id_order = self.request._params.get('id_order') if not user_accessable_order(conn, id_order, self.users_id): raise UserError( E_C.PSPL_PRIORITY_ERROR[0], E_C.PSPL_PRIORITY_ERROR[1] % (id_order, self.users_id))