lf 前后端分离 (5) 优惠券

关于优惠券

优惠券主要通过前端传回来的course_id_list 创建数据结构

首先清空操作,将所有的优惠券清空,

并将所有优惠劵放到redis中的过程

 

  1 import datetime
  2 import json
  3 import redis
  4 
  5 REDIS_CONN = redis.Redis(decode_responses=True)
  6 
  7 from rest_framework.views import APIView
  8 from rest_framework.response import Response
  9 
 10 from app01.models import *
 11 from app01.utils.auth import LoginAuth
 12 from app01.utils.response import BaseResponse
 13 from app01.utils.exception import CommonException
 14 
 15 from django.core.exceptions import ObjectDoesNotExist
 16 from django.conf import settings
 17 
 18 
 19 class AccountView(APIView):
 20     authentication_classes = [LoginAuth]
 21 
 22     def get_coupon_dict(self, request, course_id=None):
 23         now = datetime.datetime.now()
 24         coupon_record_list = CouponRecord.objects.filter(
 25             account=request.user,
 26             coupon__content_type=9,
 27             coupon__object_id=course_id,
 28             status=0,
 29             coupon__valid_begin_date__lte=now,
 30             coupon__valid_end_date__gte=now
 31         )
 32         coupons = {}
 33 
 34         for coupon_record in coupon_record_list:
 35             coupons[coupon_record.pk] = {
 36 
 37                 "pk": coupon_record.pk,
 38                 "name": coupon_record.coupon.name,
 39                 "coupon_type": coupon_record.coupon.get_coupon_type_display(),
 40                 "money_equivalent_value": coupon_record.coupon.money_equivalent_value,
 41                 "off_percent": coupon_record.coupon.off_percent,
 42                 "minimum_consume": coupon_record.coupon.minimum_consume,
 43                 "valid_begin_date": coupon_record.coupon.valid_begin_date.strftime("%Y-%m-%d"),
 44                 "valid_end_date": coupon_record.coupon.valid_end_date.strftime("%Y-%m-%d"),
 45             }
 46         print("coupons", coupons)
 47 
 48         return coupons
 49 
 50     def post(self, request, *args, **kwargs):
 51         # 1 获取数据
 52         user = request.user
 53         course_id_list = request.data.get("course_id_list")
 54         response = BaseResponse()
 55         try:
 56             # 2 创建数据结构
 57             # 清空操作
 58             # 找到所有以account_userid_*,全部清空
 59             del_list = REDIS_CONN.keys(settings.ACCOUNT_KEY % (user.pk, "*"))
 60             if del_list:
 61                 REDIS_CONN.delete(*del_list)
 62 
 63             price_list = []
 64             for course_id in course_id_list:
 65 
 66                 account_key = settings.ACCOUNT_KEY % (user.pk, course_id)
 67                 account_dict = {}
 68                 shopping_car_key = settings.SHOPPING_CAR_KEY % (user.pk, course_id)
 69 
 70                 # 判断课程是否存在购物车中
 71                 if not REDIS_CONN.exists(shopping_car_key):
 72                     raise CommonException("购物车不存在该课程", 1040)
 73 
 74                 # 将课程信息加入到每一个课程结算字典中
 75                 course_info = json.loads(REDIS_CONN.get(shopping_car_key))
 76                 account_dict["course_info"] = course_info
 77 
 78                 # 课程价格加入到价格列表
 79                 price_list.append(float(course_info["default_price"]))
 80 
 81                 # 查询当前用户拥有未使用的,在有效期的且与当前课程相关的优惠券
 82                 account_dict["course_coupons"] = self.get_coupon_dict(request, course_id)
 83 
 84                 # 存储结算信息
 85                 REDIS_CONN.set(account_key, json.dumps(account_dict))
 86 
 87                 print("account_dict",account_dict)
 88 
 89             # 获取通用优惠券,加入redis中
 90 
 91             REDIS_CONN.set("global_coupon_%s" % user.pk, json.dumps(self.get_coupon_dict(request)))
 92             REDIS_CONN.set("total_price", sum(price_list))
 93 
 94         except CommonException as e:
 95             response.code = e.code
 96             response.msg = e.msg
 97 
 98         except ObjectDoesNotExist as e:
 99             response.code = 1001
