From d366d2db9728941ffea2ca634a1df5104fe4399a Mon Sep 17 00:00:00 2001 From: Welton Moura Date: Tue, 4 Mar 2025 22:17:30 -0300 Subject: [PATCH] =?UTF-8?q?websocket=20part2=20|=20notifica=C3=A7=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../__pycache__/htmx_views.cpython-310.pyc | Bin 4817 -> 5712 bytes gestaoRaul/comandas/htmx_views.py | 40 ++++++- gestaoRaul/db.sqlite3 | Bin 335872 -> 335872 bytes .../orders/__pycache__/views.cpython-310.pyc | Bin 2743 -> 2747 bytes gestaoRaul/orders/templates/orders.html | 9 +- gestaoRaul/orders/views.py | 2 +- gestaoRaul/templates/base.html | 3 +- .../orders/htmx_list_orders_fila.html | 23 ++-- gestaoRaul/templates/static/base.js | 103 ++++++++++++++++-- .../templates/static/orders/js/orders.js | 50 ++++----- gestaoRaul/websocket/servidor.py | 56 +++++----- 11 files changed, 195 insertions(+), 91 deletions(-) diff --git a/gestaoRaul/comandas/__pycache__/htmx_views.cpython-310.pyc b/gestaoRaul/comandas/__pycache__/htmx_views.cpython-310.pyc index 363284ec5deb901e2e933e11d35172400552d201..7dff6ed0d557c380c325674c35f34d40b7fb67ec 100644 GIT binary patch delta 2254 zcmb7EOKcle6!n`KkH^39C#7zZ1}2U|V;aYGm85M*N~<>gP)OXSeCn2}<9Q>;j^nZ3 zjDc7ad65kp#NsWe`jJ|JgwhqLD;BJZgv6o(u`?19yKWFHQ9zV?#|}TKN}16+@4U}_ zpL_3l-;RDWu3FJ($Oqp~?XSv>!Ozrnp)d80J(J7jj~txHPamGhPvoZ#+`l0l7D$nQ zCmAGj|B!z#85##8HUdx#>$O^eS+r?5HrtQg&+~?SgdF7eN8gb=n6zZrO@M;xm)nhSWv1%N~;%=~-fI0y++9YqsXdm5$E&5E)es|A4 zb=yz(@J|Ez(SBESBd+3x-2ff9<=+sOe3`)oHU#H5)e)_doe|hLmz6W^N$BbXOU%-# z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x_views.py @@ -13,7 +13,7 @@ import asyncio import websockets async def enviar_mensagem(msg): - uri = "ws://localhost:8765" # Substitua pela URI do seu servidor WebSocket + uri = "ws://192.168.1.150:8765" async with websockets.connect(uri) as websocket: await websocket.send(msg) print(f"> Enviado: {msg}") @@ -66,7 +66,17 @@ def addProduct(request, product_id, comanda_id): order.save() msg = JsonResponse({ 'type': 'broadcast', - 'message': f'

{product.name}

{obs}

{comanda.name} - {comanda.mesa.name}

Atendente: {comanda.user.first_name}

{order.queue}

', + 'message': f""" +
+

{product.name}

+ +

{comanda.name} - {comanda.mesa.name}

+

Atendente: {comanda.user.first_name}

+

{order.queue}

+
+ """, 'local':'cozinha', 'tipo':'add', 'id':order.id, @@ -83,6 +93,15 @@ def editOrders(request, productComanda_id, obs): order = Order.objects.get(productComanda=productComanda_id) order.obs = obs order.save() + msg = JsonResponse({ + 'type': 'broadcast', + 'message': obs, + 'local':'cozinha', + 'tipo':'edit', + 'id':order.id, + 'speak': f'Pedido alterado! {order.id_product.name}, é {obs}.' + }) + asyncio.run(enviar_mensagem(msg)) return JsonResponse({'status': 'ok'}) @@ -95,8 +114,23 @@ def removeProductComanda(request, productComanda_id): comanda = Comanda.objects.get(id= product_comanda.comanda.id) parcial = Payments.objects.filter(comanda=comanda) consumo = ProductComanda.objects.filter(comanda=comanda) - product_comanda.delete() valores = somar(consumo,comanda) + if product_comanda.product.cuisine == True: + order = Order.objects.get(productComanda=product_comanda) + product_comanda.delete() + msg = JsonResponse({ + 'type': 'broadcast', + 'message': 'Atenção! Pedido cancelado', + 'local':'cozinha', + 'tipo':'delete', + 'id':order.id, + 'speak': f'Pedido cancelado! {order.id_product.name}.' + }) + asyncio.run(enviar_mensagem(msg)) + # order.delete() + else: + product_comanda.delete() + return render(request, "htmx_components/comandas/htmx_list_products_in_comanda.html",{'config':config, 'valores': valores,'parcials':parcial,'consumo': consumo, 'comanda':comanda}) @group_required(groupName='Garçom') diff --git a/gestaoRaul/db.sqlite3 b/gestaoRaul/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1u5XNzAVk4^#kW%ww5QrZW6e_9+!~qV7a_EHvr(7b}-h>sFZOz&s&OE|g z`U)JYO6{TQwUv6P)Ke?J1n>sz1d&9kx`%IPzWMofX1~_H)U3p^%rSYK-S6EGAFbcY zi>WKIzr7tLfghbGBEtuz<+O||_Fg2x1^@ZS zv$~`#;vW?!rih&;c!_y=_lQzG6LezcBou0wWl$p5A=gNOr9SYuTa<-=$zYa3^8~7d zTMZWQu3VdSi5b-;ZVg?{DX&Qr?^OrSw6L=x9nTtQ!YU;WG%Fn*b8*f>Sf@Z=u^9Ko zbsX@dP$7?Dl7jRI*dQ31m)ttK`kYe7eckIW6VX#0nsijv2wBACfd9z;U!x)WzM@nV(1s=Z)+@n`ybJqzsCJu+IFBM&!o$k((GCUmjAwb26k3o#DzA z)R!_md$6CUh4g<6=J7}6zI5|2(-Q{eJ*$d0=H4UuppLu% diff --git a/gestaoRaul/orders/templates/orders.html b/gestaoRaul/orders/templates/orders.html index d6c1740..7cfd379 100644 --- a/gestaoRaul/orders/templates/orders.html +++ b/gestaoRaul/orders/templates/orders.html @@ -41,7 +41,7 @@
{% for order in orders %} {% if order.preparing == None and order.productComanda != Null %} -
{% endif %} {% endfor %} -
{% for order in orders %} {% if order.finished == None and order.preparing != None %} -
{% for order in orders %} {% if order.delivered == None and order.finished != None %} -
{% for order in orders %} {% if order.delivered != None %} -
Enviado: {message}") diff --git a/gestaoRaul/templates/base.html b/gestaoRaul/templates/base.html index 4b4167f..a4d9638 100644 --- a/gestaoRaul/templates/base.html +++ b/gestaoRaul/templates/base.html @@ -26,6 +26,7 @@

+
- {{ user.first_name }} {{ user.last_name }} +
{{user.first_name}} {{user.last_name}}
diff --git a/gestaoRaul/templates/htmx_components/orders/htmx_list_orders_fila.html b/gestaoRaul/templates/htmx_components/orders/htmx_list_orders_fila.html index 68e17aa..d5d487b 100644 --- a/gestaoRaul/templates/htmx_components/orders/htmx_list_orders_fila.html +++ b/gestaoRaul/templates/htmx_components/orders/htmx_list_orders_fila.html @@ -1,17 +1,10 @@ - -
{% for order in orders %} {% if order.preparing == None and order.productComanda != Null %} -

{{order.id_product.name}}

-

{{order.obs}}

+

{{order.obs}}

{{order.id_comanda.name}} - {{order.id_comanda.mesa.name}}

Atendente: {{order.id_comanda.user.first_name}}

{{order.queue|date:"D"}} {{order.queue|date:"d/m/Y - H:i"}}

@@ -36,7 +29,7 @@ {% for order in orders %} {% if order.finished == None and order.preparing != None %} -

{{order.id_product.name}}

-

{{order.obs}}

+

{{order.obs}}

{{order.id_comanda.name}} - {{order.id_comanda.mesa.name}}

Atendente: {{order.id_comanda.user.first_name}}

{{order.queue|date:"D"}} {{order.queue|date:"d/m/Y - H:i"}}

@@ -59,7 +52,7 @@
{% for order in orders %} {% if order.delivered == None and order.finished != None %} -

{{order.id_product.name}}

-

{{order.obs}}

+

{{order.obs}}

{{order.id_comanda.name}} - {{order.id_comanda.mesa.name}}

Atendente: {{order.id_comanda.user.first_name}}

{{order.queue|date:"D"}} {{order.queue|date:"d/m/Y - H:i"}}

@@ -83,7 +76,7 @@ {% for order in orders %} {% if order.delivered != None %} -

{{order.id_product.name}}

-

{{order.obs}}

+

{{order.obs}}

{{order.id_comanda.name}} - {{order.id_comanda.mesa.name}}

Atendente: {{order.id_comanda.user.first_name}}

{{order.queue|date:"D"}} {{order.queue|date:"d/m/Y - H:i"}}

diff --git a/gestaoRaul/templates/static/base.js b/gestaoRaul/templates/static/base.js index 702ee59..a33130c 100644 --- a/gestaoRaul/templates/static/base.js +++ b/gestaoRaul/templates/static/base.js @@ -1,5 +1,36 @@ +function verificarCookieNotificacao() { + console.log('cookie notificacao verificado'); + if (document.cookie.indexOf('notificacao=') === -1) { + document.cookie = 'notificacao=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/'; + var iconNotify = document.getElementById('icon-notify'); + iconNotify.style.backgroundColor = 'green'; + console.log('cookie notificacao criado'); + }else{ + let valorAtual = document.cookie.replace(/(?:(?:^|.*;\s*)notificacao\s*\=\s*([^;]*).*$)|^.*$/, "$1"); + var iconNotify = document.getElementById('icon-notify'); + iconNotify.style.backgroundColor = valorAtual === 'true' ? 'green' : 'red'; + } +} +verificarCookieNotificacao(); -const websocket = new WebSocket('ws://localhost:8765'); +function cookieNotificacao() { + if (document.cookie.indexOf('notificacao=') !== -1) { + let valorAtual = document.cookie.replace(/(?:(?:^|.*;\s*)notificacao\s*\=\s*([^;]*).*$)|^.*$/, "$1"); + var iconNotify = document.getElementById('icon-notify'); + let novoValor = valorAtual === 'true' ? 'false' : 'true'; + if (novoValor === 'true') { + iconNotify.style.backgroundColor = 'green'; + }else{ + iconNotify.style.backgroundColor = 'red'; + } + document.cookie = 'notificacao=' + novoValor + '; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/'; + } else { + document.cookie = 'notificacao=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/'; + } +} + +const websocket = new WebSocket('ws://192.168.1.150:8765'); +const nomeUsuario = document.getElementById('user-info').textContent; websocket.addEventListener('open', (event) => { console.log('Conectado ao servidor WebSocket'); @@ -7,18 +38,66 @@ websocket.addEventListener('open', (event) => { websocket.addEventListener('message', (event) => { const data = JSON.parse(event.data); - if (data.local === 'cozinha' && data.tipo === 'add'){ - const novoElemento = document.createElement('div'); - novoElemento.innerHTML = data.message; - var fila = document.getElementById('Fila').appendChild(novoElemento); - texto = new SpeechSynthesisUtterance(data.speak); - window.speechSynthesis.speak(texto); - console.log('Mensagem recebida:', data.local); - } - else if (data.local === 'cozinha' && data.tipo === 'edit'){ - var card = document.getElementById('obs-'+data.id).innerHTML = data.message - console.log('Mensagem recebida:', data.local); + + switch (data.local) { + case 'cozinha': + if (document.getElementById('Fila') !== null && data.tipo === 'add'){ + const novoElemento = document.createElement('div'); + novoElemento.innerHTML = data.message; + var fila = document.getElementById('Fila').appendChild(novoElemento); + let valorAtual = document.cookie.replace(/(?:(?:^|.*;\s*)notificacao\s*\=\s*([^;]*).*$)|^.*$/, "$1"); + if (valorAtual === 'true') { + + texto = new SpeechSynthesisUtterance(data.speak); + window.speechSynthesis.speak(texto); + } + console.log('Mensagem recebida:', data.local); + } + else if (document.getElementById('obs-'+data.id) !== null && data.tipo === 'edit'){ + const obs = document.getElementById('obs-'+data.id) + const card = obs.parentNode; + card.style.backgroundColor = 'rgb(243, 165, 75)'; + obs.innerHTML = data.message; + let valorAtual = document.cookie.replace(/(?:(?:^|.*;\s*)notificacao\s*\=\s*([^;]*).*$)|^.*$/, "$1"); + + if (valorAtual === 'true') { + texto = new SpeechSynthesisUtterance(data.speak); + window.speechSynthesis.speak(texto); + } + console.log('Mensagem recebida:', data.local); + } + else if (document.getElementById('m-card-'+data.id) !== null && data.tipo === 'delete'){ + const card = document.getElementById('m-card-'+data.id) + card.style.backgroundColor = 'rgb(253, 69, 69)'; + // obs.innerHTML = data.message; + let valorAtual = document.cookie.replace(/(?:(?:^|.*;\s*)notificacao\s*\=\s*([^;]*).*$)|^.*$/, "$1"); + + if (valorAtual === 'true') { + texto = new SpeechSynthesisUtterance(data.speak); + window.speechSynthesis.speak(texto); + } + console.log('Mensagem recebida:', data.local); + } + + break; + case 'praca': + console.log('Código a ser executado se expressao === valor2') + break; + case 'guarita': + // Código a ser executado se expressao === valor3 + break; + case 'balcao': + // Código a ser executado se expressao === valor3 + break; + default: + console.log('Local desconhecido:', data); } + + + + + + }); websocket.addEventListener('error', (event) => { diff --git a/gestaoRaul/templates/static/orders/js/orders.js b/gestaoRaul/templates/static/orders/js/orders.js index 20dab2d..3971539 100644 --- a/gestaoRaul/templates/static/orders/js/orders.js +++ b/gestaoRaul/templates/static/orders/js/orders.js @@ -1,7 +1,7 @@ function reloadPage(){ setTimeout(function() { - location.reload();}, 4000); + location.reload();}, 3000); } function openTab(evt, etapa) { @@ -42,15 +42,13 @@ function openTab(evt, etapa) { setTimeout(function() { displayBlock(tab);}, 1000); + // reloadPage(); } displayBlock('Fila'); - - - function mostrarNotificacao(titulo,corpo,grupo) { if (Notification.permission != 'granted') { Notification.requestPermission().then(function(permission) { @@ -71,31 +69,31 @@ function openTab(evt, etapa) { } } -function notificacao(){ +// function notificacao(){ - var resposta = fetch(`/pedidos/notificacao/`, {method: 'GET', - headers: {'Content-Type': 'application/json', - },}) - .then(response => response.json()) - .then(data => { - if (data['notificacao'] == 'true'){ - document.cookie = `fila=${data['fila']}`; - mostrarNotificacao(data['titulo'], data['corpo'],'Cozinha') - texto = new SpeechSynthesisUtterance(data['corpo']+', '+data['titulo']+'.'); - window.speechSynthesis.speak(texto); - reloadPage(); +// var resposta = fetch(`/pedidos/notificacao/`, {method: 'GET', +// headers: {'Content-Type': 'application/json', +// },}) +// .then(response => response.json()) +// .then(data => { +// if (data['notificacao'] == 'true'){ +// document.cookie = `fila=${data['fila']}`; +// mostrarNotificacao(data['titulo'], data['corpo'],'Cozinha') +// texto = new SpeechSynthesisUtterance(data['corpo']+', '+data['titulo']+'.'); +// window.speechSynthesis.speak(texto); +// reloadPage(); - }else{ - console.log(data['notificacao']) - console.log('notificação foi false') - } - }) - .catch(error => { - alert('Erro verificar notificação:', error) - console.error('Erro verificar notificação:', error); - }); +// }else{ +// console.log(data['notificacao']) +// console.log('notificação foi false') +// } +// }) +// .catch(error => { +// alert('Erro verificar notificação:', error) +// console.error('Erro verificar notificação:', error); +// }); - } +// } // setInterval(()=> { diff --git a/gestaoRaul/websocket/servidor.py b/gestaoRaul/websocket/servidor.py index 7975e4a..2a82c29 100644 --- a/gestaoRaul/websocket/servidor.py +++ b/gestaoRaul/websocket/servidor.py @@ -2,70 +2,70 @@ import asyncio import websockets import json import logging +import uuid -# Configure logging + +# Configurar o registro de logs logging.basicConfig(level=logging.INFO) -connected_clients = set() # Keep track of connected clients +connected_clients = set() -async def handle_client(websocket): # Remove 'path' argument - """Handles a single client connection.""" - logging.info(f"Client connected: {websocket.remote_address}") +async def handle_client(websocket): + logging.info(f"Cliente conectado: {websocket.remote_address}") connected_clients.add(websocket) + # for client in connected_clients: + # await client.send(json.dumps({"message": "Novo cliente conectado"})) + # print(client) try: async for message in websocket: - logging.info(f"Received message from {websocket.remote_address}: {message}") - print(f"Received message from {websocket.remote_address}: {message}") + logging.info(f"Mensagem recebida de {websocket.remote_address}: {message}") + print(f"Mensagem recebida de {websocket.remote_address}: {message}") try: data = json.loads(message) - # Process the message here + # Processa a mensagem aqui await process_message(data, websocket) except json.JSONDecodeError: - logging.error(f"Invalid JSON received from {websocket.remote_address}: {message}") - await websocket.send(json.dumps({"error": "Invalid JSON format"})) + logging.error(f"JSON inválido recebido de {websocket.remote_address}: {message}") + await websocket.send(json.dumps({"error": "Formato JSON inválido"})) except Exception as e: - logging.error(f"Error processing message from {websocket.remote_address}: {e}") - await websocket.send(json.dumps({"error": "Error processing message"})) + logging.error(f"Erro ao processar mensagem de {websocket.remote_address}: {e}") + await websocket.send(json.dumps({"error": "Erro ao processar mensagem"})) except websockets.exceptions.ConnectionClosedOK: - logging.info(f"Client disconnected: {websocket.remote_address}") + logging.info(f"Cliente desconectado: {websocket.remote_address}") except websockets.exceptions.ConnectionClosedError: - logging.error(f"Client connection closed with error {websocket.remote_address}") + logging.error(f"Conexão do cliente fechada com erro {websocket.remote_address}") except Exception as e: - logging.error(f"Error during connection from {websocket.remote_address} with error {e}") + logging.error(f"Erro durante a conexão de {websocket.remote_address} com erro {e}") finally: connected_clients.remove(websocket) async def process_message(data, websocket): - """Processes the received message and takes actions.""" - # Example: check if it's a broadcast message if "type" in data and data["type"] == "broadcast" and "message" in data: await broadcast_message(data) - print("Broadcast message:", data["message"]) + print("Mensagem de Broadcast:", data["message"]) elif "type" in data and data["type"] == "echo" and "message" in data: await websocket.send(json.dumps({"response": data['message']})) elif "type" in data and data['type'] == "test": - await websocket.send(json.dumps({"response": "test is ok"})) + await websocket.send(json.dumps({"response": "teste está ok"})) else: - logging.warning(f"Unknown message type or format: {data}") - await websocket.send(json.dumps({"error": "Unknown message type"})) + logging.warning(f"Tipo de mensagem ou formato desconhecido: {data}") + await websocket.send(json.dumps({"error": "Tipo de mensagem desconhecido"})) async def broadcast_message(data): - """Broadcasts a message to all connected clients.""" if connected_clients: - logging.info(f"Broadcasting message: {data}") + logging.info(f"Enviando mensagem por broadcast: {data}") await asyncio.wait([client.send(json.dumps(data)) for client in connected_clients]) else: - logging.info("No clients connected. Message not broadcasted.") + logging.info("Nenhum cliente conectado.") async def main(): - """Starts the WebSocket server.""" - start_server = websockets.serve(handle_client, "localhost", 8765) - logging.info("WebSocket server started on ws://localhost:8765") + start_server = websockets.serve(handle_client, "192.168.1.150", 8765) + logging.info("Servidor WebSocket iniciado em ws://192.168.1.150:8765") await start_server - await asyncio.Future() # Keep the server running indefinitely + await asyncio.Future() # Mantém o servidor em execução indefinidamente if __name__ == "__main__":