feat: sistema GastroBar PDV completo

- Backend: Fastify + Prisma/SQLite com autenticacao JWT
- CRUD completo: usuarios, categorias, produtos, comandas
- Sistema de comandas com itens, status, pagamento
- Controle de estoque (entrada/saida automatica)
- Relatorios e dashboard com KPIs
- Notificacoes sonoras na cozinha
- Frontend: SPA vanilla TS com tema dark glassmorphism
- Mobile-first com bottom-sheet e cards compactos
- Busca de comandas por periodo
- Modal de detalhes com secao editavel colapsavel
This commit is contained in:
2026-07-21 12:47:15 -03:00
commit 402ac776ac
55 changed files with 7403 additions and 0 deletions

57
web/src/api.ts Normal file
View File

@@ -0,0 +1,57 @@
const API_URL = 'http://localhost:3333/api';
function getAuthHeaders() {
const token = localStorage.getItem('@gastrobar:token');
return {
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {}),
};
}
export const api = {
async post(endpoint: string, body: any) {
const response = await fetch(`${API_URL}${endpoint}`, {
method: 'POST',
headers: getAuthHeaders(),
body: JSON.stringify(body),
});
const data = await response.json();
if (!response.ok) throw new Error(data.error || data.message || 'Erro na requisição');
return data;
},
async get(endpoint: string) {
const response = await fetch(`${API_URL}${endpoint}`, {
headers: getAuthHeaders(),
});
const data = await response.json();
if (!response.ok) throw new Error(data.error || data.message || 'Erro na requisição');
return data;
},
async patch(endpoint: string, body: any) {
const response = await fetch(`${API_URL}${endpoint}`, {
method: 'PATCH',
headers: getAuthHeaders(),
body: JSON.stringify(body),
});
const data = await response.json();
if (!response.ok) throw new Error(data.error || data.message || 'Erro na requisição');
return data;
},
async delete(endpoint: string) {
const response = await fetch(`${API_URL}${endpoint}`, {
method: 'DELETE',
headers: getAuthHeaders(),
});
if (!response.ok) {
const data = await response.json().catch(() => ({}));
throw new Error(data.error || data.message || 'Erro na requisição');
}
return true;
}
};

BIN
web/src/assets/hero.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" width="32" height="32" viewBox="0 0 256 256"><path fill="#007ACC" d="M0 128v128h256V0H0z"/><path fill="#FFF" d="m56.612 128.85l-.081 10.483h33.32v94.68h23.568v-94.68h33.321v-10.28c0-5.69-.122-10.444-.284-10.566c-.122-.162-20.4-.244-44.983-.203l-44.74.122l-.121 10.443Zm149.955-10.742c6.501 1.625 11.459 4.51 16.01 9.224c2.357 2.52 5.851 7.111 6.136 8.208c.08.325-11.053 7.802-17.798 11.988c-.244.162-1.22-.894-2.317-2.52c-3.291-4.795-6.745-6.867-12.028-7.233c-7.76-.528-12.759 3.535-12.718 10.321c0 1.992.284 3.17 1.097 4.795c1.707 3.536 4.876 5.649 14.832 9.956c18.326 7.883 26.168 13.084 31.045 20.48c5.445 8.249 6.664 21.415 2.966 31.208c-4.063 10.646-14.14 17.879-28.323 20.276c-4.388.772-14.79.65-19.504-.203c-10.28-1.828-20.033-6.908-26.047-13.572c-2.357-2.6-6.949-9.387-6.664-9.874c.122-.163 1.178-.813 2.356-1.504c1.138-.65 5.446-3.129 9.509-5.485l7.355-4.267l1.544 2.276c2.154 3.29 6.867 7.801 9.712 9.305c8.167 4.307 19.383 3.698 24.909-1.26c2.357-2.153 3.332-4.388 3.332-7.68c0-2.966-.366-4.266-1.91-6.501c-1.99-2.845-6.054-5.242-17.595-10.24c-13.206-5.69-18.895-9.224-24.096-14.832c-3.007-3.25-5.852-8.452-7.03-12.8c-.975-3.617-1.22-12.678-.447-16.335c2.723-12.76 12.353-21.659 26.25-24.3c4.51-.853 14.994-.528 19.424.569Z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

1
web/src/assets/vite.svg Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 8.5 KiB

66
web/src/main.ts Normal file
View File

@@ -0,0 +1,66 @@
import './style.css';
import { renderLogin } from './views/login';
import { renderKitchen } from './views/kitchen';
import { renderOrders } from './views/orders';
import { renderCheckout } from './views/checkout';
import { renderMenu } from './views/menu';
import { renderUsers } from './views/users';
import { renderDashboard } from './views/dashboard';
const app = document.getElementById('app')!;
export function navigateTo(path: string) {
window.history.pushState({}, '', path);
router();
}
(window as any).navigateTo = navigateTo;
(window as any).logout = () => {
localStorage.removeItem('@gastrobar:token');
localStorage.removeItem('@gastrobar:user');
navigateTo('/');
};
async function router() {
const path = window.location.pathname;
const token = localStorage.getItem('@gastrobar:token');
// Proteção de rotas
if (!token && path !== '/') {
navigateTo('/');
return;
}
app.innerHTML = '';
switch (path) {
case '/':
if (token) navigateTo('/kitchen');
else renderLogin(app);
break;
case '/kitchen':
await renderKitchen(app);
break;
case '/orders':
await renderOrders(app);
break;
case '/checkout':
await renderCheckout(app);
break;
case '/menu':
await renderMenu(app);
break;
case '/users':
await renderUsers(app);
break;
case '/dashboard':
await renderDashboard(app);
break;
default:
navigateTo('/kitchen');
break;
}
}
window.addEventListener('popstate', router);
router();

1027
web/src/style.css Normal file

File diff suppressed because it is too large Load Diff

136
web/src/utils.ts Normal file
View File

@@ -0,0 +1,136 @@
/** Exibe um toast de notificação na tela */
export function toast(message: string, type: 'success' | 'error' = 'success') {
let container = document.querySelector('.toast-container');
if (!container) {
container = document.createElement('div');
container.className = 'toast-container';
document.body.appendChild(container);
}
const el = document.createElement('div');
el.className = `toast ${type}`;
el.textContent = message;
container.appendChild(el);
setTimeout(() => el.remove(), 3500);
}
/** Retorna o usuário logado do localStorage */
export function getUser(): { id: string; nome: string; email: string; role: string } | null {
const raw = localStorage.getItem('@gastrobar:user');
return raw ? JSON.parse(raw) : null;
}
/** Formata valor em R$ */
export function formatBRL(value: number): string {
return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(value);
}
/** Badges de role */
const roleLabels: Record<string, string> = {
ADMIN: 'Admin', CAIXA: 'Caixa', GARCOM: 'Garçom', COZINHA: 'Cozinha', BARMAN: 'Barman',
};
export function roleBadge(role: string) {
const cls = `badge badge-${role.toLowerCase()}`;
return `<span class="${cls}">${roleLabels[role] ?? role}</span>`;
}
/** Badges de status de comanda */
const statusLabels: Record<string, string> = {
ABERTA: 'Aberta', FECHADA: 'Fechada', PAGA: 'Paga', CANCELADA: 'Cancelada',
};
export function statusBadge(status: string) {
const cls = `badge status-${status.toLowerCase()}`;
return `<span class="${cls}">${statusLabels[status] ?? status}</span>`;
}
/** Navbar padrão com hamburger para mobile */
export function renderNavbar(activePath: string): string {
const user = getUser();
const role = user?.role ?? '';
const links = [
{ path: '/kitchen', label: '👨‍🍳 Cozinha/Bar', roles: ['ADMIN', 'COZINHA', 'BARMAN'] },
{ path: '/orders', label: '📋 Comandas', roles: ['ADMIN', 'GARCOM', 'CAIXA'] },
{ path: '/checkout',label: '💳 Caixa', roles: ['ADMIN', 'CAIXA'] },
{ path: '/menu', label: '🍔 Cardápio', roles: ['ADMIN'] },
{ path: '/users', label: '👥 Equipe', roles: ['ADMIN'] },
{ path: '/dashboard', label: '📊 Dashboard', roles: ['ADMIN'] },
];
const visibleLinks = links.filter(l => l.roles.includes(role));
const desktopLinks = visibleLinks.map(l => `
<a class="nav-link ${activePath === l.path ? 'active' : ''}"
onclick="window.navigateTo('${l.path}')">${l.label}</a>
`).join('');
const drawerLinks = visibleLinks.map(l => `
<a class="nav-link ${activePath === l.path ? 'active' : ''}"
onclick="window.closeDrawer();window.navigateTo('${l.path}')">${l.label}</a>
`).join('');
// Agendar bind do hamburger após o DOM ser inserido
setTimeout(() => {
const btn = document.getElementById('hamburger-btn');
const drawer = document.getElementById('nav-drawer');
const overlay = document.getElementById('drawer-overlay');
btn?.addEventListener('click', () => {
btn.classList.toggle('open');
drawer?.classList.toggle('open');
});
overlay?.addEventListener('click', () => {
btn?.classList.remove('open');
drawer?.classList.remove('open');
});
}, 0);
(window as any).closeDrawer = () => {
document.getElementById('hamburger-btn')?.classList.remove('open');
document.getElementById('nav-drawer')?.classList.remove('open');
};
return `
<nav class="navbar">
<div style="display:flex;align-items:center;gap:0.75rem;">
<span style="font-size:1.25rem;font-weight:700;background:linear-gradient(90deg,#ff3366,#ffb300);-webkit-background-clip:text;-webkit-text-fill-color:transparent;white-space:nowrap;">
<span style="font-size:1.75rem;">🍹 </span>Café em Saturno <span style="font-size:1.75rem;">🪐</span>
</span>
</div>
<!-- Desktop links -->
<div class="nav-links">
${desktopLinks}
</div>
<!-- Desktop user info -->
<div class="nav-links" style="align-items:center;gap:1rem;">
<span style="color:var(--text-secondary);font-size:0.875rem;">
${roleBadge(role)} ${user?.nome ?? ''}
</span>
<button class="btn btn-secondary btn-sm" onclick="window.logout()">Sair</button>
</div>
<!-- Mobile hamburger -->
<button class="hamburger" id="hamburger-btn" aria-label="Menu">
<span></span><span></span><span></span>
</button>
</nav>
<!-- Mobile Drawer -->
<div class="nav-drawer" id="nav-drawer">
<div id="drawer-overlay" style="position:absolute;inset:0;"></div>
<div class="nav-drawer-panel">
<div class="nav-drawer-user">
<div style="font-weight:600;margin-bottom:0.5rem;">${user?.nome ?? ''}</div>
${roleBadge(role)}
</div>
${drawerLinks}
<div style="margin-top:auto;padding-top:1.5rem;border-top:1px solid var(--border-color);">
<button class="btn btn-danger" style="width:100%;" onclick="window.logout()">🚪 Sair</button>
</div>
</div>
</div>
`;
}