100             response.msg = "课程不存下"
101 
102         return Response(response.dict)
103 
104     def get(self, request, *args, **kwargs):
105 
106         res = BaseResponse()
107         try:
108             # 1 取到user_id
109             user_id = request.user.id
110             # 2 拼接购物车的key
111             account_key = settings.ACCOUNT_KEY % (user_id, "*")
112             # shopping_car_1_*
113             # shopping_car_1_asdgnlaksdj
114             # 3 去redis读取该用户的所有加入购物车的课程
115             # 3.1 先去模糊匹配出所有符合要求的key
116             all_keys = REDIS_CONN.scan_iter(account_key)
117 
118             # 3.2 循环所有的keys 得到每个可以
119             account_course_list = []
120             for key in all_keys:
121 
122                 course = json.loads(REDIS_CONN.get(key))
123                 temp = {}
124                 for key, val in course["course_info"].items():
125                     temp[key] = val
126                 coupon_list = []
127                 for key, val in course["course_coupons"].items():
128                     val["pk"] = key
129                     coupon_list.append(val)
130                 temp["coupon_list"] = coupon_list
131 
132                 account_course_list.append(temp)
133 
134             global_coupons_dict = json.loads(REDIS_CONN.get("global_coupon_%s" % request.user.pk))
135             total_price = REDIS_CONN.get("total_price")
136             global_coupons = []
137             for key, val in global_coupons_dict.items():
138                 global_coupons.append(val)
139             res.data = {
140                 "account_course_list": account_course_list,
141                 "total": len(account_course_list),
142                 "global_coupons": global_coupons,
143                 "total_price": total_price
144             }
145 
146         except Exception as e:
147             res.code = 1033
148             res.error = "获取购物车失败"
149 
150         return Response(res.dict)
151 
152 
153     def cal_coupon_price(self,price,coupon_info):
154 
155         coupon_type=coupon_info["coupon_type"]
156         money_equivalent_value=coupon_info.get("money_equivalent_value")
157         off_percent=coupon_info.get("off_percent")
158         minimum_consume=coupon_info.get("minimum_consume")
159         rebate_price=0
160         if coupon_type == "立减券": # 立减券
161             rebate_price=price-money_equivalent_value
162             if rebate_price <= 0:
163                 rebate_price=0
164         elif coupon_type == "满减券": # 满减券
165              if minimum_consume > price:
166                  raise CommonException(3000,"优惠券未达到最低消费")
167              else:
168                  rebate_price=price-money_equivalent_value
169         elif coupon_type == "折扣券":
170             print("VVVV",price,off_percent)
171             rebate_price=price*off_percent/100
172 
173         return rebate_price
174 
175     def put(self,request, *args, **kwargs):
176         '''
177         choose_coupons:
178             {
179             choose_coupons={"1":"2","2":"3","global_coupon_id":5}
180             is_beli:true
181             }
182         '''
183         res=BaseResponse()
184         try:
185 
186             # 1 获取数据
187             choose_coupons=request.data.get("choose_coupons")
188             is_beli=request.data.get("is_beli")
189             user_pk=request.user.pk
190 
191             # 2 获取结算课程列表
192             cal_price={}
193             data=self.get(request).data.get("data")
194             account_course_list=data.get("account_course_list")
195             account_course_info={}
196             for account_course in account_course_list:
197                 temp={
198                     "coupons":{},
199                     "default_price":account_course["default_price"]
200                 }
201                 account_course_info[account_course["id"]]=temp
202 
203                 for item in account_course["coupon_list"]:
204                     temp["coupons"][item["pk"]]=item
205 
206             print("account_course_info",account_course_info)
207 
208             price_list=[]
209             total_price=0
210             for key,val in account_course_info.items():
211                 if str(key) not in choose_coupons:
212                     price_list.append(val["default_price"])
213                     cal_price[key]=val["default_price"]
214                 else:
215                     coupon_info=val.get("coupons").get(str(choose_coupons[str(key)]))
216                     rebate_price=self.cal_coupon_price(val["default_price"],coupon_info)
217                     price_list.append(rebate_price)
218                     cal_price[key]=rebate_price
219 
220             print("课程优惠券后价格列表price_list",price_list)
221             total_price=sum(price_list)
222             # 3 计算通用优惠券的价格
223             global_coupon_id=choose_coupons.get("global_coupon_id")
224             if global_coupon_id:
225 
226                 global_coupons=data.get("global_coupons")
227                 print("global_coupons",global_coupons)
228                 global_coupon_dict={}
229                 for item in global_coupons:
230                     global_coupon_dict[item["pk"]]=item
231 
232                 total_price=self.cal_coupon_price(total_price,global_coupon_dict[global_coupon_id])
233                 print("通用优惠券",global_coupon_dict[global_coupon_id]["coupon_type"])
234                 print("计算后total_price=",total_price)
235 
236             # 计算贝里
237             if json.loads(is_beli):
238                 total_price=total_price-request.user.beli/10
239                 if total_price<0:
240                     total_price=0
241                 print("贝里数计算后",total_price)
242 
243             #res.total_price=total_price
244             cal_price["total_price"]=total_price
245             res.data=cal_price
246 
247         except Exception as e:
248             res.code=500
249             res.msg="结算错误!"+str(e)
250 
251         return Response(res.dict)
优惠券

 

posted @ 2018-12-20 11:21  逆欢  阅读(240)  评论(0编辑  收藏  举报