def cat_set(): if request.method == "GET": id = get_int(request.args, "id", 0) if id > 0: cat_info = FoodCat.query.filter_by(id=id).first() if cat_info is None: return make_response(redirect(build_url("/food/cat"))) else: cat_info = None return render_template_with_global_vars("food/cat_set.html", context={"cat": cat_info}) elif request.method == "POST": id = get_int(request.form, "id", 0) if id > 0: cat_info = FoodCat.query.filter_by(id=id).first() if cat_info is None: return json_error_response("无效的食品类别编辑操作") else: cat_info = None name = request.form.get("name", "") weight = int(request.form.get("weight", "0")) if len(name) < 1: return json_error_response("食品类别名称不能为空!") if weight < 1 or weight > 4: return json_error_response("食品类别的权重必须在1-4之间!(含1和4)") if cat_info is None: cat_info = FoodCat() cat_info.created_time = get_current_time() cat_info.status = 1 cat_info.name = name cat_info.weight = weight cat_info.updated_time = get_current_time() db.session.add(cat_info) db.session.commit() return json_response("修改食品类别信息成功!")
def edit(): if request.method == "GET": return render_template_with_global_vars("user/edit.html") elif request.method == "POST": nickname = request.form["nickname"] if "nickname" in request.form else "" email = request.form["email"] if "email" in request.form else "" if "current_user" not in g or g.current_user is None: return json_error_response("您还没有登录,不能更改个人信息!") if len(nickname) < 1 or len(email) < 1: return json_error_response("您的姓名或邮箱不能为空!") user_info = g.current_user user_info.nickname = nickname user_info.email = email db.session.add(user_info) db.session.commit() res_data = {"nickname": nickname, "email": email} return json_response(msg="账号个人信息编辑成功!", data=res_data)
def my_order_info(): order_sn = request.values.get("order_sn", "") if not order_sn: return json_error_response("查询订单信息错误,请稍后再试(1)") pay_order_info = PayOrder.query.filter_by(order_sn=order_sn).first() if not pay_order_info: return json_error_response("查询订单信息错误,请稍后再试(2)") pay_wait_time = app.config["PAY_WAIT_TIME"] deadline = pay_order_info.created_time + datetime.timedelta(minutes=pay_wait_time) address_info = json.loads(pay_order_info.deliver_info) data = { "order_sn": pay_order_info.order_sn, "status": pay_order_info.pay_status, "status_desc": pay_order_info.pay_status_desc, "deadline": deadline.strftime("%Y-%m-%d %H:%M"), "address": address_info, "base_price": str(pay_order_info.base_price), "shipping_price": str(pay_order_info.shipping_price), "total_price": str(pay_order_info.total_price), } # "poi" short for "PayOrderItem" poi_and_food_list = db.session.query(PayOrderItem, Food).filter( PayOrderItem.pay_order_id == pay_order_info.id, PayOrderItem.food_id == Food.id ) goods = [{ "pic_url": build_image_url(food.main_image), "name": food.name, "price": str(poi.price), "unit": poi.quantity } for poi, food in poi_and_food_list] data["goods"] = goods return json_response(data=data)
def my_comment_add(): member_id = g.current_member.id order_sn = request.form.get("order_sn", None) if not order_sn: return json_error_response("评价操作失败(1)") pay_order_info = PayOrder.query.filter_by(member_id=member_id, order_sn=order_sn).first() if not pay_order_info: return json_error_response("评价操作失败(2)") if pay_order_info.comment_status: return json_error_response("已经评价过了,请勿重复评价") pay_order_items = PayOrderItem.query.filter_by(pay_order_id=pay_order_info.id).all() food_ids = "_".join(str(item.food_id) for item in pay_order_items) score = utils.get_int(request.form, "score", 10) content = request.form.get("content", "") comment_info = MemberComment() comment_info.member_id = member_id comment_info.food_ids = "_" + food_ids + "_" comment_info.pay_order_id = pay_order_info.id comment_info.score = score comment_info.content = content comment_info.created_time = utils.get_current_time() db.session.add(comment_info) db.session.commit() pay_order_info.comment_status = 1 pay_order_info.updated_time = utils.get_current_time() db.session.add(pay_order_info) db.session.commit() return json_response()
def api_member_auth(): pattern = re.compile("^/api") if not pattern.match(request.path): return pattern = re.compile("|".join(app.config["IGNORE_API_AUTH_URLS"])) if pattern.match(request.path): return g.current_member = check_api_login() if g.current_member: app.logger.info( "[%s - api_member_auth()] User is logged in by checking cookies" % request.path) else: app.logger.info("[%s - api_member_auth()] User is not yet logged in " % request.path) return json_error_response("用户未登录!")
def comment(): id = get_int(request.args, "id", 0) if id == 0: return json_error_response("无法获取评价信息(1)") comment_member_list = db.session.query(MemberComment, Member)\ .filter(MemberComment.member_id == Member.id, MemberComment.food_ids.ilike("%_{0}_%".format(id))).all() res_list = [{ "date": str(comment.created_time), "user_avatar_url": member.avatar, "content": comment.content, "score": comment.score_desc } for comment, member in comment_member_list] return json_response(data={"list":res_list})
def my_address_get(): address_id = utils.get_int(request.values, "id", 0) address_info = MemberAddress.query.filter_by(id=address_id).first() if not address_info: return json_error_response("无法获取地址信息") prov_idx, city_idx, distr_idx = \ utils.get_addr_idxs(address_info.province_id, address_info.city_id, address_info.district_id) data = { "contact_name": address_info.contact_name, "mobile": address_info.mobile, "province_name": address_info.province_str, "city_name": address_info.city_str, "district_name": address_info.district_str, "province_idx": prov_idx, "city_idx": city_idx, "distr_idx": distr_idx, "address": address_info.address } return json_response(data=data)
def order_callback_dev(): """ Dev mode handling """ if not app.config["DEV_MODE"]: return json_error_response("操作有误!") xml_data = request.form.get("xml", None) callback_data = wc_utils.xml_to_dict(xml_data) sign = callback_data.pop("sign") check_sign = wc_utils.create_sign(callback_data) if sign != check_sign: return json_error_response("操作有误(1)") order_sn = callback_data["out_trade_no"] pay_order_info = PayOrder.query.filter_by(order_sn=order_sn).first() if pay_order_info is None: return json_error_response("操作有误(2)") if int(pay_order_info.total_price * 100) != int( callback_data["total_fee"]): return json_error_response("操作有误(3)") if pay_order_info.status == 1: return json_error_response("操作有误(4)") # callback succeeded, modify records and states in database # tables affected: PayOrder, PayOrderCallbackData, FoodSaleChangeLog pay_sn = callback_data["transaction_id"] res = pay_utils.order_success(pay_order_id=pay_order_info.id, pay_sn=pay_sn) if not res: return json_error_response("操作有误(5)") # add record of this successful transaction to database pay_utils.add_pay_callback_data(pay_order_id=pay_order_info.id, data=xml_data) # pass raw form of data return json_response("【开发模式】付款成功,信息已录入数据库")
def set(): if request.method == "GET": cat_list = FoodCat.query.all() id = get_int(request.args, "id", 0) food_info = Food.query.filter_by(id=id).first() if (id > 0 and food_info is None) or (food_info is not None and food_info.status != 1): return redirect(build_url("/food/index")) ctx = {"food": food_info, "cat_list": cat_list} return render_template_with_global_vars("food/set.html", context=ctx) elif request.method == "POST": id = get_int(request.form, "id", 0) cat_id = get_int(request.form, "cat_id", 0) name = request.form.get("name", "") price = request.form.get("price", "") title_pic = request.form.get("title_pic", "") summary = request.form.get("summary", "") stock = get_int(request.form, "stock", 0) tags = request.form.get("tags", "") # form content verification if cat_id == 0: return json_error_response("请选择类别") empty_items = [] for var, item in zip([name, price, title_pic, summary, tags], ["菜品名称", "菜品价格", "封面图", "描述", "标签"]): if len(var) < 1: empty_items.append(item) if len(empty_items) > 0: return json_error_response("以下内容不能为空:" + "、".join(empty_items)) price = Decimal(price).quantize(Decimal("0.00")) if price <= 0: return json_error_response("售卖价格不能小于或者等于0") # create new entry in Food table food_info = Food.query.filter_by(id=id).first() before_stock = 0 if food_info: before_stock = food_info.stock else: food_info = Food() food_info.status = 1 food_info.created_time = get_current_time() food_info.cat_id = cat_id food_info.name = name food_info.price = price food_info.main_image = title_pic food_info.summary = summary food_info.stock = stock food_info.tags = tags food_info.updated_time = get_current_time() db.session.add(food_info) db.session.commit() # add entry into food stock change log if not set_food_stock_change_log(food_info.id, int(before_stock), int(stock) - int(before_stock), "后台直接更改"): return json_error_response("登记库存变更信息出现错误") return json_response("成功添加菜品 %s" % name)
def set(): default_pwd = "******" if request.method == "GET": # pass user info into template to fill in values of html form uid = request.args["uid"] if "uid" in request.args else None user_info = User.query.filter_by(uid=uid).first() if uid else None ctx = {"user": user_info, "default_pwd": default_pwd} return render_template_with_global_vars("account/set.html", context=ctx) elif request.method == "POST": # obtain info from form uid = int(request.form["uid"]) if "uid" in request.form else 0 username = request.form[ "login_name"] if "login_name" in request.form else "" pwd = request.form["login_pwd"] if "login_pwd" in request.form else "" nickname = request.form[ "nickname"] if "nickname" in request.form else "" mobile = request.form["mobile"] if "mobile" in request.form else "" email = request.form["email"] if "email" in request.form else "" app.logger.debug("setting info for uid %d, new username %s, pwd %s" % (uid, username, pwd)) # validate form elements if len(nickname) < 1 or len(email) < 1 or len(mobile) < 1: empty_items = [] if len(nickname) < 1: empty_items.append("姓名") if len(mobile) < 1: empty_items.append("手机") if len(email) < 1: empty_items.append("邮箱") if len(username) < 1: empty_items.append("登录名") if len(pwd) < 1: empty_items.append("登录密码") msg = "以下内容不能为空:" + "、".join(empty_items) return json_error_response(msg) if len(pwd) < 6 and uid == 0: return json_error_response("您的密码不能短于6个字符!") user_info = User.query.filter(User.login_name == username, User.uid != uid).first() if user_info: return json_error_response("该用户名已被使用,请使用别的用户名!") user_info = User.query.filter_by(uid=uid).first() app.logger.debug("uid %d user_info %s" % (uid, user_info)) new_user = False if user_info is None: new_user = True user_info = User() user_info.login_salt = generate_salt() user_info.created_time = get_current_time() user_info.login_name = username user_info.nickname = nickname user_info.mobile = mobile user_info.email = email user_info.updated_time = get_current_time() # edit password when it is not default value "*****" (see set.html) if pwd != default_pwd: user_info.login_pwd = generate_salted_pwd(pwd, user_info.login_salt) db.session.add(user_info) db.session.commit() return json_response("账号个人信息编辑成功!", data={})
def my_order(): member_id = g.current_member.id status = utils.get_int(request.form, "status", None) if status is None: return json_error_response("查询订单信息失败,请注明订单状态") pay_order_query = PayOrder.query.filter_by(member_id=member_id) if status == -8: #待付款 pay_order_query = pay_order_query.filter(PayOrder.status == -8) elif status == -7: #待付款 pay_order_query = pay_order_query.filter(PayOrder.status == 1, PayOrder.deliver_status == -7) elif status == -6: #待确认 pay_order_query = pay_order_query.filter(PayOrder.status == 1, PayOrder.deliver_status == -6) elif status == -5: #待评价 pay_order_query = pay_order_query.filter(PayOrder.status == 1, PayOrder.deliver_status == 1, PayOrder.comment_status == 0) elif status == 1: #已完成 pay_order_query = pay_order_query.filter(PayOrder.status == 1, PayOrder.deliver_status == 1, PayOrder.comment_status == 1) elif status == 0: #未完成 pay_order_query = pay_order_query.filter(PayOrder.status.in_([0, -1, -2, -9])) else: return json_error_response("查询订单信息失败,订单状态有误") # TODO: use table join method to retrieve data pay_order_list = pay_order_query.order_by(PayOrder.id.desc()).all() pay_order_data_list = [] if pay_order_list: pay_order_ids = [pay_order.id for pay_order in pay_order_list] pay_order_items_list = PayOrderItem.query.filter(PayOrderItem.pay_order_id.in_(pay_order_ids)) food_ids = [item.food_id for item in pay_order_items_list] fid_to_info = utils.get_id_to_model_dict(Food, "id", Food.id, food_ids) oid_to_items = {} for item in pay_order_items_list: oid = item.pay_order_id fid = item.food_id if oid not in oid_to_items: oid_to_items[oid] = [] food_info = fid_to_info[fid] oid_to_items[oid].append({ "pay_order_item_id": item.id, "food_id": fid, "quantity": item.quantity, "pic_url": build_image_url(food_info.main_image), "name": food_info.name }) pay_order_data_list = [{ "status": order.pay_status, "status_desc": order.pay_status_desc, "date": order.created_time.strftime("%Y-%m-%d %H:%M:%S"), "order_number": order.order_number, "order_sn": order.order_sn, "note": order.note, "total_price": str(order.total_price), "goods_list": oid_to_items[order.id] } for order in pay_order_list] data = {"pay_order_list": pay_order_data_list} return json_response(data=data)
def order_pay(): member_info = g.current_member order_sn = request.form.get("order_sn", None) if order_sn is None: return json_error_response("支付失败,请稍后再试(1)") pay_order_info = PayOrder.query.filter_by(order_sn=order_sn).first() if pay_order_info is None: return json_error_response("支付失败,请稍后再试(2)") # get openid for member oauth_bind_info = OauthMemberBind.query.filter_by( member_id=member_info.id).first() if oauth_bind_info is None: return json_error_response("支付失败,请稍后再试(3)") subscribed = request.form.get("subscribed", "False") subscribed = subscribed == "true" notify_url = build_url("/api/order/callback") data = { "appid": app.config["MINA_APP_ID"], "mch_id": app.config["MCH_ID"], "nonce_str": wc_utils.get_nonce_str(), "body": "订餐", "out_trade_no": pay_order_info.order_sn, "total_fee": int(pay_order_info.total_price * 100), #单位为分 "notify_url": notify_url, "trade_type": "JSAPI", "openid": oauth_bind_info.openid } prepay_info = wc_utils.get_pay_info(data) # save prepay_id to database pay_order_info.prepay_id = prepay_info["prepay_id"] pay_order_info.subscribed = subscribed db.session.add(pay_order_info) db.session.commit() res_data = {"prepay_info": prepay_info} if app.config["DEV_MODE"]: # prepare callback xml message right here, send to frontend, and then # frontend will send it back to backend's /order/callback_dev res_data["dev_mode"] = True cb_dev_data = { "appid": data["appid"], "bank_type": "CFT", "cash_fee": data["total_fee"], "fee_type": "CNY", "is_subscribe": "N", "mch_id": app.config["MCH_ID"], "nonce_str": wc_utils.get_nonce_str(), "openid": oauth_bind_info.openid, "out_trade_no": pay_order_info.order_sn, "result_code": "SUCCESS", "return_code": "SUCCESS", "time_end": get_current_time("%Y%m%d%H%M%S"), "total_fee": data["total_fee"], "trade_type": "JSAPI", # this is supposed to be automatically generated by WeChat API # use our own order_sn temporarily for development purposes "transaction_id": pay_order_info.order_sn } sign = wc_utils.create_sign(cb_dev_data) cb_dev_data["sign"] = sign xml_data = wc_utils.dict_to_xml(cb_dev_data) res_data["cb_dev_data"] = xml_data return json_response(data=res_data)