diff --git a/gestaoRaul/comandas/__pycache__/htmx_views.cpython-310.pyc b/gestaoRaul/comandas/__pycache__/htmx_views.cpython-310.pyc index 363284e..7dff6ed 100644 Binary files a/gestaoRaul/comandas/__pycache__/htmx_views.cpython-310.pyc and b/gestaoRaul/comandas/__pycache__/htmx_views.cpython-310.pyc differ diff --git a/gestaoRaul/comandas/htmx_views.py b/gestaoRaul/comandas/htmx_views.py index 2aea7a9..9bd6182 100644 --- a/gestaoRaul/comandas/htmx_views.py +++ b/gestaoRaul/comandas/htmx_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/db.sqlite3 index 8417e5c..92eceff 100644 Binary files a/gestaoRaul/db.sqlite3 and b/gestaoRaul/db.sqlite3 differ diff --git a/gestaoRaul/orders/__pycache__/views.cpython-310.pyc b/gestaoRaul/orders/__pycache__/views.cpython-310.pyc index 64392ab..b01e963 100644 Binary files a/gestaoRaul/orders/__pycache__/views.cpython-310.pyc and b/gestaoRaul/orders/__pycache__/views.cpython-310.pyc differ 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__":