diff --git a/gestaoRaul/comandas/__pycache__/htmx_views.cpython-312.pyc b/gestaoRaul/comandas/__pycache__/htmx_views.cpython-312.pyc index 5f0bebd..6c5f633 100644 Binary files a/gestaoRaul/comandas/__pycache__/htmx_views.cpython-312.pyc and b/gestaoRaul/comandas/__pycache__/htmx_views.cpython-312.pyc differ diff --git a/gestaoRaul/comandas/__pycache__/urls.cpython-312.pyc b/gestaoRaul/comandas/__pycache__/urls.cpython-312.pyc index a608b8d..b0a2808 100644 Binary files a/gestaoRaul/comandas/__pycache__/urls.cpython-312.pyc and b/gestaoRaul/comandas/__pycache__/urls.cpython-312.pyc differ diff --git a/gestaoRaul/comandas/__pycache__/views.cpython-312.pyc b/gestaoRaul/comandas/__pycache__/views.cpython-312.pyc index 68fd0dd..7480791 100644 Binary files a/gestaoRaul/comandas/__pycache__/views.cpython-312.pyc and b/gestaoRaul/comandas/__pycache__/views.cpython-312.pyc differ diff --git a/gestaoRaul/comandas/htmx_views.py b/gestaoRaul/comandas/htmx_views.py index 902f6a5..3c5a7ee 100644 --- a/gestaoRaul/comandas/htmx_views.py +++ b/gestaoRaul/comandas/htmx_views.py @@ -6,7 +6,7 @@ from django.shortcuts import render, redirect from comandas.models import Comanda, ProductComanda from orders.models import Order from products.models import Product -from payments.models import Payments +from payments.models import Payments, somar from typePay.models import TypePay from gestaoRaul.decorators import group_required from websocket_client.websocketClient import enviar_mensagem @@ -29,80 +29,6 @@ from asgiref.sync import async_to_sync # print(f"Erro ao enviar mensagem via websocket: {e}") -def somar(consumo:ProductComanda, comanda:Comanda): - parcial = Payments.objects.filter(comanda=comanda) - totalParcial = Decimal(0) - total:Decimal = Decimal(0) - for p in parcial: - totalParcial += p.value - for produto in consumo: - total += Decimal(produto.product.price) - valores = { - 'total':total, - 'parcial':totalParcial, - 'taxa': round(total * Decimal(0.1), 2), - 'totalSemTaxa':total - totalParcial, - 'totalComTaxa': round((total - totalParcial)+(total * Decimal(0.1)),2) - } - return valores - -def listProduct(request, comanda_id): - product = request.GET.get("search-product") - allProducts = Product.objects.filter(name__icontains=product) - products = [] - for p in allProducts: - if p.active == True: - products.append(p) - return render(request, "htmx_components/comandas/htmx_list_products.html", {"products": products,'comanda_id':comanda_id}) - -@group_required(groupName='Garçom') -def addProduct(request, product_id, comanda_id): - config = { - 'taxa': False - } - obs = request.GET.get("obs") - product_comanda = ProductComanda(comanda_id=comanda_id, product_id=product_id) - product_comanda.save() - product = Product.objects.get(id=product_id) - comanda = Comanda.objects.get(id=comanda_id) - parcial = Payments.objects.filter(comanda=comanda) - if product.cuisine == True: - order = Order(id_comanda=comanda, id_product=product, productComanda=product_comanda, obs='') - order.save() - msg = JsonResponse({ - 'type': 'broadcast', - 'message': f""" -
-

{product.name}

-

{order.obs}

-

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

-

{order.queue.strftime("%d/%m/%Y - %H:%M")}

-

Atendente: {comanda.user.first_name}

