文章目录
- 0.页面效果
- 1.思路总结
- 2.后端代码
- 3.前端js
- 4.前端html
0.页面效果
1.思路总结
1)用户点击“我的订单”,js向后端获取数据,并加载在前端的模板中;
2)用户点击相应订单的“去支付”按钮,js向引导用户跳转到支付宝链接;
3)用户交易完成之后,点击评论的“确定”按钮,js将评论数据传送给后端接口;
4)后端接口接收评论数据,并进行逻辑处理,比如修改订单状态、订单数加1、提交数据库等,并将redis中关于房屋详情页的缓存删除,以保证下次获取个人详情页时,能够重新生成最新的评论。
2.后端代码
orders.py中部分接口
获取用户订单:
# /api/v1.0/user/orders?role=custom role=landlord
@api.route("/user/orders", methods=["GET"])
@login_required
def get_user_orders():"""查询用户的订单信息"""user_id = g.user_id# 用户的身份,用户想要查询作为房客预订别人房子的订单,还是想要作为房东查询别人预订自己房子的订单role = request.args.get("role", "")# 查询订单数据try:if "landlord" == role:# 以房东的身份查询订单# 先查询属于自己的房子有哪些houses = House.query.filter(House.user_id == user_id).all()houses_ids = [house.id for house in houses]# 再查询预订了自己房子的订单orders = Order.query.filter(Order.house_id.in_(houses_ids)).order_by(Order.create_time.desc()).all()else:# 以房客的身份查询订单, 查询自己预订的订单orders = Order.query.filter(Order.user_id == user_id).order_by(Order.create_time.desc()).all()except Exception as e:current_app.logger.error(e)return jsonify(errno=RET.DBERR, errmsg="查询订单信息失败")# 将订单对象转换为字典数据orders_dict_list = []if orders:for order in orders:orders_dict_list.append(order.to_dict())return jsonify(errno=RET.OK, errmsg="OK", data={"orders": orders_dict_list})
用户评论:
@api.route("/orders/<int:order_id>/comment", methods=["PUT"])
@login_required
def save_order_comment(order_id):"""保存订单评论信息"""user_id = g.user_id# 获取参数req_data = request.get_json()comment = req_data.get("comment") # 评价信息# 检查参数if not comment:return jsonify(errno=RET.PARAMERR, errmsg="参数错误")try:# 需要确保只能评论自己下的订单,而且订单处于待评价状态才可以order = Order.query.filter(Order.id == order_id, Order.user_id == user_id,Order.status == "WAIT_COMMENT").first()house = order.houseexcept Exception as e:current_app.logger.error(e)return jsonify(errno=RET.DBERR, errmsg="无法获取订单数据")if not order:return jsonify(errno=RET.REQERR, errmsg="操作无效")try:# 将订单的状态设置为已完成order.status = "COMPLETE"# 保存订单的评价信息order.comment = comment# 将房屋的完成订单数增加1house.order_count += 1db.session.add(order)db.session.add(house)db.session.commit()except Exception as e:current_app.logger.error(e)db.session.rollback()return jsonify(errno=RET.DBERR, errmsg="操作失败")# 因为房屋详情中有订单的评价信息,为了让最新的评价信息展示在房屋详情中,所以删除redis中关于本订单房屋的详情缓存try:redis_store.delete("house_info_%s" % order.house.id)except Exception as e:current_app.logger.error(e)return jsonify(errno=RET.OK, errmsg="OK")
3.前端js
orders.js
//模态框居中的控制
function centerModals(){$('.modal').each(function(i){ //遍历每一个模态框var $clone = $(this).clone().css('display', 'block').appendTo('body'); var top = Math.round(($clone.height() - $clone.find('.modal-content').height()) / 2);top = top > 0 ? top : 0;$clone.remove();$(this).find('.modal-content').css("margin-top", top-30); //修正原先已经有的30个像素});
}function getCookie(name) {var r = document.cookie.match("\\b" + name + "=([^;]*)\\b");return r ? r[1] : undefined;
}$(document).ready(function(){$('.modal').on('show.bs.modal', centerModals); //当模态框出现的时候$(window).on('resize', centerModals);// 查询房客订单$.get("/api/v1.0/user/orders?role=custom", function(resp){if ("0" == resp.errno) {$(".orders-list").html(template("orders-list-tmpl", {orders:resp.data.orders}));$(".order-pay").on("click", function () {var orderId = $(this).parents("li").attr("order-id");$.ajax({url: "/api/v1.0/orders/" + orderId + "/payment",type: "post",dataType: "json",headers: {"X-CSRFToken": getCookie("csrf_token"),},success: function (resp) {if ("4101" == resp.errno) {location.href = "/login.html";} else if ("0" == resp.errno) {// 引导用户跳转到支付宝连接location.href = resp.data.pay_url;}}});});$(".order-comment").on("click", function(){var orderId = $(this).parents("li").attr("order-id");$(".modal-comment").attr("order-id", orderId);});$(".modal-comment").on("click", function(){var orderId = $(this).attr("order-id");var comment = $("#comment").val()if (!comment) return;var data = {order_id:orderId,comment:comment};// 处理评论$.ajax({url:"/api/v1.0/orders/"+orderId+"/comment",type:"PUT",data:JSON.stringify(data),contentType:"application/json",dataType:"json",headers:{"X-CSRFTOKEN":getCookie("csrf_token"),},success:function (resp) {if ("4101" == resp.errno) {location.href = "/login.html";} else if ("0" == resp.errno) {$(".orders-list>li[order-id="+ orderId +"]>div.order-content>div.order-text>ul li:eq(4)>span").html("已完成");$("ul.orders-list>li[order-id="+ orderId +"]>div.order-title>div.order-operate").hide();$("#comment-modal").modal("hide");}}});});}});});
4.前端html
orders.html
<!DOCTYPE html>
<html>
<head> <meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"><title>爱家-我的订单</title><link href="/static/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet"><link href="/static/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet"><link href="/static/css/reset.css" rel="stylesheet"><link href="/static/plugins/bootstrap-datepicker/css/bootstrap-datepicker.min.css" rel="stylesheet"><link href="/static/css/ihome/main.css" rel="stylesheet"><link href="/static/css/ihome/orders.css" rel="stylesheet">
</head>
<body><div class="container"><div class="top-bar"><div class="nav-bar"><h3 class="page-title">我的订单</h3><a class="nav-btn fl" href="/my.html"><span><i class="fa fa-angle-left fa-2x"></i></span></a></div></div><div class="orders-con"><ul class="orders-list"></ul><script id="orders-list-tmpl" type="text/html">{{if orders}}{{each orders as order}}<li order-id={{order.order_id}}><div class="order-title"><h3>订单编号:{{order.order_id}}</h3>{{ if "WAIT_COMMENT" == order.status }}<div class="fr order-operate"><button type="button" class="btn btn-success order-comment" data-toggle="modal" data-target="#comment-modal">发表评价</button></div>{{ else if "WAIT_PAYMENT" == order.status }}<div class="fr order-operate"><button type="button" class="btn btn-success order-pay">去支付</button></div>{{/if}}</div><div class="order-content"><img src="{{order.img_url}}"><div class="order-text"><h3>{{order.title}}</h3><ul><li>创建时间:{{order.ctime}}</li><li>入住日期:{{order.start_date}}</li><li>离开日期:{{order.end_date}}</li><li>合计金额:¥{{(order.amount/100.0).toFixed(0)}}(共{{order.days}}晚)</li><li>订单状态:<span>{{if "WAIT_ACCEPT" == order.status}}待接单{{else if "WAIT_PAYMENT" == order.status}}待支付{{else if "WAIT_COMMENT" == order.status}}待评价{{else if "COMPLETE" == order.status}}已完成{{else if "REJECTED" == order.status}}已拒单{{/if}}</span></li>{{if "COMPLETE" == order.status}}<li>我的评价: {{order.comment}}</li>{{else if "REJECTED" == order.status}}<li>拒单原因: {{order.comment}}</li>{{/if}}</ul></div></div></li>{{/each}}{{else}}暂时没有订单。{{/if}}</script><div class="modal fade" id="comment-modal" tabindex="-1" role="dialog" aria-labelledby="comment-label"><div class="modal-dialog" role="document"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span></button><h4 class="modal-title">发表评价</h4></div><div class="modal-body"><textarea class="form-control" rows="3" id="comment" placeholder="请在此处填写评价"></textarea></div><div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">取消</button><button type="button" class="btn btn-primary modal-comment">确定</button></div></div></div></div></div><div class="footer"><p><span><i class="fa fa-copyright"></i></span>爱家租房 享受家的温馨</p></div> </div><script src="/static/js/jquery.min.js"></script><script src="/static/plugins/bootstrap/js/bootstrap.min.js"></script><script src="/static/plugins/bootstrap-datepicker/js/bootstrap-datepicker.min.js"></script><script src="/static/plugins/bootstrap-datepicker/locales/bootstrap-datepicker.zh-CN.min.js"></script><script src="/static/js/template.js"></script><script src="/static/js/ihome/orders.js"></script>
</body>
</html>