Compare commits
4 Commits
01ecf06215
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| b567a45803 | |||
| 14e92c91fd | |||
| 14a36b68b5 | |||
| 4be043edf3 |
242
AGENTS.md
Normal file
242
AGENTS.md
Normal file
@@ -0,0 +1,242 @@
|
||||
# Contexto do Projeto - Gastrobar PDV (Café em Saturno)
|
||||
|
||||
## Visão Geral
|
||||
Sistema de PDV (Ponto de Venda) e gerenciamento para gastrobar/restaurante. Gerencia comandas de clientes, pedidos, cardápio de produtos, usuários com diferentes perfis de acesso e fluxo de preparo na cozinha/bar.
|
||||
|
||||
## Stack
|
||||
|
||||
### Backend (`src/`)
|
||||
- **Runtime:** Node.js + TypeScript (CommonJS)
|
||||
- **Framework:** Fastify v4.27 (porta 3333)
|
||||
- **ORM:** Prisma v5.14 com SQLite (`prisma/dev.db`)
|
||||
- **Validação:** Zod v3.23
|
||||
- **Auth:** JWT (`@fastify/jwt`) + bcrypt
|
||||
- **Dev:** tsx watch (`npm run dev`)
|
||||
|
||||
### Frontend (`web/`)
|
||||
- **Bundler:** Vite v8.1
|
||||
- **Linguagem:** TypeScript vanilla (sem framework, SPA)
|
||||
- **Dev server:** porta 5173
|
||||
- **API URL:** `http://localhost:3333/api`
|
||||
- **Token storage:** `localStorage('@gastrobar:token')` e `localStorage('@gastrobar:user')`
|
||||
|
||||
## Estrutura do Projeto
|
||||
|
||||
```
|
||||
app_ces/
|
||||
├── .env # JWT_SECRET
|
||||
├── package.json # Backend dependencies
|
||||
├── tsconfig.json
|
||||
├── prisma/
|
||||
│ ├── schema.prisma # Schema do banco (SQLite)
|
||||
│ ├── seed.ts # Seed: admin@gastrobar.com / 123456
|
||||
│ └── dev.db # Banco SQLite (gerado)
|
||||
├── src/ # Backend API
|
||||
│ ├── server.ts # Entrypoint Fastify, porta 3333
|
||||
│ ├── lib/
|
||||
│ │ ├── prisma.ts # Instância PrismaClient
|
||||
│ │ └── timezone.ts # Helpers UTC-3 (dateStart, dateEnd, dateTime, nowUTC3)
|
||||
│ ├── middlewares/
|
||||
│ │ └── auth.middleware.ts # authenticate + requireRoles
|
||||
│ ├── controllers/
|
||||
│ │ ├── auth.controller.ts
|
||||
│ │ ├── category.controller.ts
|
||||
│ │ ├── product.controller.ts
|
||||
│ │ ├── order.controller.ts
|
||||
│ │ ├── user.controller.ts
|
||||
│ │ └── report.controller.ts
|
||||
│ ├── services/
|
||||
│ │ ├── auth.service.ts
|
||||
│ │ ├── category.service.ts
|
||||
│ │ ├── product.service.ts
|
||||
│ │ ├── order.service.ts
|
||||
│ │ ├── user.service.ts
|
||||
│ │ └── report.service.ts
|
||||
│ ├── schemas/ # Validação Zod
|
||||
│ │ ├── auth.schema.ts
|
||||
│ │ ├── user.schema.ts
|
||||
│ │ ├── product.schema.ts
|
||||
│ │ ├── category.schema.ts
|
||||
│ │ └── order.schema.ts
|
||||
│ └── routes/
|
||||
│ ├── auth.routes.ts
|
||||
│ ├── category.routes.ts
|
||||
│ ├── product.routes.ts
|
||||
│ ├── order.routes.ts
|
||||
│ ├── user.routes.ts
|
||||
│ └── report.routes.ts
|
||||
└── web/ # Frontend SPA
|
||||
├── package.json # Vite + TypeScript
|
||||
├── tsconfig.json
|
||||
└── src/
|
||||
├── main.ts # Router SPA + navegação
|
||||
├── api.ts # Cliente HTTP centralizado
|
||||
├── utils.ts # renderNavbar, toast, helpers, toDisplayDate, parseDisplayDate
|
||||
├── style.css # Dark theme + glassmorphism
|
||||
└── views/
|
||||
├── login.ts
|
||||
├── kitchen.ts # Painel de preparo
|
||||
├── orders.ts # Gerenciamento de comandas
|
||||
├── checkout.ts # Caixa/pagamento
|
||||
├── menu.ts # Cardápio CRUD
|
||||
├── users.ts # Gestão de equipe
|
||||
└── dashboard.ts # KPIs admin
|
||||
```
|
||||
|
||||
## Banco de Dados (Schema Prisma)
|
||||
|
||||
### Models
|
||||
|
||||
**Usuario**
|
||||
- `id` (UUID), `nome`, `email` (unique), `senha` (hash bcrypt), `role` (ADMIN|CAIXA|GARCOM|COZINHA|BARMAN), `ativo`, `criadoEm`
|
||||
- Relations: `comandas` (1:N Comanda), `itensPedido` (1:N ItemPedido)
|
||||
|
||||
**Categoria**
|
||||
- `id` (UUID), `nome`, `produtos` (relation 1:N Produto)
|
||||
|
||||
**Produto**
|
||||
- `id` (UUID), `nome`, `descricao?`, `fotoUrl?`, `preco` (Float), `custo?`, `estoqueAtual`, `estoqueMinimo`, `itemCozinha` (boolean: true=cozinha, false=bar), `ativo`, `categoriaId` (FK)
|
||||
|
||||
**Comanda**
|
||||
- `id` (UUID), `identificador` (mesa/código), `nomeCliente?`, `status` (ABERTA|FECHADA|PAGA|CANCELADA), `total`, `valorPago`, `desconto`, `acrescimo`, `taxaServico` (boolean, +10%), `formaPagamento?`, `motivoCancelamento?`, `criadoEm`, `fechadoEm?`
|
||||
- `usuarioId?` (FK) - Usuário que abriu a comanda
|
||||
- Relations: `itens` (1:N ItemPedido), `pagamentos` (1:N Pagamento), `usuario` (N:1 Usuario)
|
||||
|
||||
**ItemPedido**
|
||||
- `id` (UUID), `quantidade`, `precoUnitario`, `observacao?`, `status` (PENDENTE|PREPARANDO|PRONTO|ENTREGUE), `produtoId` (FK), `comandaId` (FK), `criadoEm`
|
||||
- `usuarioId?` (FK) - Usuário que adicionou o item
|
||||
- Relations: `produto` (N:1 Produto), `comanda` (N:1 Comanda), `usuario` (N:1 Usuario)
|
||||
|
||||
**Pagamento**
|
||||
- `id` (UUID), `comandaId` (FK), `valor`, `formaPagamento` (DINHEIRO|CARTAO_CREDITO|CARTAO_DEBITO|PIX), `observacao?`, `estornado` (boolean, default false), `criadoEm`
|
||||
|
||||
## Rotas da API
|
||||
|
||||
### Auth (`/api/auth`)
|
||||
| Método | Rota | Permissão | Descrição |
|
||||
|--------|------|-----------|-----------|
|
||||
| POST | `/auth/login` | Público | Login, retorna JWT + user |
|
||||
| PATCH | `/auth/senha` | Autenticado | Alterar própria senha |
|
||||
|
||||
### Categorias (`/api`)
|
||||
| Método | Rota | Permissão |
|
||||
|--------|------|-----------|
|
||||
| GET | `/categorias` | Autenticado |
|
||||
| GET | `/categorias/:id` | Autenticado |
|
||||
| POST | `/categorias` | ADMIN |
|
||||
| PUT | `/categorias/:id` | ADMIN |
|
||||
| DELETE | `/categorias/:id` | ADMIN |
|
||||
|
||||
### Produtos (`/api`)
|
||||
| Método | Rota | Permissão |
|
||||
|--------|------|-----------|
|
||||
| GET | `/produtos` | Autenticado |
|
||||
| GET | `/produtos/mais-vendidos` | Autenticado |
|
||||
| GET | `/produtos/busca` | Autenticado |
|
||||
| GET | `/produtos/baixo-estoque` | ADMIN |
|
||||
| GET | `/produtos/:id` | Autenticado |
|
||||
| POST | `/produtos` | ADMIN |
|
||||
| PUT | `/produtos/:id` | ADMIN |
|
||||
| DELETE | `/produtos/:id` | ADMIN |
|
||||
|
||||
### Comandas (`/api`)
|
||||
| Método | Rota | Permissão |
|
||||
|--------|------|-----------|
|
||||
| GET | `/comandas` | Autenticado |
|
||||
| GET | `/pagamentos` | Autenticado |
|
||||
| POST | `/comandas` | GARCOM/CAIXA/ADMIN |
|
||||
| POST | `/comandas/:id/itens` | GARCOM/CAIXA/ADMIN |
|
||||
| PATCH | `/comandas/:id` | GARCOM/CAIXA/ADMIN |
|
||||
| POST | `/comandas/:id/pagar` | CAIXA/ADMIN |
|
||||
| POST | `/comandas/:id/pagamentos` | CAIXA/ADMIN |
|
||||
| PATCH | `/pagamentos/:id/estornar` | CAIXA/ADMIN |
|
||||
| PATCH | `/comandas/itens/:id/observacao` | GARCOM/CAIXA/ADMIN |
|
||||
| DELETE | `/comandas/itens/:id` | CAIXA/ADMIN |
|
||||
|
||||
### Painel Cozinha/Bar (`/api`)
|
||||
| Método | Rota | Permissão |
|
||||
|--------|------|-----------|
|
||||
| GET | `/painel/itens` | COZINHA/BARMAN/ADMIN |
|
||||
| PATCH | `/painel/itens/:id/status` | COZINHA/BARMAN/ADMIN |
|
||||
|
||||
### Relatórios (`/api`)
|
||||
| Método | Rota | Permissão |
|
||||
|--------|------|-----------|
|
||||
| GET | `/relatorios/vendas` | ADMIN |
|
||||
| GET | `/relatorios/dashboard` | ADMIN |
|
||||
|
||||
### Usuários (`/api`)
|
||||
| Método | Rota | Permissão |
|
||||
|--------|------|-----------|
|
||||
| GET | `/usuarios` | ADMIN |
|
||||
| POST | `/usuarios` | ADMIN |
|
||||
| PATCH | `/usuarios/:id` | ADMIN |
|
||||
| PATCH | `/usuarios/:id/senha` | ADMIN |
|
||||
| DELETE | `/usuarios/:id` | ADMIN |
|
||||
|
||||
## Roles e Permissões
|
||||
|
||||
| Role | Descrição | Acesso Principal |
|
||||
|------|-----------|-----------------|
|
||||
| `ADMIN` | Administrador | Acesso total ao sistema |
|
||||
| `CAIXA` | Operador de caixa | Comandas, checkout, pagamento, exclusão de itens |
|
||||
| `GARCOM` | Garçom | Criar/gerenciar comandas, adicionar itens |
|
||||
| `COZINHA` | Cozinheiro | Painel de preparo (itens `itemCozinha=true`) |
|
||||
| `BARMAN` | Bartender | Painel de preparo (itens `itemCozinha=false`) |
|
||||
|
||||
## Lógica de Negócio Importante
|
||||
|
||||
### Fluxo de Comanda
|
||||
1. Criar comanda (identificador = mesa/código) - **registra usuário logado**
|
||||
2. Adicionar itens (baixa estoque automaticamente, atualiza total) - **registra usuário logado**
|
||||
3. Itens aparecem no painel de cozinha/bar com status `PENDENTE` (apenas últimos 12h)
|
||||
4. Cozinha/bar avança: `PENDENTE → PREPARANDO → PRONTO → ENTREGUE`
|
||||
5. Caixa fecha com pagamento (integral ou parcial)
|
||||
6. Status da comanda: `ABERTA → PAGA`
|
||||
|
||||
### Pagamento
|
||||
- **Integral**: `POST /comandas/:id/pagar` - registra pagamento do restante e fecha comanda
|
||||
- **Parcial**: `POST /comandas/:id/pagamentos` - registra pagamento parcial, pode selecionar itens específicos
|
||||
- **Cálculo do total final**: `total - desconto + acrescimo + (taxaServico ? 10% : 0)`
|
||||
- Formas: `DINHEIRO`, `CARTAO_CREDITO`, `CARTAO_DEBITO`, `PIX`
|
||||
- **Estorno**: `PATCH /pagamentos/:id/estornar` - marca pagamento como estornado, subtrai valor de `comanda.valorPago`, se comanda era `PAGA` volta para `FECHADA`. Pagamento continua visível com indicador visual (opacity + line-through + badge "ESTORNADO")
|
||||
|
||||
### Estoque
|
||||
- Decrementa ao adicionar item na comanda
|
||||
- Incrementa ao remover item da comanda
|
||||
- **Permite estoque negativo** (sem validação de insuficiência)
|
||||
|
||||
### Frontend
|
||||
- Rotas SPA manuais via `window.history.pushState`
|
||||
- Auto-refresh no painel de cozinha a cada 10 segundos
|
||||
- Notificações sonoras via Web Audio API para novos pedidos
|
||||
- Navbar dinâmica baseada no role do usuário logado
|
||||
- Filtros de data em formato `dd/mm/yyyy` (inputs `type="text"`, conversão via `parseDisplayDate`)
|
||||
|
||||
## Comandos Úteis
|
||||
|
||||
```bash
|
||||
# Backend
|
||||
npm run dev # Iniciar dev server (tsx watch)
|
||||
npm run build # Compilar TypeScript
|
||||
npm run db:push # Aplicar schema no banco
|
||||
npm run db:seed # Popular banco com dados iniciais
|
||||
|
||||
# Frontend
|
||||
cd web && npm run dev # Iniciar Vite dev server
|
||||
cd web && npm run build # Build de produção
|
||||
```
|
||||
|
||||
## Credenciais Padrão (Seed)
|
||||
- **Email:** admin@gastrobar.com
|
||||
- **Senha:** 123456
|
||||
- **Role:** ADMIN
|
||||
|
||||
## Notas Técnicas
|
||||
- CORS habilitado para qualquer origem (`origin: '*'`)
|
||||
- JWT secret definido em `.env` (fallback: `fallback_secret_change_me`)
|
||||
- Error handler global trata `ZodError` (400) e erros HTTP
|
||||
- **Fuso horário UTC-3** configurado em `src/lib/timezone.ts` - todas as datas no backend e frontend usam offset UTC-3
|
||||
- Frontend não usa framework UI - renderiza HTML via template literals
|
||||
- Utiliza `event delegation` para botões dinâmicos no painel
|
||||
- Cleanup de listeners ao navegar entre views
|
||||
@@ -15,6 +15,8 @@ model Usuario {
|
||||
role String @default("GARCOM") // ADMIN, CAIXA, GARCOM, COZINHA, BARMAN
|
||||
ativo Boolean @default(true)
|
||||
criadoEm DateTime @default(now())
|
||||
comandas Comanda[]
|
||||
itensPedido ItemPedido[]
|
||||
}
|
||||
|
||||
model Categoria {
|
||||
@@ -45,6 +47,7 @@ model Comanda {
|
||||
nomeCliente String?
|
||||
status String @default("ABERTA") // ABERTA, FECHADA, PAGA, CANCELADA
|
||||
total Float @default(0.0)
|
||||
valorPago Float @default(0.0)
|
||||
desconto Float @default(0.0)
|
||||
acrescimo Float @default(0.0)
|
||||
taxaServico Boolean @default(false)
|
||||
@@ -52,7 +55,10 @@ model Comanda {
|
||||
motivoCancelamento String?
|
||||
criadoEm DateTime @default(now())
|
||||
fechadoEm DateTime?
|
||||
usuarioId String?
|
||||
usuario Usuario? @relation(fields: [usuarioId], references: [id])
|
||||
itens ItemPedido[]
|
||||
pagamentos Pagamento[]
|
||||
}
|
||||
|
||||
model ItemPedido {
|
||||
@@ -65,5 +71,18 @@ model ItemPedido {
|
||||
produto Produto @relation(fields: [produtoId], references: [id])
|
||||
comandaId String
|
||||
comanda Comanda @relation(fields: [comandaId], references: [id])
|
||||
usuarioId String?
|
||||
usuario Usuario? @relation(fields: [usuarioId], references: [id])
|
||||
criadoEm DateTime @default(now())
|
||||
}
|
||||
|
||||
model Pagamento {
|
||||
id String @id @default(uuid())
|
||||
comandaId String
|
||||
comanda Comanda @relation(fields: [comandaId], references: [id])
|
||||
valor Float
|
||||
formaPagamento String // DINHEIRO, CARTAO_CREDITO, CARTAO_DEBITO, PIX
|
||||
observacao String?
|
||||
estornado Boolean @default(false)
|
||||
criadoEm DateTime @default(now())
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { createOrderSchema, addItemOrderSchema, updateItemStatusSchema, updateOrderSchema, payOrderSchema } from '../schemas/order.schema';
|
||||
import { createOrderSchema, addItemOrderSchema, updateItemStatusSchema, updateItemObservacaoSchema, updateOrderSchema, payOrderSchema, partialPaymentSchema } from '../schemas/order.schema';
|
||||
import * as orderService from '../services/order.service';
|
||||
import { z } from 'zod';
|
||||
|
||||
@@ -23,18 +23,37 @@ export async function listOrdersController(request: FastifyRequest, reply: Fasti
|
||||
return reply.send(orders);
|
||||
}
|
||||
|
||||
export async function listPaymentsController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const querySchema = z.object({
|
||||
dataInicio: z.string().optional(),
|
||||
dataFim: z.string().optional(),
|
||||
});
|
||||
|
||||
const query = querySchema.parse(request.query);
|
||||
const filter: any = {};
|
||||
if (query.dataInicio) filter.dataInicio = query.dataInicio;
|
||||
if (query.dataFim) filter.dataFim = query.dataFim;
|
||||
|
||||
const payments = await orderService.listPayments(
|
||||
(filter.dataInicio || filter.dataFim) ? filter : undefined
|
||||
);
|
||||
return reply.send(payments);
|
||||
}
|
||||
|
||||
export async function createOrderController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const data = createOrderSchema.parse(request.body);
|
||||
const order = await orderService.createOrder(data);
|
||||
const user = request.user as { id: string };
|
||||
const order = await orderService.createOrder(data, user.id);
|
||||
return reply.status(201).send(order);
|
||||
}
|
||||
|
||||
export async function addItemToOrderController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const { id } = z.object({ id: z.string().uuid() }).parse(request.params);
|
||||
const data = addItemOrderSchema.parse(request.body);
|
||||
const user = request.user as { id: string };
|
||||
|
||||
try {
|
||||
const item = await orderService.addItemToOrder(id, data);
|
||||
const item = await orderService.addItemToOrder(id, data, user.id);
|
||||
return reply.status(201).send(item);
|
||||
} catch (error: any) {
|
||||
return reply.status(400).send({ error: error.message });
|
||||
@@ -59,6 +78,17 @@ export async function updateItemStatusController(request: FastifyRequest, reply:
|
||||
return reply.send(item);
|
||||
}
|
||||
|
||||
export async function updateItemObservacaoController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const { id } = z.object({ id: z.string().uuid() }).parse(request.params);
|
||||
const data = updateItemObservacaoSchema.parse(request.body);
|
||||
try {
|
||||
const item = await orderService.updateItemObservacao(id, data);
|
||||
return reply.send(item);
|
||||
} catch (error: any) {
|
||||
return reply.status(400).send({ error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
export async function payOrderController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const { id } = z.object({ id: z.string().uuid() }).parse(request.params);
|
||||
const body = request.body && Object.keys(request.body as object).length > 0
|
||||
@@ -72,6 +102,17 @@ export async function payOrderController(request: FastifyRequest, reply: Fastify
|
||||
}
|
||||
}
|
||||
|
||||
export async function registerPaymentController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const { id } = z.object({ id: z.string().uuid() }).parse(request.params);
|
||||
const data = partialPaymentSchema.parse(request.body);
|
||||
try {
|
||||
const pagamento = await orderService.registerPayment(id, data);
|
||||
return reply.status(201).send(pagamento);
|
||||
} catch (error: any) {
|
||||
return reply.status(400).send({ error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateOrderController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const { id } = z.object({ id: z.string().uuid() }).parse(request.params);
|
||||
const data = updateOrderSchema.parse(request.body);
|
||||
@@ -92,3 +133,13 @@ export async function deleteItemFromOrderController(request: FastifyRequest, rep
|
||||
return reply.status(400).send({ error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
export async function reversePaymentController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const { id } = z.object({ id: z.string().uuid() }).parse(request.params);
|
||||
try {
|
||||
const pagamento = await orderService.reversePayment(id);
|
||||
return reply.send(pagamento);
|
||||
} catch (error: any) {
|
||||
return reply.status(400).send({ error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,25 @@
|
||||
import { FastifyRequest, FastifyReply } from 'fastify';
|
||||
import * as reportService from '../services/report.service';
|
||||
import { z } from 'zod';
|
||||
import { dateTime, nowUTC3, todayStrUTC3 } from '../lib/timezone';
|
||||
|
||||
export async function salesReportController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const querySchema = z.object({
|
||||
inicio: z.string().optional(),
|
||||
fim: z.string().optional(),
|
||||
horaInicio: z.string().optional(),
|
||||
horaFim: z.string().optional(),
|
||||
});
|
||||
const query = querySchema.parse(request.query);
|
||||
|
||||
const inicio = query.inicio ? new Date(query.inicio) : new Date(new Date().setDate(new Date().getDate() - 30));
|
||||
const fim = query.fim ? new Date(query.fim + 'T23:59:59') : new Date();
|
||||
const today = todayStrUTC3();
|
||||
const inicioStr = query.inicio || today;
|
||||
const horaInicio = query.horaInicio || '00:00';
|
||||
const inicio = dateTime(inicioStr, horaInicio);
|
||||
|
||||
const fimStr = query.fim || today;
|
||||
const horaFim = query.horaFim || '23:59';
|
||||
const fim = dateTime(fimStr, horaFim, 59);
|
||||
|
||||
const report = await reportService.getSalesReport(inicio, fim);
|
||||
return reply.send(report);
|
||||
|
||||
62
src/lib/timezone.ts
Normal file
62
src/lib/timezone.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
const OFFSET_HOURS = -3;
|
||||
|
||||
/** Componentes de data/hora em UTC-3 */
|
||||
export interface UTC3 {
|
||||
year: number;
|
||||
month: number; // 0-indexed
|
||||
date: number;
|
||||
hours: number;
|
||||
minutes: number;
|
||||
seconds: number;
|
||||
}
|
||||
|
||||
/** Retorna componentes de agora em UTC-3 */
|
||||
export function nowUTC3(): UTC3 {
|
||||
const d = new Date(Date.now() + OFFSET_HOURS * 60 * 60 * 1000);
|
||||
return {
|
||||
year: d.getUTCFullYear(),
|
||||
month: d.getUTCMonth(),
|
||||
date: d.getUTCDate(),
|
||||
hours: d.getUTCHours(),
|
||||
minutes: d.getUTCMinutes(),
|
||||
seconds: d.getUTCSeconds(),
|
||||
};
|
||||
}
|
||||
|
||||
/** Cria Date cuja representação UTC = meia-noite UTC-3 do dateStr (YYYY-MM-DD) */
|
||||
export function dateStart(dateStr: string): Date {
|
||||
const [y, m, d] = dateStr.split('-').map(Number);
|
||||
return new Date(Date.UTC(y, m - 1, d, 0 - OFFSET_HOURS, 0, 0, 0));
|
||||
}
|
||||
|
||||
/** Cria Date cuja representação UTC = 23:59:59.999 UTC-3 do dateStr */
|
||||
export function dateEnd(dateStr: string): Date {
|
||||
const [y, m, d] = dateStr.split('-').map(Number);
|
||||
return new Date(Date.UTC(y, m - 1, d, 23 - OFFSET_HOURS, 59, 59, 999));
|
||||
}
|
||||
|
||||
/** Date + hora em UTC-3. dateStr = YYYY-MM-DD, timeStr = HH:mm */
|
||||
export function dateTime(dateStr: string, timeStr: string, seconds = 0): Date {
|
||||
const [y, m, d] = dateStr.split('-').map(Number);
|
||||
const [hh, mm] = timeStr.split(':').map(Number);
|
||||
return new Date(Date.UTC(y, m - 1, d, hh - OFFSET_HOURS, mm, seconds, 0));
|
||||
}
|
||||
|
||||
/** Converte Date (UTC no banco) para UTC-3 para exibição */
|
||||
export function toUTC3(d: Date): Date {
|
||||
return new Date(d.getTime() + OFFSET_HOURS * 60 * 60 * 1000);
|
||||
}
|
||||
|
||||
/** YYYY-MM-DD em UTC-3 */
|
||||
export function todayStrUTC3(): string {
|
||||
const c = nowUTC3();
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
return `${c.year}-${pad(c.month + 1)}-${pad(c.date)}`;
|
||||
}
|
||||
|
||||
/** YYYY-MM-DD do primeiro dia do mês atual em UTC-3 */
|
||||
export function firstDayOfMonthUTC3(): string {
|
||||
const c = nowUTC3();
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
return `${c.year}-${pad(c.month + 1)}-01`;
|
||||
}
|
||||
@@ -6,6 +6,9 @@ export async function orderRoutes(app: FastifyInstance) {
|
||||
// Listagem geral (qualquer autenticado)
|
||||
app.get('/comandas', { preHandler: [authenticate] }, orderController.listOrdersController);
|
||||
|
||||
// Listagem de pagamentos (qualquer autenticado)
|
||||
app.get('/pagamentos', { preHandler: [authenticate] }, orderController.listPaymentsController);
|
||||
|
||||
// Comandas (Garçom, Caixa, Admin)
|
||||
app.post('/comandas', { preHandler: [requireRoles(['GARCOM', 'CAIXA', 'ADMIN'])] }, orderController.createOrderController);
|
||||
app.post('/comandas/:id/itens', { preHandler: [requireRoles(['GARCOM', 'CAIXA', 'ADMIN'])] }, orderController.addItemToOrderController);
|
||||
@@ -13,11 +16,18 @@ export async function orderRoutes(app: FastifyInstance) {
|
||||
|
||||
// Pagamento (Caixa, Admin)
|
||||
app.post('/comandas/:id/pagar', { preHandler: [requireRoles(['CAIXA', 'ADMIN'])] }, orderController.payOrderController);
|
||||
app.post('/comandas/:id/pagamentos', { preHandler: [requireRoles(['CAIXA', 'ADMIN'])] }, orderController.registerPaymentController);
|
||||
|
||||
// Painel Cozinha / Bar
|
||||
app.get('/painel/itens', { preHandler: [requireRoles(['COZINHA', 'BARMAN', 'ADMIN'])] }, orderController.listKitchenBarController);
|
||||
app.patch('/painel/itens/:id/status', { preHandler: [requireRoles(['COZINHA', 'BARMAN', 'ADMIN'])] }, orderController.updateItemStatusController);
|
||||
|
||||
// Editar observação de item (Garçom, Caixa, Admin)
|
||||
app.patch('/comandas/itens/:id/observacao', { preHandler: [requireRoles(['GARCOM', 'CAIXA', 'ADMIN'])] }, orderController.updateItemObservacaoController);
|
||||
|
||||
// Excluir item de comanda (apenas CAIXA e ADMIN)
|
||||
app.delete('/comandas/itens/:id', { preHandler: [requireRoles(['CAIXA', 'ADMIN'])] }, orderController.deleteItemFromOrderController);
|
||||
|
||||
// Estornar pagamento (Caixa, Admin)
|
||||
app.patch('/pagamentos/:id/estornar', { preHandler: [requireRoles(['CAIXA', 'ADMIN'])] }, orderController.reversePaymentController);
|
||||
}
|
||||
|
||||
@@ -29,9 +29,25 @@ export const payOrderSchema = z.object({
|
||||
formaPagamento: z.enum(['DINHEIRO', 'CARTAO_CREDITO', 'CARTAO_DEBITO', 'PIX']),
|
||||
});
|
||||
|
||||
export const partialPaymentSchema = z.object({
|
||||
valor: z.number().min(0).optional(),
|
||||
formaPagamento: z.enum(['DINHEIRO', 'CARTAO_CREDITO', 'CARTAO_DEBITO', 'PIX']),
|
||||
observacao: z.string().optional(),
|
||||
itemIds: z.array(z.string().uuid()).optional(),
|
||||
}).refine(
|
||||
(data) => (data.itemIds && data.itemIds.length > 0) || (data.valor !== undefined && data.valor > 0),
|
||||
{ message: 'Informe um valor positivo ou selecione itens para pagamento' }
|
||||
);
|
||||
|
||||
export type CreateOrderInput = z.infer<typeof createOrderSchema>;
|
||||
export type AddItemOrderInput = z.infer<typeof addItemOrderSchema>;
|
||||
export const updateItemObservacaoSchema = z.object({
|
||||
observacao: z.string().optional(),
|
||||
});
|
||||
|
||||
export type UpdateItemStatusInput = z.infer<typeof updateItemStatusSchema>;
|
||||
export type UpdateItemObservacaoInput = z.infer<typeof updateItemObservacaoSchema>;
|
||||
export type UpdateOrderInput = z.infer<typeof updateOrderSchema>;
|
||||
export type PayOrderInput = z.infer<typeof payOrderSchema>;
|
||||
export type PartialPaymentInput = z.infer<typeof partialPaymentSchema>;
|
||||
|
||||
|
||||
@@ -6,8 +6,8 @@ export const productSchema = z.object({
|
||||
fotoUrl: z.string().url().optional(),
|
||||
preco: z.number().positive(),
|
||||
custo: z.number().positive().optional(),
|
||||
estoqueAtual: z.number().int().nonnegative().default(0),
|
||||
estoqueMinimo: z.number().int().nonnegative().default(0),
|
||||
estoqueAtual: z.number().int().default(0),
|
||||
estoqueMinimo: z.number().int().default(0),
|
||||
itemCozinha: z.boolean(),
|
||||
ativo: z.boolean().default(true),
|
||||
categoriaId: z.string().uuid(),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { prisma } from '../lib/prisma';
|
||||
import { CreateOrderInput, AddItemOrderInput, UpdateItemStatusInput, UpdateOrderInput, PayOrderInput } from '../schemas/order.schema';
|
||||
import { CreateOrderInput, AddItemOrderInput, UpdateItemStatusInput, UpdateItemObservacaoInput, UpdateOrderInput, PayOrderInput, PartialPaymentInput } from '../schemas/order.schema';
|
||||
import { dateStart, dateEnd, nowUTC3 } from '../lib/timezone';
|
||||
|
||||
export interface ListOrdersFilter {
|
||||
statuses?: string[];
|
||||
@@ -7,6 +8,36 @@ export interface ListOrdersFilter {
|
||||
dataFim?: string;
|
||||
}
|
||||
|
||||
export interface ListPaymentsFilter {
|
||||
dataInicio?: string;
|
||||
dataFim?: string;
|
||||
}
|
||||
|
||||
export async function listPayments(filter?: ListPaymentsFilter) {
|
||||
const where: any = {};
|
||||
|
||||
if (filter?.dataInicio || filter?.dataFim) {
|
||||
where.criadoEm = {};
|
||||
if (filter.dataInicio) where.criadoEm.gte = dateStart(filter.dataInicio);
|
||||
if (filter.dataFim) where.criadoEm.lte = dateEnd(filter.dataFim);
|
||||
}
|
||||
|
||||
return prisma.pagamento.findMany({
|
||||
where,
|
||||
orderBy: { criadoEm: 'desc' },
|
||||
include: {
|
||||
comanda: {
|
||||
select: {
|
||||
id: true,
|
||||
identificador: true,
|
||||
nomeCliente: true,
|
||||
status: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function listOrders(filter?: ListOrdersFilter) {
|
||||
const where: any = {};
|
||||
|
||||
@@ -16,37 +47,43 @@ export async function listOrders(filter?: ListOrdersFilter) {
|
||||
|
||||
if (filter?.dataInicio || filter?.dataFim) {
|
||||
where.criadoEm = {};
|
||||
if (filter.dataInicio) where.criadoEm.gte = new Date(filter.dataInicio);
|
||||
if (filter.dataFim) {
|
||||
const end = new Date(filter.dataFim);
|
||||
end.setHours(23, 59, 59, 999);
|
||||
where.criadoEm.lte = end;
|
||||
}
|
||||
if (filter.dataInicio) where.criadoEm.gte = dateStart(filter.dataInicio);
|
||||
if (filter.dataFim) where.criadoEm.lte = dateEnd(filter.dataFim);
|
||||
}
|
||||
|
||||
return prisma.comanda.findMany({
|
||||
where,
|
||||
orderBy: { criadoEm: 'desc' },
|
||||
include: {
|
||||
usuario: {
|
||||
select: { id: true, nome: true, email: true },
|
||||
},
|
||||
itens: {
|
||||
include: { produto: true }
|
||||
include: {
|
||||
produto: true,
|
||||
usuario: {
|
||||
select: { id: true, nome: true },
|
||||
},
|
||||
}
|
||||
},
|
||||
pagamentos: true,
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export async function createOrder(data: CreateOrderInput) {
|
||||
export async function createOrder(data: CreateOrderInput, usuarioId?: string) {
|
||||
return prisma.comanda.create({
|
||||
data: {
|
||||
identificador: data.identificador,
|
||||
nomeCliente: data.nomeCliente,
|
||||
status: 'ABERTA',
|
||||
total: 0,
|
||||
usuarioId: usuarioId ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function addItemToOrder(comandaId: string, data: AddItemOrderInput) {
|
||||
export async function addItemToOrder(comandaId: string, data: AddItemOrderInput, usuarioId?: string) {
|
||||
const produto = await prisma.produto.findUnique({
|
||||
where: { id: data.produtoId },
|
||||
});
|
||||
@@ -55,10 +92,6 @@ export async function addItemToOrder(comandaId: string, data: AddItemOrderInput)
|
||||
throw new Error('Produto não encontrado');
|
||||
}
|
||||
|
||||
if (produto.estoqueAtual < data.quantidade) {
|
||||
throw new Error(`Estoque insuficiente. Disponível: ${produto.estoqueAtual}`);
|
||||
}
|
||||
|
||||
const precoTotalItem = produto.preco * data.quantidade;
|
||||
|
||||
const [, itemPedido] = await prisma.$transaction([
|
||||
@@ -73,6 +106,7 @@ export async function addItemToOrder(comandaId: string, data: AddItemOrderInput)
|
||||
precoUnitario: produto.preco,
|
||||
produtoId: data.produtoId,
|
||||
comandaId: comandaId,
|
||||
usuarioId: usuarioId ?? null,
|
||||
status: 'PENDENTE',
|
||||
},
|
||||
}),
|
||||
@@ -88,6 +122,10 @@ export async function addItemToOrder(comandaId: string, data: AddItemOrderInput)
|
||||
export async function listKitchenBarItems(itemCozinha?: boolean, status?: string) {
|
||||
const filter: any = {};
|
||||
|
||||
const now = nowUTC3();
|
||||
const dozeHorasAtrasMs = Date.UTC(now.year, now.month, now.date, now.hours - 12, now.minutes, now.seconds, 0);
|
||||
filter.criadoEm = { gte: new Date(dozeHorasAtrasMs) };
|
||||
|
||||
if (status) {
|
||||
filter.status = status;
|
||||
}
|
||||
@@ -103,6 +141,9 @@ export async function listKitchenBarItems(itemCozinha?: boolean, status?: string
|
||||
include: {
|
||||
produto: true,
|
||||
comanda: true,
|
||||
usuario: {
|
||||
select: { id: true, nome: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -116,6 +157,28 @@ export async function updateItemStatus(itemId: string, data: UpdateItemStatusInp
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateItemObservacao(itemId: string, data: UpdateItemObservacaoInput) {
|
||||
const item = await prisma.itemPedido.findUnique({
|
||||
where: { id: itemId },
|
||||
include: { comanda: true },
|
||||
});
|
||||
|
||||
if (!item) {
|
||||
throw new Error('Item do pedido não encontrado');
|
||||
}
|
||||
|
||||
if (item.comanda.status !== 'ABERTA') {
|
||||
throw new Error('Não é possível editar itens de uma comanda fechada/paga/cancelada');
|
||||
}
|
||||
|
||||
return prisma.itemPedido.update({
|
||||
where: { id: itemId },
|
||||
data: {
|
||||
observacao: data.observacao ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function payOrder(comandaId: string, data?: PayOrderInput) {
|
||||
const comanda = await prisma.comanda.findUnique({
|
||||
where: { id: comandaId },
|
||||
@@ -129,14 +192,109 @@ export async function payOrder(comandaId: string, data?: PayOrderInput) {
|
||||
throw new Error('Comanda não está aberta para pagamento');
|
||||
}
|
||||
|
||||
return prisma.comanda.update({
|
||||
const totalFinal = calcularTotalFinal(comanda);
|
||||
const restante = Math.max(totalFinal - comanda.valorPago, 0);
|
||||
|
||||
if (restante <= 0) {
|
||||
throw new Error('Comanda já foi paga integralmente');
|
||||
}
|
||||
|
||||
const [, comandaAtualizada] = await prisma.$transaction([
|
||||
prisma.pagamento.create({
|
||||
data: {
|
||||
comandaId,
|
||||
valor: restante,
|
||||
formaPagamento: data?.formaPagamento ?? 'DINHEIRO',
|
||||
observacao: 'Pagamento integral',
|
||||
},
|
||||
}),
|
||||
prisma.comanda.update({
|
||||
where: { id: comandaId },
|
||||
data: {
|
||||
status: 'PAGA',
|
||||
fechadoEm: new Date(),
|
||||
formaPagamento: data?.formaPagamento,
|
||||
valorPago: totalFinal,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
return comandaAtualizada;
|
||||
}
|
||||
|
||||
function calcularTotalFinal(comanda: { total: number; desconto: number; acrescimo: number; taxaServico: boolean }): number {
|
||||
let total = comanda.total || 0;
|
||||
total -= (comanda.desconto || 0);
|
||||
total += (comanda.acrescimo || 0);
|
||||
if (comanda.taxaServico) total += total * 0.10;
|
||||
return Math.max(total, 0);
|
||||
}
|
||||
|
||||
export async function registerPayment(comandaId: string, data: PartialPaymentInput) {
|
||||
const comanda = await prisma.comanda.findUnique({
|
||||
where: { id: comandaId },
|
||||
include: { itens: true },
|
||||
});
|
||||
|
||||
if (!comanda) {
|
||||
throw new Error('Comanda não encontrada');
|
||||
}
|
||||
|
||||
if (comanda.status === 'PAGA') {
|
||||
throw new Error('Comanda já foi paga integralmente');
|
||||
}
|
||||
|
||||
if (comanda.status === 'CANCELADA') {
|
||||
throw new Error('Não é possível pagar uma comanda cancelada');
|
||||
}
|
||||
|
||||
const totalFinal = calcularTotalFinal(comanda);
|
||||
const restante = Math.max(totalFinal - comanda.valorPago, 0);
|
||||
|
||||
if (restante <= 0) {
|
||||
throw new Error('Comanda já foi paga integralmente');
|
||||
}
|
||||
|
||||
let valorPagamento = data.valor ?? 0;
|
||||
|
||||
if (data.itemIds && data.itemIds.length > 0) {
|
||||
const itensSelecionados = comanda.itens.filter(i => data.itemIds!.includes(i.id));
|
||||
if (itensSelecionados.length === 0) {
|
||||
throw new Error('Nenhum item válido selecionado');
|
||||
}
|
||||
valorPagamento = itensSelecionados.reduce((acc, i) => acc + i.precoUnitario * i.quantidade, 0);
|
||||
}
|
||||
|
||||
if (!valorPagamento || valorPagamento <= 0) {
|
||||
throw new Error('Valor do pagamento deve ser maior que zero');
|
||||
}
|
||||
|
||||
if (valorPagamento > restante) {
|
||||
throw new Error(`Valor excede o restante. Disponível: R$ ${restante.toFixed(2)}`);
|
||||
}
|
||||
|
||||
const novoValorPago = comanda.valorPago + valorPagamento;
|
||||
const totalmentePago = novoValorPago >= totalFinal;
|
||||
|
||||
const pagamento = await prisma.$transaction([
|
||||
prisma.pagamento.create({
|
||||
data: {
|
||||
comandaId,
|
||||
valor: valorPagamento,
|
||||
formaPagamento: data.formaPagamento,
|
||||
observacao: data.observacao ?? null,
|
||||
},
|
||||
}),
|
||||
prisma.comanda.update({
|
||||
where: { id: comandaId },
|
||||
data: {
|
||||
valorPago: novoValorPago,
|
||||
...(totalmentePago ? { status: 'PAGA', fechadoEm: new Date() } : {}),
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
return pagamento[0];
|
||||
}
|
||||
|
||||
export async function updateOrder(comandaId: string, data: UpdateOrderInput) {
|
||||
@@ -166,9 +324,18 @@ export async function updateOrder(comandaId: string, data: UpdateOrderInput) {
|
||||
where: { id: comandaId },
|
||||
data: updateData,
|
||||
include: {
|
||||
usuario: {
|
||||
select: { id: true, nome: true, email: true },
|
||||
},
|
||||
itens: {
|
||||
include: { produto: true }
|
||||
include: {
|
||||
produto: true,
|
||||
usuario: {
|
||||
select: { id: true, nome: true },
|
||||
},
|
||||
}
|
||||
},
|
||||
pagamentos: true,
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -205,6 +372,49 @@ export async function deleteItemFromOrder(itemId: string) {
|
||||
|
||||
return prisma.comanda.findUnique({
|
||||
where: { id: item.comandaId },
|
||||
include: { itens: { include: { produto: true } } },
|
||||
include: {
|
||||
itens: {
|
||||
include: {
|
||||
produto: true,
|
||||
usuario: {
|
||||
select: { id: true, nome: true },
|
||||
},
|
||||
}
|
||||
},
|
||||
usuario: {
|
||||
select: { id: true, nome: true, email: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function reversePayment(pagamentoId: string) {
|
||||
const pagamento = await prisma.pagamento.findUnique({
|
||||
where: { id: pagamentoId },
|
||||
include: { comanda: true },
|
||||
});
|
||||
|
||||
if (!pagamento) throw new Error('Pagamento não encontrado');
|
||||
if (pagamento.estornado) throw new Error('Pagamento já foi estornado');
|
||||
|
||||
const novoValorPago = Math.max(pagamento.comanda.valorPago - pagamento.valor, 0);
|
||||
|
||||
const statusComanda = pagamento.comanda.status === 'PAGA' ? 'FECHADA' : pagamento.comanda.status;
|
||||
|
||||
const [, pagamentoEstornado] = await prisma.$transaction([
|
||||
prisma.pagamento.update({
|
||||
where: { id: pagamentoId },
|
||||
data: { estornado: true },
|
||||
}),
|
||||
prisma.comanda.update({
|
||||
where: { id: pagamento.comandaId },
|
||||
data: {
|
||||
valorPago: novoValorPago,
|
||||
status: statusComanda,
|
||||
...(pagamento.comanda.status === 'PAGA' ? { fechadoEm: null, formaPagamento: null } : {}),
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
return pagamentoEstornado;
|
||||
}
|
||||
|
||||
@@ -2,9 +2,9 @@ import { prisma } from '../lib/prisma';
|
||||
import { ProductInput } from '../schemas/product.schema';
|
||||
|
||||
export async function getTopProducts(limit = 10) {
|
||||
// Agrega a soma de quantidades vendidas para cada produto
|
||||
const topItems = await prisma.itemPedido.groupBy({
|
||||
by: ['produtoId'],
|
||||
where: { produto: { ativo: true } },
|
||||
_sum: { quantidade: true },
|
||||
orderBy: { _sum: { quantidade: 'desc' } },
|
||||
take: limit,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { prisma } from '../lib/prisma';
|
||||
import { nowUTC3, toUTC3 } from '../lib/timezone';
|
||||
|
||||
export async function getSalesReport(inicio: Date, fim: Date) {
|
||||
const comandas = await prisma.comanda.findMany({
|
||||
@@ -39,7 +40,7 @@ export async function getSalesReport(inicio: Date, fim: Date) {
|
||||
// Vendas por dia
|
||||
const vendasPorDia: Record<string, { vendas: number; comandas: number }> = {};
|
||||
for (const c of comandas) {
|
||||
const dia = c.fechadoEm!.toISOString().split('T')[0];
|
||||
const dia = toUTC3(c.fechadoEm!).toISOString().split('T')[0];
|
||||
if (!vendasPorDia[dia]) vendasPorDia[dia] = { vendas: 0, comandas: 0 };
|
||||
vendasPorDia[dia].vendas += c.total;
|
||||
vendasPorDia[dia].comandas += 1;
|
||||
@@ -80,12 +81,11 @@ export async function getSalesReport(inicio: Date, fim: Date) {
|
||||
}
|
||||
|
||||
export async function getDashboardData() {
|
||||
const now = new Date();
|
||||
const inicioDia = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
const inicioSemana = new Date(now);
|
||||
inicioSemana.setDate(now.getDate() - now.getDay());
|
||||
inicioSemana.setHours(0, 0, 0, 0);
|
||||
const inicioMes = new Date(now.getFullYear(), now.getMonth(), 1);
|
||||
const now = nowUTC3();
|
||||
const inicioDia = new Date(Date.UTC(now.year, now.month, now.date, 0, 0, 0, 0));
|
||||
const diaSemana = new Date(Date.UTC(now.year, now.month, now.date)).getUTCDay();
|
||||
const inicioSemana = new Date(Date.UTC(now.year, now.month, now.date - diaSemana, 0, 0, 0, 0));
|
||||
const inicioMes = new Date(Date.UTC(now.year, now.month, 1, 0, 0, 0, 0));
|
||||
|
||||
const [comandasHoje, comandasSemana, comandasMes, totalProdutos, produtosEstoqueBaixo, comandasAbertas] = await Promise.all([
|
||||
prisma.comanda.findMany({
|
||||
|
||||
16
test-api.ts
Normal file
16
test-api.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
(async () => {
|
||||
const res = await fetch('http://localhost:3333/api/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email: 'admin@gastrobar.com', senha: '123456' }),
|
||||
});
|
||||
const data = await res.json();
|
||||
console.log('TOKEN:', data.token);
|
||||
|
||||
const res2 = await fetch('http://localhost:3333/api/comandas?status=ABERTA,FECHADA', {
|
||||
headers: { Authorization: `Bearer ${data.token}` },
|
||||
});
|
||||
const data2 = await res2.json();
|
||||
console.log('COMANDAS STATUS:', res2.status);
|
||||
console.log('COMANDAS:', JSON.stringify(data2, null, 2));
|
||||
})();
|
||||
@@ -9,9 +9,9 @@ import { renderDashboard } from './views/dashboard';
|
||||
|
||||
const app = document.getElementById('app')!;
|
||||
|
||||
export function navigateTo(path: string) {
|
||||
export async function navigateTo(path: string) {
|
||||
window.history.pushState({}, '', path);
|
||||
router();
|
||||
await router();
|
||||
}
|
||||
|
||||
(window as any).navigateTo = navigateTo;
|
||||
|
||||
@@ -803,6 +803,24 @@ tbody td {
|
||||
white-space: nowrap;
|
||||
text-align: right;
|
||||
}
|
||||
#detalhes-itens-tbody td.item-obs .item-obs-editable {
|
||||
cursor: pointer;
|
||||
display: inline-block;
|
||||
padding: 0.15rem 0.3rem;
|
||||
border-radius: 4px;
|
||||
border: 1px dashed transparent;
|
||||
transition: border-color 0.15s, background 0.15s;
|
||||
max-width: 100%;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
#detalhes-itens-tbody td.item-obs .item-obs-editable:hover {
|
||||
border-color: var(--accent-primary);
|
||||
background: var(--bg-secondary);
|
||||
}
|
||||
#detalhes-itens-tbody td.item-obs .obs-inline-input {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* Line 3 — status + actions */
|
||||
#detalhes-itens-tbody td.item-status { text-align: left; }
|
||||
@@ -1008,6 +1026,16 @@ tbody td {
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
|
||||
#pag-itens-list label:hover {
|
||||
background: var(--bg-secondary);
|
||||
border-radius: 4px;
|
||||
}
|
||||
#pag-itens-list input[type="checkbox"] {
|
||||
accent-color: var(--accent-primary);
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
}
|
||||
|
||||
|
||||
@media (max-width: 480px) {
|
||||
h1 { font-size: 1.5rem; }
|
||||
|
||||
@@ -21,6 +21,28 @@ export function getUser(): { id: string; nome: string; email: string; role: stri
|
||||
return raw ? JSON.parse(raw) : null;
|
||||
}
|
||||
|
||||
/** Retorna YYYY-MM-DD de hoje em UTC-3 */
|
||||
export function todayStr(): string {
|
||||
const d = new Date(Date.now() - 3 * 60 * 60 * 1000);
|
||||
const y = d.getUTCFullYear();
|
||||
const m = String(d.getUTCMonth() + 1).padStart(2, '0');
|
||||
const day = String(d.getUTCDate()).padStart(2, '0');
|
||||
return `${y}-${m}-${day}`;
|
||||
}
|
||||
|
||||
/** Formata Date → dd/mm/yyyy para exibição */
|
||||
export function toDisplayDate(iso: string): string {
|
||||
const [y, m, d] = iso.split('-');
|
||||
return `${d}/${m}/${y}`;
|
||||
}
|
||||
|
||||
/** Converte dd/mm/yyyy → YYYY-MM-DD para a API */
|
||||
export function parseDisplayDate(display: string): string {
|
||||
const [d, m, y] = display.split('/');
|
||||
if (!d || !m || !y) return '';
|
||||
return `${y}-${m.padStart(2, '0')}-${d.padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
/** Formata valor em R$ */
|
||||
export function formatBRL(value: number): string {
|
||||
return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(value);
|
||||
|
||||
@@ -1,14 +1,24 @@
|
||||
import { api } from '../api';
|
||||
import { renderNavbar, toast, formatBRL } from '../utils';
|
||||
import { renderNavbar, formatBRL, toDisplayDate, parseDisplayDate, todayStr, getUser, toast } 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' },
|
||||
];
|
||||
const FORMAS_PAGAMENTO_LABEL: Record<string, string> = {
|
||||
DINHEIRO: '💵 Dinheiro',
|
||||
CARTAO_CREDITO: '💳 Cartão Crédito',
|
||||
CARTAO_DEBITO: '💳 Cartão Débito',
|
||||
PIX: '📱 PIX',
|
||||
};
|
||||
|
||||
function getDefaultDateRange(): { inicio: string; fim: string } {
|
||||
const hoje = todayStr();
|
||||
const ontemMs = new Date(hoje + 'T12:00:00Z').getTime() - 12 * 60 * 60 * 1000;
|
||||
const ontem = new Date(ontemMs);
|
||||
const ontemStr = `${ontem.getUTCFullYear()}-${String(ontem.getUTCMonth() + 1).padStart(2, '0')}-${String(ontem.getUTCDate()).padStart(2, '0')}`;
|
||||
return { inicio: toDisplayDate(ontemStr), fim: toDisplayDate(hoje) };
|
||||
}
|
||||
|
||||
export async function renderCheckout(container: HTMLElement) {
|
||||
const { inicio, fim } = getDefaultDateRange();
|
||||
|
||||
container.innerHTML = `
|
||||
${renderNavbar('/checkout')}
|
||||
<div class="container animate-fade-in">
|
||||
@@ -16,160 +26,140 @@ export async function renderCheckout(container: HTMLElement) {
|
||||
<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 class="glass-panel" style="margin-bottom:1.5rem;">
|
||||
<div style="display:flex;align-items:center;gap:1rem;flex-wrap:wrap;">
|
||||
<label style="color:var(--text-secondary);font-size:0.875rem;font-weight:600;">Período:</label>
|
||||
<div style="display:flex;align-items:center;gap:0.4rem;">
|
||||
<label style="font-size:0.8rem;color:var(--text-secondary);">De</label>
|
||||
<input type="text" id="checkout-data-inicio" class="form-control" value="${inicio}" style="font-size:0.85rem;" placeholder="dd/mm/yyyy" maxlength="10">
|
||||
</div>
|
||||
<div style="display:flex;align-items:center;gap:0.4rem;">
|
||||
<label style="font-size:0.8rem;color:var(--text-secondary);">Até</label>
|
||||
<input type="text" id="checkout-data-fim" class="form-control" value="${fim}" style="font-size:0.85rem;" placeholder="dd/mm/yyyy" maxlength="10">
|
||||
</div>
|
||||
<button class="btn btn-sm" id="checkout-btn-filtrar">Filtrar</button>
|
||||
<button class="btn btn-sm btn-secondary" id="checkout-btn-limpar" style="color:var(--text-secondary);">Últimas 12h</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="checkout-result"></div>
|
||||
<div id="checkout-pagamentos-total" style="margin-bottom:0.75rem;"></div>
|
||||
<div id="checkout-pagamentos-lista">
|
||||
<p class="card-subtitle">Carregando pagamentos...</p>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
document.getElementById('btn-buscar')?.addEventListener('click', searchComanda);
|
||||
document.getElementById('search-input')?.addEventListener('keydown', (e) => {
|
||||
if ((e as KeyboardEvent).key === 'Enter') searchComanda();
|
||||
document.getElementById('checkout-btn-filtrar')?.addEventListener('click', loadPagamentos);
|
||||
document.getElementById('checkout-btn-limpar')?.addEventListener('click', () => {
|
||||
const range = getDefaultDateRange();
|
||||
(document.getElementById('checkout-data-inicio') as HTMLInputElement).value = range.inicio;
|
||||
(document.getElementById('checkout-data-fim') as HTMLInputElement).value = range.fim;
|
||||
loadPagamentos();
|
||||
});
|
||||
|
||||
await loadPagamentos();
|
||||
}
|
||||
|
||||
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 loadPagamentos() {
|
||||
const dataInicio = parseDisplayDate((document.getElementById('checkout-data-inicio') as HTMLInputElement).value);
|
||||
const dataFim = parseDisplayDate((document.getElementById('checkout-data-fim') as HTMLInputElement).value);
|
||||
const lista = document.getElementById('checkout-pagamentos-lista')!;
|
||||
const totalEl = document.getElementById('checkout-pagamentos-total')!;
|
||||
|
||||
async function searchComanda() {
|
||||
const query = (document.getElementById('search-input') as HTMLInputElement).value.trim();
|
||||
const result = document.getElementById('checkout-result')!;
|
||||
lista.innerHTML = `<p class="card-subtitle">Carregando...</p>`;
|
||||
|
||||
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'
|
||||
);
|
||||
const qs = new URLSearchParams();
|
||||
if (dataInicio) qs.set('dataInicio', dataInicio);
|
||||
if (dataFim) qs.set('dataFim', dataFim);
|
||||
const query = qs.toString();
|
||||
const pagamentos = await api.get(`/pagamentos${query ? '?' + query : ''}`);
|
||||
|
||||
if (!found.length) {
|
||||
result.innerHTML = `<p class="card-subtitle">Nenhuma comanda ABERTA encontrada para "<strong>${query}</strong>".</p>`;
|
||||
if (!pagamentos.length) {
|
||||
lista.innerHTML = `<p class="card-subtitle" style="text-align:center;margin-top:2rem;">Nenhum pagamento registrado no período.</p>`;
|
||||
totalEl.innerHTML = '';
|
||||
return;
|
||||
}
|
||||
|
||||
result.innerHTML = found.map((c: any) => buildComandaCard(c)).join('');
|
||||
const totalGeral = pagamentos.reduce((acc: number, p: any) => acc + p.valor, 0);
|
||||
totalEl.innerHTML = `
|
||||
<div style="display:flex;justify-content:space-between;align-items:center;background:var(--bg-secondary);border-radius:8px;padding:0.75rem 1rem;">
|
||||
<span style="font-size:0.9rem;color:var(--text-secondary);">${pagamentos.length} pagamento(s) encontrado(s)</span>
|
||||
<span style="font-size:1.1rem;font-weight:700;color:var(--success);">Total: ${formatBRL(totalGeral)}</span>
|
||||
</div>
|
||||
`;
|
||||
|
||||
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;
|
||||
const user = getUser();
|
||||
const canReverse = user?.role === 'ADMIN' || user?.role === 'CAIXA';
|
||||
|
||||
if (!forma) {
|
||||
toast('Selecione a forma de pagamento', 'error');
|
||||
return;
|
||||
}
|
||||
lista.innerHTML = `
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Data / Hora</th>
|
||||
<th>Comanda</th>
|
||||
<th>Cliente</th>
|
||||
<th>Forma de Pagamento</th>
|
||||
<th style="text-align:right;">Valor</th>
|
||||
<th>Obs</th>
|
||||
${canReverse ? '<th style="text-align:center;">Ação</th>' : ''}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${pagamentos.map((p: any) => {
|
||||
const estornado = p.estornado;
|
||||
const rowStyle = estornado ? 'opacity:0.5;text-decoration:line-through;' : '';
|
||||
const valorStyle = estornado
|
||||
? 'text-align:right;font-weight:700;color:var(--accent-primary);'
|
||||
: 'text-align:right;font-weight:700;color:var(--success);';
|
||||
return `
|
||||
<tr style="${rowStyle}">
|
||||
<td data-label="Data" style="white-space:nowrap;">${new Date(p.criadoEm).toLocaleString('pt-BR', { day: '2-digit', month: '2-digit', year: '2-digit', hour: '2-digit', minute: '2-digit' })}</td>
|
||||
<td data-label="Comanda">
|
||||
<a href="#" class="checkout-link-comanda" data-comanda-id="${p.comanda.id}" style="color:var(--accent-primary);text-decoration:none;font-weight:600;">
|
||||
${p.comanda.identificador}
|
||||
</a>
|
||||
<span class="badge status-${p.comanda.status.toLowerCase()}" style="font-size:0.65rem;margin-left:0.3rem;">${p.comanda.status}</span>
|
||||
</td>
|
||||
<td data-label="Cliente" style="color:var(--text-secondary);">${p.comanda.nomeCliente ?? '—'}</td>
|
||||
<td data-label="Pagamento">${FORMAS_PAGAMENTO_LABEL[p.formaPagamento] ?? p.formaPagamento}</td>
|
||||
<td data-label="Valor" style="${valorStyle}">${formatBRL(p.valor)}</td>
|
||||
<td data-label="Obs" style="color:var(--text-secondary);font-style:italic;font-size:0.8rem;">${p.observacao ?? '—'}</td>
|
||||
${canReverse ? `<td data-label="Ação" style="text-align:center;">${estornado
|
||||
? '<span class="badge status-cancelada" style="font-size:0.65rem;">ESTORNADO</span>'
|
||||
: `<button class="btn btn-sm btn-danger checkout-btn-estornar" data-pagamento-id="${p.id}" data-comanda-id="${p.comanda.id}">Estornar</button>`
|
||||
}</td>` : ''}
|
||||
</tr>`;
|
||||
}).join('')}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
`;
|
||||
|
||||
if (!confirm(`Confirmar pagamento de ${formatBRL(total)} para "${ident}" via ${forma.replace('_', ' ')}?`)) return;
|
||||
lista.querySelectorAll('.checkout-link-comanda').forEach(link => {
|
||||
link.addEventListener('click', async (e) => {
|
||||
e.preventDefault();
|
||||
const comandaId = (link as HTMLElement).dataset.comandaId!;
|
||||
await (window as any).navigateTo('/orders#' + comandaId);
|
||||
});
|
||||
});
|
||||
|
||||
lista.querySelectorAll('.checkout-btn-estornar').forEach(btn => {
|
||||
btn.addEventListener('click', async (e) => {
|
||||
e.preventDefault();
|
||||
const pagamentoId = (btn as HTMLElement).dataset.pagamentoId!;
|
||||
if (!confirm('Deseja estornar este pagamento? A comanda será reaberta.')) 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>`;
|
||||
await api.patch(`/pagamentos/${pagamentoId}/estornar`, {});
|
||||
toast('Pagamento estornado com sucesso', 'success');
|
||||
await loadPagamentos();
|
||||
} catch (err: any) {
|
||||
toast(err.message, 'error');
|
||||
}
|
||||
});
|
||||
});
|
||||
} catch (err: any) {
|
||||
result.innerHTML = `<p style="color:var(--accent-primary)">Erro: ${err.message}</p>`;
|
||||
lista.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>
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { api } from '../api';
|
||||
import { renderNavbar, toast, formatBRL } from '../utils';
|
||||
import { renderNavbar, toast, formatBRL, toDisplayDate, parseDisplayDate, todayStr } from '../utils';
|
||||
|
||||
export async function renderDashboard(container: HTMLElement) {
|
||||
container.innerHTML = `
|
||||
@@ -39,9 +39,11 @@ export async function renderDashboard(container: HTMLElement) {
|
||||
<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;">
|
||||
<input type="text" id="rel-inicio" class="form-control" style="width:auto;" placeholder="dd/mm/yyyy" maxlength="10">
|
||||
<input type="time" id="rel-hora-inicio" class="form-control" style="width:auto;" value="15:00">
|
||||
<span style="color:var(--text-secondary);">até</span>
|
||||
<input type="date" id="rel-fim" class="form-control" style="width:auto;">
|
||||
<input type="text" id="rel-fim" class="form-control" style="width:auto;" placeholder="dd/mm/yyyy" maxlength="10">
|
||||
<input type="time" id="rel-hora-fim" class="form-control" style="width:auto;" value="04:00">
|
||||
<button class="btn btn-sm" id="btn-gerar-relatorio">Gerar</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -59,10 +61,10 @@ export async function renderDashboard(container: HTMLElement) {
|
||||
`;
|
||||
|
||||
// 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 hoje = todayStr();
|
||||
const inicioMes = hoje.substring(0, 7) + '-01';
|
||||
(document.getElementById('rel-inicio') as HTMLInputElement).value = toDisplayDate(inicioMes);
|
||||
(document.getElementById('rel-fim') as HTMLInputElement).value = toDisplayDate(hoje);
|
||||
|
||||
const loadDashboard = async () => {
|
||||
try {
|
||||
@@ -80,12 +82,16 @@ export async function renderDashboard(container: HTMLElement) {
|
||||
};
|
||||
|
||||
const loadRelatorio = async () => {
|
||||
const inicio = (document.getElementById('rel-inicio') as HTMLInputElement).value;
|
||||
const fim = (document.getElementById('rel-fim') as HTMLInputElement).value;
|
||||
const inicio = parseDisplayDate((document.getElementById('rel-inicio') as HTMLInputElement).value);
|
||||
const horaInicio = (document.getElementById('rel-hora-inicio') as HTMLInputElement).value || '15:00';
|
||||
const fim = parseDisplayDate((document.getElementById('rel-fim') as HTMLInputElement).value);
|
||||
const horaFim = (document.getElementById('rel-hora-fim') as HTMLInputElement).value || '04:00';
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
if (inicio) params.set('inicio', inicio);
|
||||
if (fim) params.set('fim', fim);
|
||||
params.set('horaInicio', horaInicio);
|
||||
params.set('horaFim', horaFim);
|
||||
const data = await api.get(`/relatorios/vendas?${params.toString()}`);
|
||||
|
||||
// Resumo
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { api } from '../api';
|
||||
import { renderNavbar, toast } from '../utils';
|
||||
|
||||
let previousItemIds: Set<string> = new Set<string>();
|
||||
let previousItemIdsByStatus: Map<string, Set<string>> = new Map();
|
||||
let audioCtx: AudioContext | null = null;
|
||||
|
||||
function playNotificationSound() {
|
||||
try {
|
||||
if (!audioCtx) audioCtx = new AudioContext();
|
||||
if (audioCtx.state === 'suspended') audioCtx.resume();
|
||||
const osc = audioCtx.createOscillator();
|
||||
const gain = audioCtx.createGain();
|
||||
osc.connect(gain);
|
||||
@@ -58,25 +59,30 @@ export async function renderKitchen(container: HTMLElement) {
|
||||
let currentStatus = 'PENDENTE';
|
||||
let currentFilter = '';
|
||||
let autoRefreshInterval: ReturnType<typeof setInterval> | null = null;
|
||||
let requestId = 0;
|
||||
|
||||
const loadItems = async () => {
|
||||
const grid = document.getElementById('items-grid')!;
|
||||
grid.innerHTML = '<p class="card-subtitle">Carregando...</p>';
|
||||
const myRequestId = ++requestId;
|
||||
try {
|
||||
let url = `/painel/itens?status=${currentStatus}`;
|
||||
if (currentFilter !== '') url += `&itemCozinha=${currentFilter}`;
|
||||
const items = await api.get(url);
|
||||
|
||||
if (myRequestId !== requestId) return;
|
||||
|
||||
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));
|
||||
const previousIds = previousItemIdsByStatus.get(currentStatus);
|
||||
if (previousIds && previousIds.size > 0) {
|
||||
const newItems = items.filter((i: any) => !previousIds.has(i.id));
|
||||
if (newItems.length > 0) {
|
||||
playNotificationSound();
|
||||
toast(`${newItems.length} novo(s) pedido(s) recebido(s)!`, 'success');
|
||||
}
|
||||
}
|
||||
previousItemIds = currentIds;
|
||||
previousItemIdsByStatus.set(currentStatus, currentIds);
|
||||
|
||||
if (!items.length) {
|
||||
grid.innerHTML = `<p class="card-subtitle" style="grid-column:1/-1;text-align:center;padding:3rem 0;">
|
||||
@@ -104,11 +110,12 @@ export async function renderKitchen(container: HTMLElement) {
|
||||
</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;">
|
||||
<p class="card-subtitle" style="margin-bottom:0.5rem;">
|
||||
Pedido às ${new Date(item.criadoEm).toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' })}
|
||||
</p>
|
||||
${item.usuario ? `<p style="color:var(--text-secondary);font-size:0.8rem;margin-bottom:1rem;">Adicionado por: <strong>${item.usuario.nome}</strong></p>` : '<p style="margin-bottom:1rem;"></p>'}
|
||||
${action.label ? `
|
||||
<button class="btn" style="width:100%;" onclick="window.advanceStatus('${item.id}','${action.next}')">
|
||||
<button class="btn" style="width:100%;" data-action="advance" data-item-id="${item.id}" data-next-status="${action.next}">
|
||||
${action.label}
|
||||
</button>
|
||||
` : `<p class="card-subtitle" style="text-align:center;">✅ Entregue</p>`}
|
||||
@@ -159,7 +166,12 @@ export async function renderKitchen(container: HTMLElement) {
|
||||
else stopAutoRefresh();
|
||||
});
|
||||
|
||||
(window as any).advanceStatus = async (id: string, status: string) => {
|
||||
// Event delegation for advance buttons
|
||||
document.getElementById('items-grid')?.addEventListener('click', async (e) => {
|
||||
const btn = (e.target as HTMLElement).closest('[data-action="advance"]') as HTMLElement | null;
|
||||
if (!btn) return;
|
||||
const id = btn.dataset.itemId!;
|
||||
const status = btn.dataset.nextStatus!;
|
||||
try {
|
||||
await api.patch(`/painel/itens/${id}/status`, { status });
|
||||
toast('Status atualizado!', 'success');
|
||||
@@ -167,12 +179,26 @@ export async function renderKitchen(container: HTMLElement) {
|
||||
} catch (err: any) {
|
||||
toast(err.message, 'error');
|
||||
}
|
||||
});
|
||||
|
||||
// Pause auto-refresh when tab is hidden
|
||||
const handleVisibilityChange = () => {
|
||||
if (document.hidden) {
|
||||
stopAutoRefresh();
|
||||
} else {
|
||||
const checkbox = document.getElementById('auto-refresh-toggle') as HTMLInputElement | null;
|
||||
if (checkbox?.checked) startAutoRefresh();
|
||||
}
|
||||
};
|
||||
document.addEventListener('visibilitychange', handleVisibilityChange);
|
||||
|
||||
// Cleanup on navigation
|
||||
const cleanup = () => {
|
||||
stopAutoRefresh();
|
||||
previousItemIds.clear();
|
||||
previousItemIdsByStatus.clear();
|
||||
document.removeEventListener('visibilitychange', handleVisibilityChange);
|
||||
audioCtx?.close();
|
||||
audioCtx = null;
|
||||
};
|
||||
window.addEventListener('popstate', cleanup);
|
||||
|
||||
|
||||
@@ -43,11 +43,11 @@ export async function renderMenu(container: HTMLElement) {
|
||||
</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">
|
||||
<input type="number" id="p-estoque" class="form-control" value="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">
|
||||
<input type="number" id="p-estoque-min" class="form-control" value="0">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group" style="margin-top:1rem;">
|
||||
@@ -87,6 +87,10 @@ export async function renderMenu(container: HTMLElement) {
|
||||
`;
|
||||
|
||||
let categorias: any[] = [];
|
||||
let allProducts: any[] = [];
|
||||
let filterCategoria = '';
|
||||
let filterAtivo = '';
|
||||
let filterCozinha = '';
|
||||
|
||||
const loadCategorias = async () => {
|
||||
categorias = await api.get('/categorias');
|
||||
@@ -96,19 +100,90 @@ export async function renderMenu(container: HTMLElement) {
|
||||
|
||||
const renderTabProdutos = async () => {
|
||||
const tc = document.getElementById('tab-content')!;
|
||||
const products = await api.get('/produtos');
|
||||
allProducts = 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>
|
||||
<span class="card-subtitle" id="produtos-count"></span>
|
||||
<button class="btn" id="btn-novo-produto">+ Novo Produto</button>
|
||||
</div>
|
||||
<div style="display:flex;gap:0.5rem;flex-wrap:wrap;margin-bottom:1.5rem;align-items:flex-end;">
|
||||
<div class="form-group" style="margin:0;width:auto;">
|
||||
<label style="color:var(--text-secondary);font-size:0.8rem;">Categoria</label>
|
||||
<select id="f-categoria" class="form-control" style="padding:0.4rem 0.75rem;">
|
||||
<option value="">Todas</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group" style="margin:0;width:auto;">
|
||||
<label style="color:var(--text-secondary);font-size:0.8rem;">Status</label>
|
||||
<select id="f-ativo" class="form-control" style="padding:0.4rem 0.75rem;">
|
||||
<option value="">Todos</option>
|
||||
<option value="true">Ativos</option>
|
||||
<option value="false">Inativos</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group" style="margin:0;width:auto;">
|
||||
<label style="color:var(--text-secondary);font-size:0.8rem;">Tipo</label>
|
||||
<select id="f-cozinha" class="form-control" style="padding:0.4rem 0.75rem;">
|
||||
<option value="">Todos</option>
|
||||
<option value="true">🍳 Cozinha</option>
|
||||
<option value="false">🍹 Bar</option>
|
||||
</select>
|
||||
</div>
|
||||
<button class="btn btn-secondary btn-sm" id="btn-clear-filters" style="margin-bottom:0;">✕ Limpar</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) => `
|
||||
<tbody id="produtos-tbody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const catSel = document.getElementById('f-categoria') as HTMLSelectElement;
|
||||
catSel.innerHTML = '<option value="">Todas</option>' +
|
||||
categorias.map((c: any) => `<option value="${c.id}">${c.nome}</option>`).join('');
|
||||
catSel.value = filterCategoria;
|
||||
(document.getElementById('f-ativo') as HTMLSelectElement).value = filterAtivo;
|
||||
(document.getElementById('f-cozinha') as HTMLSelectElement).value = filterCozinha;
|
||||
|
||||
catSel.addEventListener('change', () => { filterCategoria = catSel.value; renderProductsTable(); });
|
||||
(document.getElementById('f-ativo') as HTMLSelectElement).addEventListener('change', (e) => { filterAtivo = (e.target as HTMLSelectElement).value; renderProductsTable(); });
|
||||
(document.getElementById('f-cozinha') as HTMLSelectElement).addEventListener('change', (e) => { filterCozinha = (e.target as HTMLSelectElement).value; renderProductsTable(); });
|
||||
document.getElementById('btn-clear-filters')?.addEventListener('click', () => {
|
||||
filterCategoria = '';
|
||||
filterAtivo = '';
|
||||
filterCozinha = '';
|
||||
(document.getElementById('f-categoria') as HTMLSelectElement).value = '';
|
||||
(document.getElementById('f-ativo') as HTMLSelectElement).value = '';
|
||||
(document.getElementById('f-cozinha') as HTMLSelectElement).value = '';
|
||||
renderProductsTable();
|
||||
});
|
||||
|
||||
renderProductsTable();
|
||||
|
||||
document.getElementById('btn-novo-produto')?.addEventListener('click', () => {
|
||||
clearProductForm();
|
||||
(document.getElementById('modal-produto') as HTMLElement).style.display = 'flex';
|
||||
});
|
||||
};
|
||||
|
||||
const renderProductsTable = () => {
|
||||
let filtered = allProducts;
|
||||
if (filterCategoria) filtered = filtered.filter((p: any) => p.categoriaId === filterCategoria);
|
||||
if (filterAtivo !== '') filtered = filtered.filter((p: any) => String(p.ativo) === filterAtivo);
|
||||
if (filterCozinha !== '') filtered = filtered.filter((p: any) => String(p.itemCozinha) === filterCozinha);
|
||||
|
||||
const countEl = document.getElementById('produtos-count');
|
||||
if (countEl) countEl.textContent = `${filtered.length} de ${allProducts.length} produto(s)`;
|
||||
|
||||
const tbody = document.getElementById('produtos-tbody')!;
|
||||
if (!filtered.length) {
|
||||
tbody.innerHTML = `<tr><td colspan="7" style="text-align:center;padding:2rem;color:var(--text-secondary);">Nenhum produto encontrado com os filtros selecionados.</td></tr>`;
|
||||
return;
|
||||
}
|
||||
tbody.innerHTML = filtered.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>
|
||||
@@ -125,16 +200,7 @@ export async function renderMenu(container: HTMLElement) {
|
||||
<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';
|
||||
});
|
||||
`).join('');
|
||||
};
|
||||
|
||||
const renderTabCategorias = async () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { api } from '../api';
|
||||
import { renderNavbar, toast, formatBRL, getUser, statusBadge } from '../utils';
|
||||
import { renderNavbar, toast, formatBRL, getUser, statusBadge, parseDisplayDate } from '../utils';
|
||||
|
||||
let localComandas: any[] = [];
|
||||
|
||||
@@ -22,11 +22,11 @@ export async function renderOrders(container: HTMLElement) {
|
||||
<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">
|
||||
<input type="text" id="busca-data-inicio" class="form-control" placeholder="dd/mm/yyyy" maxlength="10">
|
||||
</div>
|
||||
<div class="comandas-search-field">
|
||||
<label>Até</label>
|
||||
<input type="date" id="busca-data-fim" class="form-control">
|
||||
<input type="text" id="busca-data-fim" class="form-control" placeholder="dd/mm/yyyy" maxlength="10">
|
||||
</div>
|
||||
<div class="comandas-search-actions">
|
||||
<button type="submit" class="btn btn-sm btn-secondary">Buscar</button>
|
||||
@@ -108,6 +108,7 @@ export async function renderOrders(container: HTMLElement) {
|
||||
<span class="detalhes-summary-client" id="detalhes-label-client"></span>
|
||||
</div>
|
||||
<div id="detalhes-label-status"></div>
|
||||
<div id="detalhes-label-usuario" style="font-size:0.8rem;color:var(--text-secondary);margin-top:0.25rem;"></div>
|
||||
</div>
|
||||
|
||||
<div class="detalhes-edit-section">
|
||||
@@ -175,6 +176,7 @@ export async function renderOrders(container: HTMLElement) {
|
||||
<th style="text-align:center;">Qtd</th>
|
||||
<th style="text-align:right;">Subtotal</th>
|
||||
<th>Obs</th>
|
||||
<th>Adicionado por</th>
|
||||
<th>Status</th>
|
||||
<th>Ações</th>
|
||||
</tr>
|
||||
@@ -196,10 +198,72 @@ export async function renderOrders(container: HTMLElement) {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal Pagamento Parcial -->
|
||||
<div id="modal-pagamento-parcial" class="modal-overlay" style="display:none;">
|
||||
<div class="modal" style="max-width: 500px;">
|
||||
<div class="modal-header">
|
||||
<h3>Receber Pagamento</h3>
|
||||
<button class="btn-icon" id="modal-pagamento-close">✕</button>
|
||||
</div>
|
||||
<input type="hidden" id="pagamento-comanda-id">
|
||||
<div id="pagamento-restante-info" style="background:var(--bg-secondary);border-radius:8px;padding:0.75rem 1rem;margin-bottom:1rem;font-size:0.9rem;"></div>
|
||||
|
||||
<div class="tabs" style="margin-bottom:1rem;">
|
||||
<button class="tab-btn active" data-pagtab="itens">Selecionar Itens</button>
|
||||
<button class="tab-btn" data-pagtab="fixo">Valor Fixo</button>
|
||||
</div>
|
||||
|
||||
<!-- Tab: Selecionar Itens -->
|
||||
<div id="pagtab-itens">
|
||||
<div style="max-height:200px;overflow-y:auto;margin-bottom:1rem;">
|
||||
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:0.5rem;">
|
||||
<label style="display:flex;align-items:center;gap:0.4rem;cursor:pointer;font-size:0.85rem;">
|
||||
<input type="checkbox" id="pag-select-all"> Selecionar todos
|
||||
</label>
|
||||
<span id="pag-itens-valor" style="font-weight:600;color:var(--accent-primary);font-size:0.9rem;">R$ 0,00</span>
|
||||
</div>
|
||||
<div id="pag-itens-list"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Tab: Valor Fixo -->
|
||||
<div id="pagtab-fixo" style="display:none;">
|
||||
<div class="form-group">
|
||||
<label>Valor (R$)</label>
|
||||
<input type="number" id="pag-valor-fixo" class="form-control" step="0.01" min="0.01" placeholder="0,00">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group" style="margin-top:0.75rem;">
|
||||
<label>Forma de Pagamento</label>
|
||||
<select id="pag-forma" class="form-control">
|
||||
${FORMAS_PAGAMENTO.map(fp => `<option value="${fp.value}">${fp.label}</option>`).join('')}
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Observação (opcional)</label>
|
||||
<input type="text" id="pag-obs" class="form-control" placeholder="Ex: pagamento referente à mesa 5...">
|
||||
</div>
|
||||
|
||||
<button type="button" class="btn btn-success" style="width:100%;margin-top:0.5rem;" id="btn-confirmar-pagamento">
|
||||
💳 Confirmar Pagamento
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
await loadComandas({ status: 'ABERTA,FECHADA' });
|
||||
bindOrderEvents();
|
||||
|
||||
const hash = window.location.hash.slice(1);
|
||||
if (hash) {
|
||||
await loadComandas({});
|
||||
setTimeout(() => {
|
||||
(window as any).openDetails(hash);
|
||||
window.history.replaceState({}, '', '/orders');
|
||||
}, 50);
|
||||
}
|
||||
}
|
||||
|
||||
function calcularTotalFinal(c: any): number {
|
||||
@@ -232,6 +296,7 @@ async function loadComandas(params?: { status?: string; dataInicio?: string; dat
|
||||
<tr>
|
||||
<th>Identificador</th>
|
||||
<th>Cliente</th>
|
||||
<th>Aberto por</th>
|
||||
<th>Status</th>
|
||||
<th>Total</th>
|
||||
<th>Aberta em</th>
|
||||
@@ -243,6 +308,7 @@ async function loadComandas(params?: { status?: string; dataInicio?: string; dat
|
||||
<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="Aberto por" class="cmd-usuario" style="color:var(--text-secondary);font-size:0.85rem;">${c.usuario?.nome ?? '—'}</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>
|
||||
@@ -318,8 +384,8 @@ function bindOrderEvents() {
|
||||
|
||||
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;
|
||||
const dataInicio = parseDisplayDate((document.getElementById('busca-data-inicio') as HTMLInputElement).value);
|
||||
const dataFim = parseDisplayDate((document.getElementById('busca-data-fim') as HTMLInputElement).value);
|
||||
if (!dataInicio && !dataFim) return loadComandas({ status: 'ABERTA,FECHADA' });
|
||||
loadComandas({ dataInicio, dataFim });
|
||||
});
|
||||
@@ -392,7 +458,19 @@ function bindOrderEvents() {
|
||||
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';
|
||||
|
||||
(document.getElementById('qtd') as HTMLInputElement).value = '1';
|
||||
(document.getElementById('obs') as HTMLInputElement).value = '';
|
||||
(document.getElementById('selected-produto-id') as HTMLInputElement).value = '';
|
||||
const preview = document.getElementById('selected-produto-preview')!;
|
||||
preview.textContent = 'Nenhum produto selecionado';
|
||||
preview.style.color = 'var(--text-primary)';
|
||||
|
||||
try {
|
||||
const topProducts = await api.get('/produtos/mais-vendidos');
|
||||
renderProductCards(topProducts);
|
||||
} catch {}
|
||||
|
||||
await loadComandas({ status: 'ABERTA,FECHADA' });
|
||||
} catch (err: any) {
|
||||
toast(err.message, 'error');
|
||||
@@ -422,6 +500,71 @@ function bindOrderEvents() {
|
||||
}, 300);
|
||||
});
|
||||
|
||||
// Modal Pagamento Parcial - close
|
||||
document.getElementById('modal-pagamento-close')?.addEventListener('click', () => {
|
||||
(document.getElementById('modal-pagamento-parcial') as HTMLElement).style.display = 'none';
|
||||
});
|
||||
|
||||
// Modal Pagamento Parcial - tab switching
|
||||
document.querySelectorAll('[data-pagtab]').forEach(btn => {
|
||||
btn.addEventListener('click', () => {
|
||||
document.querySelectorAll('[data-pagtab]').forEach(b => b.classList.remove('active'));
|
||||
btn.classList.add('active');
|
||||
const tab = (btn as HTMLElement).dataset.pagtab;
|
||||
(document.getElementById('pagtab-itens') as HTMLElement).style.display = tab === 'itens' ? 'block' : 'none';
|
||||
(document.getElementById('pagtab-fixo') as HTMLElement).style.display = tab === 'fixo' ? 'block' : 'none';
|
||||
});
|
||||
});
|
||||
|
||||
// Modal Pagamento Parcial - select all
|
||||
document.getElementById('pag-select-all')?.addEventListener('change', (e) => {
|
||||
const checked = (e.target as HTMLInputElement).checked;
|
||||
document.querySelectorAll('.pag-item-check').forEach(cb => {
|
||||
(cb as HTMLInputElement).checked = checked;
|
||||
});
|
||||
updatePagamentoItensValor();
|
||||
});
|
||||
|
||||
// Modal Pagamento Parcial - confirm
|
||||
document.getElementById('btn-confirmar-pagamento')?.addEventListener('click', async () => {
|
||||
const comandaId = (document.getElementById('pagamento-comanda-id') as HTMLInputElement).value;
|
||||
const forma = (document.getElementById('pag-forma') as HTMLSelectElement).value;
|
||||
const obs = (document.getElementById('pag-obs') as HTMLInputElement).value;
|
||||
const activeTab = document.querySelector('[data-pagtab].active') as HTMLElement;
|
||||
const isItensTab = activeTab?.dataset.pagtab === 'itens';
|
||||
|
||||
let payload: any = { formaPagamento: forma };
|
||||
if (obs.trim()) payload.observacao = obs.trim();
|
||||
|
||||
if (isItensTab) {
|
||||
const checked = document.querySelectorAll('.pag-item-check:checked');
|
||||
const itemIds = Array.from(checked).map(cb => (cb as HTMLInputElement).dataset.itemId);
|
||||
if (itemIds.length === 0) {
|
||||
toast('Selecione pelo menos um item!', 'error');
|
||||
return;
|
||||
}
|
||||
payload.itemIds = itemIds;
|
||||
payload.valor = 0;
|
||||
} else {
|
||||
const valor = parseFloat((document.getElementById('pag-valor-fixo') as HTMLInputElement).value);
|
||||
if (!valor || valor <= 0) {
|
||||
toast('Informe um valor válido!', 'error');
|
||||
return;
|
||||
}
|
||||
payload.valor = valor;
|
||||
}
|
||||
|
||||
try {
|
||||
await api.post(`/comandas/${comandaId}/pagamentos`, payload);
|
||||
toast('Pagamento registrado!', 'success');
|
||||
(document.getElementById('modal-pagamento-parcial') as HTMLElement).style.display = 'none';
|
||||
await loadComandas({ status: 'ABERTA,FECHADA' });
|
||||
(window as any).openDetails(comandaId);
|
||||
} catch (err: any) {
|
||||
toast(err.message, 'error');
|
||||
}
|
||||
});
|
||||
|
||||
(window as any).openAddItem = async (comandaId: string) => {
|
||||
(document.getElementById('current-comanda-id') as HTMLInputElement).value = comandaId;
|
||||
(document.getElementById('selected-produto-id') as HTMLInputElement).value = '';
|
||||
@@ -468,6 +611,12 @@ function bindOrderEvents() {
|
||||
document.getElementById('detalhes-label-client')!.textContent = c.nomeCliente ? `· ${c.nomeCliente}` : '';
|
||||
document.getElementById('detalhes-label-status')!.innerHTML = statusBadge(c.status);
|
||||
|
||||
// Exibir quem abriu a comanda
|
||||
const detalhesUsuario = document.getElementById('detalhes-label-usuario');
|
||||
if (detalhesUsuario) {
|
||||
detalhesUsuario.textContent = c.usuario ? `Aberto por: ${c.usuario.nome}` : '';
|
||||
}
|
||||
|
||||
// Render itens
|
||||
const tbody = document.getElementById('detalhes-itens-tbody')!;
|
||||
const itens = c.itens ?? [];
|
||||
@@ -475,14 +624,20 @@ function bindOrderEvents() {
|
||||
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>`;
|
||||
tbody.innerHTML = `<tr><td colspan="7" 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="Obs" class="item-obs">
|
||||
${canDelete
|
||||
? `<span class="item-obs-editable" data-item-id="${i.id}">${i.observacao ?? '<i style="opacity:0.4">adicionar obs</i>'}</span>`
|
||||
: (i.observacao ?? '')
|
||||
}
|
||||
</td>
|
||||
<td data-label="Adicionado por" class="item-usuario" style="font-size:0.8rem;color:var(--text-secondary);">${i.usuario?.nome ?? '—'}</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 ? `
|
||||
@@ -510,6 +665,49 @@ function bindOrderEvents() {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Inline edit observacao
|
||||
tbody.querySelectorAll('.item-obs-editable').forEach(span => {
|
||||
span.addEventListener('click', () => {
|
||||
const itemId = (span as HTMLElement).dataset.itemId!;
|
||||
const currentText = span.textContent ?? '';
|
||||
const input = document.createElement('input');
|
||||
input.type = 'text';
|
||||
input.className = 'obs-inline-input';
|
||||
input.value = currentText;
|
||||
input.style.cssText = 'width:100%;padding:0.25rem 0.4rem;border:1px solid var(--accent-primary);border-radius:4px;font-size:0.8rem;background:var(--bg-primary);color:var(--text-primary);';
|
||||
|
||||
const save = async () => {
|
||||
const novaObs = input.value.trim();
|
||||
if (novaObs === currentText) {
|
||||
span.textContent = currentText || '';
|
||||
if (!currentText) span.innerHTML = '<i style="opacity:0.4">adicionar obs</i>';
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await api.patch(`/comandas/itens/${itemId}/observacao`, { observacao: novaObs || undefined });
|
||||
span.textContent = novaObs;
|
||||
if (!novaObs) span.innerHTML = '<i style="opacity:0.4">adicionar obs</i>';
|
||||
toast('Observação atualizada!', 'success');
|
||||
await loadComandas({ status: 'ABERTA,FECHADA' });
|
||||
} catch (err: any) {
|
||||
toast(err.message, 'error');
|
||||
span.textContent = currentText;
|
||||
}
|
||||
};
|
||||
|
||||
input.addEventListener('blur', save);
|
||||
input.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter') { e.preventDefault(); input.blur(); }
|
||||
if (e.key === 'Escape') { span.textContent = currentText; if (!currentText) span.innerHTML = '<i style="opacity:0.4">adicionar obs</i>'; }
|
||||
});
|
||||
|
||||
span.textContent = '';
|
||||
span.appendChild(input);
|
||||
input.focus();
|
||||
input.select();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Resumo financeiro
|
||||
@@ -519,6 +717,9 @@ function bindOrderEvents() {
|
||||
const acrescimo = c.acrescimo || 0;
|
||||
const taxaServico = c.taxaServico ? (subtotal - desconto + acrescimo) * 0.10 : 0;
|
||||
const totalFinal = Math.max(subtotal - desconto + acrescimo + taxaServico, 0);
|
||||
const valorPago = c.valorPago || 0;
|
||||
const restante = Math.max(totalFinal - valorPago, 0);
|
||||
const pagamentos = c.pagamentos ?? [];
|
||||
|
||||
resumoEl.innerHTML = `
|
||||
<div style="background:var(--bg-secondary);border-radius:8px;padding:0.75rem 1rem;font-size:0.85rem;">
|
||||
@@ -535,39 +736,58 @@ function bindOrderEvents() {
|
||||
${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>
|
||||
${valorPago > 0 ? `<div style="display:flex;justify-content:space-between;margin-bottom:0.25rem;color:var(--success);font-weight:600;">
|
||||
<span>Já pago:</span><span>-${formatBRL(valorPago)}</span>
|
||||
</div>` : ''}
|
||||
${restante > 0 && valorPago > 0 ? `<div style="display:flex;justify-content:space-between;margin-bottom:0.25rem;font-weight:700;color:var(--accent-primary);border-top:1px solid var(--border-color);padding-top:0.35rem;">
|
||||
<span>Restante:</span><span>${formatBRL(restante)}</span>
|
||||
</div>` : ''}
|
||||
</div>
|
||||
${pagamentos.length > 0 ? `
|
||||
<div style="margin-top:0.75rem;">
|
||||
<div style="font-size:0.8rem;color:var(--text-secondary);margin-bottom:0.35rem;font-weight:600;">Histórico de Pagamentos</div>
|
||||
${pagamentos.map((p: any) => `
|
||||
<div style="display:flex;justify-content:space-between;align-items:center;font-size:0.8rem;padding:0.3rem 0;border-bottom:1px solid var(--border-color);${p.estornado ? 'opacity:0.5;text-decoration:line-through;' : ''}">
|
||||
<div>
|
||||
<span style="color:var(--text-secondary);">${new Date(p.criadoEm).toLocaleString('pt-BR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })}</span>
|
||||
<span style="margin-left:0.4rem;">${p.formaPagamento.replace('_', ' ')}</span>
|
||||
${p.observacao ? `<span style="margin-left:0.4rem;color:var(--text-secondary);font-style:italic;">— ${p.observacao}</span>` : ''}
|
||||
${p.estornado ? '<span class="badge status-cancelada" style="font-size:0.6rem;margin-left:0.4rem;">ESTORNADO</span>' : ''}
|
||||
</div>
|
||||
<span style="font-weight:600;color:${p.estornado ? 'var(--accent-primary)' : 'var(--success)'};">${formatBRL(p.valor)}</span>
|
||||
</div>
|
||||
`).join('')}
|
||||
</div>
|
||||
` : ''}
|
||||
`;
|
||||
|
||||
document.getElementById('detalhes-total')!.textContent = formatBRL(totalFinal);
|
||||
document.getElementById('detalhes-total')!.textContent = formatBRL(restante > 0 ? restante : 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') {
|
||||
if (canPay && c.status !== 'PAGA' && c.status !== 'CANCELADA' && restante > 0) {
|
||||
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 type="button" class="btn btn-success" style="flex:1;" id="btn-pagamento-parcial">
|
||||
💰 Pagamento Parcial
|
||||
</button>
|
||||
<button type="button" class="btn btn-success" style="flex:1;" id="btn-pagamento-total">
|
||||
💳 Pagar Tudo
|
||||
</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;
|
||||
document.getElementById('btn-pagamento-parcial')?.addEventListener('click', () => {
|
||||
openPagamentoModal(c);
|
||||
});
|
||||
|
||||
document.getElementById('btn-pagamento-total')?.addEventListener('click', async () => {
|
||||
const forma = prompt('Forma de pagamento:\n1 - Dinheiro\n2 - Cartão Crédito\n3 - Cartão Débito\n4 - PIX\n\nDigite o número:');
|
||||
const formaMap: Record<string, string> = { '1': 'DINHEIRO', '2': 'CARTAO_CREDITO', '3': 'CARTAO_DEBITO', '4': 'PIX' };
|
||||
const formaPagamento = formaMap[forma ?? ''] ?? 'DINHEIRO';
|
||||
if (!confirm(`Confirmar pagamento de ${formatBRL(restante)} (restante) para "${c.identificador}"?`)) return;
|
||||
try {
|
||||
await api.post(`/comandas/${c.id}/pagar`, { formaPagamento: forma });
|
||||
await api.post(`/comandas/${c.id}/pagar`, { formaPagamento });
|
||||
toast('Pagamento registrado!', 'success');
|
||||
(document.getElementById('modal-detalhes-comanda') as HTMLElement).style.display = 'none';
|
||||
await loadComandas({ status: 'ABERTA,FECHADA' });
|
||||
@@ -575,9 +795,66 @@ function bindOrderEvents() {
|
||||
toast(err.message, 'error');
|
||||
}
|
||||
});
|
||||
} else if (canPay && c.status === 'PAGA') {
|
||||
acoesContainer.innerHTML = `<p style="text-align:center;color:var(--success);width:100%;font-weight:600;">✅ Comanda Paga</p>`;
|
||||
}
|
||||
|
||||
(document.getElementById('modal-detalhes-comanda') as HTMLElement).style.display = 'flex';
|
||||
document.querySelector('.detalhes-edit-section')?.classList.remove('expanded');
|
||||
};
|
||||
|
||||
function openPagamentoModal(c: any) {
|
||||
const totalFinal = calcularTotalFinal(c);
|
||||
const restante = Math.max(totalFinal - (c.valorPago || 0), 0);
|
||||
|
||||
(document.getElementById('pagamento-comanda-id') as HTMLInputElement).value = c.id;
|
||||
(document.getElementById('pagamento-restante-info') as HTMLElement).innerHTML =
|
||||
`<div style="display:flex;justify-content:space-between;"><span>Restante a pagar:</span><strong style="color:var(--accent-primary);">${formatBRL(restante)}</strong></div>`;
|
||||
|
||||
// Reset tabs
|
||||
document.querySelectorAll('[data-pagtab]').forEach(b => b.classList.remove('active'));
|
||||
document.querySelector('[data-pagtab="itens"]')?.classList.add('active');
|
||||
(document.getElementById('pagtab-itens') as HTMLElement).style.display = 'block';
|
||||
(document.getElementById('pagtab-fixo') as HTMLElement).style.display = 'none';
|
||||
(document.getElementById('pag-valor-fixo') as HTMLInputElement).value = '';
|
||||
(document.getElementById('pag-obs') as HTMLInputElement).value = '';
|
||||
(document.getElementById('pag-select-all') as HTMLInputElement).checked = false;
|
||||
|
||||
// Render items
|
||||
const itensList = document.getElementById('pag-itens-list')!;
|
||||
const itens = c.itens ?? [];
|
||||
itensList.innerHTML = itens.map((i: any) => {
|
||||
const subtotal = i.precoUnitario * i.quantidade;
|
||||
return `
|
||||
<label style="display:flex;align-items:center;gap:0.5rem;padding:0.4rem 0;border-bottom:1px solid var(--border-color);font-size:0.85rem;cursor:pointer;">
|
||||
<input type="checkbox" class="pag-item-check" data-item-id="${i.id}" data-item-valor="${subtotal}">
|
||||
<span style="flex:1;">${i.quantidade}x ${i.produto?.nome ?? '—'}</span>
|
||||
<span style="color:var(--text-secondary);">${formatBRL(subtotal)}</span>
|
||||
</label>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
// Bind item checkboxes
|
||||
itensList.querySelectorAll('.pag-item-check').forEach(cb => {
|
||||
cb.addEventListener('change', () => {
|
||||
updatePagamentoItensValor();
|
||||
const totalChecks = itensList.querySelectorAll('.pag-item-check').length;
|
||||
const checkedChecks = itensList.querySelectorAll('.pag-item-check:checked').length;
|
||||
(document.getElementById('pag-select-all') as HTMLInputElement).checked = totalChecks === checkedChecks;
|
||||
});
|
||||
});
|
||||
|
||||
updatePagamentoItensValor();
|
||||
|
||||
(document.getElementById('modal-pagamento-parcial') as HTMLElement).style.display = 'flex';
|
||||
}
|
||||
|
||||
function updatePagamentoItensValor() {
|
||||
const checked = document.querySelectorAll('.pag-item-check:checked');
|
||||
let total = 0;
|
||||
checked.forEach(cb => {
|
||||
total += parseFloat((cb as HTMLElement).dataset.itemValor || '0');
|
||||
});
|
||||
(document.getElementById('pag-itens-valor')!.textContent) = formatBRL(total);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user