def get_payment_params(self, payment_params): order_id = payment_params['order_id'] total_price = payment_params['total_price'] product_title = payment_params['product_title'] cn_header = payment_params['cn_header'] nonce_str = payment_util.wechat_payment_str(order_id) prepaid_data = payment_util.get_payment_wechat_app(False, order_id, total_price, product_title, nonce_str) self.logger_info.info(prepaid_data) headers = {'Content-Type': 'application/xml'} response = requests.post(url=get_wechat_prepaid_url(), data=prepaid_data, headers=headers) if response.status_code != code.ARIES_200_SUCCESS: self.logger_error.error(code.ERROR_4004_PAYMENT_INTERFACE_FAILED) raise BusinessLogicError(message_mapper.get(4004, cn_header), 4004, None) response_data = response.text prepaid_result = xmltodict.parse(response_data)['xml'] self.logger_info.info(prepaid_result) if not self.check_prepaid_result(prepaid_result): self.logger_error.error(code.ERROR_4004_PAYMENT_INTERFACE_FAILED) raise BusinessLogicError(message_mapper.get(4004, cn_header), 4004, None) prepaid_id = prepaid_result['prepay_id'] payment_order = payment_util.get_payment_order_app( False, self.wechat_app_id, self.merchant_id, prepaid_id, nonce_str, self.api_key ) self.logger_info.info(payment_order) param_result = {'wechat_pay_order': payment_order} return param_result
def get_payment_params(self, payment_params): ip_addr = payment_params['ip_addr'] wechat_code = payment_params['wechat_code'] cn_header = payment_params['cn_header'] order_id = payment_params['order_id'] total_price = payment_params['total_price'] product_title = payment_params['product_title'] # WeChat public account login payload = {'appid': 'wx41b86399fee7a2ec', 'secret': '1b3d5dce9860be7e4fc04847df6a6177', 'code': wechat_code, 'grant_type': 'authorization_code'} response = requests.get(resources.WECHAT_ACCESS_TOKEN_URL, params=payload) response_json = response.json() if response.status_code != code.ARIES_200_SUCCESS or not response_json.get('openid'): raise BusinessLogicError(message_mapper.get(4004, cn_header), 4004, None) wechat_openid = response_json['openid'] nonce_str = payment_util.wechat_payment_str(order_id) prepaid_data = payment_util.get_payment_wechat_public( order_id, total_price, product_title, nonce_str, ip_addr, wechat_openid ) self.logger_info.info(prepaid_data) headers = {'Content-Type': 'application/xml'} response = requests.post(url=get_wechat_prepaid_url(), data=prepaid_data, headers=headers) if response.status_code != code.ARIES_200_SUCCESS: raise BusinessLogicError(message_mapper.get(4004, cn_header), 4004, None) response_data = response.text.encode('utf-8') prepaid_result = xmltodict.parse(response_data)['xml'] self.logger_info.info(prepaid_result) if prepaid_result['return_code'] == 'FAIL' or prepaid_result['result_code'] != 'SUCCESS': raise BusinessLogicError(message_mapper.get(4004, cn_header), 4004, None) prepaid_id = prepaid_result['prepay_id'] mobile_web_payment_params = { 'appId': 'wx41b86399fee7a2ec', 'timeStamp': str(dateformatter.get_timestamp()), 'nonceStr': nonce_str, 'package': 'prepay_id=' + prepaid_id, 'signType': 'MD5' } sign = payment_util.get_payment_wechat_public_signing(mobile_web_payment_params, nonce_str) mobile_web_payment_params['paySign'] = sign param_result = {'mobile_web_payment_params': mobile_web_payment_params} return param_result
def set_time_bomb_activate(self, time_bomb_id, activation): inactivation_status = 0 activation_status = 1 try: # set activation time_bomb_ins = TimeBomb.objects.get(id=time_bomb_id) hub = time_bomb_ins.hub # Time change and verification start_time = time_bomb_ins.start_time end_time = time_bomb_ins.end_time # Check same time in current time bomb if activation: # First condition time_bomb_qs = TimeBomb.objects.filter( hub=hub, status=activation_status, start_time__range=(start_time, end_time) ) if time_bomb_qs.exists(): raise BusinessLogicError('There is a time bomb at same time', None, None) time_bomb_qs = TimeBomb.objects.filter( hub=hub, status=activation_status, end_time__range=(start_time, end_time) ) if time_bomb_qs.exists(): raise BusinessLogicError('There is a time bomb at same time', None, None) time_bomb_qs = TimeBomb.objects.filter( hub=hub, status=activation_status, start_time__lte=start_time, end_time__gte=end_time ) if time_bomb_qs.exists(): raise BusinessLogicError('There is a time bomb at same time', None, None) status = activation_status else: status = inactivation_status # Change status time_bomb_ins.status = status time_bomb_ins.save() except Exception as e: msg = '[TimeBombService][set_time_bomb_activate][' + str(e) + ']' self.logger_error.error(msg) raise BusinessLogicError(msg, None, None) else: self.result = True return self.result
def product_validation(self, validation_result): has_changed = validation_result['has_changed'] response_list = validation_result['product_list'] valid_list = list() invalid_list = list() if has_changed: original_product_count = len(self.product_list_json) response_product_count = len(response_list) if original_product_count != response_product_count: error_message = message_mapper.get(3001, self.cn_header) data_set = {'product_list': response_list, 'has_changed': has_changed} raise BusinessLogicError(error_message, 3001, data_set) for product in self.product_list_json: for response_product in response_list: if product['product_id'] == response_product['prev_product_id']: if product['quantity'] <= response_product['stock']: valid_list.append({ 'product_id': response_product['product_id'], 'quantity': product['quantity'] }) else: invalid_list.append({ 'product_id': response_product['product_id'], 'quantity': response_product['stock'], }) elif product['product_id'] == response_product['product_id']: if product['quantity'] <= response_product['stock']: valid_list.append({ 'product_id': response_product['product_id'], 'quantity': product['quantity'] }) else: invalid_list.append({ 'product_id': response_product['product_id'], 'quantity': response_product['stock'], }) if len(invalid_list) > 0: self.logger_error.error(code.ERROR_3001_PRODUCT_ALREADY_SOLD) error_message = message_mapper.get(3001, self.cn_header) data_set = {'product_list': response_list, 'has_changed': has_changed} raise BusinessLogicError(error_message, 3001, data_set) response_list = valid_list else: response_list = self.product_list_json return response_list
def coupon_validate(self, open_id, product_list, coupon_list): self.logger_info.info( '[coupon_manager_v2][CouponManagerV2][coupon_validate][' + open_id + ']') self.product_list = product_list self.coupon_list = coupon_list coupon_service = CouponService(self.logger_info, self.logger_error) for coupon in coupon_list: # Get coupon information coupon_id = coupon['coupon_id'] cs_coupon_ins = coupon_service.read_customer_coupon_ins_with_id( coupon_id) coupon_instance = cs_coupon_ins.coupon coupon_data = coupon_service.read_coupon_data(coupon_instance) coupon_data['target_product_ids'] = json.loads( coupon_data['target_product_ids']) target_id = coupon['target_id'] # Coupon validate if cs_coupon_ins.open_id != open_id or cs_coupon_ins.status != 0: self.logger_info.info(code.ERROR_3004_COUPON_OWNER_NOT_FOUND) error_code = code.ERROR_3004_COUPON_OWNER_NOT_FOUND raise BusinessLogicError(get_msg(error_code), error_code, None) coupon_validator = CouponInstance.factory( coupon_data['coupon_type'], coupon_data, target_id, product_list) if not coupon_validator.check_coupon_rule(): error_code = code.ERROR_3005_COUPON_APPLY_ERROR raise BusinessLogicError(get_msg(error_code), error_code, None) discount_amount = coupon_validator.get_discount_price() self.discount_price += discount_amount coupon_str = payment_util.get_coupon_title_str( coupon_instance.name, coupon_instance.is_primary_coupon, target_id, product_list) coupon_json = { 'coupon_title': coupon_str, 'discount_amount': discount_amount, 'coupon_type': coupon_instance.coupon_type, 'target_type': coupon_instance.target_type, 'target_id': target_id } self.coupon_detail.append(coupon_json)
def draw_event_validation(event_list, cn_header): if len(event_list) <= 0: err_code = 5003 message = message_mapper.get(err_code, cn_header) raise BusinessLogicError(message, err_code) prob_sum = 0 for event in event_list: prob_sum += event['probability'] if prob_sum != 1: err_code = 5003 message = message_mapper.get(err_code, cn_header) raise BusinessLogicError(message, err_code)
def get_current_time_bomb_after(self, hub_id, os_type, has_after): try: current_date = datetime.datetime.today() if has_after: after_date = current_date - datetime.timedelta(minutes=30) else: after_date = current_date query_str = get_time_bomb_platform_query(os_type) query_str['hub'] = hub_id query_str['status'] = self.STATUS_ACTIVATED query_str['start_time__lte'] = current_date query_str['end_time__gte'] = after_date time_bomb = TimeBomb.objects.filter(**query_str) except Exception as e: msg = '[TimeBombService][get_current_time_bomb_after][' + str(e) + ']' self.logger_error.error(msg) raise BusinessLogicError(msg, None, None) else: if time_bomb.count() == 1: self.result = time_bomb[0].id return self.result
def read_time_bomb_with_id(self, time_bomb_id, lang_type, os_type): try: time_bomb = TimeBomb.objects.get(id=time_bomb_id) time_bomb_content = TimeBombContent.objects.get(time_bomb=time_bomb, language_type=lang_type) time_bomb_data = TimeBombSerializer(time_bomb).data content_data = TimeBombContentSerializer(time_bomb_content).data # Status check start_time = time_bomb.start_time.time() end_time = time_bomb.end_time.time() if not self.check_time_bomb_now(time_bomb.hub.code, os_type): status = self.STATUS_TIME_EXPIRED elif check_status(start_time, end_time): status = self.STATUS_AVAILABLE time_bomb_data['products'] = self.read_time_bomb_products(time_bomb_id) else: status = self.STATUS_TIME_EXPIRED del content_data['id'] time_bomb_data['status'] = status time_bomb_data.update(content_data) except Exception as e: msg = '[TimeBombService][read_time_bomb_with_id][' + str(e) + ']' self.logger_error.error(msg) raise BusinessLogicError(msg, None, None) else: self.result = time_bomb_data return self.result
def create_coupon_pack(self, auth_info, coupon_list, cn_header): coupon_service = CouponService(self.logger_info, self.logger_error) coupon_id_list = [coupon[0] for coupon in coupon_list] if coupon_service.read_customer_coupon_count(auth_info[0], coupon_id_list) != 0: raise BusinessLogicError(message_mapper.get(3105, cn_header), 3105) start_date = datetime.datetime.today() for coupon in coupon_list: coupon_id = coupon[0] period = coupon[1] coupon_code = coupon[2] sender_id = coupon[3] end_date = start_date + datetime.timedelta(days=period) if period >= 1: end_date = end_date - datetime.timedelta(days=1) coupon_service.create_customer_coupon(auth_info[0], coupon_id, coupon_code, start_date, end_date, sender_id) update_coupon_count(self.logger_info, self.logger_error, auth_info[0], auth_info[1], 0, len(coupon_list))
def set_total_price(self, coupon_detail, discount_amount, open_id): self.order_details['coupons_detail'] = coupon_detail delivery_price = self.request_data['shipping_cost'] total_price = round((self.product_total_price + discount_amount + delivery_price), 2) self.logger_info.info(str(self.product_total_price) + ' ' + str(discount_amount) + ' ' + str(delivery_price) + ' ' + str(total_price)) if float(self.request_data['price_sub_total']) != float(self.product_total_price) \ or -float(self.request_data['price_discount']) != float(discount_amount) \ or float(self.request_data['price_delivery_fee']) != float(delivery_price) \ or float(self.request_data['price_total']) != float(total_price): error_code = code.ERROR_3006_PAYMENT_PRICE_INVALID self.logger_error.error(error_code) raise BusinessLogicError(get_msg(error_code), error_code, None) self.request_data['order_details'] = json.dumps(self.order_details) self.request_data['product_list'] = json.dumps(self.request_data['product_list']) self.request_data['coupon_list'] = json.dumps(self.request_data['coupon_list']) # Make order response datetime_now = datetime.now() telephone = self.request_data['user_telephone'] delivery_date = self.request_data['delivery_date'] hub_id = self.request_data['hub_id'] order_hash = payment_util.get_order_hash(datetime_now, telephone, delivery_date, open_id) order_id = payment_util.get_order_id(order_hash, open_id, hub_id) self.order_id = order_id self.payment_params['order_id'] = order_id self.request_data['order_hash'] = order_hash self.request_data['order_id'] = order_id self.request_data['created_date'] = datetime_now self.payment_params['total_price'] = total_price
def add_order_detail(self, order_id, receiver_address, receiver_lat, receiver_lng): # make dada order model and api model order_detail_model = OrderDetailModel() order_detail_model.order_id = order_id order_detail_api = OrderDetailClass(model=order_detail_model) # Call dada api self.logger_info.info(order_detail_model) dada_result = self.dada_client.do_rpc(api=order_detail_api) self.logger_info.info(dada_result.to_string()) dada_dict_result = dada_result.to_dict() if dada_dict_result['status'] != 'success': raise BusinessLogicError('API connect failed', None, None) order_detail_result = dada_dict_result['result'] # Receiver information add order_detail_result['receiver_address'] = receiver_address order_detail_result['receiver_lat'] = receiver_lat order_detail_result['receiver_lng'] = receiver_lng # Create dada detail self.dada_service.create_dada_order_detail(order_detail_result)
def event_coupon_validator(request, cn_header=True): request_data = request.data if 'open_id' not in request_data or 'coupon_id' not in request_data: raise BusinessLogicError(message_mapper.get(1016, cn_header), 1016) return request_data
def check_issue_coupon_pack(self, auth_info, coupon_list, cn_header): coupon_service = CouponService(self.logger_info, self.logger_error) coupon_id_list = [coupon[0] for coupon in coupon_list] if coupon_service.read_customer_coupon_count(auth_info[0], coupon_id_list) != 0: raise BusinessLogicError(message_mapper.get(3105, cn_header), 3105)
def read_coupon_instance_with_id(self, coupon_id, target_db='default'): try: coupon_instance = Coupon.objects.using(target_db).get(id=coupon_id) except Exception as e: self.logger_error.error(str(e)) raise BusinessLogicError(str(e), None, None) else: self.result = coupon_instance return self.result
def read_hub_instance_with_id(self, hub_id): try: hub = Hub.objects.get(code=hub_id) except Exception as e: msg = '[HubService][read_hub_instance_with_id][' + str(e) + ']' self.logger_error.error(msg) raise BusinessLogicError(msg, None, None) return hub
def read_menu_data(self, menu_instance): try: menu_data = MenuListInfoSerializer(menu_instance).data except Exception as e: msg = '[MenuService][read_menu_data][' + str(e) + ']' self.logger_error.error(msg) raise BusinessLogicError(msg, None, None) return menu_data
def request_purchase_validation(hub_id, accept_lang, product_list): headers = {'accept-language': accept_lang} payload = {'product_list': product_list} response = requests.post(urlmapper.get_purchase_validation(hub_id, 'lunch'), headers=headers, json=payload) if response.status_code != code.ARIES_200_SUCCESS: raise BusinessLogicError('Internal server error', None, None) return response.json()
def read_product_with_id(self, product_id): try: product = Product.objects.get(id=product_id) except Exception as e: msg = '[ProductService][read_product_with_id][' + str(e) + ']' self.logger_error.error(msg) raise BusinessLogicError(msg, None, None) return product
def read_restaurant_with_id(self, restaurant_id): try: restaurant_data = RestaurantInfoSerializer(Restaurant.objects.get(id=restaurant_id)).data except Exception as e: msg = '[RestaurantService][read_restaurant_with_id][' + str(e) + ']' self.logger_error.error(msg) raise BusinessLogicError(msg, None, None) return restaurant_data
def read_customer_coupon_ins_with_id(self, coupon_id): try: coupon_instance = CustomerCoupon.objects.get(id=coupon_id) except Exception as e: self.logger_error.error(str(e)) raise BusinessLogicError(str(e), None, None) else: self.result = coupon_instance return self.result
def read_coupon_data(self, coupon_instance): try: coupon_data = CouponSerializer(coupon_instance).data except Exception as e: self.logger_error.error(str(e)) raise BusinessLogicError(str(e), None, None) else: self.result = coupon_data return self.result
def read_menu_instance(self, menu_id): try: menu_instance = Menu.objects.using(self.target_db).get(id=menu_id) except Exception as e: msg = '[MenuService][read_menu_instance][' + str(e) + ']' self.logger_error.error(msg) raise BusinessLogicError(msg, None, None) return menu_instance
def set_delivery_detail(self, cn_header): # Shipping method self.request_data['shipping_method'] = 1 if 'delivery_on_site' in self.request_data: delivery_on_site = self.request_data['delivery_on_site'] else: delivery_on_site = False self.request_data['delivery_on_site'] = False if delivery_on_site: delivery_type = 2 self.request_data['shipping_method'] = 2 self.request_data['shipping_cost'] = 0.0 self.request_data['delivery_as_fast'] = False else: self.request_data['shipping_cost'] = 8.0 delivery_type = self.request_data['shipping_method'] # add shipping name delivery_name = hub_data.get_delivery_service_str(cn_header, delivery_type) self.request_data['shipping_name'] = delivery_name delivery_price = self.request_data['shipping_cost'] # Check delivery price if float(hub_data.get_shipping_cost(delivery_type)) != float(delivery_price): self.logger_info.info('Some cost is incorrect') raise DataValidationError('Some costs are incorrect') delivery_detail_json = {'delivery_title': hub_data.get_delivery_str(cn_header, delivery_type), 'price': delivery_price} self.order_details['delivery_detail'] = delivery_detail_json delivery_date = self.request_data['delivery_date'].replace('.', '-') self.request_data['delivery_date'] = delivery_date time_table_delivery_type = delivery_type if delivery_on_site: time_table_delivery_type = 1 time_table_address = '{}/{}/{}/{}/{}'.format( urlmapper.get_url('TIMETABLE_LIST'), str(self.request_data['hub_id']), delivery_date, str(self.request_data['delivery_schedule']), str(time_table_delivery_type) ) response = requests.get(time_table_address) response_json = response.json() if response.status_code != code.ARIES_200_SUCCESS: self.logger_error.error(code.ERROR_3007_DELIVERY_SCHEDULE_INVALID) raise BusinessLogicError(message_mapper.get(3007, cn_header), 3007, None) self.logger_info.info(response_json) self.request_data['shipping_detail'] = json.dumps(response_json['shipping_detail']) self.request_data['delivery_start_time'] = response_json['delivery_start_time'] self.request_data['delivery_end_time'] = response_json['delivery_end_time']
def read_brand_info_with_id(self, restaurant_id): try: brand = RestaurantBrandInfo.objects.using(self.target_db).get(restaurant=restaurant_id) brand_data = RestaurantBrandInfoSerializer(brand).data except Exception as e: msg = '[RestaurantService][read_brand_info_with_id][' + str(e) + ']' self.logger_error.error(msg) raise BusinessLogicError(msg, None, None) return brand_data
def read_customer_coupon_qs(self, open_id, status, current_date): try: coupon_qs = CustomerCoupon.objects.filter(open_id=open_id, status=status, start_date__lte=current_date, end_date__gte=current_date) except Exception as e: self.logger_error.error(str(e)) raise BusinessLogicError(str(e), None, None) else: self.result = coupon_qs return self.result
def read_menu_data_with_id(self, menu_id): try: menu_instance = Menu.objects.using(self.target_db).get(id=menu_id) menu_data = MenuListInfoSerializer(menu_instance).data except Exception as e: msg = '[MenuService][read_menu_instance][' + str(e) + ']' self.logger_error.error(msg) raise BusinessLogicError(msg, None, None) return menu_data
def read_customer_coupon_count(self, open_id, coupon_list): try: coupon_count = CustomerCoupon.objects.filter(open_id=open_id, coupon_id__in=coupon_list).count() except Exception as e: self.logger_error.error(str(e)) raise BusinessLogicError(str(e)) else: self.result = coupon_count return self.result
def delete_curation_page(self, page_id): try: page_instance = CurationPage.objects.get(id=page_id) page_instance.delete() except Exception as e: raise BusinessLogicError(str(e), None, None) else: self.result = True return self.result
def read_hub_list_with_status(self, status, target_db='default'): try: hubs = Hub.objects.using(target_db).filter(status=status) hub_data = HubSerializer(hubs, many=True).data except Exception as e: msg = '[HubService][read_hub_list_with_status][' + str(e) + ']' self.logger_error.error(msg) raise BusinessLogicError(msg, None, None) return hub_data
def read_hub_stock_instance(self, hub_instance, menu_instance): try: hub_stock_instance = HubStock.objects.get(hub=hub_instance, menu=menu_instance) except Exception as e: msg = '[MenuService][read_hub_stock_instance][' + str(e) + ']' self.logger_error.error(msg) raise BusinessLogicError(msg, None, None) return hub_stock_instance