def receive_coupon(request): """领取优惠券""" coupon_id = request.data.get('id') if not coupon_id: raise ValidateException().add_message('error:error', 'Incomplete Params!') coupon = Coupon.objects.filter(id=coupon_id).first() if not coupon: raise ValidateException().add_message('error:error', 'Incomplete Params!') user = request.auth['user_id'] MyCoupon.objects.get_or_create(user_id=user, coupon_id=coupon_id) data = CouponSerializer(coupon, context={"request": request}).data return Response(data)
def get(self, request): commodity_id = request.query_params.get("id") if not commodity_id: raise ValidateException().add_message( 'error:error', 'Incomplete Params commodity!') commodity = Commodity.objects.filter(delete_status=0, id=commodity_id) if not commodity: raise ValidateException().add_message('error:error', 'commodity non-existent!') data = CommoditySerializer(commodity[0], context={ "request": request }).data return Response(data)
def set_default_addr(request): """设为默认收货地址""" addr_id = request.data.get('id') if not addr_id: raise ValidateException().add_message('error:error', 'Incomplete Params!') user = request.auth['user_id'] addr = ShippingAddr.objects.filter(delete_status=0, user_id=user, id=addr_id) if not addr: raise ValidateException().add_message('error:error', 'Addr Id Error!') with transaction.atomic(): ShippingAddr.objects.filter(delete_status=0, user_id=user, default=True).update(default=False) addr.update(default=True) return Response("success")
def post(self, request): code = request.data.get("code") if not code: raise ValidateException().add_message('error:param', 'Incomplete Params!') params = { 'appid': settings.WEAAPP_KEY, 'secret': settings.WEAAPP_SECRET, 'js_code': code, 'grant_type': 'authorization_code', } data = requests.post(self.URL, data=params, timeout=600) json_data = data.json() openid = json_data.get('openid') if not openid: raise LogicException('error:error', 'Getting openid exceptions!') unionid = json_data.get('unionid') print(json_data) # 获取用户ip if 'HTTP_X_FORWARDED_FOR' in request.META: user_ip = request.META['HTTP_X_FORWARDED_FOR'] else: user_ip = request.META['REMOTE_ADDR'] user, _created = MyUser.objects.get_or_create(openid=openid, defaults={ 'unionid': unionid, 'provider': 'Wechat', 'user_lastip': user_ip, }) user.last_login = datetime.datetime.today() if _created: # 首次授权登陆,注册,记录登陆ip user.set_password(openid) user.user_regip = user_ip user.save() else: user.user_lastip = user_ip user.save() # 手动签发jwt jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user) token = jwt_encode_handler(payload) result = { 'data': { 'openid': openid, 'unionid': unionid, 'nick_name': user.nick_name, 'pic': user.pic, 'user_status': user.is_active, 'access_token': token, } } return Response(result)
def file_download(request): file_name = request.query_params.get('file_name') if not file_name: raise ValidateException().add_message("error:params error", "缺少文件名") file_path = os.path.join(settings.MEDIA_ROOT, file_name) if not os.path.exists(file_path): raise ValidateException().add_message("error:file not found", "未找到对应文件") file_info = FileUpload.objects.filter(file=file_name).first() if file_info: file_name = file_info.file_name # fw = FileWrapper(open(file_path, 'rb')) response = FileResponse(open(file_path, 'rb'), as_attachment=True, filename=file_name) return response
def put(self, request): update_data = request.data addr_id = update_data.pop('id') if not all((addr_id, update_data)): raise ValidateException().add_message('error:error', 'Incomplete Params!') user = request.auth['user_id'] addr = ShippingAddr.objects.filter(delete_status=0, user_id=user, id=addr_id) with transaction.atomic(): addr.update(**update_data) data = ShippingAddrSerializer(addr.first()).data return Response(data)
def commodity_collect(request): """商品(取消)收藏""" commodity_id = request.data.get("id") if not commodity_id: raise ValidateException().add_message('error:error', 'Incomplete Params commodity!') commodity = Commodity.objects.filter(delete_status=0, id=commodity_id).first() if not commodity: raise ValidateException().add_message('error:error', 'commodity non-existent!') user = request.auth['user_id'] obj, _created = CommodityCollect.objects.get_or_create( user_id=user, commodity=commodity, ) if not _created: obj.delete_status = not obj.delete_status obj.save() return Response(not obj.delete_status)
def delete(self, request): """购物车删除""" items = request.data.get("items") if not items: raise ValidateException().add_message('error:error', 'Incomplete Params!') user = request.auth['user_id'] with transaction.atomic(): for item in items: shopping = ShoppingCart.objects.filter( user_id=user, commodity_id=item["prodId"], specification_id=item["skuId"]) shopping.update(delete_status=1, count=0) return Response('success')
def delete(self, request): addr_id = request.data.get('id') if not addr_id: raise ValidateException().add_message('error:error', 'Incomplete Params!') user = request.auth['user_id'] addr = ShippingAddr.objects.filter(delete_status=0, user_id=user, id=addr_id) addr.update(delete_status=1) addr = ShippingAddr.objects.filter(delete_status=0, user_id=user).first() if addr: addr.default = True addr.save() return Response('success')
def post(self, request): """购物车改数量""" commodity_id = request.data.get("prodId") specification_id = request.data.get("skuId") count = request.data.get("count") if not all((commodity_id, count)): raise ValidateException().add_message('error:error', 'Incomplete Params!') user = request.auth['user_id'] shopping = ShoppingCart.objects.filter( user_id=user, commodity_id=commodity_id, specification_id=specification_id) with transaction.atomic(): shopping.update(count=count) return Response('success')
def put(self, request): user_info = request.data.get('user_info') if not user_info: raise ValidateException().add_message('error:error', 'Incomplete Params!') user_id = request.auth.get('user_id') nick_name = user_info.get('nickName') pic = user_info.get('avatarUrl') sex = user_info.get('gender') MyUser.objects.filter(id=user_id).update( nick_name=nick_name, pic=pic, sex=sex, ) return Response('success')
def put(self, request): """加入购物车""" commodity_id = request.data.get("prodId") specification_id = request.data.get("skuId") count = request.data.get("count") if not all((commodity_id, count)): raise ValidateException().add_message('error:error', 'Incomplete Params!') user = request.auth['user_id'] shopping = ShoppingCart.objects.filter( user_id=user, commodity_id=commodity_id, specification_id=specification_id) if shopping: shopping.update(count=F("count")+count, delete_status=0) else: ShoppingCart.objects.create( user_id=user, commodity_id=commodity_id, specification_id=specification_id, count=count) return Response('success')
def confirm(request): """获取订单确认信息""" data = request.data addr_id = data.get("addrId") order_item = data.get("orderItem") baskets = data.get("basketIds") coupon_id = data.get("couponId") user = request.auth['user_id'] prod_items = [] if order_item: commodity = Commodity.objects.filter(delete_status=0, id=order_item['prodId']).first() if not commodity: raise ValidateException().add_message('error:error', '此商品已下架!') if order_item['skuId']: specification = Specification.objects.filter(id=order_item['skuId'], commodity=commodity).first() if specification.stocks < order_item["prodCount"]: raise ValidateException().add_message('error:error', '抱歉,商品库存不足!') pic = specification.pic specification_name = specification.name price = specification.price else: if commodity.total_stocks < order_item["prodCount"]: raise ValidateException().add_message('error:error', '抱歉,商品库存不足!') pic = commodity.pic specification_name = " " price = commodity.price prod = { "prodId": order_item['prodId'], "skuId": order_item['skuId'], "name": commodity.name, "pic": pic, "specification": specification_name, "price": "%.2f" % price, "count": order_item["prodCount"], } prod_items.append(prod) elif baskets: for item in baskets: commodity = Commodity.objects.filter(delete_status=0, id=item['prodId']).first() if not commodity: raise ValidateException().add_message('error:error', '含有已下架商品!') if item['skuId']: specification = Specification.objects.filter(id=item['skuId'], commodity=commodity).first() if specification.stocks < item["prodCount"]: raise ValidateException().add_message('error:error', '抱歉,商品【{}】库存不足!'.format(commodity.name)) pic = specification.pic specification_name = specification.name price = specification.price else: if commodity.total_stocks < item["prodCount"]: raise ValidateException().add_message('error:error', '抱歉,商品【{}】库存不足!'.format(commodity.name)) pic = commodity.pic specification_name = " " price = commodity.price prod = { "prodId": item['prodId'], "skuId": item['skuId'], "name": commodity.name, "pic": pic, "specification": specification_name, "price": "%.2f" % price, "count": item["prodCount"], } prod_items.append(prod) else: raise ValidateException().add_message('error:error', 'Incomplete Params!') # 地址 if addr_id: shipping_addr = ShippingAddr.objects.get(id=addr_id) addr = None else: shipping_addr = ShippingAddr.objects.filter(delete_status=0, user_id=user, default=True).first() addr = ShippingAddrSerializer(shipping_addr).data if shipping_addr else None province_id = shipping_addr.province_id if shipping_addr else None # TODO 运费计算 freight = Decimal() for item in prod_items: commodity = Commodity.objects.filter(delete_status=0, id=item['prodId']).first() if commodity.is_free_fee: continue freight_template = commodity.freight_template if freight_template.charge_type == 0: if item["count"] >= freight_template.piece: continue else: freight += freight_template.freight elif freight_template.charge_type == 1: if item["count"] * float(item["price"]) >= freight_template.amount: continue else: freight += freight_template.freight elif freight_template.charge_type == 2: if item["count"] >= freight_template.piece or item["count"] * float(item["price"]) >= freight_template.amount: continue else: freight += freight_template.freight elif freight_template.charge_type == 3: if province_id in eval(freight_template.area_list): continue else: freight += freight_template.freight # 最终计算 count = sum([x["count"] for x in prod_items]) prod_total = Decimal(sum([x["count"] * float(x["price"]) for x in prod_items])) # TODO 优惠券 my_coupons = MyCoupon.objects.filter(user_id=user, used=False, delete_status=0) now_date = datetime.now().date() prod_id_list = [x['prodId'] for x in prod_items] available, unavailable = [], [] for my_coupon in my_coupons: if my_coupon.coupon.min_data <= now_date < my_coupon.coupon.max_data and \ ((my_coupon.coupon.type == 2 and my_coupon.coupon.commodity.get().id in prod_id_list and my_coupon.coupon.condition <= sum([x["count"] * float(x["price"]) for x in prod_items if x['prodId'] == my_coupon.coupon.commodity.get().id])) or (my_coupon.coupon.type == 1 and my_coupon.coupon.condition <= prod_total)): available.append({ 'id': my_coupon.coupon_id, 'type': my_coupon.coupon.type, 'amount': my_coupon.coupon.amount, 'condition': my_coupon.coupon.condition, 'min_data': my_coupon.coupon.min_data, 'max_data': my_coupon.coupon.max_data, 'choose': False, }) else: unavailable.append({ 'id': my_coupon.coupon_id, 'type': my_coupon.coupon.type, 'amount': my_coupon.coupon.amount, 'condition': my_coupon.coupon.condition, 'min_data': my_coupon.coupon.min_data, 'max_data': my_coupon.coupon.max_data, }) coupon = { "available": available, "unavailable": unavailable, "count": len(available) + len(unavailable) } discounted_price = Decimal() if coupon_id: discounted_coupons = my_coupons.filter(coupon_id=coupon_id).first() if not discounted_coupons and coupon_id not in [x['id'] for x in available]: raise ValidateException().add_message('error:error', 'Params Error!') for x in coupon["available"]: if x['id'] == coupon_id: x['choose'] = True discounted_price = discounted_coupons.coupon.amount # 将预定确认订单存缓存,方便确认订单接口直接获取 order_uuid = 'ORDER_{}'.format(uuid.uuid1()) if addr_id: order_data = { 'order': { 'user_id': user, 'user_addr_id': addr_id, 'price': prod_total + freight - discounted_price, 'coupon_id': coupon_id, 'reduce_amount': discounted_price, 'product_nums': count, 'freight_amount': freight, }, 'order_item': [{ 'commodity_id': x['prodId'], 'specification_id': x['skuId'], 'count': x['count'], } for x in prod_items] } cache.set(order_uuid, order_data, 60 * 10) data = { "addr": addr, 'prodItems': prod_items, "count": count, "prod_total": "%.2f" % prod_total, "coupon": coupon, "freight": "%.2f" % freight, "discounted_price": "%.2f" % discounted_price, "total": "%.2f" % (prod_total + freight - discounted_price), 'order_uuid': order_uuid } return Response(data)