def post(self, request): res = BaseResponse() # 拿到前端传过来的数据 course_id = request.data.get('course') price_policy_id = request.data.get('price_policy') user = request.user multi = request.data.get('multi') # 传来多个课程参数 # 检测数据合法 try: # 这里可以判断是一个课程还是多个课程 # 如果前端传来单个课程参数 if not multi: # {"course": 1, "price_policy": 1} res = self.post_func(res, course_id, price_policy_id, user) # 如果前端传来多个课程参数 else: for item in multi: # {"multi":[{"course":2,"price_policy":10},{"course":3,"price_policy":4}]} course = item['course'] price_policy = item['price_policy'] ret = self.post_func(res, course, price_policy, user) except Exception as e: print(e) res.code = 1042 res.error = '操作失败,请重试' return Response(res.dict) else: res.data = '加入购物车成功' return Response(res.dict)
def get(self, request): # 调用业务数据库的数据进行查看展示 """ 账单详情: [ 账单id:{ 商品名: 简介: 数量: 价格: 图片: }, ] 创建订单时间: 下单付款时间: 流水号: 付款方式: 实付金额: 收获地址: """ res = BaseResponse() user_trades = models.TradeRecord.objects.filter(account=request.user).all() user_order = models.OrderDetail.objects.filter(order__account=request.user).all() pay_dict = {} # 商品数量 order_menu = {} for order in user_order: order_menu[order.object_id] = { 'real_price': order.price, 'order_date': order.order.date, 'pay_date': order.order.pay_time } for trade in user_trades: product = eval(trade.product) # print(product) pay_dict[trade.id] = {} for item in product: brief = models.Course.objects.filter(id=int(item['id'])).first().coursedetail.brief pay_dict[trade.id][item['id']] = item pay_dict[trade.id][item['id']]['brief'] = brief for order_id in order_menu: if int(order_id) == int(item['id']): pay_dict[trade.id][item['id']]['real_price'] = order_menu[order_id]['real_price'] pay_dict[trade.id]['order_date'] = order_menu[order_id]['order_date'] pay_dict[trade.id]['pay_date'] = order_menu[order_id]['pay_date'] res.data = pay_dict pay_dict[trade.id]['transaction_number'] = trade.transaction_number pay_dict[trade.id]['user_address'] = trade.user_address pay_dict[trade.id]['pay_success_time'] = trade.date return Response(res.dict)
def post(self, request): """创建订单""" res = BaseResponse() # 拿到前端传来的课程id数据 course_list = request.data.get('course_list') user = request.user try: # 因为前段传来的有单个和多个,所以作解耦 if isinstance(course_list, list): for course_id in course_list: course_id = int(course_id) res = self.post_func(user.id, course_id, res) else: course_id = int(course_list) # 传来一个数据 res = self.post_func(user.id, course_id, res) except Exception as e: print(e) res.code = 1071 res.error = '操作失败,请重试' return Response(res.dict) else: res.data = '加入结算中心成功' return Response(res.dict)
def post(self, request): res = BaseResponse() user_obj = RegisterSerializer(data=request.data) if user_obj.is_valid(): user_obj.save() res.data = user_obj.data else: res.code = 1020 res.error = user_obj.errors return Response(res.dict)
def put(self, request): res = BaseResponse() # 获取前端传来的数据 course_id = request.data.get('course') course_coupon_id = request.data.get('coupon') global_coupon_id = request.data.get('global_coupon') user_id = request.user.pk key = SETTLEMENT_KEY % (user_id, course_id) global_key = GLOBAL_COUPON_KEY % user_id # 验证数据合法 if course_id: if not CONN.exists(key): res.code = 1080 res.error = '课程id不合法' return Response(res.dict) if course_coupon_id: user_coupon_dict = json.loads(CONN.hget(key, 'course_coupon_dict')) if str(course_coupon_id) not in user_coupon_dict: res.code = 1081 res.error = '课程优惠券id不合法' return Response(res.dict) CONN.hset(key, 'default_coupon_id', course_coupon_id) if global_coupon_id: if not CONN.exists(global_key): res.code = 1082 res.error = '全局优惠券id不合法' return Response(res.dict) CONN.hset(global_key, 'default_global_coupon_id', global_coupon_id) res.data = '已选择优惠券' return Response(res.dict)
def delete(self, request): """删除账单""" res = BaseResponse() orders = request.data.get('order') user = request.user if not isinstance(orders, int): for order_id in orders: res = self.delete_func(user, order_id, res) else: res = self.delete_func(user, orders, res) res.data = '账单删除成功' return Response(res.dict)
def delete(self, request): """取消订单""" res = BaseResponse() user_id = request.user.pk course_list = request.data.get('course') if not isinstance(course_list, int): for course in course_list: res = self.delete_func(user_id, course, res) else: res = self.delete_func(user_id, course_list, res) res.data = '订单删除成功' return Response(res.dict)
def post(self, request): res = BaseResponse() username = request.data.get('username') pwd = request.data.get('pwd') user_obj = models.Account.objects.filter(username=username, pwd=pwd).first() if not user_obj: res.code = 1031 res.error = '用户名或者密码错误' conn = redis.Redis(connection_pool=POOL) # 用户登录成功创建一个token,存到redis中 try: token = uuid.uuid4() # conn.set(str(token), user_obj.id, ex=60) # ex是用来设置过期时间 conn.set(str(token), user_obj.id) res.code = 1030 res.data = token except Exception as e: res.code = 1032 res.error = '创建令牌失败' return Response(res.dict)
def delete(self, request): res = BaseResponse() user_id = request.user.pk course_id_list = request.data.get('course_id_list', '') for course_id in course_id_list: key = SHOPPINGCAR_KEY % (user_id, course_id) if not CONN.exists(key): res.code = 1061 res.error = '课程id不合法' return Response(res.dict) CONN.delete(key) res.data = '删除成功' return Response(res.dict)
def get(self, request): res = BaseResponse() # 从redis数据库中取出购物车的数据 user_id = request.user.pk key = SHOPPING_KEY % (user_id, '*') # 找到跟当前用户相关的所有购物车数据的key all_keys = CONN.scan_iter(key) course_info = [] for key in all_keys: course_info.append(CONN.hgetall(key)) if len(course_info) == 0: res.data = '您的购物车空空如也哦~' else: res.data = course_info # 返回给前端 return Response(res.dict)
def post(self, request): res = BaseResponse() user = request.user user_obj = models.Student.objects.filter(account=user).first() if not user_obj: res.code = 1401 res.data = '非法用户' return Response(res.dict) tutor = user_obj.tutor question = request.data.get('question') models.StudyQuestion.objects.create(student=user, question=question, tutor=tutor) res.data = '提交问题成功' return Response(res.dict)
def post(self, request): res = BaseResponse() username = request.data.get('username') passwd = request.data.get('passwd') # 密码加盐 hash_key = 'password' passwd = passwd + hash_key passwd_md5 = hashlib.md5(passwd.encode()).hexdigest() user_obj = Account.objects.filter(username=username, passwd=passwd_md5).first() if not user_obj: res.code = 1030 res.error = '用户名密码不匹配' try: token = uuid.uuid4() RedisConn.set(str(token), user_obj.id) shop_cart = ShoppingView().get(request) # 购物车数据 res.data = { 'access_token': token, 'avatar': 'http://127.0.0.1:8000/media/avatar.png', # 真实部署时改成公网地址 'username': user_obj.username, 'shop_cart_num': shop_cart.data.get('data'), 'balance': user_obj.balance } # 头像,购物车数据,token,用户名,账户余额 except Exception as e: print('........', e) res.code = 1031 res.error = '创建令牌失败' return Response(res.dict)
def put(self, request): res = BaseResponse() # 获取前端传来的用户id和课程id,和价格策略id user_id = request.user.pk course_id = request.data.get('course_id', '') price_policy_id = request.data.get('price_policy_id', '') key = SHOPPINGCAR_KEY % (user_id, course_id) # 判断课程是否合法 if not CONN.exists(key): res.code = 1061 res.error = '课程id不合法' return Response(res.dict) # 判断价格策略id是否合法 price_policy_dict = json.loads(CONN.hget(key, 'price_policy_dict')) if str(price_policy_id) not in price_policy_dict: res.code = 1062 res.error = '价格策略不合法' return Response(res.dict) # 修改数据 CONN.hset(key, "default_price_policy_id", price_policy_id) res.data = '更新成功' return Response(res.dict)
def post(self, request): """领取优惠券""" res = BaseResponse() # 优惠券只能一个一个领取,所以不考虑多个操作 coupon_id = request.data.get('coupon') # 检查数据合法性 coupon_obj = models.Coupon.objects.filter(id=coupon_id).first() if not coupon_obj: res.code = 1108 res.error = '优惠券id不合法' return Response(res.dict) models.Coupon.objects.filter(id=coupon_id).update(count=F('count') - 1) models.CouponDetail.objects.create(coupon=coupon_obj, number=str(time.time()), account=request.user, get_time=now()) res.data = '优惠券领取成功' return Response(res.dict)
def get(self, request): """获取订单数据""" res = BaseResponse() # 获取redis里的数据 user_id = request.user.pk key = SETTLEMENT_KEY % (user_id, '*') global_key = GLOBAL_COUPON_KEY % user_id user_settlement_keys = CONN.scan_iter(key) settlement_info = [] for field in user_settlement_keys: settlement_info.append(CONN.hgetall(field)) global_data = CONN.hgetall(global_key) res.data = { 'settlement_info': settlement_info, 'global_coupon_dict': global_data } return Response(res.dict)
def get(self, request): res = BaseResponse() user_id = request.user.pk # *表示在redis中查找数据时是进行模糊匹配 shopping_car_key = SHOPPINGCAR_KEY % (user_id, "*") # scan_iter在redis中进行模糊查询,返回的是一个生成器 all_keys = CONN.scan_iter(shopping_car_key) ret = [] for key in all_keys: ret.append(CONN.hgetall(key)) res.data = ret return Response(res.dict)
def get(self, request): """查看优惠券""" res = BaseResponse() all_coupon = models.Coupon.objects.all() coupon_dict = {} for item in all_coupon: coupon_dict[item.id] = { 'id': item.id, 'title': item.title, 'brief': item.brief, 'coupon_type': item.coupon_type, 'coupon_type_display': item.get_coupon_type_display(), 'grant_begin_time': item.grant_begin_time, 'grant_end_time': item.grant_end_time, 'start_time': item.start_time, 'end_time': item.end_time, 'period': item.date } res.data = coupon_dict return Response(res.dict)
def get(self, request): res = BaseResponse() user_id = request.user.pk settlement_key = SETTLEMENT_KEY % (user_id, "*") global_coupon_key = GLOBAL_COUPON_KEY % user_id all_keys = CONN.scan_iter(settlement_key) ret = [] for key in all_keys: ret.append(CONN.hgetall(key)) global_coupon_info = CONN.hgetall(global_coupon_key) res.data = { "settlement_info": ret, "global_coupon_info": global_coupon_info } return Response(res.dict)
def delete(self, request): res = BaseResponse() # 拿到前端传过来的数据 course_list = request.data.get('course') user = request.user # 检测是否有该课程 try: # 如果前端传来的数据只有一个 if not isinstance(course_list, list): res = self.delete_func(user, course_list, res) # 如果前端传来的数据有多个 else: for course in course_list: res = self.delete_func(user, course, res) except Exception as e: print(e) res.code = 1061 res.error = '操作失败请重试' return Response(res.dict) else: res.data = '已删除选中课程' return Response(res.dict)
def get(self, request): res = BaseResponse() # 从redis数据库中取出购物车的数据 user_id = request.user.pk key = SHOPPING_KEY % (user_id, '*') # 找到跟当前用户相关的所有购物车数据的key all_keys = CONN.scan_iter(key) course_info = [] for key in all_keys: course_info.append(CONN.hgetall(key)) if len(course_info) == 0: res.data = 0 else: for index, item in enumerate(course_info): course_info[index]['price_policy_dict'] = json.loads( item['price_policy_dict']) res.data = course_info # 返回给前端 return Response(res.dict)
def get(self, request): # 获取用户的账单 res = BaseResponse() order_res = PaymentView().get(request) # 当前用户账单数据 user_order_products = order_res.data['data'].values() course_ids = [] for product in user_order_products: print(product) for item in list(product.keys()): if isinstance(item, int): course_ids.append(item) course_ids = list(set(course_ids)) # 去重 # 从账单中拿到对应的商品数据 courses = [] for course_id in course_ids: course_res = CourseDetailView().get(request, course_id) if len(courses) == 0: courses = course_res.data else: courses.extend(course_res.data) res.data = courses # 返回展示已购买的商品内容,视频链接接入保利威视频,作业, return Response(res.dict)
def get(self, request): res = BaseResponse() user_coupons = models.Coupon.objects.filter( coupondetail__account=request.user, coupondetail__status=0).all().distinct() coupon_dict = {} for item in user_coupons: coupon_dict[item.id] = { 'id': item.id, 'object_id': item.object_id, 'title': item.title, 'brief': item.brief, 'equal_money': item.equal_money, 'off_percent': item.off_percent, 'coupon_type': item.coupon_type, 'coupon_type_display': item.get_coupon_type_display(), 'grant_begin_time': item.grant_begin_time, 'grant_end_time': item.grant_end_time, 'start_time': item.start_time, 'end_time': item.end_time, 'period': str(item.period) + '天' } res.data = coupon_dict return Response(res.dict)
def put(self, request): res = BaseResponse() user_id = user_id = request.user.pk course_id = request.data.get('course_id', '') course_coupon_id = request.data.get('course_coupon_id', '') global_coupon_id = request.data.get('global_coupon_id', '') # 校验课程合法性 key = SETTLEMENT_KEY % (user_id, course_id) if course_id: if not CONN.exists(key): res.code = 1071 res.error = '课程id不合法' return Response(res.dict) # 校验课程优惠券是否合法 if course_coupon_id: course_coupon_dict = json.loads( CONN.hget(key, 'course_coupon_dict')) if str(course_coupon_id) not in course_coupon_dict: res.code = 1072 res.error = '课程优惠券id不合法' return Response(res.dict) # 修改redis中数据 CONN.hset(key, "default_course_coupon_id", course_coupon_id) # 校验全局优惠券是否合法 if global_coupon_id: global_coupon_key = GLOBAL_COUPON_KEY % user_id if not CONN.exists(global_coupon_key): res.code = 1072 res.error = '全局优惠券id不合法' return Response(res.dict) # 修改redis中数据 CONN.hset(global_coupon_key, "default_global_coupon_id", global_coupon_id) res.data = '更新成功' return Response(res.dict)
def put(self, request): """ 对账单对应的课程做评价 order_id:{ { "course":xx, "assess":xx, } } or { "course":xx, "assess":xx, } 以下功能暂时用不到,后续再补充: 退款,退货 售后服务、纠纷 追评 """ # 评价有两种,一种是从账单页面的评价(带有订单id),一种是学习界面里的评价(不带有订单id) res = BaseResponse() user = request.user flag_yang = request.data.keys() if len(flag_yang) > 1: # 大于1则是从学习界面来的评价 res = self.put_func(data=request.data, res=res, user=user) return Response(res.dict) else: # 账单页面来的评价 order_id = list(flag_yang)[0] order_db_obj = models.Order.objects.filter(id=order_id, account=user).first() if not order_db_obj: res.error = '不存在的账单' res.code = 1201 return Response(res.dict) try: data = request.data.get(order_id) res = self.put_func(data, res, user, order_db_obj) except Exception as e: print(e) res.code = 1301 res.error = '操作有误' return Response(res.dict) else: return Response(res.dict)
def post(self, request): res = BaseResponse() # 获取前端传过来的user_id和课程 user_id = request.user.pk course_id = request.data.get('course_id', '') price_policy_id = request.data.get('price_policy_id', '') course_obj = models.Course.objects.filter(id=course_id).first() # 校验课程是否合法 if not course_obj: res.code = 1051 res.error = '课程不存在' return Response(res.dict) # 校验价格策略是否合法 price_policy_queryset = course_obj.price_policy.all() price_policy_dict = {} for policy in price_policy_queryset: price_policy_dict[policy.id] = { "price": policy.price, "valid_period": policy.valid_period, "valid_period_display": policy.get_valid_period_display() } if price_policy_id not in price_policy_dict: res.code = 1052 res.error = '价格策略不合法' return Response(res.dict) # 构建存到redis中的数据 key = SHOPPINGCAR_KEY % (user_id, course_id) course_info = { "id": course_id, "title": course_obj.title, "course_img": str(course_obj.course_img), "price_policy_dict": json.dumps(price_policy_dict, ensure_ascii=False), "default_price_policy_id": price_policy_id } CONN.hmset(key, course_info) res.data = '加入购物车成功' return Response(res.dict)
def post(self, request): res = BaseResponse() homework_id = request.data.get('homework') file = request.data.get('file') file.name = '%s-' % request.user + file.name user_obj = models.Student.objects.filter( account_id=request.user.pk).first() homework_obj = models.HomeworkDetail.objects.filter( homework_id=homework_id, student=user_obj).first() if not homework_obj: res.code = 1501 res.data = '非法操作,不存在该作业' return Response(res.dict) homework_obj.status = 3 if homework_obj.file: res.data = '您已上传过啦' return Response(res.dict) homework_obj.file = file homework_obj.save() res.data = '上传成功' return Response(res.dict)
def get(self, request): # 调用业务数据库的数据进行查看展示 """ 账单详情: [ 账单id:[{ 商品名: 简介: 数量: 价格: 图片: }, { 商品名: 简介: 数量: 价格: 图片: }] 账单ID 创建订单时间: 下单付款时间: 流水号: 付款方式: 实付金额: 收获地址: ] """ res = BaseResponse() user_trades = models.TradeRecord.objects.filter( account=request.user).all() user_orders = models.OrderDetail.objects.filter( order__account=request.user).all().distinct() # 商品数量 trade_menu = {} product_dict = {} for item in user_trades: trade_menu[item.order_id] = { 'user_address': item.user_address, 'use_balance': item.amount, 'pay_date': item.date.strftime("%Y-%m-%d %H:%M:%S") } product_dict = {} for item in user_orders: product_dict[item.order_id] = {} for item in user_orders: product = eval(item.product) product_dict[item.order_id]['id'] = item.order_id product_dict[item.order_id][ 'status'] = item.order.get_assess_status_display() product_dict[item.order_id][item.object_id] = product product_dict[item.order_id][ item.object_id]['real_price'] = item.price for trade in trade_menu: if trade == item.order_id: product_dict[item.order_id]['user_address'] = str( trade_menu[trade]['user_address']) product_dict[item.order_id]['pay_date'] = trade_menu[ trade]['pay_date'] product_dict[item.order_id]['use_balance'] = trade_menu[ trade]['use_balance'] product_dict[ item.order_id]['transaction_number'] = item.transaction_number product_dict[ item.order_id]['create_order_time'] = item.order.date.strftime( "%Y-%m-%d %H:%M:%S") product_dict[item.order_id][ 'pay_time'] = item.order.pay_time.strftime("%Y-%m-%d %H:%M:%S") res.data = product_dict return Response(res.dict)
def post(self, request): res = BaseResponse() # 1、获取数据 user_id = request.user.id balance = int(request.data.get('balance', 0)) price = int(request.data.get('price', '')) # 前端提交的打折后的价格 # 2、校验数据是否合法 # 2.1、校验贝里数是否合法 if balance > request.user.balance: res.code = 1081 res.error = '抵扣的贝里错误' return Response(res.dict) # 2.2、从用户的结算中心拿数据,与数据库存放数据比对 settlement_key = SETTLEMENT_KEY % (user_id,'*') all_keys = CNN.scan_iter(settlement_key) course_total_price = 0 for key in all_keys: settlement_info = CNN.hgetall(key) course_id = settlement_info['id'] course_obj = models.Course.objects.filter(id=course_id).first() # 课程id是否合法 if not course_obj and course_obj.status == 0: res.code = 1082 res.error = '课程id不合法' return Response(res.dict) # 优惠券是否过期 course_coupon_id = settlement_info.get('default_course_coupon_id', 0) course_coupon_dict = None if course_coupon_id: course_coupon_dict = models.Coupon.objects.filter( id=course_coupon_id, couponrecord__status=0, couponrecord__account_id=user_id, object_id = course_id, valid_begin_date__lte=now(), valid_end_date__gte=now(), ).values('coupon_type', 'money_equivalent_value', 'off_percent', 'minimum_consume') if not course_coupon_dict: res.code = 1083 res.error = '课程优惠券不合法' return Response(res.dict) course_price = int(settlement_info['price']) course_rebate_price = self.account_price(course_coupon_dict, 0) if course_rebate_price == -1: res.code = 1085 res.error = '课程优惠券不合法' return Response(res.dict) course_total_price += course_price # 校验全局优惠券 global_coupon_key = GLOBAL_COUPON_KEY % user_id global_coupon_info = CNN.hgetall(global_coupon_key) global_coupon_id = int(global_coupon_info.get('default_global_coupon_id')) if global_coupon_id: global_coupon_dict = models.Coupon.objects.filter( id=global_coupon_id, couponrecord__status=0, couponrecord__account_id=user_id, valid_begin_date__lte=now(), valid_end_date__gte=now(), ).values('coupon_type', 'money_equivalent_value', 'off_percent', 'minimum_consume') if not global_coupon_dict: res.code = 1086 res.error = '全局优惠券不合法' return Response(res.dict) course_rebate_price = self.account_price(global_coupon_dict, course_total_price) if course_rebate_price == -1: res.code = 1087 res.error = '全局优惠券不合法' return Response(res.dict) course_total_price += course_rebate_price # 计算贝里折扣 balance_money = balance / 100 course_total_price -= balance_money # 2.3、校验价格是否合法 if price != course_total_price: res.code = 1088 res.error = '价格不合法' return Response(res.dict) # 3、调用支付接口支付 # 4、支付成功后修改数据库中用户信息 res.data = '支付成功' return Response(res.dict)
def put(self, request): """设置订单中商品的优惠券""" res = BaseResponse() # 获取前端传来的数据 # {"course_id1":{'course':xx,'coupon':xx},"course_id2":{'course':xx,'coupon':xx},global_coupon:''} # 例:{'1': {'course': 1, 'coupon': 5}, '4': {'course': 4, 'coupon': 2}, 'global_coupon': 4} global_coupon_id = request.data.get('global_coupon') request_data = dict(request.data) courses = [] for value in request_data.values(): if isinstance(value, dict): courses.append(value) for course_coupon in courses: course_id = course_coupon.get('course') course_coupon_id = course_coupon.get('coupon') user_id = request.user.pk key = SETTLEMENT_KEY % (user_id, course_id) # 订单数据 global_key = GLOBAL_COUPON_KEY % user_id # 验证数据合法 if course_id: if not CONN.exists(key): res.code = 1080 res.error = '课程id不合法' return Response(res.dict) if course_coupon_id: user_coupon_dict = json.loads( CONN.hget(key, 'course_coupon_dict')) # 先加入结算中心之后又领取优惠券,并选择优惠券购买的情况 if user_coupon_dict == {}: user_coupon_dicts, user_global_coupon_dict = self.put_func( user_id, course_id) CONN.hset( key, 'course_coupon_dict', json.dumps(user_coupon_dicts, ensure_ascii=False)) user_coupon_dict = user_coupon_dicts if user_global_coupon_dict: user_global_coupons = GLOBAL_COUPON_KEY % user_id # 多套了一层,不然redis报错,不能内层直接套一个字典 global_settlement_info = { 'global_course_coupon_dict': json.dumps(user_global_coupon_dict, ensure_ascii=False) } CONN.hmset(user_global_coupons, global_settlement_info) if str(course_coupon_id) not in user_coupon_dict: res.code = 1081 res.error = '课程优惠券id不合法' return Response(res.dict) CONN.hset(key, 'default_coupon_id', course_coupon_id) if global_coupon_id: if not CONN.exists(global_key): res.code = 1082 res.error = '全局优惠券id不合法' return Response(res.dict) CONN.hset(global_key, 'default_global_coupon_id', global_coupon_id) res.data = '已选择优惠券' return Response(res.dict)
def post(self, request): """支付""" res = BaseResponse() # 获取前端传来的数据 # {"balance": 20, "price": 73.1} balance = request.data.get('balance') price = request.data.get('price') user = request.user if balance and int(balance) > request.user.balance: res.code = 1100 res.error = '抵扣贝里失败,贝里余额不足' return Response(res.dict) if price and isinstance(price, str): price = eval(price) # 购买有两种情况,一种直接购买,一种是添加购物车之后购买,已处理好此情况 user_key = SETTLEMENT_KEY % (user.id, "*") user_settlements = CONN.scan_iter(user_key) total_price = 0 # user_coupon_dict = {} # 专项优惠券 # global_coupon_dict = {} # 全局优惠券 global_coupon_key = None for item in user_settlements: settlement_info = CONN.hgetall(item) course_id = str(settlement_info['id']) # 检验课程合法性 course_obj = models.Course.objects.filter(id=course_id).first() if not course_obj and course_obj.state == 2: # 状态2表示课程下架 res.code = 1101 res.error = '课程id不正确,可能已下架' return Response(res.dict) course_coupon_id = int(settlement_info.get('default_coupon_id', 0)) # 有优惠券,检验课程优惠券有效期 # 这里有四个情况: # 1.当前用户本来就没有领取专项优惠券 # 2.当前用户有专项优惠券但和redis里的数据不匹配 # 2.当前用户有专项优惠券但并没有勾选使用优惠券 # 3.正常使用专项优惠券 if course_coupon_id: user_coupon_dict = models.Coupon.objects.filter( id=course_coupon_id, object_id=course_id, start_time__lte=now(), end_time__gte=now(), coupondetail__account=user, coupondetail__status=0).exclude(coupon_type=0).values( 'coupon_type', 'equal_money', 'off_percent', 'minimum_consume').all().distinct() # 优惠券已使用 # 有勾选优惠券,但没有数据库内没有 if course_coupon_id and not user_coupon_dict: res.code = 1102 res.error = '优惠券id不合法' return Response(res.dict) course_db_price = settlement_info['price'] course_count_price = self.counts(user_coupon_dict, course_db_price) if course_count_price == -1: res.code = 1103 res.error = '优惠券不符合使用要求' return Response(res.dict) total_price += course_count_price # 没有优惠券的情况 else: total_price += float(settlement_info['price']) # 全局优惠券 # 有三个情况: # 1.当前用户本来就没有领取全局优惠券 # 2.当前用户有全局优惠券但和redis里的数据不匹配 # 3.正常使用优惠券 # 判断用户是否有优惠券 user_global_coupon = models.CouponDetail.objects.filter( account_id=user.id, coupon__coupon_type=0, status=0).all() # 有全局优惠券,检查优惠券使用场景合法性 if user_global_coupon: global_coupon_key = GLOBAL_COUPON_KEY % user.id # 当前用户有全局优惠券但和redis里的数据不匹配,优惠券不可用,价格默认为之前的值 if not CONN.exists(global_coupon_key): # 报一个警告 res.code = 1104 res.error = '全局优惠券当前不可用' global_count_price = total_price # return Response(res.dict) global_coupon_id = CONN.hget(global_coupon_key, 'default_global_coupon_id') if global_coupon_id: global_coupon_dict = models.Coupon.objects.filter( id=global_coupon_id, start_time__lte=now(), end_time__gte=now(), coupondetail__account_id=user.id, coupondetail__status=0).values('coupon_type', 'equal_money', 'off_percent', 'minimum_consume') if not global_coupon_dict: res.code = 1105 res.error = '全局优惠券不合法' return Response(res.dict) global_count_price = self.counts(global_coupon_dict, total_price) if global_count_price == -1: res.code = 1106 res.error = '全局优惠券不符合使用要求' return Response(res.dict) # 没有全局优惠券,最后的价格就是前面的专项优惠券打折之后的值 else: global_count_price = total_price # 抵扣账户余额金币,按平台换算比例,1:100 balance_equivalent = balance / 100 # balance是前端传来的数据 total_price = global_count_price - balance_equivalent if total_price < 0: total_price = 0 total_price = float('%.2f' % total_price) # 最后的检验 if price != total_price: # price是前端传来的总价格 """ 有个小问题,需要先领券再加入购物车才能使用优惠券,不然就会走这里""" print(total_price, type(total_price)) print(price, type(price)) # 说明前端传来的数据不正确 res.code = 1107 res.error = '操作失败,数据可能被篡改' return Response(res.dict) # 调用支付接口 res.data = '付款成功' # ########## 更新业务数据库里的数据 ############# # 删掉redis结算中心里的数据 # 这里又要再取一次才能删除 user_key = SETTLEMENT_KEY % (user.id, "*") user_settlements = CONN.scan_iter(user_key) # 把课程数据从redis里删除并存入交易表中 product = [] for item in user_settlements: product.append(CONN.hgetall(item)) CONN.delete(item) if global_coupon_key: CONN.delete(global_coupon_key) # 此处不用判断是否有优惠券,redis删除,如果没有值不会报错 # 更新数据库信息 user_obj = models.Account.objects.filter(id=user.id) user_obj.update(balance=F('balance') - balance) # 修改优惠券使用状态 models.CouponDetail.objects.filter( account_id=user.id, coupon__coupon_type=0).update(status=1) # 修改优惠券使用状态 models.CouponDetail.objects.filter( account_id=user.id, coupon__coupon_type__in=[1, 2]).update(status=1, use_time=now()) # 用余额交易 models.TradeRecord.objects.create( account_id=user.id, amount=balance, balance=user_obj.first().balance, ) # 用其他方式交易 # 获取交易类型 order_obj = models.Order.objects.create(payment_type=0, account_id=user.id, payment_amount=total_price, status=0, pay_time=now()) # 买了课程就是申请状态的学生了,如果已经买过课程的学生直接查询获取 student_obj = models.Student.objects.filter( account=user_obj.first()).first() if not student_obj: student_obj = models.Student.objects.create( account=user_obj.first()) for item in product: pay_course_obj = models.Course.objects.filter( id=item['id']).first() # 加入到缴费申请表 models.PaymentRecord.objects.create(account=user_obj.first(), paid_fee=total_price, course=pay_course_obj) # 购买的用户信息链接到学生表里 student_obj.courses.add(pay_course_obj) course_coupon_dict = json.loads(item['course_coupon_dict']) price = float('%.2f' % float(item['price'])) # 不失真的转为浮点型数据,并取两位小数 """这里会创建多条重复数据""" # 如果有优惠券 if len(course_coupon_dict) != 0: for key, value in course_coupon_dict.items(): real_price = price - value['equal_money'] models.OrderDetail.objects.create( order=order_obj, original_price=item['price'], price=real_price, transaction_type=1, transaction_number='pay' + str(time.time()), valid_period=item['valid_period'], content_object=pay_course_obj, product=item) # 没有优惠券 else: models.OrderDetail.objects.create( order=order_obj, original_price=item['price'], price=price, transaction_type=1, transaction_number='pay' + str(time.time()), valid_period=item['valid_period'], content_object=pay_course_obj, product=item) return Response(res.dict)