-
- -
-
- """, - 'local':'cozinha', - 'tipo':'add', - 'id':order.id, - 'speak': f'Novo pedido! {product.name}, para {comanda.name}.' - }) - try: - # Chama a função async dentro da view normal - async_to_sync(enviar_mensagem)(mensagem) - - # return JsonResponse({"status": "Mensagem enviada com sucesso"}) - - except Exception as e: - print("Erro add product websocket: ",e) - # return JsonResponse({"status": "Erro", "erro": str(e)}, status=500) - # asyncio.run(enviar_mensagem(msg)) - consumo = ProductComanda.objects.filter(comanda=comanda_id) - valores = somar(consumo,comanda) - - 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/comandas/templates/viewcomanda.html b/gestaoRaul/comandas/templates/viewcomanda.html index d46ef9b..6af1eb6 100644 --- a/gestaoRaul/comandas/templates/viewcomanda.html +++ b/gestaoRaul/comandas/templates/viewcomanda.html @@ -13,6 +13,16 @@ Detalhes {{comanda.name}} {% block 'head' %} + {% endblock %} @@ -22,7 +32,7 @@ Detalhes {{comanda.name}}
- + +
+ """, + 'local':'cozinha', + 'tipo':'add', + 'id':order.id, + 'speak': f'Novo pedido! {product.name}, para {comanda.name}.' + }) + try: + # Chama a função async dentro da view normal + async_to_sync(enviar_mensagem)(mensagem) + + # return JsonResponse({"status": "Mensagem enviada com sucesso"}) + + except Exception as e: + print("Erro add product websocket: ",e) + # return JsonResponse({"status": "Erro", "erro": str(e)}, status=500) + # asyncio.run(enviar_mensagem(msg)) + consumo = ProductComanda.objects.filter(comanda=comanda_id) + valores = somar(consumo,comanda) + + return render(request, "htmx_components/comandas/htmx_list_products_in_comanda.html",{'config':config, 'valores':valores,'parcials':parcial,'consumo': consumo,'comanda':comanda}) + + + +def listProduct(request, comanda_id, product): + allProducts = Product.objects.filter(name__icontains=product) + products = [] + for p in allProducts: + if p.active == True: + products.append(p) + return render(request, "htmx_components/comandas/htmx_list_products.html", {"products": products,'comanda_id':comanda_id}) \ No newline at end of file diff --git a/gestaoRaul/db.sqlite3 b/gestaoRaul/db.sqlite3 index dd384d2..20d86d7 100644 Binary files a/gestaoRaul/db.sqlite3 and b/gestaoRaul/db.sqlite3 differ diff --git a/gestaoRaul/templates/htmx_components/comandas/htmx_list_products.html b/gestaoRaul/templates/htmx_components/comandas/htmx_list_products.html index eedce97..9245b3d 100644 --- a/gestaoRaul/templates/htmx_components/comandas/htmx_list_products.html +++ b/gestaoRaul/templates/htmx_components/comandas/htmx_list_products.html @@ -3,11 +3,9 @@ {% for product in products %}
+> {{product.name}}
R$ {{product.price}}
diff --git a/gestaoRaul/templates/static/base.js b/gestaoRaul/templates/static/base.js index 10a7897..9a0f4d5 100644 --- a/gestaoRaul/templates/static/base.js +++ b/gestaoRaul/templates/static/base.js @@ -178,7 +178,6 @@ function openFullscreen() { function feedback(message, icon, subMessage) { - console.log(subMessage) var feedbackMsg = Swal.fire({ color: 'white', title: message, @@ -189,5 +188,6 @@ function openFullscreen() { background: 'rgb(23, 38, 54)', confirmButtonColor: 'linear-gradient(145deg, #1E2A3B, #2C3E50)', }); -return feedbackMsg; + + } \ No newline at end of file diff --git a/gestaoRaul/templates/static/comandas/css/viewcomanda.css b/gestaoRaul/templates/static/comandas/css/viewcomanda.css index cfce875..a667610 100644 --- a/gestaoRaul/templates/static/comandas/css/viewcomanda.css +++ b/gestaoRaul/templates/static/comandas/css/viewcomanda.css @@ -53,6 +53,7 @@ } .popover{ + display: none; position: relative; width: 98%; height: 96%; diff --git a/gestaoRaul/templates/static/comandas/js/viewcomanda.js b/gestaoRaul/templates/static/comandas/js/viewcomanda.js index 25741c5..028858c 100644 --- a/gestaoRaul/templates/static/comandas/js/viewcomanda.js +++ b/gestaoRaul/templates/static/comandas/js/viewcomanda.js @@ -1,23 +1,52 @@ +async function openModal() { + var htmlModal = document.getElementById('addProduct').innerHTML + htmlModal = htmlModal.replace('search-product','search-product-modal') + htmlModal = htmlModal.replace('product-list','product-list-modal') + +const { value: formValues } = await Swal.fire({ + title: "Adicionar Produto", + html: htmlModal, + width: '100em', + theme: "dark", + didOpen: () => { + Swal.getPopup().classList.add('swal2-noautoclose'); + }, + showConfirmButton: false, + showCancelButton: true, + cancelButtonText: '×', + customClass:{ + cancelButton:'posi' + }, + focusConfirm: false, +}); + + -function openModal() { - textField = document.getElementById('search-product') -if (textField) { +} + +function searchProduct() { setTimeout(() => { - textField.focus(); - }, 500); -} - textField.value = ''; -} + time(); + }, 100); + function time(){ + var search_product = document.getElementById('search-product-modal').value.trim() + var productListElement = document.getElementById("product-list-modal"); + var comanda_id = document.getElementById("id-comanda").value; - -function closeModal() { - var popover = document.getElementById('addProduct'); - popover.hidePopover() + if(search_product.length == 0 ){search_product ='*';} + fetch(`/comandas/listProduct/${comanda_id}/${search_product}`, { + method: 'GET',} + ).then(function(response) { + return response.text(); + }).then(function(text) { + productListElement.innerHTML = text; + + + })} } - function openModalAlter() { document.getElementById('Modal-alter-comanda').style.display = 'block'; var name = document.getElementById('name-comanda').innerText.replace('Nome: ','').replace(' | ', '') @@ -328,43 +357,80 @@ function addOrder(id, obs){ } -function showToastAdd(message, type ,duration = 3000) { - const toast = document.getElementById('toast-add'); - if (type === 'success') { - toast.style.backgroundColor = '#28a745'; - } else if (type === 'error') { - toast.style.backgroundColor = '#dc3545'; - } else if (type === 'info') { - toast.style.backgroundColor = '#ffc107'; +async function addProductComanda(productId, comandaId, cuisine) { + try { + if (!productId || !comandaId) { + throw new Error('IDs de produto ou comanda inválidos'); + } + + const csrfToken = document.querySelector('[name="csrfmiddlewaretoken"]').value + if (!csrfToken) { + throw new Error('Token de segurança não encontrado'); + } + + // if (cuisine === 'ggg') { + // openModalObs(); + // return; + // } + + // Mostra estado de carregamento + Swal.update({ + title: 'Adicionando produto...', + }); + + // Requisição POST + const response = await fetch(`/comandas/product=${productId}/comanda=${comandaId}/`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-CSRFToken': csrfToken + }, + body: JSON.stringify({ + product_id: productId, + comanda_id: comandaId + }) + }); + + // Trata resposta + if (!response.ok) { + const errorData = await response.json().catch(() => ({})); + throw new Error(errorData.message || `Erro HTTP: ${response.status}`); + } + + const result = await response.text(); + + // Atualiza a lista de produtos + const listElement = document.getElementById("list-products-comanda"); + if (listElement) { + listElement.innerHTML = result; + } + + // Feedback de sucesso + Swal.update({ + title: 'Produto adicionado! 😁', + }); + + // Reseta após 2.5 segundos + setTimeout(() => { + Swal.update({ + title: 'Adicionar Produto' + }); + }, 2500); + + } catch (error) { + console.error('Erro:', error); + + // Feedback de erro + Swal.update({ + title: 'Falha ao adicionar!', + html: `
+ ${error.message || 'Erro desconhecido'} +
`, + icon: 'error', + + }); } - const toastMessage = document.getElementById('toast-message-add'); - toastMessage.textContent = message; - toast.classList.add('show'); - - setTimeout(() => { - toast.classList.remove('show'); - }, duration); -} -function addProductComanda(productId,comandaId, cuisine) { - obs = document.getElementById('obs'); - if(cuisine == 'ggg'){ - var obs = openModalObs(); - }else{ - fetch(`/comandas/addProduct${productId}/${comandaId}`, { - method: 'GET', - headers: { - 'Content-Type': 'application/json'} - }) - .then(function(response) { - return response.text(); - }).then(function(text) { - var listProductsBalcaoElement = document.getElementById("list-products-comanda"); - listProductsBalcaoElement.innerHTML = text; - }) - showToastAdd('Produto adicionado com sucesso!😁','success'); - } - } function taxa(){