175
web/src/views/checkout.ts Normal file
View File

@@ -0,0 +1,175 @@
import { api } from '../api';
import { renderNavbar, toast, formatBRL } from '../utils';
const FORMAS_PAGAMENTO = [
{ value: 'DINHEIRO', label: '💵 Dinheiro' },
{ value: 'CARTAO_CREDITO', label: '💳 Cartão Crédito' },
{ value: 'CARTAO_DEBITO', label: '💳 Cartão Débito' },
{ value: 'PIX', label: '📱 PIX' },
];
export async function renderCheckout(container: HTMLElement) {
container.innerHTML = `
${renderNavbar('/checkout')}
<div class="container animate-fade-in">
<div class="page-header">
<h1>Caixa / Checkout 💳</h1>
</div>
<div class="glass-panel" style="max-width:500px;margin-bottom:2rem;">
<h3>Buscar Comanda</h3>
<div style="display:flex;gap:0.75rem;margin-top:1rem;flex-wrap:wrap;">
<input type="text" id="search-input" class="form-control" style="flex:1;min-width:180px;" placeholder="Identificador (ex: Mesa 5)">
<button class="btn" id="btn-buscar" style="white-space:nowrap;">Buscar</button>
</div>
</div>
<div id="checkout-result"></div>
</div>
`;
document.getElementById('btn-buscar')?.addEventListener('click', searchComanda);
document.getElementById('search-input')?.addEventListener('keydown', (e) => {
if ((e as KeyboardEvent).key === 'Enter') searchComanda();
});
}
function calcularTotalFinal(c: any): number {
let total = c.total || 0;
total -= (c.desconto || 0);
total += (c.acrescimo || 0);
if (c.taxaServico) total += total * 0.10;
return Math.max(total, 0);
}
async function searchComanda() {
const query = (document.getElementById('search-input') as HTMLInputElement).value.trim();
const result = document.getElementById('checkout-result')!;
if (!query) { toast('Digite um identificador para buscar', 'error'); return; }
result.innerHTML = `<p class="card-subtitle">Buscando...</p>`;
try {
const all = await api.get('/comandas');
const found: any[] = all.filter((c: any) =>
c.identificador.toLowerCase().includes(query.toLowerCase()) && c.status === 'ABERTA'
);
if (!found.length) {
result.innerHTML = `<p class="card-subtitle">Nenhuma comanda ABERTA encontrada para "<strong>${query}</strong>".</p>`;
return;
}
result.innerHTML = found.map((c: any) => buildComandaCard(c)).join('');
document.querySelectorAll('.btn-pay').forEach(btn => {
btn.addEventListener('click', async () => {
const id = (btn as HTMLElement).dataset.id!;
const ident = (btn as HTMLElement).dataset.ident!;
const total = parseFloat((btn as HTMLElement).dataset.total!);
const forma = (document.getElementById(`pagamento-${id}`) as HTMLSelectElement)?.value;
if (!forma) {
toast('Selecione a forma de pagamento', 'error');
return;
}
if (!confirm(`Confirmar pagamento de ${formatBRL(total)} para "${ident}" via ${forma.replace('_', ' ')}?`)) return;
try {
await api.post(`/comandas/${id}/pagar`, { formaPagamento: forma });
toast(`Comanda "${ident}" fechada com sucesso!`, 'success');
result.innerHTML = `
<div class="glass-panel" style="max-width:500px;text-align:center;">
<p style="font-size:3rem;margin-bottom:1rem;">✅</p>
<h2 style="color:var(--success)">Pagamento Realizado!</h2>
<p class="card-subtitle">Comanda "${ident}" foi fechada.</p>
</div>`;
} catch (err: any) {
toast(err.message, 'error');
}
});
});
} catch (err: any) {
result.innerHTML = `<p style="color:var(--accent-primary)">Erro: ${err.message}</p>`;
}
}
function buildComandaCard(c: any): string {
const itens = c.itens ?? [];
const itensHtml = itens.length
? itens.map((i: any) => `
<tr>
<td data-label="Produto">${i.produto?.nome ?? '—'}</td>
<td data-label="Qtd" style="text-align:center;">${i.quantidade}</td>
<td data-label="Unitário" style="text-align:right;">${formatBRL(i.precoUnitario)}</td>
<td data-label="Subtotal" style="text-align:right;">${formatBRL(i.precoUnitario * i.quantidade)}</td>
<td data-label="Status"><span class="badge badge-${i.status === 'ENTREGUE' ? 'success' : 'warning'}">${i.status}</span></td>
</tr>
`).join('')
: `<tr><td colspan="5" style="text-align:center;color:var(--text-secondary);">Nenhum item ainda</td></tr>`;
const totalFinal = calcularTotalFinal(c);
const desconto = c.desconto || 0;
const acrescimo = c.acrescimo || 0;
return `
<div class="glass-panel" style="max-width:700px;margin-bottom:2rem;">
<div class="page-header" style="margin-bottom:1.5rem;">
<div>
<h2 style="margin:0;">${c.identificador}</h2>
${c.nomeCliente ? `<p class="card-subtitle" style="margin:0.25rem 0 0;">${c.nomeCliente}</p>` : ''}
</div>
<span class="badge status-${c.status.toLowerCase()}">${c.status}</span>
</div>
<div class="table-wrap" style="margin-bottom:1.5rem;">
<table>
<thead>
<tr>
<th>Produto</th>
<th style="text-align:center;">Qtd</th>
<th style="text-align:right;">Unitário</th>
<th style="text-align:right;">Subtotal</th>
<th>Status</th>
</tr>
</thead>
<tbody>${itensHtml}</tbody>
</table>
</div>
<div style="background:var(--bg-secondary);border-radius:8px;padding:0.75rem 1rem;font-size:0.85rem;margin-bottom:1rem;">
<div style="display:flex;justify-content:space-between;margin-bottom:0.25rem;">
<span style="color:var(--text-secondary);">Subtotal:</span>
<span>${formatBRL(c.total || 0)}</span>
</div>
${desconto > 0 ? `<div style="display:flex;justify-content:space-between;margin-bottom:0.25rem;color:var(--warning);">
<span>Desconto:</span><span>-${formatBRL(desconto)}</span>
</div>` : ''}
${acrescimo > 0 ? `<div style="display:flex;justify-content:space-between;margin-bottom:0.25rem;color:var(--accent-secondary);">
<span>Acréscimo:</span><span>+${formatBRL(acrescimo)}</span>
</div>` : ''}
${c.taxaServico ? `<div style="display:flex;justify-content:space-between;margin-bottom:0.25rem;color:var(--text-secondary);">
<span>Taxa Serviço (10%):</span><span>+${formatBRL((c.total - desconto + acrescimo) * 0.10)}</span>
</div>` : ''}
</div>
<div class="total-bar">
<span style="color:var(--text-secondary);font-size:1rem;font-weight:500;">Total a Pagar</span>
<span class="total-value">${formatBRL(totalFinal)}</span>
</div>
${c.status === 'ABERTA' ? `
<div class="form-group" style="margin-top:1.25rem;margin-bottom:0.75rem;">
<label>Forma de Pagamento</label>
<select id="pagamento-${c.id}" class="form-control">
${FORMAS_PAGAMENTO.map(fp => `<option value="${fp.value}">${fp.label}</option>`).join('')}
</select>
</div>
<button class="btn btn-success btn-pay" style="width:100%;font-size:1.1rem;"
data-id="${c.id}" data-ident="${c.identificador}" data-total="${totalFinal}">
💳 Finalizar Pagamento
</button>
` : ''}
</div>
`;
}

200
web/src/views/dashboard.ts Normal file
View File

