Advertisements
Vậy là chúng ta đã add hóa đơn thành công cho khách hàng ở bài trước. Bạn sẽ thấy sau khi insert xong hóa đơn mới vào cơ sở dữ liệu, app sẽ đưa người sử dụng trở về trang xem thông tin của khách hàng mà hóa đơn này được gán vào.
Tuy nhiên ở blueprint cũ của customer view, chúng ta chưa lấy thông tin invoice. Trong bài này, chúng ta sẽ hoàn thiện nốt bước đó.
Bạn mở blueprint của customer (customer.py) và thêm dòng code sau vào route view:
@bp.route('/<int:id>', methods=('GET',))
def view(id):
customer = get_db().execute(
'SELECT * FROM customer'
' WHERE id = ?',
(id,)
).fetchone()
# Thêm đoạn code này để lấy các hóa đơn của khách hàng
# get all invoices
invoices = get_db().execute(
'SELECT * FROM invoice WHERE customer_id = ?',
(id,)
).fetchall()
if customer is None:
abort(404, f"customer id {id} doesn't exist.")
# truyền danh sách các hóa đơn tìm được vào view:
return render_template('customer/view.html', customer=customer, invoices=invoices)
Trong view của templates/customer/view.html, chúng ta thêm đoạn code sau để hiện thi danh sách các hóa đơn ở dạng bảng:
{% block content %}
<h1>{{ customer['name'] }}</h1>
<hr/>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Information</h3>
</div>
<div class="panel-body">{{ customer['email']}}</div>
</div>
<!-- THÊM ĐOẠN BLOCK div NÀY -->
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Invoices</h3>
</div>
<div class="panel-body">
<table class="table">
<tr>
<th>ID</th>
<th>Invoice Date</th>
<th>Description</th>
<th>Sub-total</th>
<th>Discount</th>
<th>Tax</th>
<th>Total</th>
</tr>
{% for inv in invoices %}
{% set inv_total = inv['sub_total'] - inv['discount'] + inv['tax'] %}
<td>{{ inv['id'] }}</td>
<td>{{ inv['invoice_date'] }}</td>
<td>{{ inv['description'] }}</td>
<td>{{ inv['sub_total'] }}</td>
<td>{{ inv['discount'] }}</td>
<td>{{ inv['tax'] }}</td>
<td>{{ inv_total }}</td>
{% endfor %}
</table>
</div>
</div>
<!-- KẾT THÚC BLOCK HIỆN DANH SÁCH HÓA ĐƠN -->
{% endblock %}
Như thế chúng ta đã hoàn thành bước cơ bản cho việc tạo hóa đơn và hiện thị. Bạn hãy click New Invoice trên thanh menu để trải nghiệm toàn bộ chức năng mà mình vừa làm!

