def account_price(self, coupon_record_obj, price): #获取优惠券类型 coupon_type = coupon_record_obj.coupon.coupon_type #与人民币比值 money_equivalent_value = coupon_record_obj.counpon.money_equivalent_value #优惠折扣百分比 off_percent = coupon_record_obj.coupon.off_percent #最低消费多少可用 minimum_consume = coupon_record_obj.coupon.minimum_consume real_price = 0 #如果是0表示是立减券 if coupon_type == 0: #有一个原则就是实际消费价格肯定要比优惠券的多,哪有不赚倒贴的买卖呀 if price > money_equivalent_value: real_price = price - money_equivalent_value #如果是满减券 elif coupon_type == 1: if price > minimum_consume: real_price = price - money_equivalent_value else: raise CommonException('优惠券无效') #折扣券 elif coupon_type == 2: real_price = price * (off_percent / 100) return real_price
def cal_coupon_price(self, price, coupon_record_obj): """ :param price: :param coupon_record_obj: :return: """ coupon_type = coupon_record_obj.coupon.content_type money_equivalent_value = coupon_record_obj.coupon.money_equivalent_value off_percent = coupon_record_obj.coupon.off_percent minimum_consume = coupon_record_obj.coupon.minimum_consume rebate_price = 0 if coupon_type == 0: # 立减卷 rebate_price = price - money_equivalent_value if rebate_price <= 0: rebate_price = 0 elif coupon_type == 1: # 满减卷 if minimum_consume > price: raise CommonException(1007, "优惠卷未达到最低消费水平") else: rebate_price = price - money_equivalent_value elif coupon_type == 2: rebate_price = price * off_percent / 100 return rebate_price
def post(self, request): res = BaseResponse() # 1.取值 course_id = request.data.get('courseId') price_policy_id = request.data.get('validPeriodId') user_id = request.user.pk # 2.校验数据 try: course_obj = Course.objects.get(pk=course_id) relate_price_police = course_obj.price_policy.all() if price_policy_id not in [obj.pk for obj in relate_price_police]: raise CommonException(1002, '价格策略非法') # 3.存到缓存 # 3.1 构建redis的键 shoppingcar_key = settings.SHOPPINGCAR_REDIS_KEY % (user_id, course_id) # 3.2 构建redis的值-shoppingcar_val relate_price_policy_dict = {} for price_policy in relate_price_police: relate_price_policy_dict[price_policy.pk] = { 'pk': price_policy.pk, 'valid_period': price_policy.valid_period, 'valid_period_text': price_policy.get_valid_period_display(), 'price': price_policy.price, 'default': False, } relate_price_policy_dict[price_policy_id]['default'] = True shoppingcar_val = { 'id': course_obj.id, 'title': course_obj.name, 'img': course_obj.course_img, 'relate_price_policy': relate_price_policy_dict, 'choosen_price_policy_id': price_policy_id, 'choosen_price': relate_price_policy_dict[price_policy_id]['price'], 'choosen_valid_period': relate_price_policy_dict[price_policy_id]['valid_period'], 'choosen_valid_period_text': relate_price_policy_dict[price_policy_id]['valid_period_text'], } cache.set(shoppingcar_key, json.dumps(shoppingcar_val)) res.data = '加入购物车成功' except ObjectDoesNotExist as e: res.code = 1001 res.msg = '提交异常,课程对象不存在!' except CommonException as e: res.code = e.code res.msg = e.msg return Response(res.dict)
def post(self, request): res = BaseResponse() try: # 1 获取前端传过来的course_id 以及price_policy_id user_id course_id = request.data.get("course_id", "") price_policy_id = request.data.get("price_policy_id", "") user_id = request.user.id # 2 验证数据的合法性 # 2.1 验证course_id是否合法 course_obj = Course.objects.get(pk=course_id) # 2.2 校验价格策略是否能合法 # 查找课程关联的价格策略 price_policy_list = course_obj.price_policy.all() price_policy_dict = {} for price_policy in price_policy_list: price_policy_dict[price_policy.pk] = { "prcie": price_policy.price, "valid_period": price_policy.valid_period, "valid_period_text": price_policy.get_valid_period_display(), "default": price_policy.pk == price_policy_id } if price_policy_id not in price_policy_dict: raise CommonException(1001, "价格策略异常!") # 3 构建我们想要的数据结构 # 价格策略对象 pp = PricePolicy.objects.get(pk=price_policy_id) course_info = { "id": course_id, "name": course_obj.name, "course_img": course_obj.course_img, "relate_price_policy": price_policy_dict, "default_price": pp.price, "default_price_period": pp.valid_period, "default_price_policy_id": pp.pk } # 4 写入redis # 4.1 先拼接购物车的key shopping_car_key = settings.SHOPPING_CAR_KEY % (user_id, course_id) # 4.2 写入redis print("------>") REDIS_CONN.set(shopping_car_key, json.dumps(course_info)) res.msg = "加入购物车成功!" except CommonException as e: res.code = e.code res.error = e.error except Exception as e: res.code = 1030 res.error = "加入购物车失败!" return Response(res.dict)
def cal_coupon_price(self, price, coupon_record_obj): coupon_type = coupon_record_obj.coupon.coupon_type money_equivalent_value = coupon_record_obj.coupon.money_equivalent_value off_percent = coupon_record_obj.coupon.off_percent minimum_consume = coupon_record_obj.coupon.minimum_consume rebate_price = 0 if coupon_type == 0: # 立减券 rebate_price = price - money_equivalent_value if rebate_price <= 0: rebate_price = 0 elif coupon_type == 1: # 满减券 if minimum_consume > price: raise CommonException(1307, "优惠券未达到最低消费") else: rebate_price = price - money_equivalent_value elif coupon_type == 2: rebate_price = price * off_percent / 100 return rebate_price
def cal_coupon_price(self, price, coupon_info): coupon_type = coupon_info['coupon_type'] money_equivalent_value = coupon_info.get('money_equivalent_value') off_percent = coupon_info.get('off_percent') minimun_coupon = coupon_info.get('minimum_consume') rebate_price = 0 if coupon_type == '立减券': rebate_price = price - money_equivalent_value if rebate_price <= 0: rebate_price = 0 elif coupon_type == '满减券': if minimun_coupon > price: raise CommonException(3000, "优惠券未达到最低消费") else: rebate_price = price - money_equivalent_value elif coupon_type == "折扣券": rebate_price = price * off_percent / 100 return rebate_price
def cal_coupon_price(self, price, coupon_info): coupon_type = coupon_info["coupon_type"] money_equivalent_value = coupon_info.get("money_equivalent_value") off_percent = coupon_info.get("off_percent") minimum_consume = coupon_info.get("minimum_consume") rebate_price = 0 if coupon_type == "立减券": # 立减券 rebate_price = price - money_equivalent_value if rebate_price <= 0: rebate_price = 0 elif coupon_type == "满减券": # 满减券 if minimum_consume > price: raise CommonException(3000, "优惠券未达到最低消费") else: rebate_price = price - money_equivalent_value elif coupon_type == "折扣券": rebate_price = price * off_percent / 100 return rebate_price
def post(self, request, *args, **kwargs): print(request.data) response = BaseResponse() # 1 获取数据 user_id = request.user.pk global_coupon_id = request.data.get("global_coupon_id") pay_money = request.data.get("pay_money") course_list = request.data.get("course_list") is_beli = request.data.get("is_beli") now = datetime.datetime.now() try: # 2 校验数据 # 2.2 校验课程 course_price_list = [] for course_dict in course_list: # 2.2.1 校验课程id course_id = course_dict.get("course_id") print("course_id",course_id) course_obj = Course.objects.get(pk=course_id) # 2.2.2 价格策略id if course_dict.get("default_price_policy_id") not in [obj.pk for obj in course_obj.price_policy.all()]: raise CommonException("价格策略异常!", 1002) # 2.2.3 课程优惠券id price_policy_obj = PricePolicy.objects.get(pk=course_dict.get("default_price_policy_id")) course_dict["original_price"]=price_policy_obj.price course_dict["valid_period_display"]=price_policy_obj.get_valid_period_display() course_dict["valid_period"]=price_policy_obj.valid_period coupon_record_id = course_dict.get("coupon_record_id") if coupon_record_id: coupon_record_list = CouponRecord.objects.filter(account=request.user, status=0, coupon__valid_begin_date__lt=now, coupon__valid_end_date__gt=now, coupon__content_type_id=14, coupon__object_id=course_id ) print("coupon_record_id",coupon_record_id) if coupon_record_id and coupon_record_id not in [obj.pk for obj in coupon_record_list]: raise CommonException("课程优惠券异常!", 1006) # 计算循环课程的课程优惠券优惠后的价格 coupon_record_obj = CouponRecord.objects.get(pk=coupon_record_id) rebate_price = self.cal_coupon_price(price_policy_obj.price, coupon_record_obj) course_price_list.append(rebate_price) course_dict["rebate_price"]=rebate_price else: course_price_list.append(price_policy_obj.price) # 2.3 校验通用优惠券id global_coupon_record_list = CouponRecord.objects.filter(account=request.user, status=0, coupon__valid_begin_date__lt=now, coupon__valid_end_date__gt=now, coupon__content_type_id=14, coupon__object_id=None ) if global_coupon_id and global_coupon_id not in [obj.pk for obj in global_coupon_record_list]: raise CommonException("通用优惠券异常", 1006) if global_coupon_id: global_coupon_record_obj = CouponRecord.objects.get(pk=global_coupon_id) final_price = self.cal_coupon_price(sum(course_price_list), global_coupon_record_obj) else: final_price=sum(course_price_list) # 2.4 计算实际支付价格与money做校验 cost_beli_num=0 if is_beli: final_price = final_price - request.user.beli / 10 cost_beli_num=request.user.beli if final_price < 0: final_price = 0 cost_beli_num=final_price*10 print(final_price) if final_price != float(pay_money): raise CommonException(1008, "支付总价格异常!") # 3 生成订单记录 # Order记录 # orderDetail # orderDetail # orderDetail order_number=self.get_order_num() print("order_number",order_number) order_obj=Order.objects.create( payment_type=1, order_number=order_number, account=request.user, status=1, order_type=1, actual_amount=pay_money, ) print("course_list",course_list) for course_item in course_list: OrderDetail.objects.create( order=order_obj, content_type_id=14, object_id=course_item.get("course_id"), original_price=course_item.get("original_price"), price=course_item.get("rebate_price") or course_item.get("original_price"), valid_period=course_item.get("valid_period"), valid_period_display=course_item.get("valid_period_display"), ) request.user.beli=request.user.beli-cost_beli_num request.user.save() REDIS_CONN.set(order_number+"|"+str(cost_beli_num),"",20) account_key=settings.ACCOUNT_KEY%(user_id,"*") REDIS_CONN.delete(*REDIS_CONN.keys(account_key)) ''' [ { course_id:1 default_price_policy_id:1, coupon_record_id:2 }, { course_id:2 default_price_policy_id:4, coupon_record_id:6 } ] ''' response.data = self.get_pay_url(request,order_number,final_price) except ObjectDoesNotExist as e: response.code = 1001 response.msg = "课程不存在!" except CommonException as e: response.code = e.code response.msg = e.error except Exception as e: response.code = 500 response.msg = str(e) return Response(response.dict)
def post(self, request): ''' request.data=>course_list=[{ "course_id":1, "price_policy_id":2 }, ''' # self.dispatch() res = BaseResponse() # 1.取值 course_list = request.data user_id = request.user.id # 2.校验数据 try: del_list = cache.keys(settings.ACCOUNT_REDIS_KEY % (user_id, "*")) if del_list: cache.delete(*del_list) price_list = [] for course_dict in course_list: course_id = course_dict.get("course_id") price_policy_id = course_dict.get("price_policy_id") # 校验课程是否存在 course_obj = Course.objects.get(pk=course_id) # 查找课程关联的价格策略 price_policy_list = course_obj.price_policy.all() price_policy_dict = {} for price_policy in price_policy_list: price_policy_dict[price_policy.pk] = { "prcie": price_policy.price, "valid_period": price_policy.valid_period, "valid_period_text": price_policy.get_valid_period_display(), "default": price_policy.pk == price_policy_id } if price_policy_id not in price_policy_dict: raise CommonException(1001, "价格策略异常!") pp = PricePolicy.objects.get(pk=price_policy_id) # 将课程信息加入到每一个课程结算字典中 account_dict = { "id": course_id, "name": course_obj.name, "course_img": course_obj.course_img, "relate_price_policy": price_policy_dict, "default_price": pp.price, "rebate_price": pp.price, "default_price_period": pp.valid_period, "default_price_policy_id": pp.pk } # 课程价格加入到价格列表 price_list.append(float(pp.price)) # 查询当前用户拥有未使用的,在有效期的且与当前课程相关的优惠券 account_dict["coupon_list"] = self.get_coupon_list( request, course_id) # 存储结算信息 account_key = settings.ACCOUNT_REDIS_KEY % (user_id, course_id) cache.set(account_key, json.dumps(account_dict)) # 获取通用优惠券,加入redis中 cache.set("global_coupon_%s" % user_id, json.dumps(self.get_coupon_list(request))) cache.set("total_price", sum(price_list)) except ObjectDoesNotExist as e: res.code = 1001 res.msg = '提交异常,课程对象不存在!' except CommonException as e: res.code = e.code res.msg = e.msg except Exception as e: print(e) return Response(res.dict)
def post(self, request): print(request.data) """ 状态码: 1000:成功 1001:课程不存在 1002:价格策略错误 :return: 模拟请求数据 { "course_id":1, "prcie_policy_id":2 } """ # 1.获取请求数据 course_id = request.data.get("course_id") price_policy_id = request.data.get("price_policy_id") # 在liginAuth 里面讲 user_id = request.user.pk # 实例化一个响应类 res = BaseResponse() # 2 校验数据(这里yuan先生try的,) ''' 我这样写有很多分支,而且还得总返回一个字典,yuan先生抛异常这个好,学习 ''' # if course_id not in [obj.pk for obj in Course.objects.all()]: # res.code=1001auth_permission # res.data="课程不存在" # # else: try: # 2.1效验课程数据 course_obj = Course.objects.get(pk=course_id) # 2.2 效验价格策略数据 price_policy_dict = {} for price_policy in course_obj.price_policy.all(): price_policy_dict[price_policy.pk] = { "pk": price_policy.pk, "valid_period": price_policy.valid_period, "valid_period_text": price_policy.get_valid_period_display(), "price": price_policy.price, # 为了前端默认显示 "default": int(price_policy_id) == price_policy.pk } print(price_policy_id, price_policy.pk) print(price_policy_dict) # 因为有课程策略的替换,而且还有默认值显示 所以需要将价格策略全部存储起来,然后还需要当前价格策略id设置默认显示 if int(price_policy_id) not in price_policy_dict: print(type(price_policy_id)) print([obj.pk for obj in course_obj.price_policy.all()]) raise CommonException("1002", "价格策略错误") price_policy_obj = PricePolicy.objects.filter( pk=price_policy_id).first() """ # 想要购建的数据结构 REDIS={ shoppingcar_1_1:{ "title":"....", "img":"...." } shoppingcar_1_2:{ "title":"....", "img":"...." } } """ # 3 写进redis 中 # 哪个用户的哪个课程 pp = PricePolicy.objects.get(pk=price_policy_id) shoppingcar_key = settings.SHOPPING_CAR_KEY % (user_id, course_obj.pk) shoppingcar_val = { "id": course_obj.pk, "default_price_period": PricePolicy.objects.filter( pk=price_policy_id).first().valid_period, "title": course_obj.name, "img": course_obj.course_img, "relate_price_policy": price_policy_dict, "choose_price_policy_id": price_policy_id, "default_price": pp.price, "valid_period": price_policy_obj.valid_period, "valid_period_text": price_policy_obj.get_valid_period_display(), } print(shoppingcar_key, shoppingcar_val) r.set(shoppingcar_key, json.dumps(shoppingcar_val)) except CommonException as e: res.code = e.code res.msg = e.__str__() except ObjectDoesNotExist as e: res.code = 1001 res.msg = "课程不存在" return Response(res.dict)
def post(self, request): """ 模拟请求数据: { "course_id": 1, "price_policy_id": 2 } :param request: :return: """ # 1 获取请求数据 course_id = request.data.get("course_id") price_policy_id = request.data.get("price_policy_id") user_id = request.user.pk res = BaseResponse() # 2.校验数据 try: # 2.1 校验课程是否存在 course_obj = Course.objects.get(pk=course_id) # 2.2 校验价格策略是否合法 # ret = course_obj.price_policy.all() # print(ret) price_policy_dict = {} for price_policy in course_obj.price_policy.all(): price_policy_dict[price_policy.pk] = { "valid_period": price_policy.valid_period, "valid_period_text": price_policy.get_valid_period_display(), "price": price_policy.price, "default": price_policy_id == price_policy.pk } if price_policy_id not in price_policy_dict: raise CommonException(1002, "价格策略错误!") pp = PricePolicy.objects.get(pk=price_policy_id) # 3 写入 redis shoppingcar_key = settings.SHOPPINGCAR_KEY % (user_id, course_id) shoppingcar_val = { "title": course_obj.name, "img": course_obj.course_img, "relate_price_policy": price_policy_dict, "choose_price_policy_id": price_policy_id, "price": pp.price, "valid_period": pp.valid_period, "valid_period_text": pp.get_valid_period_display(), } cache.set(shoppingcar_key, json.dumps(shoppingcar_val)) res.data = "加入购物车成功!" except CommonException as e: res.code = e.code res.msg = "课程不存在" except ObjectDoesNotExist as e: res.code = 1001 res.msg = "课程不存在" return Response(res.dict)
def post(self, request): ''' 状态码: 1000: 成功 1001: 课程不存在 模拟请求数据: { "course_id_list":[1,2] } ''' # 1 获取请求数据 course_id_list = request.data.get('course_id_list') user_id = request.user.pk res = BaseResponse() try: # 结算情况: 1 直接购买 2 购物车结算 # 2 创建数据结构 # 清空操作,找到所有account_userid_*,全部清空 del_list = cache.keys(settings.ACCOUNT_KEY % (user_id, '*')) if del_list: cache.delete(*del_list) price_list = [] for course_id in course_id_list: # 结算key account_key = settings.ACCOUNT_KEY % (user_id, course_id) # 结算字典 account_val = {} # 获取课程基本信息 shoppingcart_key = settings.SHOPPINGCART_KEY % (user_id, course_id) # 判断课程是否存在购物车中 if not cache.exists(shoppingcart_key): raise CommonException('购物车不存在该课程', 1040) course_obj = Course.objects.get(pk=course_id) course_info = json.loads(cache.get(shoppingcart_key)) # 添加到结算字典中 account_val['course_info'] = course_info # 课程价格加入到价格列表 price_list.append(float(course_info['price'])) # 获取优惠券信息:查询当前用户当前课程有效的未使用的优惠券 coupons = self.get_coupon_dict(request, course_id) # 将优惠券字典添加到结算字典中 account_val['coupons'] = coupons cache.set(account_key, json.dumps(account_val)) # 获取通用优惠券 global_coupons = self.get_coupon_dict(request) cache.set('global_coupons_%s' % user_id, json.dumps(global_coupons)) cache.set('total_price', sum(price_list)) except CommonException as e: res.code = e.code res.msg = e.msg except ObjectDoesNotExist as e: res.code = 1001 res.msg = "课程不存在" return Response(res.dict)
def post(self, request, *args, **kwargs): """ 根据前端传来的 [{"course_id":1,"price_policy_id":2},] 新建一个 account 存储到 redis :param request: :param args: :param kwargs:q :return: """ user = request.user course_list = request.data response = BaseResponse() try: # 创建存储到redis的数据结构 redis_data = {} redis_data['account_course_list'] = [] price_list = [] for course_dict in course_list: course_id = course_dict.get("course_id") price_policy_id = course_dict.get("price_policy_id") # 校验课程是否存在 course_obj = Course.objects.get(pk=course_id) # 查找课程关联的价格策略 price_policy_list = course_obj.price_policy.all() price_policy_dict = {} for price_policy in price_policy_list: price_policy_dict[price_policy.pk] = { "prcie": price_policy.price, "valid_period": price_policy.valid_period, "valid_period_text": price_policy.get_valid_period_display(), "default": price_policy.pk == price_policy_id } if price_policy_id not in price_policy_dict: raise CommonException(1102, "价格策略异常!") pp = PricePolicy.objects.get(pk=price_policy_id) # 将课程信息加入到每一个课程结算字典中 account_dict = { "id": course_id, "name": course_obj.name, "course_img": course_obj.course_img, "relate_price_policy": price_policy_dict, "default_price": pp.price, "rebate_price": pp.price, "default_price_period": pp.valid_period, "default_price_policy_id": pp.pk } # 课程价格加入到价格列表 price_list.append(float(pp.price)) # 查询当前用户拥有未使用的,在有效期的且与当前课程相关的优惠券 account_dict["coupon_list"] = self.get_coupon_list( request, course_id) # 记录当前课程信息 redis_data['account_course_list'].append(account_dict) # 获取通用优惠券 redis_data['global_coupons'] = self.get_coupon_list(request) # 计算总价格 redis_data['total_price'] = sum(price_list) # 存储到redis中 account_key = settings.ACCOUNT_KEY % user.pk REDIS_CONN.set(account_key, json.dumps(redis_data)) except ObjectDoesNotExist as e: response.code = 1103 response.error = "课程不存在!" except CommonException as e: response.code = e.code response.error = e.error return Response(response.dict)
def post(self, request): ''' 大致思路:前端传过来的数据对于我们来说都可能存在恶意串改行为 所以我们需要对这些数据都进行一次校验,自己计算出实际金额 与前端传过来的金额做比较,最终再确定是否展示真正的交易二维码 :param request: :return: ''' #先获取用户的贝利数 总交易金额 通用优惠券 课程详细信息(包括各个课程id 价格策略等) bely = request.data.get('bely') #前端总金额 balance = request.data.get('balance') #通用优惠券 global_coupon_id = request.data.get('global_coupon_id') #课程详细 courses_detail = request.data.get("courses_detail") #产生回复消息对象 response = BaseResponse() try: #由于使用了认证功能,所以拿到用户对象 即可做相应查询操作 if bely > request.user.bely: raise CommonException('贝里数据有问题') #由于用户可能一次交易买了多门课程。我们应该将没门课程的价格算出来再求和 price_list = [] current_time = datetime.datetime.now().date() for course_id, course_info in courses_detail.items(): #校验课程是否存在 course_obj = models.Course.objects.filter(pk=course_id).first() if not course_obj: raise CommonException("课程不存在") #校验价格策略是否正常 price_policy_id = int(course_info.get("price_policy_id")) price_policy_set = course_obj.price_policy.all() #判断价格策略是否是该课程真实拥有的 if price_policy_id not in [ price_policy.pk for price_policy in price_policy_set ]: raise CommonException('价格策略有问题') #先获取该课程的实际价格策略对应的价格 price = models.PricePolicy.objects.filter( pk=price_policy_id).first().price # 校验课程优惠券是否有效 coupon_record_id = int(course_info.get('coupon_record_id')) #如果获取不到优惠券id,说明用户没有使用优惠券。直接将原价放入价格列表中 if not coupon_record_id: price_list.append(price) continue coupon_record_obj = models.CouponRecord.objects.filter( pk=coupon_record_id, user=request.user, coupon__valid_begin_date__lt=current_time, coupon__valid_begin_date__gt=current_time, ).first() if not coupon_record_obj: raise CommonException('优惠券有问题') # 校验该优惠券是否属于该课程 if coupon_record_obj.coupon.object_id != int(course_id): raise CommonException('优惠券与课程不匹配') # 计算该循环课程经过课程优惠券处理后的价格 counted_price = self.account_price(coupon_record_obj, price) # 将优惠券相关的计算最终得到的结果存放到价格列表中 price_list.append(counted_price) #校验通用优惠券 if not global_coupon_id: #用户没有使用通用优惠券 account_price = sum(price_list) else: global_coupon_record_obj = models.CouponRecord.objects.filter( pk=global_coupon_id, user=request.user, coupon__valid_begin_date__lt=current_time, coupon__valid_begin_date__gt=current_time, ).first() if not global_coupon_record_obj: raise CommonException('通用优惠券有问题') #将价格列表求和后再经过通用优惠券处理出一个实际价格 account_price = self.account_price(global_coupon_record_obj, sum(price_list)) #校验前端传过来的实际价格与我们计算的动啊的价格是否一致 final_price = account_price - bely / 10 if final_price < 0: final_price = 0 if final_price != balance: raise CommonException('提交的价格有问题') ''' 价格计算准确无误后,创建相应订单,这里订单有两张表,一张是总的订单表 还有一张是针对某个课程的单一订单表 ''' ''' 订单创建完毕后应调用支付宝接口来使用户完成订单金额支付 ''' return JsonResponse(self.response.dict) except CommonException as e: self.response.error_msg = e.msg self.response.code = 2000
def post(self, request): """ 模拟前端数据: { is_bei: true, course_list = [ { course_id: 1, default_price_policy_id: 1, coupon_record_id: 2 }, { course_id: 2, default_price_policy_id: 4, coupon_record_id: 6 } ], global_coupon_id: 3, pay_money: 298 } :param request: :return: """ # 1. 获取数据 is_bei = request.data.get("is_beili") course_list = request.data.get("course_list") global_coupon_id = request.data.get("global_coupon_id") pay_money = request.data.get("pay_money") user_id = request.user.pk res = BaseResponse() # 2. 校验数据 # 2.1 校验每一个课程 try: price_list = [] for course in course_list: course_id = course.gat("course_id") default_price_policy_id = course.gat("default_price_policy_id") coupon_record_id = course.gat("coupon_record_id") # 2.1.1 校验课程是否存在 course_obj = Course.objects.get(pk=course_id) # 2.1.2 校验价格策略 if default_price_policy_id not in [ obj.pk for obj in course_obj.price_policy.all() ]: raise CommonException(1002, "价格策略错误!") pp = PricePolicy.objects.get(pk=default_price_policy_id) if coupon_record_id: # 2.1.3 校验课程优惠卷 now = datetime.datetime.now() coupon_record_obj = CouponRecord.objects.filter( pk=coupon_record_id, account=request.user, coupon__content_type=9, coupon__object_id=course_id, status=0, coupon__valid_begin_date__lte=now, coupon__valid_end_date__gte=now).first() if not coupon_record_obj: raise CommonException(1003, "课程优惠卷异常!") # 计算折后价格 rebate_money = self.cal_coupon_price( pp.price, coupon_record_obj) price_list.append(rebate_money) else: price_list.append(pp.price) final_price = sum(price_list) # 2.2校验通用优惠卷 if global_coupon_id: # 2.2.1 校验通用优惠卷合法 now = datetime.datetime.now() g_coupon_record_obj = CouponRecord.objects.filter( pk=global_coupon_id, account=request.user, coupon__content_type=9, coupon__object_id=None, status=0, coupon__valid_begin_date__lte=now, coupon__valid_end_date__gte=now).first() if not g_coupon_record_obj: raise CommonException(1004, "通用优惠卷异常!") # 2.2.2 计算折后价格 final_price = self.cal_coupon_price(final_price, g_coupon_record_obj) # 2.3校验贝里 if json.loads(is_bei): final_price = final_price - request.user.beili / 10 if final_price < 0: final_price = 0 # 2.4 校验最终价格 if final_price != pay_money: raise CommonException(1005, "支付价格异常!") # 3.生成订单 # 生成订单表 order_obj = Order.objects.create(payment_type=1, order_number=uuid.uuid4(), account=request.user, status=1, order_type=1, actual_amount=pay_money) print("course_list", course_list) for course_item in course_list: OrderDetail.objects.create( order=order_obj, content_type_id=14, object_id=course_item.get("course_id"), original_price=course_item.get("original_price"), price=course_item.get("valid_period"), valid_period=course_item.get("valid_period"), valid_period_display=course_item.get( "valid_period_display")) # 4. 调用 alipay 接口 alipay = self.get_alipay() # 生成支付的url query_params = alipay.direct_pay( subject="路飞学城", # 商品简单描述 out_trade_no="x345" + str(time.time()), # 商户订单号 total_amount=pay_money, # 交易金额(单位: 元 保留俩位小数) ) pay_url = "https://openapi.alipaydev.com/gateway.do?{}".format( query_params) res.data = {"url": pay_url} except ObjectDoesNotExist as e: res.code = 1001 res.msg = "课程不存在!" except CommonException as e: res.code = e.code res.msg = e.msg return Response(res.dict)
def post(self, request, *args, **kwargs): # 1 获取数据 ''' course_list=[{ "course_id":1, "price_policy_id":2 }, ] :param request: :param args: :param kwargs: :return: ''' user = request.user course_list = request.data print("course_list", course_list) print("course_list", type(course_list)) response = BaseResponse() try: # 2 创建数据结构 # 清空操作 # 找到所有以account_userid_*,全部清空 del_list = REDIS_CONN.keys(settings.ACCOUNT_KEY % (user.pk, "*")) if del_list: REDIS_CONN.delete(*del_list) price_list = [] for course_dict in course_list: course_id = course_dict.get("course_id") price_policy_id = course_dict.get("price_policy_id") # 校验课程是否存在 course_obj = Course.objects.get(pk=course_id) # 查找课程关联的价格策略 price_policy_list = course_obj.price_policy.all() price_policy_dict = {} for price_policy in price_policy_list: price_policy_dict[price_policy.pk] = { "prcie": price_policy.price, "valid_period": price_policy.valid_period, "valid_period_text": price_policy.get_valid_period_display(), "default": price_policy.pk == price_policy_id } if price_policy_id not in price_policy_dict: raise CommonException(1001, "价格策略异常!") pp = PricePolicy.objects.get(pk=price_policy_id) # 将课程信息加入到每一个课程结算字典中 account_dict = { "id": course_id, "name": course_obj.name, "course_img": course_obj.course_img, "relate_price_policy": price_policy_dict, "default_price": pp.price, "rebate_price": pp.price, "default_price_period": pp.valid_period, "default_price_policy_id": pp.pk } # 课程价格加入到价格列表 price_list.append(float(pp.price)) # 查询当前用户拥有未使用的,在有效期的且与当前课程相关的优惠券 account_dict["coupon_list"] = self.get_coupon_list( request, course_id) # 存储结算信息 account_key = settings.ACCOUNT_KEY % (user.pk, course_id) REDIS_CONN.set(account_key, json.dumps(account_dict)) # 获取通用优惠券,加入redis中 REDIS_CONN.set("global_coupon_%s" % user.pk, json.dumps(self.get_coupon_list(request))) REDIS_CONN.set("total_price", sum(price_list)) except ObjectDoesNotExist as e: response.code = 1001 response.error = "课程不存在!" except CommonException as e: response.code = e.code response.error = e.error # except Exception as e: # response.code = 500 # response.error = str(e) return Response(response.dict)
def post(self, request): ''' 状态码: 1000: 成功 1001: 课程不存在 模拟请求数据: { "course_id":1, "price_policy_id":2 } ''' # 1 获取请求数据 course_id = request.data.get('course_id') price_policy_id = request.data.get('price_policy_id') user_id = request.user.pk res = BaseResponse() try: # 2 校验数据 # 2.1 校验课程是否存在 course_obj = Course.objects.get(pk=course_id) # 2.2 校验价格策略是否合法 price_policy_dict = {} for price_policy in course_obj.price_policy.all(): price_policy_dict[price_policy.pk] = { 'pk': price_policy.pk, 'valid_period': price_policy.valid_period, 'valid_period_text': price_policy.get_valid_period_display(), 'price': price_policy.price, 'default': price_policy_id == price_policy.pk } if price_policy_id not in price_policy_dict: raise CommonException(1002, '价格策略错误!') pp = PricePolicy.objects.get(pk=price_policy_id) # 3 写入redis shoppingcart_key = settings.SHOPPINGCART_KEY%(user_id,course_id) shoppingcart_val = { 'title': course_obj.name, 'img': course_obj.course_img, 'relate_price_policy': price_policy_dict, 'choose_price_policy_id': price_policy_id, 'price': pp.price, 'valid_period': pp.valid_period, 'valid_period_text': pp.get_valid_period_display() } cache.set(shoppingcart_key, json.dumps(shoppingcart_val)) res.data = "加入购物车成功!" ''' REDIS={ shoppingcart_1_1:{ "title":"....", "img":"...." } shoppingcart_1_2:{ "title":"....", "img":"...." } ''' except CommonException as e: res.code = e.code res.msg = e.msg except ObjectDoesNotExist as e: res.code = 1001 res.msg = "课程不存在" return Response(res.dict)
def post(self, request): # 1.获取数据 is_beli = request.data.get('is_beli') course_list = request.data.get('course_list') global_coupon_id = request.data.get('global_coupon_id') pay_money = request.data.get('pay_money') user_id = request.user.pk # 2.校验 res = BaseResponse() price_list = [] try: now = datetime.datetime.now() # 2.1 每个课程 for course_dict in course_list: course_id = course_dict.get("course_id") default_price_policy_id = course_dict.get( 'default_price_policy_id') # coupon_record_id = course_dict.get('coupon_record_id','') course_obj = Course.objects.get(pk=course_id) if default_price_policy_id not in [ obj.pk for obj in course_obj.price_policy.all() ]: raise CommonException(1002, '价格策略不存在') content_obj = ContentType.objects.get( app_label='api', model='course', ) price_policy_obj = PricePolicy.objects.get( pk=course_dict.get("default_price_policy_id")) course_dict["original_price"] = price_policy_obj.price course_dict[ "valid_period_display"] = price_policy_obj.get_valid_period_display( ) course_dict["valid_period"] = price_policy_obj.valid_period coupon_record_id = course_dict.get("coupon_record_id") # 检验课程优惠券,并计算出折后的总价格(不带通用优惠券和贝利) if not coupon_record_id: price_list.append(price_policy_obj.price) else: coupon_record_list = CouponRecord.objects.filter( account=request.user, coupon__content_type=content_obj, coupon__object_id=course_id, status=0, coupon__valid_begin_date__lte=now, coupon__valid_end_date__gte=now, ) if coupon_record_id and coupon_record_id not in [ obj.pk for obj in coupon_record_list ]: raise CommonException("课程优惠券异常!", 1006) coupon_record_obj = CouponRecord.objects.get( pk=coupon_record_id) rebate_money = self.cal_coupon_price( price_policy_obj.price, coupon_record_obj) price_list.append(rebate_money) # 2.2 通用优惠券 global_coupon_record_list = CouponRecord.objects.filter( account=request.user, status=0, coupon__valid_begin_date__lt=now, coupon__valid_end_date__gt=now, coupon__content_type_id=14, coupon__object_id=None) if not global_coupon_record_list: global_coupon_record_list = [] if global_coupon_id and global_coupon_id not in [ obj.pk for obj in global_coupon_record_list ]: raise CommonException("通用优惠券异常", 1006) if global_coupon_id: global_coupon_record_obj = CouponRecord.objects.get( pk=global_coupon_id) final_price = self.cal_coupon_price(sum(price_list), global_coupon_record_obj) else: final_price = sum(price_list) # 2.3 贝利 cost_beli_num = 0 if is_beli: final_price = final_price - request.user.beli / 10 cost_beli_num = request.user.beli if final_price < 0: final_price = 0 cost_beli_num = final_price * 10 if final_price != float(pay_money): raise CommonException(1008, "支付总价格异常!") # 生成订单 order_number = self.get_order_num() order_obj = Order.objects.create( payment_type=1, order_number=order_number, account=request.user, status=1, order_type=1, actual_amount=pay_money, ) for course_item in course_list: OrderDetail.objects.create( order=order_obj, content_type_id=14, object_id=course_item.get("course_id"), original_price=course_item.get("original_price"), price=course_item.get("rebate_price") or course_item.get("original_price"), valid_period=course_item.get("valid_period"), valid_period_display=course_item.get( "valid_period_display"), ) request.user.beli = request.user.beli - cost_beli_num request.user.save() cache.set(order_number + "|" + str(cost_beli_num), "", 20) account_key = settings.ACCOUNT_REDIS_KEY % (user_id, "*") cache.delete(*cache.keys(account_key)) res.data = self.get_pay_url(request, order_number, final_price) except ObjectDoesNotExist as e: res.code = 1001 res.msg = '课程不存在!' except CommonException as e: res.code = e.code res.msg = e.msg return Response(res.dict)
def post(self, request, *args, **kwargs): """ 重新计算总价格,生成订单,返回支付URL 模拟请求数据格式: { is_beli:true, course_list=[ { course_id:1 default_price_policy_id:1, coupon_record_id:2 }, { course_id:2 default_price_policy_id:4, coupon_record_id:6 } ], global_coupon_id:3, pay_money:298 } 状态码: 1300: 成功 1301: 课程不存在 1302: 价格策略不合法 1303: 加入购物车失败 1304: 获取购物车失败 1305: 贝里数有问题 1306: 优惠券异常 1307: 优惠券未达到最低消费 1308: 支付总价格异常 :param request: :param args: :param kwargs: :return: """ response = BaseResponse() # 1 获取数据 user_id = request.user.pk global_coupon_id = request.data.get("global_coupon_id") pay_money = request.data.get("pay_money") course_list = request.data.get("course_list") is_beli = request.data.get("is_beli") now = timezone.now() try: # 2 校验数据 # 2.2 校验课程 course_price_list = [] for course_dict in course_list: # 2.2.1 校验课程id course_id = course_dict.get("course_id") course_obj = Course.objects.get(pk=course_id) # 2.2.2 价格策略id if course_dict.get("default_price_policy_id") not in [ obj.pk for obj in course_obj.price_policy.all() ]: raise CommonException("价格策略异常!", 1302) # 2.2.3 课程优惠券id price_policy_obj = PricePolicy.objects.get( pk=course_dict.get("default_price_policy_id")) course_dict["original_price"] = price_policy_obj.price course_dict[ "valid_period_display"] = price_policy_obj.get_valid_period_display( ) course_dict["valid_period"] = price_policy_obj.valid_period coupon_record_id = course_dict.get("coupon_record_id") if coupon_record_id: coupon_record_list = CouponRecord.objects.filter( account=request.user, status=0, coupon__valid_begin_date__lt=now, coupon__valid_end_date__gt=now, coupon__content_type_id=9, coupon__object_id=course_id) if coupon_record_id and coupon_record_id not in [ obj.pk for obj in coupon_record_list ]: raise CommonException("课程优惠券异常!", 1306) # 计算循环课程的课程优惠券优惠后的价格 coupon_record_obj = CouponRecord.objects.get( pk=coupon_record_id) rebate_price = self.cal_coupon_price( price_policy_obj.price, coupon_record_obj) course_price_list.append(rebate_price) course_dict["rebate_price"] = rebate_price else: course_price_list.append(price_policy_obj.price) # 2.3 校验通用优惠券id if global_coupon_id: global_coupon_record_list = CouponRecord.objects.filter( account=request.user, status=0, coupon__valid_begin_date__lt=now, coupon__valid_end_date__gt=now, coupon__content_type_id=9, coupon__object_id=None) if global_coupon_id and global_coupon_id not in [ obj.pk for obj in global_coupon_record_list ]: raise CommonException("通用优惠券异常", 1306) global_coupon_record_obj = CouponRecord.objects.get( pk=global_coupon_id) final_price = self.cal_coupon_price(sum(course_price_list), global_coupon_record_obj) else: final_price = sum(course_price_list) # 2.4 计算实际支付价格与money做校验 cost_beli_num = 0 if is_beli: final_price = final_price - request.user.beli / 10 cost_beli_num = request.user.beli if final_price < 0: final_price = 0 cost_beli_num = int(final_price * 10) if final_price != float(pay_money): raise CommonException(1308, "支付总价格异常!") # 3 生成订单记录 order_number = self.get_order_num() order_obj = Order.objects.create( payment_type=1, order_number=order_number, account=request.user, status=1, actual_amount=pay_money, ) for course_item in course_list: OrderDetail.objects.create( order=order_obj, content_type_id=9, object_id=course_item.get("course_id"), original_price=course_item.get("original_price"), price=course_item.get("rebate_price") or course_item.get("original_price"), valid_period=course_item.get("valid_period"), valid_period_display=course_item.get( "valid_period_display"), ) # 3 保存数据 request.user.beli = request.user.beli - cost_beli_num request.user.save() REDIS_CONN.set(order_number + "|" + str(cost_beli_num), "", 20) # 删除 redis 中 account 信息 account_key = settings.ACCOUNT_KEY % user_id REDIS_CONN.delete(account_key) # 4 获取支付URL response.data = self.get_pay_url(request, order_number, final_price) except ObjectDoesNotExist as e: response.code = 1301 response.msg = "课程不存在!" except CommonException as e: response.code = e.code response.msg = e.error except Exception as e: response.code = 5000 response.msg = str(e) return Response(response.dict)
def post(self, request): res = BaseResponse() # 1 获取数据 user_id = request.user.pk global_coupon_id = request.data.get('global_coupon_id') pay_money = request.data.get('pay_money') course_list = request.data.get('course_list') is_beli = request.data.get('is_beli') now = datetime.datetime.now() try: # 2 校验数据 # 2.1 校验课程 course_price_list = [] for course_dict in course_list: # 校验课程id course_id = course_dict.get('course_id') course_obj = Course.objects.get(pk=course_id) # 价格策略id if course_dict.get('default_price_id') not in [ obj.pk for obj in course_obj.price_policy.all() ]: raise CommonException("价格策略异常!", 1002) # 课程优惠券id price_policy_obj = PricePolicy.objects.get( pk=course_dict.get('default_price_policy_id')) course_dict['original_price'] = price_policy_obj.price course_dict[ 'valid_period_display'] = price_policy_obj.get_valid_period_display course_dict['valid_period'] = price_policy_obj.valid_period coupon_record_id = course_dict.get('coupon_record_id') if coupon_record_id: coupon_record_list = CouponRecord.objects.filter( account=request.user, status=0, coupon__valid_begin_date__lt=now, coupon__valid_end_date__gt=now, coupon__content_type_id=13, coupon__object_id=course_id) if coupon_record_list and coupon_record_id not in [ obj.pk for obj in coupon_record_list ]: raise CommonException("课程优惠券异常!", 1006) # 计算循环课程的课程优惠券优惠后的价格 coupon_record_obj = CouponRecord.objects.get( pk=coupon_record_id) rebate_price = self.cal_coupon_price( price_policy_obj.price, coupon_record_obj) course_price_list.append(rebate_price) course_dict['rebate_price'] = rebate_price else: course_price_list.append(price_policy_obj.price) # 2.2 校验通用优惠券id if global_coupon_id: global_coupon_record_list = CouponRecord.objects.filter( account=request.user, status=0, coupon__valid_begin_date__lt=now, coupon__valid_end_date__gt=now, coupon__content_type_id=13, coupon__object_id=None) if global_coupon_record_list and global_coupon_id not in [ obj.pk for obj in global_coupon_record_list ]: raise CommonException("通用优惠券异常", 1006) global_coupon_record_obj = CouponRecord.objects.get( pk=global_coupon_id) final_price = self.cal_coupon_price(sum(course_price_list), global_coupon_record_obj) else: final_price = sum(course_price_list) # 2.3 计算实际支付价格与money做校验 cost_beli_num = 0 if is_beli: price = final_price - request.user.beli / 10 cost_beli_num = request.user.beli if price < 0: price = 0 cost_beli_num = final_price * 10 final_price = price if final_price != float(pay_money): raise CommonException(1008, "支付总价格异常!") # 3 生成订单记录 order_number = self.get_order_num() order_obj = Order.objects.create(payment_type=1, order_number=order_number, account=request.user, status=1, order_type=1, actual_amount=pay_money) for course_item in course_list: OrderDetail.objects.create( order=order_obj, content_type_id=7, object_id=course_item.get('course_id'), original_price=course_item.get('original_price'), price=course_item.get('rebate_price') or course_item.get('original_price'), valid_period=course_item.get('valid_period'), valid_period_display=course_item.get( 'valid_period_display')) request.user.beli = request.user.beli - cost_beli_num request.user.save() cache.set(order_number + '|' + str(cost_beli_num), '', 20) account_key = settings.ACCOUNT_KEY % (user_id, "*") cache.delete(*cache.keys(account_key)) ''' [ { course_id:1 default_price_policy_id:1, coupon_record_id:2 }, { course_id:2 default_price_policy_id:4, coupon_record_id:6 } ] ''' res.data = self.get_pay_url(request, order_number, final_price) except ObjectDoesNotExist as e: res.code = 1001 res.msg = "课程不存在!" except CommonException as e: res.code = e.code res.msg = e.msg except Exception as e: res.code = 500 res.msg = str(e) return Response(res.dict)