@@ -0,0 +1,200 @@
import { api } from '../api';
import { renderNavbar, toast, formatBRL } from '../utils';
export async function renderDashboard(container: HTMLElement) {
container.innerHTML = `
${renderNavbar('/dashboard')}
<div class="container animate-fade-in">
<div class="page-header">
<h1>Dashboard & Relatórios 📊</h1>
<button class="btn btn-secondary btn-sm" id="btn-refresh-dashboard">🔄 Atualizar</button>
</div>
<!-- KPI Cards -->
<div id="kpi-section" class="grid" style="grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin-bottom: 2rem;">
<div class="card" style="text-align:center;">
<p class="card-subtitle" style="margin-bottom:0.5rem;">Vendas Hoje</p>
<p style="font-size:1.75rem;font-weight:700;color:var(--success);" id="kpi-vendas-hoje">R$ 0,00</p>
<p class="card-subtitle" id="kpi-comandas-hoje">0 comandas</p>
</div>
<div class="card" style="text-align:center;">
<p class="card-subtitle" style="margin-bottom:0.5rem;">Vendas Semana</p>
<p style="font-size:1.75rem;font-weight:700;color:var(--accent-primary);" id="kpi-vendas-semana">R$ 0,00</p>
<p class="card-subtitle" id="kpi-comandas-semana">0 comandas</p>
</div>
<div class="card" style="text-align:center;">
<p class="card-subtitle" style="margin-bottom:0.5rem;">Comandas Abertas</p>
<p style="font-size:1.75rem;font-weight:700;color:var(--warning);" id="kpi-comandas-abertas">0</p>
</div>
<div class="card" style="text-align:center;">
<p class="card-subtitle" style="margin-bottom:0.5rem;">Estoque Baixo</p>
<p style="font-size:1.75rem;font-weight:700;color:var(--accent-primary);" id="kpi-estoque-baixo">0</p>
<p class="card-subtitle" id="kpi-total-produtos">0 produtos ativos</p>
</div>
</div>
<!-- Relatório de Vendas -->
<div class="glass-panel" style="margin-bottom:2rem;">
<div class="page-header" style="margin-bottom:1rem;">
<h3 style="margin:0;">Relatório de Vendas</h3>
<div style="display:flex;gap:0.5rem;align-items:center;flex-wrap:wrap;">
<label style="color:var(--text-secondary);font-size:0.85rem;">Período:</label>
<input type="date" id="rel-inicio" class="form-control" style="width:auto;">
<span style="color:var(--text-secondary);">até</span>
<input type="date" id="rel-fim" class="form-control" style="width:auto;">
<button class="btn btn-sm" id="btn-gerar-relatorio">Gerar</button>
</div>
</div>
<div id="relatorio-resumo" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:1rem;margin-bottom:1.5rem;">
</div>
<div id="relatorio-top-produtos" style="margin-bottom:1.5rem;"></div>
<div id="relatorio-vendas-dia" style="margin-bottom:1.5rem;"></div>
<div id="relatorio-pagamento"></div>
</div>
</div>
`;
// Set default dates
const hoje = new Date().toISOString().split('T')[0];
const inicioMes = new Date(new Date().getFullYear(), new Date().getMonth(), 1).toISOString().split('T')[0];
(document.getElementById('rel-inicio') as HTMLInputElement).value = inicioMes;
(document.getElementById('rel-fim') as HTMLInputElement).value = hoje;
const loadDashboard = async () => {
try {
const data = await api.get('/relatorios/dashboard');
document.getElementById('kpi-vendas-hoje')!.textContent = formatBRL(data.vendasHoje.total);
document.getElementById('kpi-comandas-hoje')!.textContent = `${data.vendasHoje.comandas} comandas`;
document.getElementById('kpi-vendas-semana')!.textContent = formatBRL(data.vendasSemana.total);
document.getElementById('kpi-comandas-semana')!.textContent = `${data.vendasSemana.comandas} comandas`;
document.getElementById('kpi-comandas-abertas')!.textContent = `${data.comandasAbertas}`;
document.getElementById('kpi-estoque-baixo')!.textContent = `${data.produtosEstoqueBaixo}`;
document.getElementById('kpi-total-produtos')!.textContent = `${data.totalProdutos} produtos ativos`;
} catch (err: any) {
toast(err.message, 'error');
}
};
const loadRelatorio = async () => {
const inicio = (document.getElementById('rel-inicio') as HTMLInputElement).value;
const fim = (document.getElementById('rel-fim') as HTMLInputElement).value;
try {
const params = new URLSearchParams();
if (inicio) params.set('inicio', inicio);
if (fim) params.set('fim', fim);
const data = await api.get(`/relatorios/vendas?${params.toString()}`);
// Resumo
document.getElementById('relatorio-resumo')!.innerHTML = `
<div class="card" style="text-align:center;padding:1rem;">
<p class="card-subtitle" style="margin-bottom:0.25rem;">Total Vendido</p>
<p style="font-size:1.25rem;font-weight:700;color:var(--success);">${formatBRL(data.resumo.totalVendas)}</p>
</div>
<div class="card" style="text-align:center;padding:1rem;">
<p class="card-subtitle" style="margin-bottom:0.25rem;">Comandas</p>
<p style="font-size:1.25rem;font-weight:700;">${data.resumo.totalComandas}</p>
</div>
<div class="card" style="text-align:center;padding:1rem;">
<p class="card-subtitle" style="margin-bottom:0.25rem;">Ticket Médio</p>
<p style="font-size:1.25rem;font-weight:700;color:var(--accent-primary);">${formatBRL(data.resumo.ticketMedio)}</p>
</div>
<div class="card" style="text-align:center;padding:1rem;">
<p class="card-subtitle" style="margin-bottom:0.25rem;">Descontos</p>
<p style="font-size:1.25rem;font-weight:700;color:var(--warning);">${formatBRL(data.resumo.totalDescontos)}</p>
</div>
<div class="card" style="text-align:center;padding:1rem;">
<p class="card-subtitle" style="margin-bottom:0.25rem;">Acréscimos</p>
<p style="font-size:1.25rem;font-weight:700;color:var(--accent-secondary);">${formatBRL(data.resumo.totalAcrescimos)}</p>
</div>
`;
// Top produtos
if (data.topProdutos.length > 0) {
document.getElementById('relatorio-top-produtos')!.innerHTML = `
<h4 style="margin-bottom:0.75rem;">🏆 Mais Vendidos</h4>
<div class="table-wrap">
<table>
<thead><tr><th>#</th><th>Produto</th><th style="text-align:center;">Qtd</th><th style="text-align:right;">Total</th></tr></thead>
<tbody>
${data.topProdutos.map((p: any, i: number) => `
<tr>
<td>${i + 1}º</td>
<td><strong>${p.nome}</strong></td>
<td style="text-align:center;">${p.quantidade}</td>
<td style="text-align:right;">${formatBRL(p.total)}</td>
</tr>
`).join('')}
</tbody>
</table>
</div>
`;
} else {
document.getElementById('relatorio-top-produtos')!.innerHTML = '';
}
// Vendas por dia
if (data.vendasPorDia.length > 0) {
document.getElementById('relatorio-vendas-dia')!.innerHTML = `
<h4 style="margin-bottom:0.75rem;">📅 Vendas por Dia</h4>
<div class="table-wrap">
<table>
<thead><tr><th>Data</th><th style="text-align:center;">Comandas</th><th style="text-align:right;">Total</th></tr></thead>
<tbody>
${data.vendasPorDia.map((d: any) => `
<tr>
<td>${new Date(d.data + 'T12:00:00').toLocaleDateString('pt-BR')}</td>
<td style="text-align:center;">${d.comandas}</td>
<td style="text-align:right;">${formatBRL(d.vendas)}</td>
</tr>
`).join('')}
</tbody>
</table>
</div>
`;
} else {
document.getElementById('relatorio-vendas-dia')!.innerHTML = '';
}
// Vendas por pagamento
if (data.vendasPorPagamento.length > 0) {
const pagLabels: Record<string, string> = {
DINHEIRO: '💵 Dinheiro', CARTAO_CREDITO: '💳 Cartão Crédito',
CARTAO_DEBITO: '💳 Cartão Débito', PIX: '📱 PIX', NAO_INFORMADO: '❓ Não informado',
};
document.getElementById('relatorio-pagamento')!.innerHTML = `
<h4 style="margin-bottom:0.75rem;">💰 Por Forma de Pagamento</h4>
<div class="table-wrap">
<table>
<thead><tr><th>Forma</th><th style="text-align:right;">Total</th></tr></thead>
<tbody>
${data.vendasPorPagamento.map((p: any) => `
<tr>
<td>${pagLabels[p.forma] ?? p.forma}</td>
<td style="text-align:right;">${formatBRL(p.total)}</td>
</tr>
`).join('')}
</tbody>
</table>
</div>
`;
} else {
document.getElementById('relatorio-pagamento')!.innerHTML = '';
}
} catch (err: any) {
toast(err.message, 'error');
}
};
document.getElementById('btn-refresh-dashboard')?.addEventListener('click', () => {
loadDashboard();
loadRelatorio();
});
document.getElementById('btn-gerar-relatorio')?.addEventListener('click', loadRelatorio);
await Promise.all([loadDashboard(), loadRelatorio()]);
}

181
web/src/views/kitchen.ts Normal file
View File

