poll messages on the phone reservation page

This commit is contained in:
Son 2022-01-04 16:24:50 +01:00
parent 4d8c89105f
commit 4ac8da1e8f
2 changed files with 62 additions and 25 deletions

View File

@ -3,7 +3,7 @@ from flask import render_template, flash, redirect, url_for, request
from flask_login import login_required, current_user
from app.db import Session
from app.models import PhoneReservation, PhoneMessage, User
from app.models import PhoneReservation, User
from app.phone.base import phone_bp
current_user: User
@ -18,11 +18,6 @@ def reservation_route(reservation_id: int):
return redirect(url_for("phone.index"))
phone_number = reservation.number
messages = PhoneMessage.filter(
PhoneMessage.number_id == phone_number.id,
PhoneMessage.created_at > reservation.start,
PhoneMessage.created_at < reservation.end,
).all()
if request.method == "POST":
if request.form.get("form-name") == "release":
@ -43,6 +38,5 @@ def reservation_route(reservation_id: int):
"phone/phone_reservation.html",
phone_number=phone_number,
reservation=reservation,
messages=messages,
now=arrow.now(),
)

View File

@ -32,29 +32,34 @@
</div>
<div class="card">
<div class="card-body">
<div class="card-body" id="message-app">
<h2 class="mb-2">Received Messages</h2>
<div class="mb-4">Please refresh the page to have the latest messages</div>
<table class="table">
<thead>
<tr>
<th scope="col">From</th>
<th scope="col">Time</th>
<th scope="col">Message</th>
</tr>
</thead>
<tbody>
{% for message in messages %}
<div v-if="loading">
Loading ...
</div>
<div v-else>
<table class="table">
<thead>
<tr>
<td>{{ message.from_number }}</td>
<td>{{ message.created_at.humanize() }}</td>
<td>{{ message.body }}</td>
<th scope="col">From</th>
<th scope="col">Time</th>
<th scope="col">Message</th>
</tr>
{% endfor %}
</tbody>
</table>
</thead>
<tbody>
<tr v-for="message in messages">
<td>[[ message.from_number ]]</td>
<td>[[ message.created_at ]]</td>
<td>[[ message.body ]]</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
@ -72,9 +77,47 @@
</div>
{% endif %}
{% endblock %}
{% block script %}
<script>
var app = new Vue({
el: '#message-app',
delimiters: ["[[", "]]"], // necessary to avoid conflict with jinja
data: {
messages: [],
loading: true,
},
async mounted() {
await this.loadMessage();
// refresh every 5 seconds
this.intervalId = window.setInterval(this.loadMessage, 5000)
},
methods: {
loadMessage: async function () {
let that = this;
console.log("load messages");
let res = await fetch(`/api/phone/reservations/{{reservation.id}}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
}
});
if (res.ok) {
let json = await res.json();
that.messages = json.messages;
that.loading = false;
if (res.ended) {
console.log("clear interval")
window.clearInterval(that.intervalId);
}
}
}
}
})
</script>
{% endblock %}