@@ -0,0 +1,181 @@
import { api } from '../api';
import { renderNavbar, toast } from '../utils';
let previousItemIds: Set<string> = new Set<string>();
let audioCtx: AudioContext | null = null;
function playNotificationSound() {
try {
if (!audioCtx) audioCtx = new AudioContext();
const osc = audioCtx.createOscillator();
const gain = audioCtx.createGain();
osc.connect(gain);
gain.connect(audioCtx.destination);
osc.type = 'sine';
osc.frequency.setValueAtTime(800, audioCtx.currentTime);
osc.frequency.setValueAtTime(1000, audioCtx.currentTime + 0.1);
osc.frequency.setValueAtTime(800, audioCtx.currentTime + 0.2);
gain.gain.setValueAtTime(0.3, audioCtx.currentTime);
gain.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 0.4);
osc.start(audioCtx.currentTime);
osc.stop(audioCtx.currentTime + 0.4);
} catch (e) {
// Audio not supported, silently fail
}
}
export async function renderKitchen(container: HTMLElement) {
container.innerHTML = `
${renderNavbar('/kitchen')}
<div class="container animate-fade-in">
<div class="page-header">
<h1>Painel de Preparo 👨‍🍳</h1>
<div style="display:flex;gap:0.75rem;align-items:center;flex-wrap:wrap;">
<label style="color:var(--text-secondary);font-size:0.875rem;">Filtrar:</label>
<button class="btn btn-secondary btn-sm filter-btn active" data-filter="">Todos</button>
<button class="btn btn-secondary btn-sm filter-btn" data-filter="true">🍳 Cozinha</button>
<button class="btn btn-secondary btn-sm filter-btn" data-filter="false">🍹 Bar</button>
<button class="btn btn-secondary btn-sm" id="btn-refresh">🔄 Atualizar</button>
<label style="display:flex;align-items:center;gap:0.4rem;cursor:pointer;color:var(--text-secondary);font-size:0.875rem;">
<input type="checkbox" id="auto-refresh-toggle" checked> Auto-refresh
</label>
</div>
</div>
<div class="tabs">
<button class="tab-btn active" data-status="PENDENTE">🔴 Pendente</button>
<button class="tab-btn" data-status="PREPARANDO">🟡 Preparando</button>
<button class="tab-btn" data-status="PRONTO">🟢 Pronto</button>
<button class="tab-btn" data-status="ENTREGUE">✅ Entregue</button>
</div>
<div class="grid" id="items-grid">
<p>Carregando pedidos...</p>
</div>
</div>
`;
let currentStatus = 'PENDENTE';
let currentFilter = '';
let autoRefreshInterval: ReturnType<typeof setInterval> | null = null;
const loadItems = async () => {
const grid = document.getElementById('items-grid')!;
grid.innerHTML = '<p class="card-subtitle">Carregando...</p>';
try {
let url = `/painel/itens?status=${currentStatus}`;
if (currentFilter !== '') url += `&itemCozinha=${currentFilter}`;
const items = await api.get(url);
const currentIds = new Set<string>(items.map((i: any) => i.id));
if (previousItemIds.size > 0) {
const newItems = items.filter((i: any) => !previousItemIds.has(i.id));
if (newItems.length > 0) {
playNotificationSound();
toast(`${newItems.length} novo(s) pedido(s) recebido(s)!`, 'success');
}
}
previousItemIds = currentIds;
if (!items.length) {
grid.innerHTML = `<p class="card-subtitle" style="grid-column:1/-1;text-align:center;padding:3rem 0;">
Nenhum pedido com status <strong>${currentStatus}</strong> 🎉
</p>`;
return;
}
const statusActions: Record<string, { label: string; next: string }> = {
PENDENTE: { label: '▶ Iniciar Preparo', next: 'PREPARANDO' },
PREPARANDO: { label: '✔ Marcar Pronto', next: 'PRONTO' },
PRONTO: { label: '🚀 Marcar Entregue', next: 'ENTREGUE' },
ENTREGUE: { label: '', next: '' },
};
grid.innerHTML = items.map((item: any) => {
const action = statusActions[item.status];
return `
<div class="card animate-fade-in">
<div style="display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:1rem;flex-wrap:wrap;gap:0.5rem;">
<span class="badge ${item.produto.itemCozinha ? 'badge-cozinha' : 'badge-barman'}">
${item.produto.itemCozinha ? '🍳 Cozinha' : '🍹 Bar'}
</span>
<span class="card-subtitle" style="margin:0;">Mesa: <strong>${item.comanda.identificador}</strong></span>
</div>
<h3 class="card-title">${item.quantidade}× ${item.produto.nome}</h3>
${item.observacao ? `<p style="color:var(--warning);font-size:0.875rem;margin-bottom:1rem;">⚠️ ${item.observacao}</p>` : ''}
<p class="card-subtitle" style="margin-bottom:1.5rem;">
Pedido às ${new Date(item.criadoEm).toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' })}
</p>
${action.label ? `
<button class="btn" style="width:100%;" onclick="window.advanceStatus('${item.id}','${action.next}')">
${action.label}
</button>
` : `<p class="card-subtitle" style="text-align:center;">✅ Entregue</p>`}
</div>
`;
}).join('');
} catch (err: any) {
grid.innerHTML = `<p style="color:var(--accent-primary)">Erro: ${err.message}</p>`;
}
};
const startAutoRefresh = () => {
stopAutoRefresh();
autoRefreshInterval = setInterval(loadItems, 10000);
};
const stopAutoRefresh = () => {
if (autoRefreshInterval) {
clearInterval(autoRefreshInterval);
autoRefreshInterval = null;
}
};
// Tab switching
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
currentStatus = (btn as HTMLElement).dataset.status!;
loadItems();
});
});
// Filter buttons
document.querySelectorAll('.filter-btn').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
currentFilter = (btn as HTMLElement).dataset.filter!;
loadItems();
});
});
document.getElementById('btn-refresh')?.addEventListener('click', loadItems);
document.getElementById('auto-refresh-toggle')?.addEventListener('change', (e) => {
if ((e.target as HTMLInputElement).checked) startAutoRefresh();
else stopAutoRefresh();
});
(window as any).advanceStatus = async (id: string, status: string) => {
try {
await api.patch(`/painel/itens/${id}/status`, { status });
toast('Status atualizado!', 'success');
loadItems();
} catch (err: any) {
toast(err.message, 'error');
}
};
// Cleanup on navigation
const cleanup = () => {
stopAutoRefresh();
previousItemIds.clear();
};
window.addEventListener('popstate', cleanup);
await loadItems();
startAutoRefresh();
}

58
web/src/views/login.ts Normal file
View File

@@ -0,0 +1,58 @@
import { api } from '../api';
import { navigateTo } from '../main';
export function renderLogin(container: HTMLElement) {
container.innerHTML = `
<div class="login-view animate-fade-in">
<div class="login-box" style="padding: 1rem;">
<div class="glass-panel">
<div style="text-align:center;margin-bottom:2rem;">
<div style="font-size:3rem;margin-bottom:0.5rem;">🍹</div>
<h2 style="margin:0 0 0.25rem;">Café em Saturno</h2>
<p class="card-subtitle" style="margin:0;">Entre com suas credenciais</p>
</div>
<form id="login-form">
<div class="form-group">
<label for="email">E-mail</label>
<input type="email" id="email" class="form-control" value="admin@gastrobar.com"
autocomplete="email" inputmode="email" required>
</div>
<div class="form-group">
<label for="password">Senha</label>
<input type="password" id="password" class="form-control" value="123456"
autocomplete="current-password" required>
</div>
<p id="login-error" class="error-message"></p>
<button type="submit" id="btn-login" class="btn" style="width:100%;margin-top:0.75rem;padding:0.875rem;">
Entrar
</button>
</form>
</div>
</div>
</div>
`;
const form = document.getElementById('login-form');
const errorEl = document.getElementById('login-error');
form?.addEventListener('submit', async (e) => {
e.preventDefault();
const email = (document.getElementById('email') as HTMLInputElement).value;
const senha = (document.getElementById('password') as HTMLInputElement).value;
if (errorEl) errorEl.style.display = 'none';
try {
const data = await api.post('/auth/login', { email, senha });
localStorage.setItem('@gastrobar:token', data.token);
localStorage.setItem('@gastrobar:user', JSON.stringify(data.user));
navigateTo('/kitchen');
} catch (err: any) {
if (errorEl) {
errorEl.textContent = err.message;
errorEl.style.display = 'block';
}
}
});
}

269
web/src/views/menu.ts Normal file
View File

@@ -0,0 +1,269 @@
import { api } from '../api';
import { renderNavbar, toast, formatBRL } from '../utils';
export async function renderMenu(container: HTMLElement) {
container.innerHTML = `
${renderNavbar('/menu')}
<div class="container animate-fade-in">
<div class="page-header">
<h1>Cardápio 🍔</h1>
</div>
<div class="tabs">
<button class="tab-btn active" id="tab-produtos">Produtos</button>
<button class="tab-btn" id="tab-categorias">Categorias</button>
</div>
<div id="tab-content"></div>
</div>
<!-- Modal Produto -->
<div id="modal-produto" class="modal-overlay" style="display:none;">
<div class="modal" style="max-width:600px;">
<div class="modal-header">
<h3 id="modal-produto-title">Novo Produto</h3>
<button class="btn-icon" onclick="document.getElementById('modal-produto').style.display='none'">✕</button>
</div>
<form id="form-produto">
<input type="hidden" id="produto-id">
<div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;">
<div class="form-group" style="margin:0;">
<label>Nome *</label>
<input type="text" id="p-nome" class="form-control" required>
</div>
<div class="form-group" style="margin:0;">
<label>Categoria *</label>
<select id="p-categoria" class="form-control" required></select>
</div>
<div class="form-group" style="margin:0;">
<label>Preço de Venda (R$) *</label>
<input type="number" id="p-preco" class="form-control" step="0.01" min="0" required>
</div>
<div class="form-group" style="margin:0;">
<label>Custo (R$)</label>
<input type="number" id="p-custo" class="form-control" step="0.01" min="0">
</div>
<div class="form-group" style="margin:0;">
<label>Estoque Atual</label>
<input type="number" id="p-estoque" class="form-control" value="0" min="0">
</div>
<div class="form-group" style="margin:0;">
<label>Estoque Mínimo</label>
<input type="number" id="p-estoque-min" class="form-control" value="0" min="0">
</div>
</div>
<div class="form-group" style="margin-top:1rem;">
<label>Descrição</label>
<input type="text" id="p-desc" class="form-control" placeholder="Descrição breve do produto">
</div>
<div style="display:flex;gap:2rem;margin-bottom:1.5rem;align-items:center;">
<label style="display:flex;align-items:center;gap:0.5rem;cursor:pointer;color:var(--text-primary);">
<input type="checkbox" id="p-cozinha"> Item de Cozinha
</label>
<label style="display:flex;align-items:center;gap:0.5rem;cursor:pointer;color:var(--text-primary);">
<input type="checkbox" id="p-ativo" checked> Ativo
</label>
</div>
<button type="submit" class="btn" style="width:100%;">Salvar Produto</button>
</form>
</div>
</div>
</div>
<div id="modal-categoria" class="modal-overlay" style="display:none;">
<div class="modal">
<div class="modal-header">
<h3>Nova Categoria</h3>
<button class="btn-icon" onclick="document.getElementById('modal-categoria').style.display='none'">✕</button>
</div>
<div class="modal-body">
<form id="form-categoria">
<div class="form-group">
<label>Nome da Categoria *</label>
<input type="text" id="cat-nome" class="form-control" required>
</div>
<button type="submit" class="btn" style="width:100%;">Criar Categoria</button>
</form>
</div>
</div>
</div>
`;
let categorias: any[] = [];
const loadCategorias = async () => {
categorias = await api.get('/categorias');
const sel = document.getElementById('p-categoria') as HTMLSelectElement;
if (sel) sel.innerHTML = categorias.map((c: any) => `<option value="${c.id}">${c.nome}</option>`).join('');
};
const renderTabProdutos = async () => {
const tc = document.getElementById('tab-content')!;
const products = await api.get('/produtos');
tc.innerHTML = `
<div class="page-header" style="margin-bottom:1rem;">
<span class="card-subtitle">${products.length} produto(s) cadastrado(s)</span>
<button class="btn" id="btn-novo-produto"> Novo Produto</button>
</div>
<div class="table-wrap">
<table>
<thead>
<tr><th>Nome</th><th>Categoria</th><th>Preço</th><th>Estoque</th><th>Tipo</th><th>Status</th><th>Ações</th></tr>
</thead>
<tbody>
${products.map((p: any) => `
<tr>
<td data-label="Produto"><strong>${p.nome}</strong>${p.descricao ? `<br><small style="color:var(--text-secondary)">${p.descricao}</small>` : ''}</td>
<td data-label="Categoria">${p.categoria?.nome ?? '—'}</td>
<td data-label="Preço">${formatBRL(p.preco)}</td>
<td data-label="Estoque">
<span style="color:${p.estoqueAtual <= p.estoqueMinimo ? 'var(--accent-primary)' : 'var(--text-primary)'}">
${p.estoqueAtual} ${p.estoqueAtual <= p.estoqueMinimo ? '⚠️' : ''}
</span>
</td>
<td data-label="Tipo"><span class="badge ${p.itemCozinha ? 'badge-cozinha' : 'badge-barman'}">${p.itemCozinha ? 'Cozinha' : 'Bar'}</span></td>
<td data-label="Status"><span class="badge ${p.ativo ? 'badge-success' : 'badge-warning'}">${p.ativo ? 'Ativo' : 'Inativo'}</span></td>
<td data-label="Ações" style="display:flex;gap:0.5rem;flex-wrap:wrap;">
<button class="btn btn-sm btn-secondary" onclick="window.editProduct(${JSON.stringify(p).replace(/"/g, '&quot;')})">✏️</button>
<button class="btn btn-sm btn-danger" onclick="window.deleteProduct('${p.id}','${p.nome}')">🗑</button>
</td>
</tr>
`).join('')}
</tbody>
</table>
</div>
`;
document.getElementById('btn-novo-produto')?.addEventListener('click', () => {
clearProductForm();
(document.getElementById('modal-produto') as HTMLElement).style.display = 'flex';
});
};
const renderTabCategorias = async () => {
const tc = document.getElementById('tab-content')!;
const cats = await api.get('/categorias');
tc.innerHTML = `
<div class="page-header" style="margin-bottom:1rem;">
<span class="card-subtitle">${cats.length} categoria(s)</span>
<button class="btn" id="btn-nova-cat"> Nova Categoria</button>
</div>
<div class="table-wrap">
<table>
<thead><tr><th>Nome</th><th>Nº Produtos</th><th>Ações</th></tr></thead>
<tbody>
${cats.map((c: any) => `
<tr>
<td data-label="Nome"><strong>${c.nome}</strong></td>
<td data-label="Nº Produtos">${c.produtos?.length ?? 0}</td>
<td data-label="Ações">
<button class="btn btn-sm btn-danger" onclick="window.deleteCategory('${c.id}','${c.nome}')">🗑 Excluir</button>
</td>
</tr>
`).join('')}
</tbody>
</table>
</div>
`;
document.getElementById('btn-nova-cat')?.addEventListener('click', () => {
(document.getElementById('modal-categoria') as HTMLElement).style.display = 'flex';
});
};
// Tabs
document.getElementById('tab-produtos')?.addEventListener('click', async () => {
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
document.getElementById('tab-produtos')?.classList.add('active');
await renderTabProdutos();
});
document.getElementById('tab-categorias')?.addEventListener('click', async () => {
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
document.getElementById('tab-categorias')?.classList.add('active');
await renderTabCategorias();
});
// Form Produto
document.getElementById('form-produto')?.addEventListener('submit', async (e) => {
e.preventDefault();
const id = (document.getElementById('produto-id') as HTMLInputElement).value;
const payload: any = {
nome: (document.getElementById('p-nome') as HTMLInputElement).value,
categoriaId: (document.getElementById('p-categoria') as HTMLSelectElement).value,
preco: parseFloat((document.getElementById('p-preco') as HTMLInputElement).value),
custo: parseFloat((document.getElementById('p-custo') as HTMLInputElement).value) || undefined,
estoqueAtual: parseInt((document.getElementById('p-estoque') as HTMLInputElement).value),
estoqueMinimo: parseInt((document.getElementById('p-estoque-min') as HTMLInputElement).value),
descricao: (document.getElementById('p-desc') as HTMLInputElement).value || undefined,
itemCozinha: (document.getElementById('p-cozinha') as HTMLInputElement).checked,
ativo: (document.getElementById('p-ativo') as HTMLInputElement).checked,
};
try {
if (id) await api.patch(`/produtos/${id}`, payload);
else await api.post('/produtos', payload);
toast(id ? 'Produto atualizado!' : 'Produto cadastrado!', 'success');
(document.getElementById('modal-produto') as HTMLElement).style.display = 'none';
await renderTabProdutos();
} catch (err: any) { toast(err.message, 'error'); }
});
// Form Categoria
document.getElementById('form-categoria')?.addEventListener('submit', async (e) => {
e.preventDefault();
const nome = (document.getElementById('cat-nome') as HTMLInputElement).value;
try {
await api.post('/categorias', { nome });
toast('Categoria criada!', 'success');
(document.getElementById('modal-categoria') as HTMLElement).style.display = 'none';
await loadCategorias();
await renderTabCategorias();
} catch (err: any) { toast(err.message, 'error'); }
});
// Global handlers
(window as any).editProduct = (p: any) => {
(document.getElementById('produto-id') as HTMLInputElement).value = p.id;
(document.getElementById('p-nome') as HTMLInputElement).value = p.nome;
(document.getElementById('p-preco') as HTMLInputElement).value = p.preco;
(document.getElementById('p-custo') as HTMLInputElement).value = p.custo ?? '';
(document.getElementById('p-estoque') as HTMLInputElement).value = p.estoqueAtual;
(document.getElementById('p-estoque-min') as HTMLInputElement).value = p.estoqueMinimo;
(document.getElementById('p-desc') as HTMLInputElement).value = p.descricao ?? '';
(document.getElementById('p-cozinha') as HTMLInputElement).checked = p.itemCozinha;
(document.getElementById('p-ativo') as HTMLInputElement).checked = p.ativo;
const sel = document.getElementById('p-categoria') as HTMLSelectElement;
if (sel) sel.value = p.categoriaId;
(document.getElementById('modal-produto-title') as HTMLElement).textContent = 'Editar Produto';
(document.getElementById('modal-produto') as HTMLElement).style.display = 'flex';
};
(window as any).deleteProduct = async (id: string, nome: string) => {
if (!confirm(`Excluir o produto "${nome}"?`)) return;
try {
await api.patch(`/produtos/${id}`, { ativo: false });
toast('Produto desativado!', 'success');
await renderTabProdutos();
} catch (err: any) { toast(err.message, 'error'); }
};
(window as any).deleteCategory = async (id: string, nome: string) => {
if (!confirm(`Excluir a categoria "${nome}"?`)) return;
try {
await api.delete(`/categorias/${id}`);
toast('Categoria excluída!', 'success');
await renderTabCategorias();
} catch (err: any) { toast(err.message, 'error'); }
};
await loadCategorias();
await renderTabProdutos();
}
function clearProductForm() {
(document.getElementById('produto-id') as HTMLInputElement).value = '';
(document.getElementById('p-nome') as HTMLInputElement).value = '';
(document.getElementById('p-preco') as HTMLInputElement).value = '';
(document.getElementById('p-custo') as HTMLInputElement).value = '';
(document.getElementById('p-estoque') as HTMLInputElement).value = '0';
(document.getElementById('p-estoque-min') as HTMLInputElement).value = '0';
(document.getElementById('p-desc') as HTMLInputElement).value = '';
(document.getElementById('p-cozinha') as HTMLInputElement).checked = false;
(document.getElementById('p-ativo') as HTMLInputElement).checked = true;
(document.getElementById('modal-produto-title') as HTMLElement).textContent = 'Novo Produto';
}

583
web/src/views/orders.ts Normal file
View File

@@ -0,0 +1,583 @@
import { api } from '../api';
import { renderNavbar, toast, formatBRL, getUser, statusBadge } from '../utils';
let localComandas: any[] = [];
const FORMAS_PAGAMENTO = [
{ value: 'DINHEIRO', label: '💵 Dinheiro' },
{ value: 'CARTAO_CREDITO', label: '💳 Cartão Crédito' },
{ value: 'CARTAO_DEBITO', label: '💳 Cartão Débito' },
{ value: 'PIX', label: '📱 PIX' },
];
export async function renderOrders(container: HTMLElement) {
container.innerHTML = `
${renderNavbar('/orders')}
<div class="container animate-fade-in">
<div class="page-header">
<h1>Comandas 📋</h1>
<button class="btn" id="btn-nova-comanda"> Nova Comanda</button>
</div>
<form id="form-busca-comandas" class="comandas-search-bar">
<div class="comandas-search-field">
<label>De</label>
<input type="date" id="busca-data-inicio" class="form-control">
</div>
<div class="comandas-search-field">
<label>Até</label>
<input type="date" id="busca-data-fim" class="form-control">
</div>
<div class="comandas-search-actions">
<button type="submit" class="btn btn-sm btn-secondary">Buscar</button>
<button type="button" class="btn btn-sm" id="btn-busca-limpar" style="color:var(--text-secondary);">Limpar</button>
</div>
</form>
<div id="comandas-list"><p class="card-subtitle">Carregando...</p></div>
</div>
<!-- Modal Nova Comanda -->
<div id="modal-nova-comanda" class="modal-overlay" style="display:none;">
<div class="modal">
<div class="modal-header">
<h3>Abrir Nova Comanda</h3>
<button class="btn-icon" id="modal-close">✕</button>
</div>
<form id="form-nova-comanda">
<div class="form-group">
<label>Identificador (Mesa / Nome)</label>
<input type="text" id="identificador" class="form-control" placeholder="Ex: Mesa 5, João Silva" required>
</div>
<div class="form-group">
<label>Nome do Cliente (opcional)</label>
<input type="text" id="nomeCliente" class="form-control" placeholder="Nome do cliente">
</div>
<button type="submit" class="btn" style="width:100%;margin-top:0.5rem;">Abrir Comanda</button>
</form>
</div>
</div>
<!-- Modal Adicionar Item -->
<div id="modal-add-item" class="modal-overlay" style="display:none;">
<div class="modal" style="max-width: 500px;">
<div class="modal-header">
<h3>Adicionar Pedido</h3>
<button class="btn-icon" id="modal-item-close">✕</button>
</div>
<input type="hidden" id="current-comanda-id">
<form id="form-add-item">
<div class="form-group">
<label>Buscar Produto</label>
<input type="text" id="modal-produto-busca" class="form-control" placeholder="Digite o nome do produto...">
</div>
<div class="form-group">
<label id="grid-label">Produtos Sugeridos (Mais Vendidos)</label>
<div id="modal-produtos-grid" class="product-mini-grid">
</div>
</div>
<input type="hidden" id="selected-produto-id" required>
<div id="selected-produto-preview" class="card-subtitle" style="margin-top: -0.5rem; margin-bottom: 1.5rem; font-weight: 600; color: var(--accent-primary);">
Nenhum produto selecionado
</div>
<div class="form-group">
<label>Quantidade</label>
<input type="number" id="qtd" class="form-control" value="1" min="1" required>
</div>
<div class="form-group">
<label>Observação</label>
<input type="text" id="obs" class="form-control" placeholder="Ex: sem cebola, bem passado...">
</div>
<button type="submit" class="btn" style="width:100%;margin-top:0.5rem;">Adicionar Pedido</button>
</form>
</div>
</div>
<!-- Modal Detalhes da Comanda -->
<div id="modal-detalhes-comanda" class="modal-overlay" style="display:none;">
<div class="modal" style="max-width: 650px;">
<div class="modal-header">
<h3>Detalhes da Comanda</h3>
<button class="btn-icon" id="modal-detalhes-close">✕</button>
</div>
<input type="hidden" id="detalhes-comanda-id">
<div class="detalhes-summary" id="detalhes-summary">
<div class="detalhes-summary-row">
<span class="detalhes-summary-label" id="detalhes-label-ident">—</span>
<span class="detalhes-summary-client" id="detalhes-label-client"></span>
</div>
<div id="detalhes-label-status"></div>
</div>
<div class="detalhes-edit-section">
<button type="button" class="detalhes-edit-toggle" id="detalhes-edit-toggle">
<span>✏️ Editar Informações</span>
<span class="detalhes-edit-arrow">▾</span>
</button>
<div class="detalhes-edit-body" id="detalhes-edit-body">
<form id="form-editar-comanda">
<div style="display:grid; grid-template-columns: 1fr 1fr; gap: 0.75rem;">
<div class="form-group" style="margin:0;">
<label>Identificador</label>
<input type="text" id="detalhes-identificador" class="form-control" required>
</div>
<div class="form-group" style="margin:0;">
<label>Cliente</label>
<input type="text" id="detalhes-cliente" class="form-control">
</div>
<div class="form-group" style="margin:0;">
<label>Status</label>
<select id="detalhes-status" class="form-control">
<option value="ABERTA">Aberta</option>
<option value="FECHADA">Fechada</option>
<option value="PAGA">Paga</option>
<option value="CANCELADA">Cancelada</option>
</select>
</div>
<div class="form-group" style="margin:0;">
<label>Forma de Pagamento</label>
<select id="detalhes-forma-pagamento" class="form-control">
<option value="">Não informado</option>
${FORMAS_PAGAMENTO.map(fp => `<option value="${fp.value}">${fp.label}</option>`).join('')}
</select>
</div>
<div class="form-group" style="margin:0;">
<label>Desconto (R$)</label>
<input type="number" id="detalhes-desconto" class="form-control" step="0.01" min="0" value="0">
</div>
<div class="form-group" style="margin:0;">
<label>Acréscimo (R$)</label>
<input type="number" id="detalhes-acrescimo" class="form-control" step="0.01" min="0" value="0">
</div>
<div class="form-group" style="margin:0; grid-column: 1 / -1; display:flex; align-items:center; gap:0.75rem;">
<input type="checkbox" id="detalhes-taxa-servico">
<label for="detalhes-taxa-servico" style="cursor:pointer;color:var(--text-primary);">Taxa de Serviço (10%)</label>
</div>
<div class="form-group" style="margin:0; grid-column: 1 / -1;" id="motivo-cancelamento-group" style="display:none;">
<label>Motivo do Cancelamento</label>
<input type="text" id="detalhes-motivo-cancelamento" class="form-control" placeholder="Motivo (opcional)">
</div>
</div>
<button type="submit" class="btn btn-sm btn-secondary" style="width:100%; margin-top: 1rem;">Salvar Informações</button>
</form>
</div>
</div>
<hr style="border: 0; border-top: 1px solid var(--border-color); margin: 1.25rem 0;">
<h4>Itens Consumidos</h4>
<div class="table-wrap" style="max-height: 180px; overflow-y: auto; margin-top: 0.5rem; margin-bottom: 1rem;">
<table style="font-size: 0.85rem;">
<thead>
<tr>
<th>Produto</th>
<th style="text-align:center;">Qtd</th>
<th style="text-align:right;">Subtotal</th>
<th>Obs</th>
<th>Status</th>
<th>Ações</th>
</tr>
</thead>
<tbody id="detalhes-itens-tbody">
</tbody>
</table>
</div>
<div id="detalhes-resumo-financeiro" style="margin-top:0.5rem;">
</div>
<div class="total-bar" style="margin-top:0.5rem; padding: 0.75rem 1rem;">
<span style="color:var(--text-secondary); font-size: 0.9rem;">Total Final:</span>
<span class="total-value" id="detalhes-total" style="font-size: 1.3rem;">R$ 0,00</span>
</div>
<div style="display: flex; gap: 0.75rem; margin-top: 1.25rem;" id="detalhes-acoes-pagamento">
</div>
</div>
</div>
`;
await loadComandas({ status: 'ABERTA,FECHADA' });
bindOrderEvents();
}
function calcularTotalFinal(c: any): number {
let total = c.total || 0;
total -= (c.desconto || 0);
total += (c.acrescimo || 0);
if (c.taxaServico) total += total * 0.10;
return Math.max(total, 0);
}
async function loadComandas(params?: { status?: string; dataInicio?: string; dataFim?: string }) {
const list = document.getElementById('comandas-list')!;
try {
const qs = new URLSearchParams();
if (params?.status) qs.set('status', params.status);
if (params?.dataInicio) qs.set('dataInicio', params.dataInicio);
if (params?.dataFim) qs.set('dataFim', params.dataFim);
const query = qs.toString();
const comandas = await api.get(`/comandas${query ? '?' + query : ''}`);
localComandas = comandas;
if (!comandas.length) {
list.innerHTML = `<p class="card-subtitle" style="text-align:center;margin-top:2rem;">Nenhuma comanda aberta no momento.</p>`;
return;
}
list.innerHTML = `
<div class="table-wrap">
<table>
<thead>
<tr>
<th>Identificador</th>
<th>Cliente</th>
<th>Status</th>
<th>Total</th>
<th>Aberta em</th>
<th>Ações</th>
</tr>
</thead>
<tbody>
${comandas.map((c: any) => `
<tr>
<td data-label="Mesa" class="cmd-ident"><strong>${c.identificador}</strong></td>
<td data-label="Cliente" class="cmd-client">${c.nomeCliente ?? ''}</td>
<td data-label="Status" class="cmd-status"><span class="badge status-${c.status.toLowerCase()}">${c.status}</span></td>
<td data-label="Total" class="cmd-total"><strong>${formatBRL(calcularTotalFinal(c))}</strong></td>
<td data-label="Aberta em" class="cmd-data">${new Date(c.criadoEm).toLocaleString('pt-BR')}</td>
<td data-label="Ações" class="cmd-acoes">
<button class="btn btn-sm btn-secondary" onclick="window.openDetails('${c.id}')">🔍 Ver</button>
${c.status === 'ABERTA' ? `
<button class="btn btn-sm btn-secondary" onclick="window.openAddItem('${c.id}')">+ Item</button>
` : ''}
</td>
</tr>
`).join('')}
</tbody>
</table>
</div>
`;
} catch (err: any) {
list.innerHTML = `<p style="color:var(--accent-primary)">${err.message}</p>`;
}
}
function renderProductCards(products: any[]) {
const grid = document.getElementById('modal-produtos-grid');
if (!grid) return;
if (products.length === 0) {
grid.innerHTML = '<p class="card-subtitle" style="grid-column: 1/-1; text-align: center; margin: 1rem 0;">Nenhum produto encontrado</p>';
return;
}
grid.innerHTML = products.map((p: any) => `
<div class="product-mini-card" data-id="${p.id}" data-nome="${p.nome}" data-preco="${p.preco}">
<div>
<div class="product-mini-card-name">${p.nome}</div>
<div class="product-mini-card-price">${formatBRL(p.preco)}</div>
</div>
<div class="product-mini-card-badge">
${p.totalVendido !== undefined ? `Vendidos: ${p.totalVendido}` : (p.categoria?.nome ?? '')}
</div>
</div>
`).join('');
const cards = grid.querySelectorAll('.product-mini-card');
cards.forEach(card => {
card.addEventListener('click', () => {
cards.forEach(c => c.classList.remove('selected'));
card.classList.add('selected');
const id = (card as HTMLElement).dataset.id!;
const nome = (card as HTMLElement).dataset.nome!;
const preco = parseFloat((card as HTMLElement).dataset.preco!);
(document.getElementById('selected-produto-id') as HTMLInputElement).value = id;
const preview = document.getElementById('selected-produto-preview')!;
preview.textContent = `Selecionado: ${nome} (${formatBRL(preco)})`;
preview.style.color = 'var(--success)';
});
});
}
function bindOrderEvents() {
document.getElementById('btn-nova-comanda')?.addEventListener('click', () => {
(document.getElementById('modal-nova-comanda') as HTMLElement).style.display = 'flex';
});
document.getElementById('modal-close')?.addEventListener('click', () => {
(document.getElementById('modal-nova-comanda') as HTMLElement).style.display = 'none';
});
document.getElementById('modal-item-close')?.addEventListener('click', () => {
(document.getElementById('modal-add-item') as HTMLElement).style.display = 'none';
});
document.getElementById('modal-detalhes-close')?.addEventListener('click', () => {
(document.getElementById('modal-detalhes-comanda') as HTMLElement).style.display = 'none';
});
document.getElementById('form-busca-comandas')?.addEventListener('submit', (e) => {
e.preventDefault();
const dataInicio = (document.getElementById('busca-data-inicio') as HTMLInputElement).value;
const dataFim = (document.getElementById('busca-data-fim') as HTMLInputElement).value;
if (!dataInicio && !dataFim) return loadComandas({ status: 'ABERTA,FECHADA' });
loadComandas({ dataInicio, dataFim });
});
document.getElementById('btn-busca-limpar')?.addEventListener('click', () => {
(document.getElementById('busca-data-inicio') as HTMLInputElement).value = '';
(document.getElementById('busca-data-fim') as HTMLInputElement).value = '';
loadComandas({ status: 'ABERTA,FECHADA' });
});
document.getElementById('detalhes-edit-toggle')?.addEventListener('click', () => {
const section = document.querySelector('.detalhes-edit-section');
section?.classList.toggle('expanded');
});
// Toggle motivo cancelamento visibility
document.getElementById('detalhes-status')?.addEventListener('change', (e) => {
const val = (e.target as HTMLSelectElement).value;
const group = document.getElementById('motivo-cancelamento-group') as HTMLElement;
if (group) group.style.display = val === 'CANCELADA' ? 'block' : 'none';
});
document.getElementById('form-nova-comanda')?.addEventListener('submit', async (e) => {
e.preventDefault();
const ident = (document.getElementById('identificador') as HTMLInputElement).value;
const nome = (document.getElementById('nomeCliente') as HTMLInputElement).value;
try {
await api.post('/comandas', { identificador: ident, nomeCliente: nome || undefined });
toast('Comanda aberta com sucesso!', 'success');
(document.getElementById('modal-nova-comanda') as HTMLElement).style.display = 'none';
await loadComandas({ status: 'ABERTA,FECHADA' });
} catch (err: any) {
toast(err.message, 'error');
}
});
document.getElementById('form-editar-comanda')?.addEventListener('submit', async (e) => {
e.preventDefault();
const id = (document.getElementById('detalhes-comanda-id') as HTMLInputElement).value;
const payload: any = {
identificador: (document.getElementById('detalhes-identificador') as HTMLInputElement).value,
nomeCliente: (document.getElementById('detalhes-cliente') as HTMLInputElement).value || undefined,
status: (document.getElementById('detalhes-status') as HTMLSelectElement).value,
desconto: parseFloat((document.getElementById('detalhes-desconto') as HTMLInputElement).value) || 0,
acrescimo: parseFloat((document.getElementById('detalhes-acrescimo') as HTMLInputElement).value) || 0,
taxaServico: (document.getElementById('detalhes-taxa-servico') as HTMLInputElement).checked,
motivoCancelamento: (document.getElementById('detalhes-motivo-cancelamento') as HTMLInputElement).value || undefined,
};
try {
await api.patch(`/comandas/${id}`, payload);
toast('Comanda atualizada!', 'success');
(document.getElementById('modal-detalhes-comanda') as HTMLElement).style.display = 'none';
await loadComandas({ status: 'ABERTA,FECHADA' });
} catch (err: any) {
toast(err.message, 'error');
}
});
document.getElementById('form-add-item')?.addEventListener('submit', async (e) => {
e.preventDefault();
const comandaId = (document.getElementById('current-comanda-id') as HTMLInputElement).value;
const produtoId = (document.getElementById('selected-produto-id') as HTMLInputElement).value;
if (!produtoId) {
toast('Por favor, selecione um produto nos cards acima!', 'error');
return;
}
const quantidade = parseInt((document.getElementById('qtd') as HTMLInputElement).value);
const observacao = (document.getElementById('obs') as HTMLInputElement).value;
try {
await api.post(`/comandas/${comandaId}/itens`, { produtoId, quantidade, observacao: observacao || undefined });
toast('Pedido enviado para preparo!', 'success');
(document.getElementById('modal-add-item') as HTMLElement).style.display = 'none';
await loadComandas({ status: 'ABERTA,FECHADA' });
} catch (err: any) {
toast(err.message, 'error');
}
});
const buscaInput = document.getElementById('modal-produto-busca') as HTMLInputElement;
let timer: any;
buscaInput?.addEventListener('input', () => {
clearTimeout(timer);
timer = setTimeout(async () => {
const query = buscaInput.value.trim();
const gridLabel = document.getElementById('grid-label')!;
try {
if (query.length > 0) {
gridLabel.textContent = 'Resultados da Busca';
const products = await api.get(`/produtos/busca?q=${encodeURIComponent(query)}`);
renderProductCards(products);
} else {
gridLabel.textContent = 'Produtos Sugeridos (Mais Vendidos)';
const topProducts = await api.get('/produtos/mais-vendidos');
renderProductCards(topProducts);
}
} catch (err) {
console.error(err);
}
}, 300);
});
(window as any).openAddItem = async (comandaId: string) => {
(document.getElementById('current-comanda-id') as HTMLInputElement).value = comandaId;
(document.getElementById('selected-produto-id') as HTMLInputElement).value = '';
const buscaInput = document.getElementById('modal-produto-busca') as HTMLInputElement;
if (buscaInput) buscaInput.value = '';
const preview = document.getElementById('selected-produto-preview')!;
preview.textContent = 'Nenhum produto selecionado';
preview.style.color = 'var(--accent-primary)';
const gridLabel = document.getElementById('grid-label');
if (gridLabel) gridLabel.textContent = 'Produtos Sugeridos (Mais Vendidos)';
(document.getElementById('modal-add-item') as HTMLElement).style.display = 'flex';
try {
const topProducts = await api.get('/produtos/mais-vendidos');
renderProductCards(topProducts);
} catch (err) {
console.error(err);
}
};
(window as any).openDetails = (comandaId: string) => {
const c = localComandas.find((x: any) => x.id === comandaId);
if (!c) return;
(document.getElementById('detalhes-comanda-id') as HTMLInputElement).value = c.id;
(document.getElementById('detalhes-identificador') as HTMLInputElement).value = c.identificador;
(document.getElementById('detalhes-cliente') as HTMLInputElement).value = c.nomeCliente ?? '';
(document.getElementById('detalhes-status') as HTMLSelectElement).value = c.status;
(document.getElementById('detalhes-forma-pagamento') as HTMLSelectElement).value = c.formaPagamento ?? '';
(document.getElementById('detalhes-desconto') as HTMLInputElement).value = c.desconto ?? 0;
(document.getElementById('detalhes-acrescimo') as HTMLInputElement).value = c.acrescimo ?? 0;
(document.getElementById('detalhes-taxa-servico') as HTMLInputElement).checked = c.taxaServico ?? false;
(document.getElementById('detalhes-motivo-cancelamento') as HTMLInputElement).value = c.motivoCancelamento ?? '';
// Show/hide motivo cancelamento
const motivoGroup = document.getElementById('motivo-cancelamento-group') as HTMLElement;
if (motivoGroup) motivoGroup.style.display = c.status === 'CANCELADA' ? 'block' : 'none';
// Summary labels
document.getElementById('detalhes-label-ident')!.textContent = c.identificador;
document.getElementById('detalhes-label-client')!.textContent = c.nomeCliente ? `· ${c.nomeCliente}` : '';
document.getElementById('detalhes-label-status')!.innerHTML = statusBadge(c.status);
// Render itens
const tbody = document.getElementById('detalhes-itens-tbody')!;
const itens = c.itens ?? [];
const user = getUser();
const canDelete = user && ['ADMIN', 'CAIXA'].includes(user.role) && c.status === 'ABERTA';
if (itens.length === 0) {
tbody.innerHTML = `<tr><td colspan="6" style="text-align:center;color:var(--text-secondary);">Nenhum item adicionado</td></tr>`;
} else {
tbody.innerHTML = itens.map((i: any) => `
<tr>
<td data-label="Produto" class="item-name">${i.quantidade}x ${i.produto?.nome ?? '—'}</td>
<td data-label="Qtd" class="item-qty">${i.quantidade}</td>
<td data-label="Subtotal" class="item-value">${formatBRL(i.precoUnitario * i.quantidade)}</td>
<td data-label="Obs" class="item-obs">${i.observacao ?? ''}</td>
<td data-label="Status" class="item-status"><span class="badge badge-${i.status === 'ENTREGUE' ? 'success' : 'warning'}">${i.status}</span></td>
<td data-label="Ações" class="item-actions">
${canDelete ? `
<button class="btn btn-sm btn-danger btn-delete-item" data-id="${i.id}" data-nome="${i.produto?.nome ?? 'item'}">🗑</button>
` : ''}
</td>
</tr>
`).join('');
}
if (canDelete) {
tbody.querySelectorAll('.btn-delete-item').forEach(btn => {
btn.addEventListener('click', async () => {
const itemId = (btn as HTMLElement).dataset.id!;
const itemNome = (btn as HTMLElement).dataset.nome!;
if (!confirm(`Remover "${itemNome}" da comanda?`)) return;
try {
await api.delete(`/comandas/itens/${itemId}`);
toast('Item removido!', 'success');
await loadComandas({ status: 'ABERTA,FECHADA' });
(document.getElementById('modal-detalhes-comanda') as HTMLElement).style.display = 'none';
(window as any).openDetails(comandaId);
} catch (err: any) {
toast(err.message, 'error');
}
});
});
}
// Resumo financeiro
const resumoEl = document.getElementById('detalhes-resumo-financeiro')!;
const subtotal = c.total || 0;
const desconto = c.desconto || 0;
const acrescimo = c.acrescimo || 0;
const taxaServico = c.taxaServico ? (subtotal - desconto + acrescimo) * 0.10 : 0;
const totalFinal = Math.max(subtotal - desconto + acrescimo + taxaServico, 0);
resumoEl.innerHTML = `
<div style="background:var(--bg-secondary);border-radius:8px;padding:0.75rem 1rem;font-size:0.85rem;">
<div style="display:flex;justify-content:space-between;margin-bottom:0.25rem;">
<span style="color:var(--text-secondary);">Subtotal:</span>
<span>${formatBRL(subtotal)}</span>
</div>
${desconto > 0 ? `<div style="display:flex;justify-content:space-between;margin-bottom:0.25rem;color:var(--warning);">
<span>Desconto:</span><span>-${formatBRL(desconto)}</span>
</div>` : ''}
${acrescimo > 0 ? `<div style="display:flex;justify-content:space-between;margin-bottom:0.25rem;color:var(--accent-secondary);">
<span>Acréscimo:</span><span>+${formatBRL(acrescimo)}</span>
</div>` : ''}
${c.taxaServico ? `<div style="display:flex;justify-content:space-between;margin-bottom:0.25rem;color:var(--text-secondary);">
<span>Taxa Serviço (10%):</span><span>+${formatBRL(taxaServico)}</span>
</div>` : ''}
${c.formaPagamento ? `<div style="display:flex;justify-content:space-between;margin-bottom:0.25rem;">
<span style="color:var(--text-secondary);">Pagamento:</span>
<span>${c.formaPagamento.replace('_', ' ')}</span>
</div>` : ''}
</div>
`;
document.getElementById('detalhes-total')!.textContent = formatBRL(totalFinal);
const acoesContainer = document.getElementById('detalhes-acoes-pagamento')!;
acoesContainer.innerHTML = '';
const canPay = user && ['ADMIN', 'CAIXA'].includes(user.role);
if (canPay && c.status !== 'PAGA' && c.status !== 'CANCELADA') {
acoesContainer.innerHTML = `
<div style="width:100%;">
<div class="form-group" style="margin-bottom:0.75rem;">
<label>Forma de Pagamento</label>
<select id="pagamento-forma" class="form-control">
${FORMAS_PAGAMENTO.map(fp => `<option value="${fp.value}">${fp.label}</option>`).join('')}
</select>
</div>
<button type="button" class="btn btn-success" style="width: 100%;" id="btn-detalhes-receber">
💳 Receber Valor / Pagar
</button>
</div>
`;
document.getElementById('btn-detalhes-receber')?.addEventListener('click', async () => {
const forma = (document.getElementById('pagamento-forma') as HTMLSelectElement).value;
if (!confirm(`Confirmar recebimento de ${formatBRL(totalFinal)} para "${c.identificador}"?`)) return;
try {
await api.post(`/comandas/${c.id}/pagar`, { formaPagamento: forma });
toast('Pagamento registrado!', 'success');
(document.getElementById('modal-detalhes-comanda') as HTMLElement).style.display = 'none';
await loadComandas({ status: 'ABERTA,FECHADA' });
} catch (err: any) {
toast(err.message, 'error');
}
});
}
(document.getElementById('modal-detalhes-comanda') as HTMLElement).style.display = 'flex';
document.querySelector('.detalhes-edit-section')?.classList.remove('expanded');
};
}

156
web/src/views/users.ts Normal file
View File

@@ -0,0 +1,156 @@
import { api } from '../api';
import { renderNavbar, toast, roleBadge } from '../utils';
const ROLE_OPTIONS = ['ADMIN', 'CAIXA', 'GARCOM', 'COZINHA', 'BARMAN'];
export async function renderUsers(container: HTMLElement) {
container.innerHTML = `
${renderNavbar('/users')}
<div class="container animate-fade-in">
<div class="page-header">
<h1>Equipe 👥</h1>
<button class="btn" id="btn-novo-usuario"> Novo Usuário</button>
</div>
<div id="users-list"><p class="card-subtitle">Carregando...</p></div>
</div>
<!-- Modal Usuário -->
<div id="modal-usuario" class="modal-overlay" style="display:none;">
<div class="modal">
<div class="modal-header">
<h3 id="modal-user-title">Novo Usuário</h3>
<button class="btn-icon" onclick="document.getElementById('modal-usuario').style.display='none'">✕</button>
</div>
<div class="modal-body">
<form id="form-usuario">
<input type="hidden" id="user-id">
<div class="form-group">
<label>Nome Completo *</label>
<input type="text" id="u-nome" class="form-control" required>
</div>
<div class="form-group">
<label>E-mail *</label>
<input type="email" id="u-email" class="form-control" required>
</div>
<div class="form-group" id="senha-group">
<label>Senha *</label>
<input type="password" id="u-senha" class="form-control" placeholder="Mínimo 6 caracteres">
</div>
<div class="form-group">
<label>Cargo (Role) *</label>
<select id="u-role" class="form-control" required>
${ROLE_OPTIONS.map(r => `<option value="${r}">${r}</option>`).join('')}
</select>
</div>
<div style="display:flex;align-items:center;gap:0.75rem;margin-bottom:1.5rem;">
<input type="checkbox" id="u-ativo" checked>
<label for="u-ativo" style="cursor:pointer;color:var(--text-primary);">Usuário Ativo</label>
</div>
<button type="submit" class="btn" style="width:100%;">Salvar</button>
</form>
</div>
</div>
</div>
`;
await loadUsers();
bindUserEvents();
}
async function loadUsers() {
const list = document.getElementById('users-list')!;
try {
const users = await api.get('/usuarios');
list.innerHTML = `
<div class="table-wrap">
<table>
<thead>
<tr><th>Nome</th><th>E-mail</th><th>Cargo</th><th>Status</th><th>Desde</th><th>Ações</th></tr>
</thead>
<tbody>
${users.map((u: any) => `
<tr>
<td data-label="Nome"><strong>${u.nome}</strong></td>
<td data-label="E-mail" style="color:var(--text-secondary)">${u.email}</td>
<td data-label="Cargo">${roleBadge(u.role)}</td>
<td data-label="Status"><span class="badge ${u.ativo ? 'badge-success' : 'badge-warning'}">${u.ativo ? 'Ativo' : 'Inativo'}</span></td>
<td data-label="Desde" style="color:var(--text-secondary)">${new Date(u.criadoEm).toLocaleDateString('pt-BR')}</td>
<td data-label="Ações" style="display:flex;gap:0.5rem;flex-wrap:wrap;">
<button class="btn btn-sm btn-secondary" onclick="window.editUser(${JSON.stringify(u).replace(/"/g, '&quot;')})">✏️ Editar</button>
<button class="btn btn-sm btn-danger" onclick="window.toggleUser('${u.id}','${u.nome}',${u.ativo})">
${u.ativo ? '🚫 Desativar' : '✅ Ativar'}
</button>
</td>
</tr>
`).join('')}
</tbody>
</table>
</div>
`;
} catch (err: any) {
list.innerHTML = `<p style="color:var(--accent-primary)">Erro: ${err.message}</p>`;
}
}
function bindUserEvents() {
document.getElementById('btn-novo-usuario')?.addEventListener('click', () => {
clearUserForm();
(document.getElementById('modal-usuario') as HTMLElement).style.display = 'flex';
(document.getElementById('u-senha') as HTMLInputElement).required = true;
(document.getElementById('senha-group') as HTMLElement).style.display = 'block';
});
document.getElementById('form-usuario')?.addEventListener('submit', async (e) => {
e.preventDefault();
const id = (document.getElementById('user-id') as HTMLInputElement).value;
const senha = (document.getElementById('u-senha') as HTMLInputElement).value;
const payload: any = {
nome: (document.getElementById('u-nome') as HTMLInputElement).value,
email: (document.getElementById('u-email') as HTMLInputElement).value,
role: (document.getElementById('u-role') as HTMLSelectElement).value,
ativo: (document.getElementById('u-ativo') as HTMLInputElement).checked,
};
if (!id) payload.senha = senha;
try {
if (id) await api.patch(`/usuarios/${id}`, payload);
else await api.post('/usuarios', { ...payload, senha });
toast(id ? 'Usuário atualizado!' : 'Usuário cadastrado!', 'success');
(document.getElementById('modal-usuario') as HTMLElement).style.display = 'none';
await loadUsers();
} catch (err: any) { toast(err.message, 'error'); }
});
(window as any).editUser = (u: any) => {
(document.getElementById('user-id') as HTMLInputElement).value = u.id;
(document.getElementById('u-nome') as HTMLInputElement).value = u.nome;
(document.getElementById('u-email') as HTMLInputElement).value = u.email;
(document.getElementById('u-role') as HTMLSelectElement).value = u.role;
(document.getElementById('u-ativo') as HTMLInputElement).checked = u.ativo;
(document.getElementById('u-senha') as HTMLInputElement).required = false;
(document.getElementById('u-senha') as HTMLInputElement).value = '';
(document.getElementById('senha-group') as HTMLElement).style.display = 'none';
(document.getElementById('modal-user-title') as HTMLElement).textContent = 'Editar Usuário';
(document.getElementById('modal-usuario') as HTMLElement).style.display = 'flex';
};
(window as any).toggleUser = async (id: string, nome: string, ativo: boolean) => {
const action = ativo ? 'desativar' : 'ativar';
if (!confirm(`Deseja ${action} o usuário "${nome}"?`)) return;
try {
await api.patch(`/usuarios/${id}`, { ativo: !ativo });
toast(`Usuário ${ativo ? 'desativado' : 'ativado'}!`, 'success');
await loadUsers();
} catch (err: any) { toast(err.message, 'error'); }
};
}
function clearUserForm() {
(document.getElementById('user-id') as HTMLInputElement).value = '';
(document.getElementById('u-nome') as HTMLInputElement).value = '';
(document.getElementById('u-email') as HTMLInputElement).value = '';
(document.getElementById('u-senha') as HTMLInputElement).value = '';
(document.getElementById('u-role') as HTMLSelectElement).value = 'GARCOM';
(document.getElementById('u-ativo') as HTMLInputElement).checked = true;
(document.getElementById('modal-user-title') as HTMLElement).textContent = 'Novo Usuário';
}