Compare commits
6 Commits
7e19917d2c
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| b567a45803 | |||
| 14e92c91fd | |||
| 14a36b68b5 | |||
| 4be043edf3 | |||
| 01ecf06215 | |||
| 402ac776ac |
6
.gitignore
vendored
Normal file
6
.gitignore
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
node_modules/
|
||||
dist/
|
||||
.env
|
||||
*.db
|
||||
*.db-journal
|
||||
.DS_Store
|
||||
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
|
||||
156
README.md
Normal file
156
README.md
Normal file
@@ -0,0 +1,156 @@
|
||||
# Gastrobar PDV
|
||||
|
||||
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
|
||||
- **Runtime:** Node.js + TypeScript
|
||||
- **Framework:** Fastify
|
||||
- **ORM:** Prisma
|
||||
- **Banco:** SQLite (desenvolvimento)
|
||||
- **Validação:** Zod
|
||||
- **Auth:** JWT (@fastify/jwt) + bcrypt
|
||||
|
||||
### Frontend
|
||||
- **Bundler:** Vite
|
||||
- **Linguagem:** TypeScript vanilla (sem framework)
|
||||
- **Estilo:** CSS customizado com dark theme e glassmorphism
|
||||
|
||||
## Funcionalidades
|
||||
|
||||
- **Autenticação JWT** com controle por roles (ADMIN, CAIXA, GARÇOM, COZINHA, BARMAN)
|
||||
- **Painel de Cozinha/Bar** com atualização em tempo real e notificações sonoras
|
||||
- **Gestão de Comandas** com formas de pagamento, desconto, acréscimo e taxa de serviço
|
||||
- **Caixa/Checkout** com busca avançada e seleção de pagamento
|
||||
- **Cardápio** com gestão de produtos e categorias, controle de estoque
|
||||
- **Equipe** com gestão de usuários e redefinição de senha
|
||||
- **Relatórios** de vendas por período
|
||||
- **Dashboard** com KPIs para administradores
|
||||
|
||||
## Estrutura do Projeto
|
||||
|
||||
```
|
||||
app_ces/
|
||||
├── prisma/ # Schema do banco e seed
|
||||
│ ├── schema.prisma
|
||||
│ └── seed.ts
|
||||
├── src/ # Backend (API)
|
||||
│ ├── server.ts
|
||||
│ ├── lib/prisma.ts
|
||||
│ ├── middlewares/
|
||||
│ ├── controllers/
|
||||
│ ├── services/
|
||||
│ ├── schemas/
|
||||
│ └── routes/
|
||||
└── web/ # Frontend (SPA)
|
||||
└── src/
|
||||
├── main.ts
|
||||
├── api.ts
|
||||
├── utils.ts
|
||||
└── views/
|
||||
```
|
||||
|
||||
## Como Rodar
|
||||
|
||||
### Backend
|
||||
|
||||
```bash
|
||||
# Instalar dependências
|
||||
npm install
|
||||
|
||||
# Gerar cliente Prisma e aplicar schema
|
||||
npx prisma db push
|
||||
|
||||
# Popular banco com dados iniciais
|
||||
npm run db:seed
|
||||
|
||||
# Iniciar servidor de desenvolvimento
|
||||
npm run dev
|
||||
```
|
||||
|
||||
O servidor estará disponível em `http://localhost:3333`.
|
||||
|
||||
### Frontend
|
||||
|
||||
```bash
|
||||
cd web
|
||||
|
||||
# Instalar dependências
|
||||
npm install
|
||||
|
||||
# Iniciar dev server
|
||||
npm run dev
|
||||
```
|
||||
|
||||
O frontend estará disponível em `http://localhost:5173`.
|
||||
|
||||
## Rotas da API
|
||||
|
||||
### Autenticação
|
||||
| Método | Rota | Descrição |
|
||||
|--------|------|-----------|
|
||||
| POST | `/api/auth/login` | Login e geração de JWT |
|
||||
| PATCH | `/api/auth/senha` | Alterar própria senha |
|
||||
|
||||
### Categorias
|
||||
| Método | Rota | Descrição | Permissão |
|
||||
|--------|------|-----------|-----------|
|
||||
| GET | `/api/categorias` | Listar categorias | Autenticado |
|
||||
| GET | `/api/categorias/:id` | Obter categoria | Autenticado |
|
||||
| POST | `/api/categorias` | Criar categoria | ADMIN |
|
||||
| PUT | `/api/categorias/:id` | Atualizar categoria | ADMIN |
|
||||
| DELETE | `/api/categorias/:id` | Deletar categoria | ADMIN |
|
||||
|
||||
### Produtos
|
||||
| Método | Rota | Descrição | Permissão |
|
||||
|--------|------|-----------|-----------|
|
||||
| GET | `/api/produtos` | Listar produtos | Autenticado |
|
||||
| GET | `/api/produtos/mais-vendidos` | Top produtos por vendas | Autenticado |
|
||||
| GET | `/api/produtos/busca` | Buscar produto por nome | Autenticado |
|
||||
| GET | `/api/produtos/baixo-estoque` | Produtos com estoque baixo | ADMIN |
|
||||
| GET | `/api/produtos/:id` | Obter produto | Autenticado |
|
||||
| POST | `/api/produtos` | Criar produto | ADMIN |
|
||||
| PUT | `/api/produtos/:id` | Atualizar produto | ADMIN |
|
||||
| DELETE | `/api/produtos/:id` | Deletar produto | ADMIN |
|
||||
|
||||
### Comandas
|
||||
| Método | Rota | Descrição | Permissão |
|
||||
|--------|------|-----------|-----------|
|
||||
| GET | `/api/comandas` | Listar/filtrar comandas | Autenticado |
|
||||
| POST | `/api/comandas` | Criar comanda | GARÇOM/CAIXA/ADMIN |
|
||||
| POST | `/api/comandas/:id/itens` | Adicionar item | GARÇOM/CAIXA/ADMIN |
|
||||
| PATCH | `/api/comandas/:id` | Atualizar comanda | GARÇOM/CAIXA/ADMIN |
|
||||
| POST | `/api/comandas/:id/pagar` | Pagar comanda | CAIXA/ADMIN |
|
||||
| DELETE | `/api/comandas/itens/:id` | Remover item | CAIXA/ADMIN |
|
||||
|
||||
### Painel Cozinha/Bar
|
||||
| Método | Rota | Descrição | Permissão |
|
||||
|--------|------|-----------|-----------|
|
||||
| GET | `/api/painel/itens` | Listar itens do painel | COZINHA/BARMAN/ADMIN |
|
||||
| PATCH | `/api/painel/itens/:id/status` | Atualizar status | COZINHA/BARMAN/ADMIN |
|
||||
|
||||
### Relatórios
|
||||
| Método | Rota | Descrição | Permissão |
|
||||
|--------|------|-----------|-----------|
|
||||
| GET | `/api/relatorios/vendas` | Vendas por período | ADMIN |
|
||||
| GET | `/api/relatorios/dashboard` | Dados do dashboard | ADMIN |
|
||||
|
||||
### Usuários
|
||||
| Método | Rota | Descrição | Permissão |
|
||||
|--------|------|-----------|-----------|
|
||||
| GET | `/api/usuarios` | Listar usuários | ADMIN |
|
||||
| POST | `/api/usuarios` | Criar usuário | ADMIN |
|
||||
| PATCH | `/api/usuarios/:id` | Atualizar usuário | ADMIN |
|
||||
| PATCH | `/api/usuarios/:id/senha` | Resetar senha | ADMIN |
|
||||
| DELETE | `/api/usuarios/:id` | Deletar usuário | ADMIN |
|
||||
|
||||
## Roles e Permissões
|
||||
|
||||
| Role | Acesso |
|
||||
|------|--------|
|
||||
| **ADMIN** | Acesso total ao sistema |
|
||||
| **CAIXA** | Comandas, checkout, pagamento |
|
||||
| **GARÇOM** | Criar/gerenciar comandas |
|
||||
| **COZINHA** | Painel de preparo (cozinha) |
|
||||
| **BARMAN** | Painel de preparo (bar) |
|
||||
74
api.http
Normal file
74
api.http
Normal file
@@ -0,0 +1,74 @@
|
||||
### Login
|
||||
# @name login
|
||||
POST http://localhost:3333/api/auth/login
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"email": "admin@gastrobar.com",
|
||||
"senha": "123456"
|
||||
}
|
||||
|
||||
###
|
||||
|
||||
@token = {{login.response.body.token}}
|
||||
|
||||
### Criar Categoria
|
||||
POST http://localhost:3333/api/categorias
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"nome": "Bebidas"
|
||||
}
|
||||
|
||||
### Listar Categorias
|
||||
GET http://localhost:3333/api/categorias
|
||||
|
||||
### Criar Produto
|
||||
POST http://localhost:3333/api/produtos
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"nome": "Cerveja Artesanal",
|
||||
"descricao": "IPA 500ml",
|
||||
"preco": 25.50,
|
||||
"itemCozinha": false,
|
||||
"categoriaId": "COLOQUE_O_ID_DA_CATEGORIA_AQUI"
|
||||
}
|
||||
|
||||
### Listar Produtos
|
||||
GET http://localhost:3333/api/produtos
|
||||
|
||||
### Abrir Comanda
|
||||
# @name comanda
|
||||
POST http://localhost:3333/api/comandas
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"identificador": "Mesa 01",
|
||||
"nomeCliente": "João Silva"
|
||||
}
|
||||
|
||||
###
|
||||
|
||||
@comandaId = {{comanda.response.body.id}}
|
||||
|
||||
### Adicionar Item à Comanda
|
||||
POST http://localhost:3333/api/comandas/{{comandaId}}/itens
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"produtoId": "COLOQUE_O_ID_DO_PRODUTO_AQUI",
|
||||
"quantidade": 2,
|
||||
"observacao": "Sem gelo"
|
||||
}
|
||||
|
||||
### Painel da Cozinha / Bar (Listar Pendentes)
|
||||
GET http://localhost:3333/api/painel/itens?status=PENDENTE
|
||||
|
||||
### Atualizar Status do Item
|
||||
PATCH http://localhost:3333/api/painel/itens/COLOQUE_O_ID_DO_ITEM_AQUI/status
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"status": "PREPARANDO"
|
||||
}
|
||||
1980
package-lock.json
generated
Normal file
1980
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
36
package.json
Normal file
36
package.json
Normal file
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"name": "gastrobar-backend",
|
||||
"version": "1.0.0",
|
||||
"description": "Backend para o sistema de PDV e gestão do gastrobar",
|
||||
"main": "dist/server.js",
|
||||
"scripts": {
|
||||
"dev": "tsx watch src/server.ts",
|
||||
"build": "tsc",
|
||||
"start": "node dist/server.js",
|
||||
"db:push": "prisma db push",
|
||||
"db:seed": "tsx prisma/seed.ts"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@fastify/cors": "^8.0.0",
|
||||
"@fastify/jwt": "^8.0.1",
|
||||
"@prisma/client": "^5.14.0",
|
||||
"bcrypt": "^5.1.1",
|
||||
"dotenv": "^17.4.2",
|
||||
"fastify": "^4.27.0",
|
||||
"zod": "^3.23.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bcrypt": "^5.0.2",
|
||||
"@types/node": "^20.12.12",
|
||||
"prisma": "^5.14.0",
|
||||
"tsx": "^4.11.0",
|
||||
"typescript": "^5.4.5"
|
||||
},
|
||||
"prisma": {
|
||||
"seed": "tsx prisma/seed.ts"
|
||||
},
|
||||
"type": "commonjs"
|
||||
}
|
||||
88
prisma/schema.prisma
Normal file
88
prisma/schema.prisma
Normal file
@@ -0,0 +1,88 @@
|
||||
datasource db {
|
||||
provider = "sqlite"
|
||||
url = "file:./dev.db"
|
||||
}
|
||||
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
model Usuario {
|
||||
id String @id @default(uuid())
|
||||
nome String
|
||||
email String @unique
|
||||
senha String
|
||||
role String @default("GARCOM") // ADMIN, CAIXA, GARCOM, COZINHA, BARMAN
|
||||
ativo Boolean @default(true)
|
||||
criadoEm DateTime @default(now())
|
||||
comandas Comanda[]
|
||||
itensPedido ItemPedido[]
|
||||
}
|
||||
|
||||
model Categoria {
|
||||
id String @id @default(uuid())
|
||||
nome String
|
||||
produtos Produto[]
|
||||
}
|
||||
|
||||
model Produto {
|
||||
id String @id @default(uuid())
|
||||
nome String
|
||||
descricao String?
|
||||
fotoUrl String?
|
||||
preco Float
|
||||
custo Float?
|
||||
estoqueAtual Int @default(0)
|
||||
estoqueMinimo Int @default(0)
|
||||
itemCozinha Boolean
|
||||
ativo Boolean @default(true)
|
||||
categoriaId String
|
||||
categoria Categoria @relation(fields: [categoriaId], references: [id])
|
||||
itensPedido ItemPedido[]
|
||||
}
|
||||
|
||||
model Comanda {
|
||||
id String @id @default(uuid())
|
||||
identificador String
|
||||
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)
|
||||
formaPagamento String? // DINHEIRO, CARTAO_CREDITO, CARTAO_DEBITO, PIX
|
||||
motivoCancelamento String?
|
||||
criadoEm DateTime @default(now())
|
||||
fechadoEm DateTime?
|
||||
usuarioId String?
|
||||
usuario Usuario? @relation(fields: [usuarioId], references: [id])
|
||||
itens ItemPedido[]
|
||||
pagamentos Pagamento[]
|
||||
}
|
||||
|
||||
model ItemPedido {
|
||||
id String @id @default(uuid())
|
||||
quantidade Int
|
||||
precoUnitario Float
|
||||
observacao String?
|
||||
status String @default("PENDENTE") // PENDENTE, PREPARANDO, PRONTO, ENTREGUE
|
||||
produtoId String
|
||||
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())
|
||||
}
|
||||
34
prisma/seed.ts
Normal file
34
prisma/seed.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import bcrypt from 'bcrypt';
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
async function main() {
|
||||
console.log('Iniciando o seed...');
|
||||
|
||||
const passwordHash = await bcrypt.hash('123456', 10);
|
||||
|
||||
const admin = await prisma.usuario.upsert({
|
||||
where: { email: 'admin@gastrobar.com' },
|
||||
update: {},
|
||||
create: {
|
||||
nome: 'Administrador',
|
||||
email: 'admin@gastrobar.com',
|
||||
senha: passwordHash,
|
||||
role: 'ADMIN',
|
||||
ativo: true,
|
||||
},
|
||||
});
|
||||
|
||||
console.log('Usuário admin criado:', admin.email);
|
||||
}
|
||||
|
||||
main()
|
||||
.then(async () => {
|
||||
await prisma.$disconnect();
|
||||
})
|
||||
.catch(async (e) => {
|
||||
console.error(e);
|
||||
await prisma.$disconnect();
|
||||
process.exit(1);
|
||||
});
|
||||
28
src/controllers/auth.controller.ts
Normal file
28
src/controllers/auth.controller.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { loginSchema, changePasswordSchema } from '../schemas/auth.schema';
|
||||
import { loginService, changePassword } from '../services/auth.service';
|
||||
|
||||
export async function loginController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const body = loginSchema.parse(request.body);
|
||||
|
||||
try {
|
||||
const user = await loginService(body);
|
||||
const token = await reply.jwtSign(user, { expiresIn: '1d' });
|
||||
|
||||
return reply.send({ token, user });
|
||||
} catch (error: any) {
|
||||
return reply.status(401).send({ error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
export async function changePasswordController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const body = changePasswordSchema.parse(request.body);
|
||||
const user = request.user as { id: string };
|
||||
|
||||
try {
|
||||
await changePassword(user.id, body.senhaAtual, body.novaSenha);
|
||||
return reply.send({ message: 'Senha alterada com sucesso' });
|
||||
} catch (error: any) {
|
||||
return reply.status(400).send({ error: error.message });
|
||||
}
|
||||
}
|
||||
49
src/controllers/category.controller.ts
Normal file
49
src/controllers/category.controller.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { categorySchema } from '../schemas/category.schema';
|
||||
import * as categoryService from '../services/category.service';
|
||||
import { z } from 'zod';
|
||||
|
||||
export async function createCategoryController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const data = categorySchema.parse(request.body);
|
||||
try {
|
||||
const category = await categoryService.createCategory(data);
|
||||
return reply.status(201).send(category);
|
||||
} catch (error: any) {
|
||||
return reply.status(400).send({ error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
export async function listCategoriesController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const categories = await categoryService.listCategories();
|
||||
return reply.send(categories);
|
||||
}
|
||||
|
||||
export async function getCategoryController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const { id } = z.object({ id: z.string().uuid() }).parse(request.params);
|
||||
const category = await categoryService.getCategoryById(id);
|
||||
if (!category) {
|
||||
return reply.status(404).send({ error: 'Categoria não encontrada' });
|
||||
}
|
||||
return reply.send(category);
|
||||
}
|
||||
|
||||
export async function updateCategoryController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const { id } = z.object({ id: z.string().uuid() }).parse(request.params);
|
||||
const data = categorySchema.parse(request.body);
|
||||
try {
|
||||
const category = await categoryService.updateCategory(id, data);
|
||||
return reply.send(category);
|
||||
} catch (error: any) {
|
||||
return reply.status(400).send({ error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteCategoryController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const { id } = z.object({ id: z.string().uuid() }).parse(request.params);
|
||||
try {
|
||||
await categoryService.deleteCategory(id);
|
||||
return reply.status(204).send();
|
||||
} catch (error: any) {
|
||||
return reply.status(400).send({ error: error.message });
|
||||
}
|
||||
}
|
||||
145
src/controllers/order.controller.ts
Normal file
145
src/controllers/order.controller.ts
Normal file
@@ -0,0 +1,145 @@
|
||||
import { FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { createOrderSchema, addItemOrderSchema, updateItemStatusSchema, updateItemObservacaoSchema, updateOrderSchema, payOrderSchema, partialPaymentSchema } from '../schemas/order.schema';
|
||||
import * as orderService from '../services/order.service';
|
||||
import { z } from 'zod';
|
||||
|
||||
export async function listOrdersController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const querySchema = z.object({
|
||||
status: z.string().optional(),
|
||||
dataInicio: z.string().optional(),
|
||||
dataFim: z.string().optional(),
|
||||
});
|
||||
|
||||
const query = querySchema.parse(request.query);
|
||||
|
||||
const filter: any = {};
|
||||
if (query.status) filter.statuses = query.status.split(',');
|
||||
if (query.dataInicio) filter.dataInicio = query.dataInicio;
|
||||
if (query.dataFim) filter.dataFim = query.dataFim;
|
||||
|
||||
const orders = await orderService.listOrders(
|
||||
(filter.statuses || filter.dataInicio || filter.dataFim) ? filter : undefined
|
||||
);
|
||||
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 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, user.id);
|
||||
return reply.status(201).send(item);
|
||||
} catch (error: any) {
|
||||
return reply.status(400).send({ error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
export async function listKitchenBarController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const querySchema = z.object({
|
||||
status: z.string().optional(),
|
||||
itemCozinha: z.string().transform(v => v === 'true').optional()
|
||||
});
|
||||
|
||||
const query = querySchema.parse(request.query);
|
||||
const items = await orderService.listKitchenBarItems(query.itemCozinha, query.status);
|
||||
return reply.send(items);
|
||||
}
|
||||
|
||||
export async function updateItemStatusController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const { id } = z.object({ id: z.string().uuid() }).parse(request.params);
|
||||
const data = updateItemStatusSchema.parse(request.body);
|
||||
const item = await orderService.updateItemStatus(id, data);
|
||||
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
|
||||
? payOrderSchema.parse(request.body)
|
||||
: undefined;
|
||||
try {
|
||||
const comanda = await orderService.payOrder(id, body);
|
||||
return reply.send(comanda);
|
||||
} catch (error: any) {
|
||||
return reply.status(400).send({ error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
try {
|
||||
const comanda = await orderService.updateOrder(id, data);
|
||||
return reply.send(comanda);
|
||||
} catch (error: any) {
|
||||
return reply.status(400).send({ error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteItemFromOrderController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const { id } = z.object({ id: z.string().uuid() }).parse(request.params);
|
||||
try {
|
||||
const comanda = await orderService.deleteItemFromOrder(id);
|
||||
return reply.send(comanda);
|
||||
} catch (error: any) {
|
||||
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 });
|
||||
}
|
||||
}
|
||||
54
src/controllers/product.controller.ts
Normal file
54
src/controllers/product.controller.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { productSchema } from '../schemas/product.schema';
|
||||
import * as productService from '../services/product.service';
|
||||
import { z } from 'zod';
|
||||
|
||||
export async function createProductController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const data = productSchema.parse(request.body);
|
||||
const product = await productService.createProduct(data);
|
||||
return reply.status(201).send(product);
|
||||
}
|
||||
|
||||
export async function listProductsController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const products = await productService.listProducts();
|
||||
return reply.send(products);
|
||||
}
|
||||
|
||||
export async function getTopProductsController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const { limit } = z.object({ limit: z.coerce.number().default(10) }).parse(request.query);
|
||||
const products = await productService.getTopProducts(limit);
|
||||
return reply.send(products);
|
||||
}
|
||||
|
||||
export async function searchProductsController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const { q } = z.object({ q: z.string().min(1) }).parse(request.query);
|
||||
const products = await productService.searchProducts(q);
|
||||
return reply.send(products);
|
||||
}
|
||||
|
||||
export async function getProductController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const { id } = z.object({ id: z.string().uuid() }).parse(request.params);
|
||||
const product = await productService.getProductById(id);
|
||||
if (!product) {
|
||||
return reply.status(404).send({ error: 'Produto não encontrado' });
|
||||
}
|
||||
return reply.send(product);
|
||||
}
|
||||
|
||||
export async function updateProductController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const { id } = z.object({ id: z.string().uuid() }).parse(request.params);
|
||||
const data = productSchema.partial().parse(request.body);
|
||||
const product = await productService.updateProduct(id, data);
|
||||
return reply.send(product);
|
||||
}
|
||||
|
||||
export async function deleteProductController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const { id } = z.object({ id: z.string().uuid() }).parse(request.params);
|
||||
await productService.deleteProduct(id);
|
||||
return reply.status(204).send();
|
||||
}
|
||||
|
||||
export async function getLowStockProductsController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const products = await productService.getLowStockProducts();
|
||||
return reply.send(products);
|
||||
}
|
||||
31
src/controllers/report.controller.ts
Normal file
31
src/controllers/report.controller.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
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 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);
|
||||
}
|
||||
|
||||
export async function dashboardController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const dashboard = await reportService.getDashboardData();
|
||||
return reply.send(dashboard);
|
||||
}
|
||||
43
src/controllers/user.controller.ts
Normal file
43
src/controllers/user.controller.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { userSchema, updateUserSchema, resetPasswordSchema } from '../schemas/user.schema';
|
||||
import * as userService from '../services/user.service';
|
||||
import { z } from 'zod';
|
||||
|
||||
export async function createUserController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const data = userSchema.parse(request.body);
|
||||
try {
|
||||
const user = await userService.createUser(data);
|
||||
return reply.status(201).send(user);
|
||||
} catch (error: any) {
|
||||
return reply.status(400).send({ error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
export async function listUsersController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const users = await userService.listUsers();
|
||||
return reply.send(users);
|
||||
}
|
||||
|
||||
export async function updateUserController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const { id } = z.object({ id: z.string().uuid() }).parse(request.params);
|
||||
const data = updateUserSchema.parse(request.body);
|
||||
const user = await userService.updateUser(id, data);
|
||||
return reply.send(user);
|
||||
}
|
||||
|
||||
export async function deleteUserController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const { id } = z.object({ id: z.string().uuid() }).parse(request.params);
|
||||
await userService.deleteUser(id);
|
||||
return reply.status(204).send();
|
||||
}
|
||||
|
||||
export async function resetPasswordController(request: FastifyRequest, reply: FastifyReply) {
|
||||
const { id } = z.object({ id: z.string().uuid() }).parse(request.params);
|
||||
const body = resetPasswordSchema.parse(request.body);
|
||||
try {
|
||||
await userService.resetPassword(id, body.novaSenha);
|
||||
return reply.send({ message: 'Senha redefinida com sucesso' });
|
||||
} catch (error: any) {
|
||||
return reply.status(400).send({ error: error.message });
|
||||
}
|
||||
}
|
||||
3
src/lib/prisma.ts
Normal file
3
src/lib/prisma.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
export const prisma = new PrismaClient();
|
||||
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`;
|
||||
}
|
||||
24
src/middlewares/auth.middleware.ts
Normal file
24
src/middlewares/auth.middleware.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { FastifyRequest, FastifyReply } from 'fastify';
|
||||
|
||||
export async function authenticate(request: FastifyRequest, reply: FastifyReply) {
|
||||
try {
|
||||
await request.jwtVerify();
|
||||
} catch (err) {
|
||||
return reply.status(401).send({ error: 'Não autorizado' });
|
||||
}
|
||||
}
|
||||
|
||||
export function requireRoles(roles: string[]) {
|
||||
return async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
try {
|
||||
await request.jwtVerify();
|
||||
const user = request.user as { role: string };
|
||||
|
||||
if (!roles.includes(user.role)) {
|
||||
return reply.status(403).send({ error: 'Acesso negado. Permissão insuficiente.' });
|
||||
}
|
||||
} catch (err) {
|
||||
return reply.status(401).send({ error: 'Não autorizado' });
|
||||
}
|
||||
};
|
||||
}
|
||||
8
src/routes/auth.routes.ts
Normal file
8
src/routes/auth.routes.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { FastifyInstance } from 'fastify';
|
||||
import { loginController, changePasswordController } from '../controllers/auth.controller';
|
||||
import { authenticate } from '../middlewares/auth.middleware';
|
||||
|
||||
export async function authRoutes(app: FastifyInstance) {
|
||||
app.post('/login', loginController);
|
||||
app.patch('/senha', { preHandler: [authenticate] }, changePasswordController);
|
||||
}
|
||||
14
src/routes/category.routes.ts
Normal file
14
src/routes/category.routes.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { FastifyInstance } from 'fastify';
|
||||
import * as categoryController from '../controllers/category.controller';
|
||||
import { authenticate, requireRoles } from '../middlewares/auth.middleware';
|
||||
|
||||
export async function categoryRoutes(app: FastifyInstance) {
|
||||
// Leitura aberta a todos autenticados
|
||||
app.get('/categorias', { preHandler: [authenticate] }, categoryController.listCategoriesController);
|
||||
app.get('/categorias/:id', { preHandler: [authenticate] }, categoryController.getCategoryController);
|
||||
|
||||
// Escrita apenas para ADMIN
|
||||
app.post('/categorias', { preHandler: [requireRoles(['ADMIN'])] }, categoryController.createCategoryController);
|
||||
app.put('/categorias/:id', { preHandler: [requireRoles(['ADMIN'])] }, categoryController.updateCategoryController);
|
||||
app.delete('/categorias/:id', { preHandler: [requireRoles(['ADMIN'])] }, categoryController.deleteCategoryController);
|
||||
}
|
||||
33
src/routes/order.routes.ts
Normal file
33
src/routes/order.routes.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { FastifyInstance } from 'fastify';
|
||||
import * as orderController from '../controllers/order.controller';
|
||||
import { authenticate, requireRoles } from '../middlewares/auth.middleware';
|
||||
|
||||
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);
|
||||
app.patch('/comandas/:id', { preHandler: [requireRoles(['GARCOM', 'CAIXA', 'ADMIN'])] }, orderController.updateOrderController);
|
||||
|
||||
// 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);
|
||||
}
|
||||
16
src/routes/product.routes.ts
Normal file
16
src/routes/product.routes.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { FastifyInstance } from 'fastify';
|
||||
import * as productController from '../controllers/product.controller';
|
||||
import { authenticate, requireRoles } from '../middlewares/auth.middleware';
|
||||
|
||||
export async function productRoutes(app: FastifyInstance) {
|
||||
app.get('/produtos', { preHandler: [authenticate] }, productController.listProductsController);
|
||||
app.get('/produtos/mais-vendidos', { preHandler: [authenticate] }, productController.getTopProductsController);
|
||||
app.get('/produtos/busca', { preHandler: [authenticate] }, productController.searchProductsController);
|
||||
app.get('/produtos/baixo-estoque', { preHandler: [requireRoles(['ADMIN'])] }, productController.getLowStockProductsController);
|
||||
app.get('/produtos/:id', { preHandler: [authenticate] }, productController.getProductController);
|
||||
|
||||
app.post('/produtos', { preHandler: [requireRoles(['ADMIN'])] }, productController.createProductController);
|
||||
app.put('/produtos/:id', { preHandler: [requireRoles(['ADMIN'])] }, productController.updateProductController);
|
||||
app.patch('/produtos/:id', { preHandler: [requireRoles(['ADMIN'])] }, productController.updateProductController);
|
||||
app.delete('/produtos/:id', { preHandler: [requireRoles(['ADMIN'])] }, productController.deleteProductController);
|
||||
}
|
||||
8
src/routes/report.routes.ts
Normal file
8
src/routes/report.routes.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { FastifyInstance } from 'fastify';
|
||||
import * as reportController from '../controllers/report.controller';
|
||||
import { requireRoles } from '../middlewares/auth.middleware';
|
||||
|
||||
export async function reportRoutes(app: FastifyInstance) {
|
||||
app.get('/relatorios/vendas', { preHandler: [requireRoles(['ADMIN'])] }, reportController.salesReportController);
|
||||
app.get('/relatorios/dashboard', { preHandler: [requireRoles(['ADMIN'])] }, reportController.dashboardController);
|
||||
}
|
||||
13
src/routes/user.routes.ts
Normal file
13
src/routes/user.routes.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { FastifyInstance } from 'fastify';
|
||||
import * as userController from '../controllers/user.controller';
|
||||
import { requireRoles } from '../middlewares/auth.middleware';
|
||||
|
||||
export async function userRoutes(app: FastifyInstance) {
|
||||
// Apenas ADMIN pode gerenciar usuários
|
||||
app.get('/usuarios', { preHandler: [requireRoles(['ADMIN'])] }, userController.listUsersController);
|
||||
app.post('/usuarios', { preHandler: [requireRoles(['ADMIN'])] }, userController.createUserController);
|
||||
app.put('/usuarios/:id', { preHandler: [requireRoles(['ADMIN'])] }, userController.updateUserController);
|
||||
app.patch('/usuarios/:id', { preHandler: [requireRoles(['ADMIN'])] }, userController.updateUserController);
|
||||
app.patch('/usuarios/:id/senha', { preHandler: [requireRoles(['ADMIN'])] }, userController.resetPasswordController);
|
||||
app.delete('/usuarios/:id', { preHandler: [requireRoles(['ADMIN'])] }, userController.deleteUserController);
|
||||
}
|
||||
15
src/schemas/auth.schema.ts
Normal file
15
src/schemas/auth.schema.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const loginSchema = z.object({
|
||||
email: z.string().email(),
|
||||
senha: z.string().min(6),
|
||||
});
|
||||
|
||||
export type LoginInput = z.infer<typeof loginSchema>;
|
||||
|
||||
export const changePasswordSchema = z.object({
|
||||
senhaAtual: z.string().min(6),
|
||||
novaSenha: z.string().min(6),
|
||||
});
|
||||
|
||||
export type ChangePasswordInput = z.infer<typeof changePasswordSchema>;
|
||||
7
src/schemas/category.schema.ts
Normal file
7
src/schemas/category.schema.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const categorySchema = z.object({
|
||||
nome: z.string().min(2),
|
||||
});
|
||||
|
||||
export type CategoryInput = z.infer<typeof categorySchema>;
|
||||
53
src/schemas/order.schema.ts
Normal file
53
src/schemas/order.schema.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const createOrderSchema = z.object({
|
||||
identificador: z.string().min(1),
|
||||
nomeCliente: z.string().optional(),
|
||||
});
|
||||
|
||||
export const addItemOrderSchema = z.object({
|
||||
produtoId: z.string().uuid(),
|
||||
quantidade: z.number().int().positive(),
|
||||
observacao: z.string().optional(),
|
||||
});
|
||||
|
||||
export const updateItemStatusSchema = z.object({
|
||||
status: z.enum(['PENDENTE', 'PREPARANDO', 'PRONTO', 'ENTREGUE']),
|
||||
});
|
||||
|
||||
export const updateOrderSchema = z.object({
|
||||
identificador: z.string().min(1).optional(),
|
||||
nomeCliente: z.string().optional(),
|
||||
status: z.enum(['ABERTA', 'FECHADA', 'PAGA', 'CANCELADA']).optional(),
|
||||
desconto: z.number().min(0).optional(),
|
||||
acrescimo: z.number().min(0).optional(),
|
||||
taxaServico: z.boolean().optional(),
|
||||
motivoCancelamento: z.string().optional(),
|
||||
});
|
||||
|
||||
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>;
|
||||
|
||||
16
src/schemas/product.schema.ts
Normal file
16
src/schemas/product.schema.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const productSchema = z.object({
|
||||
nome: z.string().min(2),
|
||||
descricao: z.string().optional(),
|
||||
fotoUrl: z.string().url().optional(),
|
||||
preco: z.number().positive(),
|
||||
custo: z.number().positive().optional(),
|
||||
estoqueAtual: z.number().int().default(0),
|
||||
estoqueMinimo: z.number().int().default(0),
|
||||
itemCozinha: z.boolean(),
|
||||
ativo: z.boolean().default(true),
|
||||
categoriaId: z.string().uuid(),
|
||||
});
|
||||
|
||||
export type ProductInput = z.infer<typeof productSchema>;
|
||||
25
src/schemas/user.schema.ts
Normal file
25
src/schemas/user.schema.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const userSchema = z.object({
|
||||
nome: z.string().min(2),
|
||||
email: z.string().email(),
|
||||
senha: z.string().min(6),
|
||||
role: z.enum(['ADMIN', 'CAIXA', 'GARCOM', 'COZINHA', 'BARMAN']),
|
||||
ativo: z.boolean().default(true),
|
||||
});
|
||||
|
||||
export const updateUserSchema = z.object({
|
||||
nome: z.string().min(2).optional(),
|
||||
email: z.string().email().optional(),
|
||||
role: z.enum(['ADMIN', 'CAIXA', 'GARCOM', 'COZINHA', 'BARMAN']).optional(),
|
||||
ativo: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export type UserInput = z.infer<typeof userSchema>;
|
||||
export type UpdateUserInput = z.infer<typeof updateUserSchema>;
|
||||
|
||||
export const resetPasswordSchema = z.object({
|
||||
novaSenha: z.string().min(6),
|
||||
});
|
||||
|
||||
export type ResetPasswordInput = z.infer<typeof resetPasswordSchema>;
|
||||
61
src/server.ts
Normal file
61
src/server.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import 'dotenv/config';
|
||||
import fastify from 'fastify';
|
||||
import jwt from '@fastify/jwt';
|
||||
import { ZodError } from 'zod';
|
||||
import cors from '@fastify/cors';
|
||||
import { authRoutes } from './routes/auth.routes';
|
||||
import { categoryRoutes } from './routes/category.routes';
|
||||
import { productRoutes } from './routes/product.routes';
|
||||
import { orderRoutes } from './routes/order.routes';
|
||||
import { userRoutes } from './routes/user.routes';
|
||||
import { reportRoutes } from './routes/report.routes';
|
||||
|
||||
const app = fastify({ logger: true });
|
||||
|
||||
// Register CORS
|
||||
app.register(cors, {
|
||||
origin: '*', // Permitir de qualquer origem (útil em dev)
|
||||
});
|
||||
|
||||
// Register JWT
|
||||
app.register(jwt, {
|
||||
secret: process.env.JWT_SECRET || 'fallback_secret_change_me'
|
||||
});
|
||||
|
||||
// Global Error Handler
|
||||
app.setErrorHandler((error, request, reply) => {
|
||||
if (error instanceof ZodError) {
|
||||
return reply.status(400).send({
|
||||
message: 'Erro de validação',
|
||||
issues: error.format(),
|
||||
});
|
||||
}
|
||||
|
||||
if (error.statusCode) {
|
||||
return reply.status(error.statusCode).send({ message: error.message });
|
||||
}
|
||||
|
||||
console.error(error);
|
||||
return reply.status(500).send({ message: 'Erro interno do servidor' });
|
||||
});
|
||||
|
||||
// Register Routes
|
||||
app.register(authRoutes, { prefix: '/api/auth' });
|
||||
app.register(categoryRoutes, { prefix: '/api' });
|
||||
app.register(productRoutes, { prefix: '/api' });
|
||||
app.register(orderRoutes, { prefix: '/api' });
|
||||
app.register(userRoutes, { prefix: '/api' });
|
||||
app.register(reportRoutes, { prefix: '/api' });
|
||||
|
||||
// Iniciar o servidor
|
||||
const start = async () => {
|
||||
try {
|
||||
await app.listen({ port: 3333, host: '0.0.0.0' });
|
||||
console.log('Servidor rodando na porta 3333');
|
||||
} catch (err) {
|
||||
app.log.error(err);
|
||||
process.exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
start();
|
||||
40
src/services/auth.service.ts
Normal file
40
src/services/auth.service.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { prisma } from '../lib/prisma';
|
||||
import bcrypt from 'bcrypt';
|
||||
import { LoginInput } from '../schemas/auth.schema';
|
||||
|
||||
export async function loginService({ email, senha }: LoginInput) {
|
||||
const user = await prisma.usuario.findUnique({
|
||||
where: { email },
|
||||
});
|
||||
|
||||
if (!user || !user.ativo) {
|
||||
throw new Error('Credenciais inválidas ou usuário inativo');
|
||||
}
|
||||
|
||||
const isPasswordValid = await bcrypt.compare(senha, user.senha);
|
||||
|
||||
if (!isPasswordValid) {
|
||||
throw new Error('Credenciais inválidas ou usuário inativo');
|
||||
}
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
nome: user.nome,
|
||||
email: user.email,
|
||||
role: user.role,
|
||||
};
|
||||
}
|
||||
|
||||
export async function changePassword(userId: string, senhaAtual: string, novaSenha: string) {
|
||||
const user = await prisma.usuario.findUnique({ where: { id: userId } });
|
||||
if (!user) throw new Error('Usuário não encontrado');
|
||||
|
||||
const isPasswordValid = await bcrypt.compare(senhaAtual, user.senha);
|
||||
if (!isPasswordValid) throw new Error('Senha atual incorreta');
|
||||
|
||||
const passwordHash = await bcrypt.hash(novaSenha, 10);
|
||||
await prisma.usuario.update({
|
||||
where: { id: userId },
|
||||
data: { senha: passwordHash },
|
||||
});
|
||||
}
|
||||
47
src/services/category.service.ts
Normal file
47
src/services/category.service.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { prisma } from '../lib/prisma';
|
||||
import { CategoryInput } from '../schemas/category.schema';
|
||||
|
||||
export async function createCategory(data: CategoryInput) {
|
||||
return prisma.categoria.create({
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
export async function listCategories() {
|
||||
return prisma.categoria.findMany({
|
||||
include: { _count: { select: { produtos: true } } },
|
||||
});
|
||||
}
|
||||
|
||||
export async function getCategoryById(id: string) {
|
||||
return prisma.categoria.findUnique({
|
||||
where: { id },
|
||||
include: { produtos: true },
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateCategory(id: string, data: CategoryInput) {
|
||||
return prisma.categoria.update({
|
||||
where: { id },
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteCategory(id: string) {
|
||||
const categoria = await prisma.categoria.findUnique({
|
||||
where: { id },
|
||||
include: { _count: { select: { produtos: true } } },
|
||||
});
|
||||
|
||||
if (!categoria) {
|
||||
throw new Error('Categoria não encontrada');
|
||||
}
|
||||
|
||||
if (categoria._count.produtos > 0) {
|
||||
throw new Error(`Não é possível excluir: a categoria possui ${categoria._count.produtos} produto(s). Remova ou reatribua os produtos primeiro.`);
|
||||
}
|
||||
|
||||
return prisma.categoria.delete({
|
||||
where: { id },
|
||||
});
|
||||
}
|
||||
420
src/services/order.service.ts
Normal file
420
src/services/order.service.ts
Normal file
@@ -0,0 +1,420 @@
|
||||
import { prisma } from '../lib/prisma';
|
||||
import { CreateOrderInput, AddItemOrderInput, UpdateItemStatusInput, UpdateItemObservacaoInput, UpdateOrderInput, PayOrderInput, PartialPaymentInput } from '../schemas/order.schema';
|
||||
import { dateStart, dateEnd, nowUTC3 } from '../lib/timezone';
|
||||
|
||||
export interface ListOrdersFilter {
|
||||
statuses?: string[];
|
||||
dataInicio?: string;
|
||||
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 = {};
|
||||
|
||||
if (filter?.statuses?.length) {
|
||||
where.status = { in: filter.statuses };
|
||||
}
|
||||
|
||||
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.comanda.findMany({
|
||||
where,
|
||||
orderBy: { criadoEm: 'desc' },
|
||||
include: {
|
||||
usuario: {
|
||||
select: { id: true, nome: true, email: true },
|
||||
},
|
||||
itens: {
|
||||
include: {
|
||||
produto: true,
|
||||
usuario: {
|
||||
select: { id: true, nome: true },
|
||||
},
|
||||
}
|
||||
},
|
||||
pagamentos: true,
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
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, usuarioId?: string) {
|
||||
const produto = await prisma.produto.findUnique({
|
||||
where: { id: data.produtoId },
|
||||
});
|
||||
|
||||
if (!produto) {
|
||||
throw new Error('Produto não encontrado');
|
||||
}
|
||||
|
||||
const precoTotalItem = produto.preco * data.quantidade;
|
||||
|
||||
const [, itemPedido] = await prisma.$transaction([
|
||||
prisma.produto.update({
|
||||
where: { id: data.produtoId },
|
||||
data: { estoqueAtual: { decrement: data.quantidade } },
|
||||
}),
|
||||
prisma.itemPedido.create({
|
||||
data: {
|
||||
quantidade: data.quantidade,
|
||||
observacao: data.observacao,
|
||||
precoUnitario: produto.preco,
|
||||
produtoId: data.produtoId,
|
||||
comandaId: comandaId,
|
||||
usuarioId: usuarioId ?? null,
|
||||
status: 'PENDENTE',
|
||||
},
|
||||
}),
|
||||
prisma.comanda.update({
|
||||
where: { id: comandaId },
|
||||
data: { total: { increment: precoTotalItem } },
|
||||
}),
|
||||
]);
|
||||
|
||||
return itemPedido;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
if (typeof itemCozinha === 'boolean') {
|
||||
filter.produto = {
|
||||
itemCozinha,
|
||||
};
|
||||
}
|
||||
|
||||
return prisma.itemPedido.findMany({
|
||||
where: filter,
|
||||
include: {
|
||||
produto: true,
|
||||
comanda: true,
|
||||
usuario: {
|
||||
select: { id: true, nome: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateItemStatus(itemId: string, data: UpdateItemStatusInput) {
|
||||
return prisma.itemPedido.update({
|
||||
where: { id: itemId },
|
||||
data: {
|
||||
status: data.status,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
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 },
|
||||
});
|
||||
|
||||
if (!comanda) {
|
||||
throw new Error('Comanda não encontrada');
|
||||
}
|
||||
|
||||
if (comanda.status !== 'ABERTA') {
|
||||
throw new Error('Comanda não está aberta para pagamento');
|
||||
}
|
||||
|
||||
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) {
|
||||
const comanda = await prisma.comanda.findUnique({
|
||||
where: { id: comandaId },
|
||||
});
|
||||
|
||||
if (!comanda) {
|
||||
throw new Error('Comanda não encontrada');
|
||||
}
|
||||
|
||||
const updateData: any = {};
|
||||
|
||||
if (data.identificador !== undefined) updateData.identificador = data.identificador;
|
||||
if (data.nomeCliente !== undefined) updateData.nomeCliente = data.nomeCliente;
|
||||
if (data.status !== undefined) updateData.status = data.status;
|
||||
if (data.desconto !== undefined) updateData.desconto = data.desconto;
|
||||
if (data.acrescimo !== undefined) updateData.acrescimo = data.acrescimo;
|
||||
if (data.taxaServico !== undefined) updateData.taxaServico = data.taxaServico;
|
||||
if (data.motivoCancelamento !== undefined) updateData.motivoCancelamento = data.motivoCancelamento;
|
||||
|
||||
if (data.status === 'PAGA' && comanda.status !== 'PAGA') {
|
||||
updateData.fechadoEm = new Date();
|
||||
}
|
||||
|
||||
return prisma.comanda.update({
|
||||
where: { id: comandaId },
|
||||
data: updateData,
|
||||
include: {
|
||||
usuario: {
|
||||
select: { id: true, nome: true, email: true },
|
||||
},
|
||||
itens: {
|
||||
include: {
|
||||
produto: true,
|
||||
usuario: {
|
||||
select: { id: true, nome: true },
|
||||
},
|
||||
}
|
||||
},
|
||||
pagamentos: true,
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteItemFromOrder(itemId: string) {
|
||||
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 remover itens de uma comanda fechada/paga/cancelada');
|
||||
}
|
||||
|
||||
const precoTotalItem = item.precoUnitario * item.quantidade;
|
||||
|
||||
const [comanda] = await prisma.$transaction([
|
||||
prisma.itemPedido.delete({
|
||||
where: { id: itemId }
|
||||
}),
|
||||
prisma.produto.update({
|
||||
where: { id: item.produtoId },
|
||||
data: { estoqueAtual: { increment: item.quantidade } },
|
||||
}),
|
||||
prisma.comanda.update({
|
||||
where: { id: item.comandaId },
|
||||
data: { total: { decrement: precoTotalItem } },
|
||||
}),
|
||||
]);
|
||||
|
||||
return prisma.comanda.findUnique({
|
||||
where: { id: item.comandaId },
|
||||
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;
|
||||
}
|
||||
88
src/services/product.service.ts
Normal file
88
src/services/product.service.ts
Normal file
@@ -0,0 +1,88 @@
|
||||
import { prisma } from '../lib/prisma';
|
||||
import { ProductInput } from '../schemas/product.schema';
|
||||
|
||||
export async function getTopProducts(limit = 10) {
|
||||
const topItems = await prisma.itemPedido.groupBy({
|
||||
by: ['produtoId'],
|
||||
where: { produto: { ativo: true } },
|
||||
_sum: { quantidade: true },
|
||||
orderBy: { _sum: { quantidade: 'desc' } },
|
||||
take: limit,
|
||||
});
|
||||
|
||||
if (!topItems.length) {
|
||||
// Fallback: retorna os últimos produtos cadastrados
|
||||
return prisma.produto.findMany({
|
||||
where: { ativo: true },
|
||||
include: { categoria: true },
|
||||
orderBy: { nome: 'asc' },
|
||||
take: limit,
|
||||
});
|
||||
}
|
||||
|
||||
const ids = topItems.map(t => t.produtoId);
|
||||
const produtos = await prisma.produto.findMany({
|
||||
where: { id: { in: ids }, ativo: true },
|
||||
include: { categoria: true },
|
||||
});
|
||||
|
||||
// Mantém a ordem de vendas + injeta totalVendido
|
||||
return ids.map(id => {
|
||||
const prod = produtos.find(p => p.id === id)!;
|
||||
const vendas = topItems.find(t => t.produtoId === id)?._sum.quantidade ?? 0;
|
||||
return { ...prod, totalVendido: vendas };
|
||||
}).filter(Boolean);
|
||||
}
|
||||
|
||||
export async function searchProducts(query: string) {
|
||||
return prisma.produto.findMany({
|
||||
where: {
|
||||
ativo: true,
|
||||
nome: { contains: query },
|
||||
},
|
||||
include: { categoria: true },
|
||||
orderBy: { nome: 'asc' },
|
||||
take: 20,
|
||||
});
|
||||
}
|
||||
|
||||
export async function createProduct(data: ProductInput) {
|
||||
return prisma.produto.create({
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
export async function listProducts() {
|
||||
return prisma.produto.findMany({
|
||||
include: { categoria: true },
|
||||
});
|
||||
}
|
||||
|
||||
export async function getProductById(id: string) {
|
||||
return prisma.produto.findUnique({
|
||||
where: { id },
|
||||
include: { categoria: true },
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateProduct(id: string, data: Partial<ProductInput>) {
|
||||
return prisma.produto.update({
|
||||
where: { id },
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteProduct(id: string) {
|
||||
return prisma.produto.delete({
|
||||
where: { id },
|
||||
});
|
||||
}
|
||||
|
||||
export async function getLowStockProducts() {
|
||||
const products = await prisma.produto.findMany({
|
||||
where: { ativo: true },
|
||||
include: { categoria: true },
|
||||
orderBy: { estoqueAtual: 'asc' },
|
||||
});
|
||||
return products.filter(p => p.estoqueAtual <= p.estoqueMinimo);
|
||||
}
|
||||
137
src/services/report.service.ts
Normal file
137
src/services/report.service.ts
Normal file
@@ -0,0 +1,137 @@
|
||||
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({
|
||||
where: {
|
||||
status: 'PAGA',
|
||||
fechadoEm: { gte: inicio, lte: fim },
|
||||
},
|
||||
include: {
|
||||
itens: {
|
||||
include: { produto: true },
|
||||
},
|
||||
},
|
||||
orderBy: { fechadoEm: 'desc' },
|
||||
});
|
||||
|
||||
const totalVendas = comandas.reduce((acc, c) => acc + c.total, 0);
|
||||
const totalDescontos = comandas.reduce((acc, c) => acc + c.desconto, 0);
|
||||
const totalAcrescimos = comandas.reduce((acc, c) => acc + c.acrescimo, 0);
|
||||
const totalComandas = comandas.length;
|
||||
|
||||
// Produtos mais vendidos
|
||||
const produtoVendas: Record<string, { nome: string; quantidade: number; total: number }> = {};
|
||||
for (const c of comandas) {
|
||||
for (const item of c.itens) {
|
||||
const key = item.produtoId;
|
||||
if (!produtoVendas[key]) {
|
||||
produtoVendas[key] = { nome: item.produto.nome, quantidade: 0, total: 0 };
|
||||
}
|
||||
produtoVendas[key].quantidade += item.quantidade;
|
||||
produtoVendas[key].total += item.precoUnitario * item.quantidade;
|
||||
}
|
||||
}
|
||||
|
||||
const topProdutos = Object.values(produtoVendas)
|
||||
.sort((a, b) => b.quantidade - a.quantidade)
|
||||
.slice(0, 10);
|
||||
|
||||
// Vendas por dia
|
||||
const vendasPorDia: Record<string, { vendas: number; comandas: number }> = {};
|
||||
for (const c of comandas) {
|
||||
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;
|
||||
}
|
||||
|
||||
// Vendas por forma de pagamento
|
||||
const vendasPorPagamento: Record<string, number> = {};
|
||||
for (const c of comandas) {
|
||||
const fp = c.formaPagamento || 'NAO_INFORMADO';
|
||||
vendasPorPagamento[fp] = (vendasPorPagamento[fp] || 0) + c.total;
|
||||
}
|
||||
|
||||
return {
|
||||
periodo: { inicio, fim },
|
||||
resumo: {
|
||||
totalVendas,
|
||||
totalDescontos,
|
||||
totalAcrescimos,
|
||||
totalComandas,
|
||||
ticketMedio: totalComandas > 0 ? totalVendas / totalComandas : 0,
|
||||
},
|
||||
topProdutos,
|
||||
vendasPorDia: Object.entries(vendasPorDia).map(([data, v]) => ({ data, ...v })),
|
||||
vendasPorPagamento: Object.entries(vendasPorPagamento).map(([forma, total]) => ({ forma, total })),
|
||||
comandas: comandas.map(c => ({
|
||||
id: c.id,
|
||||
identificador: c.identificador,
|
||||
nomeCliente: c.nomeCliente,
|
||||
total: c.total,
|
||||
desconto: c.desconto,
|
||||
acrescimo: c.acrescimo,
|
||||
formaPagamento: c.formaPagamento,
|
||||
criadoEm: c.criadoEm,
|
||||
fechadoEm: c.fechadoEm,
|
||||
itensCount: c.itens.length,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
export async function getDashboardData() {
|
||||
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({
|
||||
where: { status: 'PAGA', fechadoEm: { gte: inicioDia } },
|
||||
include: { itens: true },
|
||||
}),
|
||||
prisma.comanda.findMany({
|
||||
where: { status: 'PAGA', fechadoEm: { gte: inicioSemana } },
|
||||
include: { itens: true },
|
||||
}),
|
||||
prisma.comanda.findMany({
|
||||
where: { status: 'PAGA', fechadoEm: { gte: inicioMes } },
|
||||
include: { itens: true },
|
||||
}),
|
||||
prisma.produto.count({ where: { ativo: true } }),
|
||||
prisma.produto.findMany({
|
||||
where: { ativo: true },
|
||||
include: { categoria: true },
|
||||
}),
|
||||
prisma.comanda.count({ where: { status: 'ABERTA' } }),
|
||||
]);
|
||||
|
||||
const sumTotal = (cs: any[]) => cs.reduce((acc, c) => acc + c.total, 0);
|
||||
const sumItens = (cs: any[]) => cs.reduce((acc, c) => acc + c.itens.reduce((a: number, i: any) => a + i.quantidade, 0), 0);
|
||||
|
||||
const estoqueBaixo = produtosEstoqueBaixo.filter(p => p.estoqueAtual <= p.estoqueMinimo);
|
||||
|
||||
return {
|
||||
vendasHoje: {
|
||||
total: sumTotal(comandasHoje),
|
||||
comandas: comandasHoje.length,
|
||||
itens: sumItens(comandasHoje),
|
||||
},
|
||||
vendasSemana: {
|
||||
total: sumTotal(comandasSemana),
|
||||
comandas: comandasSemana.length,
|
||||
itens: sumItens(comandasSemana),
|
||||
},
|
||||
vendasMes: {
|
||||
total: totalProdutos,
|
||||
comandas: comandasMes.length,
|
||||
itens: sumItens(comandasMes),
|
||||
totalVendas: sumTotal(comandasMes),
|
||||
},
|
||||
totalProdutos,
|
||||
produtosEstoqueBaixo: estoqueBaixo.length,
|
||||
comandasAbertas,
|
||||
};
|
||||
}
|
||||
49
src/services/user.service.ts
Normal file
49
src/services/user.service.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { prisma } from '../lib/prisma';
|
||||
import { UserInput, UpdateUserInput } from '../schemas/user.schema';
|
||||
import bcrypt from 'bcrypt';
|
||||
|
||||
export async function createUser(data: UserInput) {
|
||||
const existingUser = await prisma.usuario.findUnique({ where: { email: data.email } });
|
||||
if (existingUser) throw new Error('E-mail já cadastrado');
|
||||
|
||||
const passwordHash = await bcrypt.hash(data.senha, 10);
|
||||
|
||||
return prisma.usuario.create({
|
||||
data: {
|
||||
...data,
|
||||
senha: passwordHash,
|
||||
},
|
||||
select: { id: true, nome: true, email: true, role: true, ativo: true, criadoEm: true },
|
||||
});
|
||||
}
|
||||
|
||||
export async function listUsers() {
|
||||
return prisma.usuario.findMany({
|
||||
select: { id: true, nome: true, email: true, role: true, ativo: true, criadoEm: true },
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateUser(id: string, data: UpdateUserInput) {
|
||||
return prisma.usuario.update({
|
||||
where: { id },
|
||||
data,
|
||||
select: { id: true, nome: true, email: true, role: true, ativo: true, criadoEm: true },
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteUser(id: string) {
|
||||
return prisma.usuario.delete({
|
||||
where: { id },
|
||||
});
|
||||
}
|
||||
|
||||
export async function resetPassword(id: string, novaSenha: string) {
|
||||
const user = await prisma.usuario.findUnique({ where: { id } });
|
||||
if (!user) throw new Error('Usuário não encontrado');
|
||||
|
||||
const passwordHash = await bcrypt.hash(novaSenha, 10);
|
||||
await prisma.usuario.update({
|
||||
where: { id },
|
||||
data: { senha: passwordHash },
|
||||
});
|
||||
}
|
||||
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));
|
||||
})();
|
||||
15
tsconfig.json
Normal file
15
tsconfig.json
Normal file
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es2020",
|
||||
"module": "commonjs",
|
||||
"rootDir": "./src",
|
||||
"outDir": "./dist",
|
||||
"esModuleInterop": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"moduleResolution": "node",
|
||||
"resolveJsonModule": true
|
||||
},
|
||||
"include": ["src/**/*"]
|
||||
}
|
||||
24
web/.gitignore
vendored
Normal file
24
web/.gitignore
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
17
web/index.html
Normal file
17
web/index.html
Normal file
@@ -0,0 +1,17 @@
|
||||
<!doctype html>
|
||||
<html lang="pt-BR">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>PDV Gastrobar</title>
|
||||
<!-- Google Fonts: Inter -->
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
887
web/package-lock.json
generated
Normal file
887
web/package-lock.json
generated
Normal file
@@ -0,0 +1,887 @@
|
||||
{
|
||||
"name": "web",
|
||||
"version": "0.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "web",
|
||||
"version": "0.0.0",
|
||||
"devDependencies": {
|
||||
"typescript": "~6.0.2",
|
||||
"vite": "^8.1.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@emnapi/core": {
|
||||
"version": "1.11.1",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.1.tgz",
|
||||
"integrity": "sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"@emnapi/wasi-threads": "1.2.2",
|
||||
"tslib": "^2.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@emnapi/runtime": {
|
||||
"version": "1.11.1",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.1.tgz",
|
||||
"integrity": "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"tslib": "^2.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@emnapi/wasi-threads": {
|
||||
"version": "1.2.2",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.2.tgz",
|
||||
"integrity": "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"tslib": "^2.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@napi-rs/wasm-runtime": {
|
||||
"version": "1.1.6",
|
||||
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.6.tgz",
|
||||
"integrity": "sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"@tybys/wasm-util": "^0.10.3"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@emnapi/core": "^1.7.1",
|
||||
"@emnapi/runtime": "^1.7.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@oxc-project/types": {
|
||||
"version": "0.139.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.139.0.tgz",
|
||||
"integrity": "sha512-r9gHphtCs+1M7J0pw6Sn/hh/Wpa/iQrOOkrNAlVLF/gHq+/CJmHIWKKUUhdWjcD6CIa8idarspCsASiXCXvFUw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/Boshen"
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-android-arm64": {
|
||||
"version": "1.1.5",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.1.5.tgz",
|
||||
"integrity": "sha512-lZg8fqIv2v7FF237bwMgzGZEJvGL79/s5knJ/i6FmsGF4XXlzccZ4jb+TrFIxtSSxFtIpdsgrPZeMk1I9AFcyQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"android"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-darwin-arm64": {
|
||||
"version": "1.1.5",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.1.5.tgz",
|
||||
"integrity": "sha512-51Bnx9pNiMRKSUNtBfySkNJ9vMU9Hh3I1ozDd6gyPPYzaXCfnptUcEZxXGYFn+ul2dtcMUiqGR1Yai2K10uoTw==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-darwin-x64": {
|
||||
"version": "1.1.5",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.1.5.tgz",
|
||||
"integrity": "sha512-Tm+gbfC0aHu1tBA/JvKQh32S0K6YgCHkiAF4/W6xX0K0RmNuc94VeK419dJoE65R5aRxmo+noZQSWrAMF6yb6g==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-freebsd-x64": {
|
||||
"version": "1.1.5",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.1.5.tgz",
|
||||
"integrity": "sha512-JMzDKCCXq93YccG5gz3hvOs1oXRKAf0XYpfOS88e+wZrC8Iugj6j68867vrYZkvpDDpKn/KoKORThmchMpF6TA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"freebsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-linux-arm-gnueabihf": {
|
||||
"version": "1.1.5",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.1.5.tgz",
|
||||
"integrity": "sha512-uML21j2K5TfPGutKxub+M+nLjZIrWjXQ5Grx4lCe/nimTj9B4L63zHpjXLl4y0L3mcm2htEQIb06oCG/szerNw==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-linux-arm64-gnu": {
|
||||
"version": "1.1.5",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.1.5.tgz",
|
||||
"integrity": "sha512-navSiuTMogvnQoZoM/v+l3ZWo50/NTwSHSzheABx/RCnmUPaKwq9qSo4Br2OYRs21+Fz8uFqITZM3H4opOB0/Q==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-linux-arm64-musl": {
|
||||
"version": "1.1.5",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.1.5.tgz",
|
||||
"integrity": "sha512-lAryqH7IteztmCXQXk0etKj4wBQ7Gx5S6LjKhsgp9zb8I5bsuvU/2llH1hDQcjsFeqIsovMVN339/8pUDDBXxA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-linux-ppc64-gnu": {
|
||||
"version": "1.1.5",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.1.5.tgz",
|
||||
"integrity": "sha512-fsK/sNBnxzBlL4O1JNrZakVQxPspqpED5dLtNsZS9oOKmtSpdNIzxH2kkol5HYTWJN47sE20ztMJPxfZ89qGOg==",
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-linux-s390x-gnu": {
|
||||
"version": "1.1.5",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.1.5.tgz",
|
||||
"integrity": "sha512-gLYb4BIadlfTOYT5gO503n8zQjXflgzpD0FcyKh0Mzx3rqCZKnHoJWV9xe1KXUJ5lx2JfcSHr/mhzS0PC/McAA==",
|
||||
"cpu": [
|
||||
"s390x"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-linux-x64-gnu": {
|
||||
"version": "1.1.5",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.1.5.tgz",
|
||||
"integrity": "sha512-FjcpEKUyJygHgs1o50VYNvkt5+7Le/VEdYt0AkRpkL33MnyQfwr8l5mXwMmfmTbyMPr5vJLC+8/Gd9gXnwU1QQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-linux-x64-musl": {
|
||||
"version": "1.1.5",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.1.5.tgz",
|
||||
"integrity": "sha512-Me+PfPI2TMeOQk0gYWfLQZtTktrmzbr8cDboqX83XKc7UrgAi55gF+2dUkWdxd19n55Essp2yeca+O9N5rBxHg==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-openharmony-arm64": {
|
||||
"version": "1.1.5",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.1.5.tgz",
|
||||
"integrity": "sha512-yc5WrLzXks6zCQfn9Oxr8pORKyl/pF+QjHmW/Qx3qu0oyrrNC+y2JLTU1E2rcWYAmzlnqngWXHQjy51VzW70Vw==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"openharmony"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-wasm32-wasi": {
|
||||
"version": "1.1.5",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.1.5.tgz",
|
||||
"integrity": "sha512-VbQGPX2b4r48TAMIM2cjgluIM1HYutm4pcTEJsle7iEP7sB1dFqtPLBVbdLAZCxy1txCcPxf4QFf4v8uvltPqA==",
|
||||
"cpu": [
|
||||
"wasm32"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"@emnapi/core": "1.11.1",
|
||||
"@emnapi/runtime": "1.11.1",
|
||||
"@napi-rs/wasm-runtime": "^1.1.6"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-win32-arm64-msvc": {
|
||||
"version": "1.1.5",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.1.5.tgz",
|
||||
"integrity": "sha512-gHv82k63z4qpV5+Q1y/12KrK0ltWBukVDI8nZcbT7Tt/ZlOIVwppazneq0F93oDxTo3IgAMEDIoQh3E2n6mVsw==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-win32-x64-msvc": {
|
||||
"version": "1.1.5",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.1.5.tgz",
|
||||
"integrity": "sha512-tTZuDBPw85tEN5PQi1pnEBzDy0Z49HtScLAbD5t6hyeU92A95pRWaSMw1GZZi/RwgSgUIl0xrSlXIT/9QzvYSA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/pluginutils": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz",
|
||||
"integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@tybys/wasm-util": {
|
||||
"version": "0.10.3",
|
||||
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.3.tgz",
|
||||
"integrity": "sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"tslib": "^2.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/detect-libc": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
|
||||
"integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/fdir": {
|
||||
"version": "6.5.0",
|
||||
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
|
||||
"integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"picomatch": "^3 || ^4"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"picomatch": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/fsevents": {
|
||||
"version": "2.3.3",
|
||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
|
||||
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
|
||||
"dev": true,
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/lightningcss": {
|
||||
"version": "1.33.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz",
|
||||
"integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==",
|
||||
"dev": true,
|
||||
"license": "MPL-2.0",
|
||||
"dependencies": {
|
||||
"detect-libc": "^2.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 12.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/parcel"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"lightningcss-android-arm64": "1.33.0",
|
||||
"lightningcss-darwin-arm64": "1.33.0",
|
||||
"lightningcss-darwin-x64": "1.33.0",
|
||||
"lightningcss-freebsd-x64": "1.33.0",
|
||||
"lightningcss-linux-arm-gnueabihf": "1.33.0",
|
||||
"lightningcss-linux-arm64-gnu": "1.33.0",
|
||||
"lightningcss-linux-arm64-musl": "1.33.0",
|
||||
"lightningcss-linux-x64-gnu": "1.33.0",
|
||||
"lightningcss-linux-x64-musl": "1.33.0",
|
||||
"lightningcss-win32-arm64-msvc": "1.33.0",
|
||||
"lightningcss-win32-x64-msvc": "1.33.0"
|
||||
}
|
||||
},
|
||||
"node_modules/lightningcss-android-arm64": {
|
||||
"version": "1.33.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz",
|
||||
"integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"android"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 12.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/parcel"
|
||||
}
|
||||
},
|
||||
"node_modules/lightningcss-darwin-arm64": {
|
||||
"version": "1.33.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz",
|
||||
"integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 12.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/parcel"
|
||||
}
|
||||
},
|
||||
"node_modules/lightningcss-darwin-x64": {
|
||||
"version": "1.33.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz",
|
||||
"integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 12.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/parcel"
|
||||
}
|
||||
},
|
||||
"node_modules/lightningcss-freebsd-x64": {
|
||||
"version": "1.33.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz",
|
||||
"integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"freebsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 12.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/parcel"
|
||||
}
|
||||
},
|
||||
"node_modules/lightningcss-linux-arm-gnueabihf": {
|
||||
"version": "1.33.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz",
|
||||
"integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 12.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/parcel"
|
||||
}
|
||||
},
|
||||
"node_modules/lightningcss-linux-arm64-gnu": {
|
||||
"version": "1.33.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz",
|
||||
"integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 12.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/parcel"
|
||||
}
|
||||
},
|
||||
"node_modules/lightningcss-linux-arm64-musl": {
|
||||
"version": "1.33.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz",
|
||||
"integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 12.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/parcel"
|
||||
}
|
||||
},
|
||||
"node_modules/lightningcss-linux-x64-gnu": {
|
||||
"version": "1.33.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz",
|
||||
"integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 12.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/parcel"
|
||||
}
|
||||
},
|
||||
"node_modules/lightningcss-linux-x64-musl": {
|
||||
"version": "1.33.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz",
|
||||
"integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 12.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/parcel"
|
||||
}
|
||||
},
|
||||
"node_modules/lightningcss-win32-arm64-msvc": {
|
||||
"version": "1.33.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz",
|
||||
"integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 12.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/parcel"
|
||||
}
|
||||
},
|
||||
"node_modules/lightningcss-win32-x64-msvc": {
|
||||
"version": "1.33.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz",
|
||||
"integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 12.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/parcel"
|
||||
}
|
||||
},
|
||||
"node_modules/nanoid": {
|
||||
"version": "3.3.16",
|
||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.16.tgz",
|
||||
"integrity": "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ai"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"nanoid": "bin/nanoid.cjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/picocolors": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
|
||||
"integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/picomatch": {
|
||||
"version": "4.0.5",
|
||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz",
|
||||
"integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/jonschlinkert"
|
||||
}
|
||||
},
|
||||
"node_modules/postcss": {
|
||||
"version": "8.5.20",
|
||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.20.tgz",
|
||||
"integrity": "sha512-lW616l85ucIQL+FocMmL7pQFPqBmwejrCMg+iPxyImlrANNJG9NHq/RkyCZopDhd8C3LA03PHRJDjkbGu8vvug==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/postcss/"
|
||||
},
|
||||
{
|
||||
"type": "tidelift",
|
||||
"url": "https://tidelift.com/funding/github/npm/postcss"
|
||||
},
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ai"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"nanoid": "^3.3.16",
|
||||
"picocolors": "^1.1.1",
|
||||
"source-map-js": "^1.2.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^10 || ^12 || >=14"
|
||||
}
|
||||
},
|
||||
"node_modules/rolldown": {
|
||||
"version": "1.1.5",
|
||||
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.1.5.tgz",
|
||||
"integrity": "sha512-t9z29cJjXf/vxQ8dyhCSpt6H6aSwHTk8cT5I3iy6SMXuFpk5mB6PL6XfC8PCwrPTx93udwKUm9HRteAlTGBLiA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@oxc-project/types": "=0.139.0",
|
||||
"@rolldown/pluginutils": "^1.0.0"
|
||||
},
|
||||
"bin": {
|
||||
"rolldown": "bin/cli.mjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@rolldown/binding-android-arm64": "1.1.5",
|
||||
"@rolldown/binding-darwin-arm64": "1.1.5",
|
||||
"@rolldown/binding-darwin-x64": "1.1.5",
|
||||
"@rolldown/binding-freebsd-x64": "1.1.5",
|
||||
"@rolldown/binding-linux-arm-gnueabihf": "1.1.5",
|
||||
"@rolldown/binding-linux-arm64-gnu": "1.1.5",
|
||||
"@rolldown/binding-linux-arm64-musl": "1.1.5",
|
||||
"@rolldown/binding-linux-ppc64-gnu": "1.1.5",
|
||||
"@rolldown/binding-linux-s390x-gnu": "1.1.5",
|
||||
"@rolldown/binding-linux-x64-gnu": "1.1.5",
|
||||
"@rolldown/binding-linux-x64-musl": "1.1.5",
|
||||
"@rolldown/binding-openharmony-arm64": "1.1.5",
|
||||
"@rolldown/binding-wasm32-wasi": "1.1.5",
|
||||
"@rolldown/binding-win32-arm64-msvc": "1.1.5",
|
||||
"@rolldown/binding-win32-x64-msvc": "1.1.5"
|
||||
}
|
||||
},
|
||||
"node_modules/source-map-js": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
|
||||
"integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/tinyglobby": {
|
||||
"version": "0.2.17",
|
||||
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
|
||||
"integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"fdir": "^6.5.0",
|
||||
"picomatch": "^4.0.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/SuperchupuDev"
|
||||
}
|
||||
},
|
||||
"node_modules/tslib": {
|
||||
"version": "2.8.1",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
|
||||
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
|
||||
"dev": true,
|
||||
"license": "0BSD",
|
||||
"optional": true
|
||||
},
|
||||
"node_modules/typescript": {
|
||||
"version": "6.0.3",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz",
|
||||
"integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.17"
|
||||
}
|
||||
},
|
||||
"node_modules/vite": {
|
||||
"version": "8.1.5",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-8.1.5.tgz",
|
||||
"integrity": "sha512-7ULLwsCdYx/nRyrpiEwvqb5TFHrMVZyBt+rg/OAXT7rgj/z+DtTDyKFeLAdDkubDVDKD8jOsndmy7m55XcfUsw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"lightningcss": "^1.32.0",
|
||||
"picomatch": "^4.0.5",
|
||||
"postcss": "^8.5.17",
|
||||
"rolldown": "~1.1.5",
|
||||
"tinyglobby": "^0.2.17"
|
||||
},
|
||||
"bin": {
|
||||
"vite": "bin/vite.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/vitejs/vite?sponsor=1"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"fsevents": "~2.3.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/node": "^20.19.0 || >=22.12.0",
|
||||
"@vitejs/devtools": "^0.3.0",
|
||||
"esbuild": "^0.27.0 || ^0.28.0",
|
||||
"jiti": ">=1.21.0",
|
||||
"less": "^4.0.0",
|
||||
"sass": "^1.70.0",
|
||||
"sass-embedded": "^1.70.0",
|
||||
"stylus": ">=0.54.8",
|
||||
"sugarss": "^5.0.0",
|
||||
"terser": "^5.16.0",
|
||||
"tsx": "^4.8.1",
|
||||
"yaml": "^2.4.2"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/node": {
|
||||
"optional": true
|
||||
},
|
||||
"@vitejs/devtools": {
|
||||
"optional": true
|
||||
},
|
||||
"esbuild": {
|
||||
"optional": true
|
||||
},
|
||||
"jiti": {
|
||||
"optional": true
|
||||
},
|
||||
"less": {
|
||||
"optional": true
|
||||
},
|
||||
"sass": {
|
||||
"optional": true
|
||||
},
|
||||
"sass-embedded": {
|
||||
"optional": true
|
||||
},
|
||||
"stylus": {
|
||||
"optional": true
|
||||
},
|
||||
"sugarss": {
|
||||
"optional": true
|
||||
},
|
||||
"terser": {
|
||||
"optional": true
|
||||
},
|
||||
"tsx": {
|
||||
"optional": true
|
||||
},
|
||||
"yaml": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
15
web/package.json
Normal file
15
web/package.json
Normal file
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"name": "web",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc && vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "~6.0.2",
|
||||
"vite": "^8.1.1"
|
||||
}
|
||||
}
|
||||
1
web/public/favicon.svg
Normal file
1
web/public/favicon.svg
Normal file
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 9.3 KiB |
24
web/public/icons.svg
Normal file
24
web/public/icons.svg
Normal file
@@ -0,0 +1,24 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg">
|
||||
<symbol id="bluesky-icon" viewBox="0 0 16 17">
|
||||
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
|
||||
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
|
||||
</symbol>
|
||||
<symbol id="discord-icon" viewBox="0 0 20 19">
|
||||
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
|
||||
</symbol>
|
||||
<symbol id="documentation-icon" viewBox="0 0 21 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
|
||||
</symbol>
|
||||
<symbol id="github-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
<symbol id="social-icon" viewBox="0 0 20 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
|
||||
</symbol>
|
||||
<symbol id="x-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.9 KiB |
57
web/src/api.ts
Normal file
57
web/src/api.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
const API_URL = 'http://localhost:3333/api';
|
||||
|
||||
function getAuthHeaders() {
|
||||
const token = localStorage.getItem('@gastrobar:token');
|
||||
return {
|
||||
'Content-Type': 'application/json',
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export const api = {
|
||||
async post(endpoint: string, body: any) {
|
||||
const response = await fetch(`${API_URL}${endpoint}`, {
|
||||
method: 'POST',
|
||||
headers: getAuthHeaders(),
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || data.message || 'Erro na requisição');
|
||||
return data;
|
||||
},
|
||||
|
||||
async get(endpoint: string) {
|
||||
const response = await fetch(`${API_URL}${endpoint}`, {
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || data.message || 'Erro na requisição');
|
||||
return data;
|
||||
},
|
||||
|
||||
async patch(endpoint: string, body: any) {
|
||||
const response = await fetch(`${API_URL}${endpoint}`, {
|
||||
method: 'PATCH',
|
||||
headers: getAuthHeaders(),
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || data.message || 'Erro na requisição');
|
||||
return data;
|
||||
},
|
||||
|
||||
async delete(endpoint: string) {
|
||||
const response = await fetch(`${API_URL}${endpoint}`, {
|
||||
method: 'DELETE',
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const data = await response.json().catch(() => ({}));
|
||||
throw new Error(data.error || data.message || 'Erro na requisição');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
};
|
||||
BIN
web/src/assets/hero.png
Normal file
BIN
web/src/assets/hero.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
1
web/src/assets/typescript.svg
Normal file
1
web/src/assets/typescript.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" width="32" height="32" viewBox="0 0 256 256"><path fill="#007ACC" d="M0 128v128h256V0H0z"/><path fill="#FFF" d="m56.612 128.85l-.081 10.483h33.32v94.68h23.568v-94.68h33.321v-10.28c0-5.69-.122-10.444-.284-10.566c-.122-.162-20.4-.244-44.983-.203l-44.74.122l-.121 10.443Zm149.955-10.742c6.501 1.625 11.459 4.51 16.01 9.224c2.357 2.52 5.851 7.111 6.136 8.208c.08.325-11.053 7.802-17.798 11.988c-.244.162-1.22-.894-2.317-2.52c-3.291-4.795-6.745-6.867-12.028-7.233c-7.76-.528-12.759 3.535-12.718 10.321c0 1.992.284 3.17 1.097 4.795c1.707 3.536 4.876 5.649 14.832 9.956c18.326 7.883 26.168 13.084 31.045 20.48c5.445 8.249 6.664 21.415 2.966 31.208c-4.063 10.646-14.14 17.879-28.323 20.276c-4.388.772-14.79.65-19.504-.203c-10.28-1.828-20.033-6.908-26.047-13.572c-2.357-2.6-6.949-9.387-6.664-9.874c.122-.163 1.178-.813 2.356-1.504c1.138-.65 5.446-3.129 9.509-5.485l7.355-4.267l1.544 2.276c2.154 3.29 6.867 7.801 9.712 9.305c8.167 4.307 19.383 3.698 24.909-1.26c2.357-2.153 3.332-4.388 3.332-7.68c0-2.966-.366-4.266-1.91-6.501c-1.99-2.845-6.054-5.242-17.595-10.24c-13.206-5.69-18.895-9.224-24.096-14.832c-3.007-3.25-5.852-8.452-7.03-12.8c-.975-3.617-1.22-12.678-.447-16.335c2.723-12.76 12.353-21.659 26.25-24.3c4.51-.853 14.994-.528 19.424.569Z"/></svg>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
1
web/src/assets/vite.svg
Normal file
1
web/src/assets/vite.svg
Normal file
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 8.5 KiB |
66
web/src/main.ts
Normal file
66
web/src/main.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import './style.css';
|
||||
import { renderLogin } from './views/login';
|
||||
import { renderKitchen } from './views/kitchen';
|
||||
import { renderOrders } from './views/orders';
|
||||
import { renderCheckout } from './views/checkout';
|
||||
import { renderMenu } from './views/menu';
|
||||
import { renderUsers } from './views/users';
|
||||
import { renderDashboard } from './views/dashboard';
|
||||
|
||||
const app = document.getElementById('app')!;
|
||||
|
||||
export async function navigateTo(path: string) {
|
||||
window.history.pushState({}, '', path);
|
||||
await router();
|
||||
}
|
||||
|
||||
(window as any).navigateTo = navigateTo;
|
||||
(window as any).logout = () => {
|
||||
localStorage.removeItem('@gastrobar:token');
|
||||
localStorage.removeItem('@gastrobar:user');
|
||||
navigateTo('/');
|
||||
};
|
||||
|
||||
async function router() {
|
||||
const path = window.location.pathname;
|
||||
const token = localStorage.getItem('@gastrobar:token');
|
||||
|
||||
// Proteção de rotas
|
||||
if (!token && path !== '/') {
|
||||
navigateTo('/');
|
||||
return;
|
||||
}
|
||||
|
||||
app.innerHTML = '';
|
||||
|
||||
switch (path) {
|
||||
case '/':
|
||||
if (token) navigateTo('/kitchen');
|
||||
else renderLogin(app);
|
||||
break;
|
||||
case '/kitchen':
|
||||
await renderKitchen(app);
|
||||
break;
|
||||
case '/orders':
|
||||
await renderOrders(app);
|
||||
break;
|
||||
case '/checkout':
|
||||
await renderCheckout(app);
|
||||
break;
|
||||
case '/menu':
|
||||
await renderMenu(app);
|
||||
break;
|
||||
case '/users':
|
||||
await renderUsers(app);
|
||||
break;
|
||||
case '/dashboard':
|
||||
await renderDashboard(app);
|
||||
break;
|
||||
default:
|
||||
navigateTo('/kitchen');
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener('popstate', router);
|
||||
router();
|
||||
1055
web/src/style.css
Normal file
1055
web/src/style.css
Normal file
File diff suppressed because it is too large
Load Diff
158
web/src/utils.ts
Normal file
158
web/src/utils.ts
Normal file
@@ -0,0 +1,158 @@
|
||||
/** Exibe um toast de notificação na tela */
|
||||
export function toast(message: string, type: 'success' | 'error' = 'success') {
|
||||
let container = document.querySelector('.toast-container');
|
||||
if (!container) {
|
||||
container = document.createElement('div');
|
||||
container.className = 'toast-container';
|
||||
document.body.appendChild(container);
|
||||
}
|
||||
|
||||
const el = document.createElement('div');
|
||||
el.className = `toast ${type}`;
|
||||
el.textContent = message;
|
||||
container.appendChild(el);
|
||||
|
||||
setTimeout(() => el.remove(), 3500);
|
||||
}
|
||||
|
||||
/** Retorna o usuário logado do localStorage */
|
||||
export function getUser(): { id: string; nome: string; email: string; role: string } | null {
|
||||
const raw = localStorage.getItem('@gastrobar:user');
|
||||
return raw ? JSON.parse(raw) : null;
|
||||
}
|
||||
|
||||
/** 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);
|
||||
}
|
||||
|
||||
/** Badges de role */
|
||||
const roleLabels: Record<string, string> = {
|
||||
ADMIN: 'Admin', CAIXA: 'Caixa', GARCOM: 'Garçom', COZINHA: 'Cozinha', BARMAN: 'Barman',
|
||||
};
|
||||
export function roleBadge(role: string) {
|
||||
const cls = `badge badge-${role.toLowerCase()}`;
|
||||
return `<span class="${cls}">${roleLabels[role] ?? role}</span>`;
|
||||
}
|
||||
|
||||
/** Badges de status de comanda */
|
||||
const statusLabels: Record<string, string> = {
|
||||
ABERTA: 'Aberta', FECHADA: 'Fechada', PAGA: 'Paga', CANCELADA: 'Cancelada',
|
||||
};
|
||||
export function statusBadge(status: string) {
|
||||
const cls = `badge status-${status.toLowerCase()}`;
|
||||
return `<span class="${cls}">${statusLabels[status] ?? status}</span>`;
|
||||
}
|
||||
|
||||
/** Navbar padrão com hamburger para mobile */
|
||||
export function renderNavbar(activePath: string): string {
|
||||
const user = getUser();
|
||||
const role = user?.role ?? '';
|
||||
|
||||
const links = [
|
||||
{ path: '/kitchen', label: '👨🍳 Cozinha/Bar', roles: ['ADMIN', 'COZINHA', 'BARMAN'] },
|
||||
{ path: '/orders', label: '📋 Comandas', roles: ['ADMIN', 'GARCOM', 'CAIXA'] },
|
||||
{ path: '/checkout',label: '💳 Caixa', roles: ['ADMIN', 'CAIXA'] },
|
||||
{ path: '/menu', label: '🍔 Cardápio', roles: ['ADMIN'] },
|
||||
{ path: '/users', label: '👥 Equipe', roles: ['ADMIN'] },
|
||||
{ path: '/dashboard', label: '📊 Dashboard', roles: ['ADMIN'] },
|
||||
];
|
||||
|
||||
const visibleLinks = links.filter(l => l.roles.includes(role));
|
||||
|
||||
const desktopLinks = visibleLinks.map(l => `
|
||||
<a class="nav-link ${activePath === l.path ? 'active' : ''}"
|
||||
onclick="window.navigateTo('${l.path}')">${l.label}</a>
|
||||
`).join('');
|
||||
|
||||
const drawerLinks = visibleLinks.map(l => `
|
||||
<a class="nav-link ${activePath === l.path ? 'active' : ''}"
|
||||
onclick="window.closeDrawer();window.navigateTo('${l.path}')">${l.label}</a>
|
||||
`).join('');
|
||||
|
||||
// Agendar bind do hamburger após o DOM ser inserido
|
||||
setTimeout(() => {
|
||||
const btn = document.getElementById('hamburger-btn');
|
||||
const drawer = document.getElementById('nav-drawer');
|
||||
const overlay = document.getElementById('drawer-overlay');
|
||||
|
||||
btn?.addEventListener('click', () => {
|
||||
btn.classList.toggle('open');
|
||||
drawer?.classList.toggle('open');
|
||||
});
|
||||
overlay?.addEventListener('click', () => {
|
||||
btn?.classList.remove('open');
|
||||
drawer?.classList.remove('open');
|
||||
});
|
||||
}, 0);
|
||||
|
||||
(window as any).closeDrawer = () => {
|
||||
document.getElementById('hamburger-btn')?.classList.remove('open');
|
||||
document.getElementById('nav-drawer')?.classList.remove('open');
|
||||
};
|
||||
|
||||
return `
|
||||
<nav class="navbar">
|
||||
<div style="display:flex;align-items:center;gap:0.75rem;">
|
||||
<span style="font-size:1.25rem;font-weight:700;background:linear-gradient(90deg,#ff3366,#ffb300);-webkit-background-clip:text;-webkit-text-fill-color:transparent;white-space:nowrap;">
|
||||
<span style="font-size:1.75rem;">🍹 </span>Café em Saturno <span style="font-size:1.75rem;">🪐</span>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<!-- Desktop links -->
|
||||
<div class="nav-links">
|
||||
${desktopLinks}
|
||||
</div>
|
||||
|
||||
<!-- Desktop user info -->
|
||||
<div class="nav-links" style="align-items:center;gap:1rem;">
|
||||
<span style="color:var(--text-secondary);font-size:0.875rem;">
|
||||
${roleBadge(role)} ${user?.nome ?? ''}
|
||||
</span>
|
||||
<button class="btn btn-secondary btn-sm" onclick="window.logout()">Sair</button>
|
||||
</div>
|
||||
|
||||
<!-- Mobile hamburger -->
|
||||
<button class="hamburger" id="hamburger-btn" aria-label="Menu">
|
||||
<span></span><span></span><span></span>
|
||||
</button>
|
||||
</nav>
|
||||
|
||||
<!-- Mobile Drawer -->
|
||||
<div class="nav-drawer" id="nav-drawer">
|
||||
<div id="drawer-overlay" style="position:absolute;inset:0;"></div>
|
||||
<div class="nav-drawer-panel">
|
||||
<div class="nav-drawer-user">
|
||||
<div style="font-weight:600;margin-bottom:0.5rem;">${user?.nome ?? ''}</div>
|
||||
${roleBadge(role)}
|
||||
</div>
|
||||
${drawerLinks}
|
||||
<div style="margin-top:auto;padding-top:1.5rem;border-top:1px solid var(--border-color);">
|
||||
<button class="btn btn-danger" style="width:100%;" onclick="window.logout()">🚪 Sair</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
165
web/src/views/checkout.ts
Normal file
165
web/src/views/checkout.ts
Normal file
@@ -0,0 +1,165 @@
|
||||
import { api } from '../api';
|
||||
import { renderNavbar, formatBRL, toDisplayDate, parseDisplayDate, todayStr, getUser, toast } from '../utils';
|
||||
|
||||
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">
|
||||
<div class="page-header">
|
||||
<h1>Caixa / Checkout 💳</h1>
|
||||
</div>
|
||||
|
||||
<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-pagamentos-total" style="margin-bottom:0.75rem;"></div>
|
||||
<div id="checkout-pagamentos-lista">
|
||||
<p class="card-subtitle">Carregando pagamentos...</p>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
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')!;
|
||||
|
||||
lista.innerHTML = `<p class="card-subtitle">Carregando...</p>`;
|
||||
|
||||
try {
|
||||
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 (!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;
|
||||
}
|
||||
|
||||
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>
|
||||
`;
|
||||
|
||||
const user = getUser();
|
||||
const canReverse = user?.role === 'ADMIN' || user?.role === 'CAIXA';
|
||||
|
||||
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>
|
||||
`;
|
||||
|
||||
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.patch(`/pagamentos/${pagamentoId}/estornar`, {});
|
||||
toast('Pagamento estornado com sucesso', 'success');
|
||||
await loadPagamentos();
|
||||
} catch (err: any) {
|
||||
toast(err.message, 'error');
|
||||
}
|
||||
});
|
||||
});
|
||||
} catch (err: any) {
|
||||
lista.innerHTML = `<p style="color:var(--accent-primary)">Erro: ${err.message}</p>`;
|
||||
}
|
||||
}
|
||||
206
web/src/views/dashboard.ts
Normal file
206
web/src/views/dashboard.ts
Normal file
@@ -0,0 +1,206 @@
|
||||
import { api } from '../api';
|
||||
import { renderNavbar, toast, formatBRL, toDisplayDate, parseDisplayDate, todayStr } from '../utils';
|
||||
|
||||
export async function renderDashboard(container: HTMLElement) {
|
||||
container.innerHTML = `
|
||||
${renderNavbar('/dashboard')}
|
||||
<div class="container animate-fade-in">
|
||||
<div class="page-header">
|
||||
<h1>Dashboard & Relatórios 📊</h1>
|
||||
<button class="btn btn-secondary btn-sm" id="btn-refresh-dashboard">🔄 Atualizar</button>
|
||||
</div>
|
||||
|
||||
<!-- KPI Cards -->
|
||||
<div id="kpi-section" class="grid" style="grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin-bottom: 2rem;">
|
||||
<div class="card" style="text-align:center;">
|
||||
<p class="card-subtitle" style="margin-bottom:0.5rem;">Vendas Hoje</p>
|
||||
<p style="font-size:1.75rem;font-weight:700;color:var(--success);" id="kpi-vendas-hoje">R$ 0,00</p>
|
||||
<p class="card-subtitle" id="kpi-comandas-hoje">0 comandas</p>
|
||||
</div>
|
||||
<div class="card" style="text-align:center;">
|
||||
<p class="card-subtitle" style="margin-bottom:0.5rem;">Vendas Semana</p>
|
||||
<p style="font-size:1.75rem;font-weight:700;color:var(--accent-primary);" id="kpi-vendas-semana">R$ 0,00</p>
|
||||
<p class="card-subtitle" id="kpi-comandas-semana">0 comandas</p>
|
||||
</div>
|
||||
<div class="card" style="text-align:center;">
|
||||
<p class="card-subtitle" style="margin-bottom:0.5rem;">Comandas Abertas</p>
|
||||
<p style="font-size:1.75rem;font-weight:700;color:var(--warning);" id="kpi-comandas-abertas">0</p>
|
||||
</div>
|
||||
<div class="card" style="text-align:center;">
|
||||
<p class="card-subtitle" style="margin-bottom:0.5rem;">Estoque Baixo</p>
|
||||
<p style="font-size:1.75rem;font-weight:700;color:var(--accent-primary);" id="kpi-estoque-baixo">0</p>
|
||||
<p class="card-subtitle" id="kpi-total-produtos">0 produtos ativos</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Relatório de Vendas -->
|
||||
<div class="glass-panel" style="margin-bottom:2rem;">
|
||||
<div class="page-header" style="margin-bottom:1rem;">
|
||||
<h3 style="margin:0;">Relatório de Vendas</h3>
|
||||
<div style="display:flex;gap:0.5rem;align-items:center;flex-wrap:wrap;">
|
||||
<label style="color:var(--text-secondary);font-size:0.85rem;">Período:</label>
|
||||
<input type="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="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>
|
||||
|
||||
<div id="relatorio-resumo" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:1rem;margin-bottom:1.5rem;">
|
||||
</div>
|
||||
|
||||
<div id="relatorio-top-produtos" style="margin-bottom:1.5rem;"></div>
|
||||
|
||||
<div id="relatorio-vendas-dia" style="margin-bottom:1.5rem;"></div>
|
||||
|
||||
<div id="relatorio-pagamento"></div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Set default dates
|
||||
const hoje = 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 {
|
||||
const data = await api.get('/relatorios/dashboard');
|
||||
document.getElementById('kpi-vendas-hoje')!.textContent = formatBRL(data.vendasHoje.total);
|
||||
document.getElementById('kpi-comandas-hoje')!.textContent = `${data.vendasHoje.comandas} comandas`;
|
||||
document.getElementById('kpi-vendas-semana')!.textContent = formatBRL(data.vendasSemana.total);
|
||||
document.getElementById('kpi-comandas-semana')!.textContent = `${data.vendasSemana.comandas} comandas`;
|
||||
document.getElementById('kpi-comandas-abertas')!.textContent = `${data.comandasAbertas}`;
|
||||
document.getElementById('kpi-estoque-baixo')!.textContent = `${data.produtosEstoqueBaixo}`;
|
||||
document.getElementById('kpi-total-produtos')!.textContent = `${data.totalProdutos} produtos ativos`;
|
||||
} catch (err: any) {
|
||||
toast(err.message, 'error');
|
||||
}
|
||||
};
|
||||
|
||||
const loadRelatorio = async () => {
|
||||
const inicio = 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
|
||||
document.getElementById('relatorio-resumo')!.innerHTML = `
|
||||
<div class="card" style="text-align:center;padding:1rem;">
|
||||
<p class="card-subtitle" style="margin-bottom:0.25rem;">Total Vendido</p>
|
||||
<p style="font-size:1.25rem;font-weight:700;color:var(--success);">${formatBRL(data.resumo.totalVendas)}</p>
|
||||
</div>
|
||||
<div class="card" style="text-align:center;padding:1rem;">
|
||||
<p class="card-subtitle" style="margin-bottom:0.25rem;">Comandas</p>
|
||||
<p style="font-size:1.25rem;font-weight:700;">${data.resumo.totalComandas}</p>
|
||||
</div>
|
||||
<div class="card" style="text-align:center;padding:1rem;">
|
||||
<p class="card-subtitle" style="margin-bottom:0.25rem;">Ticket Médio</p>
|
||||
<p style="font-size:1.25rem;font-weight:700;color:var(--accent-primary);">${formatBRL(data.resumo.ticketMedio)}</p>
|
||||
</div>
|
||||
<div class="card" style="text-align:center;padding:1rem;">
|
||||
<p class="card-subtitle" style="margin-bottom:0.25rem;">Descontos</p>
|
||||
<p style="font-size:1.25rem;font-weight:700;color:var(--warning);">${formatBRL(data.resumo.totalDescontos)}</p>
|
||||
</div>
|
||||
<div class="card" style="text-align:center;padding:1rem;">
|
||||
<p class="card-subtitle" style="margin-bottom:0.25rem;">Acréscimos</p>
|
||||
<p style="font-size:1.25rem;font-weight:700;color:var(--accent-secondary);">${formatBRL(data.resumo.totalAcrescimos)}</p>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Top produtos
|
||||
if (data.topProdutos.length > 0) {
|
||||
document.getElementById('relatorio-top-produtos')!.innerHTML = `
|
||||
<h4 style="margin-bottom:0.75rem;">🏆 Mais Vendidos</h4>
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead><tr><th>#</th><th>Produto</th><th style="text-align:center;">Qtd</th><th style="text-align:right;">Total</th></tr></thead>
|
||||
<tbody>
|
||||
${data.topProdutos.map((p: any, i: number) => `
|
||||
<tr>
|
||||
<td>${i + 1}º</td>
|
||||
<td><strong>${p.nome}</strong></td>
|
||||
<td style="text-align:center;">${p.quantidade}</td>
|
||||
<td style="text-align:right;">${formatBRL(p.total)}</td>
|
||||
</tr>
|
||||
`).join('')}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
`;
|
||||
} else {
|
||||
document.getElementById('relatorio-top-produtos')!.innerHTML = '';
|
||||
}
|
||||
|
||||
// Vendas por dia
|
||||
if (data.vendasPorDia.length > 0) {
|
||||
document.getElementById('relatorio-vendas-dia')!.innerHTML = `
|
||||
<h4 style="margin-bottom:0.75rem;">📅 Vendas por Dia</h4>
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead><tr><th>Data</th><th style="text-align:center;">Comandas</th><th style="text-align:right;">Total</th></tr></thead>
|
||||
<tbody>
|
||||
${data.vendasPorDia.map((d: any) => `
|
||||
<tr>
|
||||
<td>${new Date(d.data + 'T12:00:00').toLocaleDateString('pt-BR')}</td>
|
||||
<td style="text-align:center;">${d.comandas}</td>
|
||||
<td style="text-align:right;">${formatBRL(d.vendas)}</td>
|
||||
</tr>
|
||||
`).join('')}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
`;
|
||||
} else {
|
||||
document.getElementById('relatorio-vendas-dia')!.innerHTML = '';
|
||||
}
|
||||
|
||||
// Vendas por pagamento
|
||||
if (data.vendasPorPagamento.length > 0) {
|
||||
const pagLabels: Record<string, string> = {
|
||||
DINHEIRO: '💵 Dinheiro', CARTAO_CREDITO: '💳 Cartão Crédito',
|
||||
CARTAO_DEBITO: '💳 Cartão Débito', PIX: '📱 PIX', NAO_INFORMADO: '❓ Não informado',
|
||||
};
|
||||
document.getElementById('relatorio-pagamento')!.innerHTML = `
|
||||
<h4 style="margin-bottom:0.75rem;">💰 Por Forma de Pagamento</h4>
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead><tr><th>Forma</th><th style="text-align:right;">Total</th></tr></thead>
|
||||
<tbody>
|
||||
${data.vendasPorPagamento.map((p: any) => `
|
||||
<tr>
|
||||
<td>${pagLabels[p.forma] ?? p.forma}</td>
|
||||
<td style="text-align:right;">${formatBRL(p.total)}</td>
|
||||
</tr>
|
||||
`).join('')}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
`;
|
||||
} else {
|
||||
document.getElementById('relatorio-pagamento')!.innerHTML = '';
|
||||
}
|
||||
} catch (err: any) {
|
||||
toast(err.message, 'error');
|
||||
}
|
||||
};
|
||||
|
||||
document.getElementById('btn-refresh-dashboard')?.addEventListener('click', () => {
|
||||
loadDashboard();
|
||||
loadRelatorio();
|
||||
});
|
||||
|
||||
document.getElementById('btn-gerar-relatorio')?.addEventListener('click', loadRelatorio);
|
||||
|
||||
await Promise.all([loadDashboard(), loadRelatorio()]);
|
||||
}
|
||||
207
web/src/views/kitchen.ts
Normal file
207
web/src/views/kitchen.ts
Normal file
@@ -0,0 +1,207 @@
|
||||
import { api } from '../api';
|
||||
import { renderNavbar, toast } from '../utils';
|
||||
|
||||
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);
|
||||
gain.connect(audioCtx.destination);
|
||||
osc.type = 'sine';
|
||||
osc.frequency.setValueAtTime(800, audioCtx.currentTime);
|
||||
osc.frequency.setValueAtTime(1000, audioCtx.currentTime + 0.1);
|
||||
osc.frequency.setValueAtTime(800, audioCtx.currentTime + 0.2);
|
||||
gain.gain.setValueAtTime(0.3, audioCtx.currentTime);
|
||||
gain.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 0.4);
|
||||
osc.start(audioCtx.currentTime);
|
||||
osc.stop(audioCtx.currentTime + 0.4);
|
||||
} catch (e) {
|
||||
// Audio not supported, silently fail
|
||||
}
|
||||
}
|
||||
|
||||
export async function renderKitchen(container: HTMLElement) {
|
||||
container.innerHTML = `
|
||||
${renderNavbar('/kitchen')}
|
||||
<div class="container animate-fade-in">
|
||||
<div class="page-header">
|
||||
<h1>Painel de Preparo 👨🍳</h1>
|
||||
<div style="display:flex;gap:0.75rem;align-items:center;flex-wrap:wrap;">
|
||||
<label style="color:var(--text-secondary);font-size:0.875rem;">Filtrar:</label>
|
||||
<button class="btn btn-secondary btn-sm filter-btn active" data-filter="">Todos</button>
|
||||
<button class="btn btn-secondary btn-sm filter-btn" data-filter="true">🍳 Cozinha</button>
|
||||
<button class="btn btn-secondary btn-sm filter-btn" data-filter="false">🍹 Bar</button>
|
||||
<button class="btn btn-secondary btn-sm" id="btn-refresh">🔄 Atualizar</button>
|
||||
<label style="display:flex;align-items:center;gap:0.4rem;cursor:pointer;color:var(--text-secondary);font-size:0.875rem;">
|
||||
<input type="checkbox" id="auto-refresh-toggle" checked> Auto-refresh
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="tabs">
|
||||
<button class="tab-btn active" data-status="PENDENTE">🔴 Pendente</button>
|
||||
<button class="tab-btn" data-status="PREPARANDO">🟡 Preparando</button>
|
||||
<button class="tab-btn" data-status="PRONTO">🟢 Pronto</button>
|
||||
<button class="tab-btn" data-status="ENTREGUE">✅ Entregue</button>
|
||||
</div>
|
||||
|
||||
<div class="grid" id="items-grid">
|
||||
<p>Carregando pedidos...</p>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
let currentStatus = 'PENDENTE';
|
||||
let currentFilter = '';
|
||||
let autoRefreshInterval: ReturnType<typeof setInterval> | null = null;
|
||||
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));
|
||||
|
||||
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');
|
||||
}
|
||||
}
|
||||
previousItemIdsByStatus.set(currentStatus, currentIds);
|
||||
|
||||
if (!items.length) {
|
||||
grid.innerHTML = `<p class="card-subtitle" style="grid-column:1/-1;text-align:center;padding:3rem 0;">
|
||||
Nenhum pedido com status <strong>${currentStatus}</strong> 🎉
|
||||
</p>`;
|
||||
return;
|
||||
}
|
||||
|
||||
const statusActions: Record<string, { label: string; next: string }> = {
|
||||
PENDENTE: { label: '▶ Iniciar Preparo', next: 'PREPARANDO' },
|
||||
PREPARANDO: { label: '✔ Marcar Pronto', next: 'PRONTO' },
|
||||
PRONTO: { label: '🚀 Marcar Entregue', next: 'ENTREGUE' },
|
||||
ENTREGUE: { label: '', next: '' },
|
||||
};
|
||||
|
||||
grid.innerHTML = items.map((item: any) => {
|
||||
const action = statusActions[item.status];
|
||||
return `
|
||||
<div class="card animate-fade-in">
|
||||
<div style="display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:1rem;flex-wrap:wrap;gap:0.5rem;">
|
||||
<span class="badge ${item.produto.itemCozinha ? 'badge-cozinha' : 'badge-barman'}">
|
||||
${item.produto.itemCozinha ? '🍳 Cozinha' : '🍹 Bar'}
|
||||
</span>
|
||||
<span class="card-subtitle" style="margin:0;">Mesa: <strong>${item.comanda.identificador}</strong></span>
|
||||
</div>
|
||||
<h3 class="card-title">${item.quantidade}× ${item.produto.nome}</h3>
|
||||
${item.observacao ? `<p style="color:var(--warning);font-size:0.875rem;margin-bottom:1rem;">⚠️ ${item.observacao}</p>` : ''}
|
||||
<p class="card-subtitle" style="margin-bottom: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%;" 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>`}
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
} catch (err: any) {
|
||||
grid.innerHTML = `<p style="color:var(--accent-primary)">Erro: ${err.message}</p>`;
|
||||
}
|
||||
};
|
||||
|
||||
const startAutoRefresh = () => {
|
||||
stopAutoRefresh();
|
||||
autoRefreshInterval = setInterval(loadItems, 10000);
|
||||
};
|
||||
|
||||
const stopAutoRefresh = () => {
|
||||
if (autoRefreshInterval) {
|
||||
clearInterval(autoRefreshInterval);
|
||||
autoRefreshInterval = null;
|
||||
}
|
||||
};
|
||||
|
||||
// Tab switching
|
||||
document.querySelectorAll('.tab-btn').forEach(btn => {
|
||||
btn.addEventListener('click', () => {
|
||||
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
|
||||
btn.classList.add('active');
|
||||
currentStatus = (btn as HTMLElement).dataset.status!;
|
||||
loadItems();
|
||||
});
|
||||
});
|
||||
|
||||
// Filter buttons
|
||||
document.querySelectorAll('.filter-btn').forEach(btn => {
|
||||
btn.addEventListener('click', () => {
|
||||
document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));
|
||||
btn.classList.add('active');
|
||||
currentFilter = (btn as HTMLElement).dataset.filter!;
|
||||
loadItems();
|
||||
});
|
||||
});
|
||||
|
||||
document.getElementById('btn-refresh')?.addEventListener('click', loadItems);
|
||||
|
||||
document.getElementById('auto-refresh-toggle')?.addEventListener('change', (e) => {
|
||||
if ((e.target as HTMLInputElement).checked) startAutoRefresh();
|
||||
else stopAutoRefresh();
|
||||
});
|
||||
|
||||
// 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');
|
||||
loadItems();
|
||||
} 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();
|
||||
previousItemIdsByStatus.clear();
|
||||
document.removeEventListener('visibilitychange', handleVisibilityChange);
|
||||
audioCtx?.close();
|
||||
audioCtx = null;
|
||||
};
|
||||
window.addEventListener('popstate', cleanup);
|
||||
|
||||
await loadItems();
|
||||
startAutoRefresh();
|
||||
}
|
||||
58
web/src/views/login.ts
Normal file
58
web/src/views/login.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import { api } from '../api';
|
||||
import { navigateTo } from '../main';
|
||||
|
||||
export function renderLogin(container: HTMLElement) {
|
||||
container.innerHTML = `
|
||||
<div class="login-view animate-fade-in">
|
||||
<div class="login-box" style="padding: 1rem;">
|
||||
<div class="glass-panel">
|
||||
<div style="text-align:center;margin-bottom:2rem;">
|
||||
<div style="font-size:3rem;margin-bottom:0.5rem;">🍹</div>
|
||||
<h2 style="margin:0 0 0.25rem;">Café em Saturno</h2>
|
||||
<p class="card-subtitle" style="margin:0;">Entre com suas credenciais</p>
|
||||
</div>
|
||||
|
||||
<form id="login-form">
|
||||
<div class="form-group">
|
||||
<label for="email">E-mail</label>
|
||||
<input type="email" id="email" class="form-control" value="admin@gastrobar.com"
|
||||
autocomplete="email" inputmode="email" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="password">Senha</label>
|
||||
<input type="password" id="password" class="form-control" value="123456"
|
||||
autocomplete="current-password" required>
|
||||
</div>
|
||||
<p id="login-error" class="error-message"></p>
|
||||
<button type="submit" id="btn-login" class="btn" style="width:100%;margin-top:0.75rem;padding:0.875rem;">
|
||||
Entrar
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const form = document.getElementById('login-form');
|
||||
const errorEl = document.getElementById('login-error');
|
||||
|
||||
form?.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const email = (document.getElementById('email') as HTMLInputElement).value;
|
||||
const senha = (document.getElementById('password') as HTMLInputElement).value;
|
||||
|
||||
if (errorEl) errorEl.style.display = 'none';
|
||||
|
||||
try {
|
||||
const data = await api.post('/auth/login', { email, senha });
|
||||
localStorage.setItem('@gastrobar:token', data.token);
|
||||
localStorage.setItem('@gastrobar:user', JSON.stringify(data.user));
|
||||
navigateTo('/kitchen');
|
||||
} catch (err: any) {
|
||||
if (errorEl) {
|
||||
errorEl.textContent = err.message;
|
||||
errorEl.style.display = 'block';
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
335
web/src/views/menu.ts
Normal file
335
web/src/views/menu.ts
Normal file
@@ -0,0 +1,335 @@
|
||||
import { api } from '../api';
|
||||
import { renderNavbar, toast, formatBRL } from '../utils';
|
||||
|
||||
export async function renderMenu(container: HTMLElement) {
|
||||
container.innerHTML = `
|
||||
${renderNavbar('/menu')}
|
||||
<div class="container animate-fade-in">
|
||||
<div class="page-header">
|
||||
<h1>Cardápio 🍔</h1>
|
||||
</div>
|
||||
<div class="tabs">
|
||||
<button class="tab-btn active" id="tab-produtos">Produtos</button>
|
||||
<button class="tab-btn" id="tab-categorias">Categorias</button>
|
||||
</div>
|
||||
<div id="tab-content"></div>
|
||||
</div>
|
||||
|
||||
<!-- Modal Produto -->
|
||||
<div id="modal-produto" class="modal-overlay" style="display:none;">
|
||||
<div class="modal" style="max-width:600px;">
|
||||
<div class="modal-header">
|
||||
<h3 id="modal-produto-title">Novo Produto</h3>
|
||||
<button class="btn-icon" onclick="document.getElementById('modal-produto').style.display='none'">✕</button>
|
||||
</div>
|
||||
<form id="form-produto">
|
||||
<input type="hidden" id="produto-id">
|
||||
<div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;">
|
||||
<div class="form-group" style="margin:0;">
|
||||
<label>Nome *</label>
|
||||
<input type="text" id="p-nome" class="form-control" required>
|
||||
</div>
|
||||
<div class="form-group" style="margin:0;">
|
||||
<label>Categoria *</label>
|
||||
<select id="p-categoria" class="form-control" required></select>
|
||||
</div>
|
||||
<div class="form-group" style="margin:0;">
|
||||
<label>Preço de Venda (R$) *</label>
|
||||
<input type="number" id="p-preco" class="form-control" step="0.01" min="0" required>
|
||||
</div>
|
||||
<div class="form-group" style="margin:0;">
|
||||
<label>Custo (R$)</label>
|
||||
<input type="number" id="p-custo" class="form-control" step="0.01" min="0">
|
||||
</div>
|
||||
<div class="form-group" style="margin:0;">
|
||||
<label>Estoque Atual</label>
|
||||
<input type="number" id="p-estoque" class="form-control" value="0">
|
||||
</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">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group" style="margin-top:1rem;">
|
||||
<label>Descrição</label>
|
||||
<input type="text" id="p-desc" class="form-control" placeholder="Descrição breve do produto">
|
||||
</div>
|
||||
<div style="display:flex;gap:2rem;margin-bottom:1.5rem;align-items:center;">
|
||||
<label style="display:flex;align-items:center;gap:0.5rem;cursor:pointer;color:var(--text-primary);">
|
||||
<input type="checkbox" id="p-cozinha"> Item de Cozinha
|
||||
</label>
|
||||
<label style="display:flex;align-items:center;gap:0.5rem;cursor:pointer;color:var(--text-primary);">
|
||||
<input type="checkbox" id="p-ativo" checked> Ativo
|
||||
</label>
|
||||
</div>
|
||||
<button type="submit" class="btn" style="width:100%;">Salvar Produto</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="modal-categoria" class="modal-overlay" style="display:none;">
|
||||
<div class="modal">
|
||||
<div class="modal-header">
|
||||
<h3>Nova Categoria</h3>
|
||||
<button class="btn-icon" onclick="document.getElementById('modal-categoria').style.display='none'">✕</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form id="form-categoria">
|
||||
<div class="form-group">
|
||||
<label>Nome da Categoria *</label>
|
||||
<input type="text" id="cat-nome" class="form-control" required>
|
||||
</div>
|
||||
<button type="submit" class="btn" style="width:100%;">Criar Categoria</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
let categorias: any[] = [];
|
||||
let allProducts: any[] = [];
|
||||
let filterCategoria = '';
|
||||
let filterAtivo = '';
|
||||
let filterCozinha = '';
|
||||
|
||||
const loadCategorias = async () => {
|
||||
categorias = await api.get('/categorias');
|
||||
const sel = document.getElementById('p-categoria') as HTMLSelectElement;
|
||||
if (sel) sel.innerHTML = categorias.map((c: any) => `<option value="${c.id}">${c.nome}</option>`).join('');
|
||||
};
|
||||
|
||||
const renderTabProdutos = async () => {
|
||||
const tc = document.getElementById('tab-content')!;
|
||||
allProducts = await api.get('/produtos');
|
||||
tc.innerHTML = `
|
||||
<div class="page-header" style="margin-bottom:1rem;">
|
||||
<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 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>
|
||||
<td data-label="Preço">${formatBRL(p.preco)}</td>
|
||||
<td data-label="Estoque">
|
||||
<span style="color:${p.estoqueAtual <= p.estoqueMinimo ? 'var(--accent-primary)' : 'var(--text-primary)'}">
|
||||
${p.estoqueAtual} ${p.estoqueAtual <= p.estoqueMinimo ? '⚠️' : ''}
|
||||
</span>
|
||||
</td>
|
||||
<td data-label="Tipo"><span class="badge ${p.itemCozinha ? 'badge-cozinha' : 'badge-barman'}">${p.itemCozinha ? 'Cozinha' : 'Bar'}</span></td>
|
||||
<td data-label="Status"><span class="badge ${p.ativo ? 'badge-success' : 'badge-warning'}">${p.ativo ? 'Ativo' : 'Inativo'}</span></td>
|
||||
<td data-label="Ações" style="display:flex;gap:0.5rem;flex-wrap:wrap;">
|
||||
<button class="btn btn-sm btn-secondary" onclick="window.editProduct(${JSON.stringify(p).replace(/"/g, '"')})">✏️</button>
|
||||
<button class="btn btn-sm btn-danger" onclick="window.deleteProduct('${p.id}','${p.nome}')">🗑</button>
|
||||
</td>
|
||||
</tr>
|
||||
`).join('');
|
||||
};
|
||||
|
||||
const renderTabCategorias = async () => {
|
||||
const tc = document.getElementById('tab-content')!;
|
||||
const cats = await api.get('/categorias');
|
||||
tc.innerHTML = `
|
||||
<div class="page-header" style="margin-bottom:1rem;">
|
||||
<span class="card-subtitle">${cats.length} categoria(s)</span>
|
||||
<button class="btn" id="btn-nova-cat">+ Nova Categoria</button>
|
||||
</div>
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead><tr><th>Nome</th><th>Nº Produtos</th><th>Ações</th></tr></thead>
|
||||
<tbody>
|
||||
${cats.map((c: any) => `
|
||||
<tr>
|
||||
<td data-label="Nome"><strong>${c.nome}</strong></td>
|
||||
<td data-label="Nº Produtos">${c.produtos?.length ?? 0}</td>
|
||||
<td data-label="Ações">
|
||||
<button class="btn btn-sm btn-danger" onclick="window.deleteCategory('${c.id}','${c.nome}')">🗑 Excluir</button>
|
||||
</td>
|
||||
</tr>
|
||||
`).join('')}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
`;
|
||||
document.getElementById('btn-nova-cat')?.addEventListener('click', () => {
|
||||
(document.getElementById('modal-categoria') as HTMLElement).style.display = 'flex';
|
||||
});
|
||||
};
|
||||
|
||||
// Tabs
|
||||
document.getElementById('tab-produtos')?.addEventListener('click', async () => {
|
||||
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
|
||||
document.getElementById('tab-produtos')?.classList.add('active');
|
||||
await renderTabProdutos();
|
||||
});
|
||||
document.getElementById('tab-categorias')?.addEventListener('click', async () => {
|
||||
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
|
||||
document.getElementById('tab-categorias')?.classList.add('active');
|
||||
await renderTabCategorias();
|
||||
});
|
||||
|
||||
// Form Produto
|
||||
document.getElementById('form-produto')?.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const id = (document.getElementById('produto-id') as HTMLInputElement).value;
|
||||
const payload: any = {
|
||||
nome: (document.getElementById('p-nome') as HTMLInputElement).value,
|
||||
categoriaId: (document.getElementById('p-categoria') as HTMLSelectElement).value,
|
||||
preco: parseFloat((document.getElementById('p-preco') as HTMLInputElement).value),
|
||||
custo: parseFloat((document.getElementById('p-custo') as HTMLInputElement).value) || undefined,
|
||||
estoqueAtual: parseInt((document.getElementById('p-estoque') as HTMLInputElement).value),
|
||||
estoqueMinimo: parseInt((document.getElementById('p-estoque-min') as HTMLInputElement).value),
|
||||
descricao: (document.getElementById('p-desc') as HTMLInputElement).value || undefined,
|
||||
itemCozinha: (document.getElementById('p-cozinha') as HTMLInputElement).checked,
|
||||
ativo: (document.getElementById('p-ativo') as HTMLInputElement).checked,
|
||||
};
|
||||
try {
|
||||
if (id) await api.patch(`/produtos/${id}`, payload);
|
||||
else await api.post('/produtos', payload);
|
||||
toast(id ? 'Produto atualizado!' : 'Produto cadastrado!', 'success');
|
||||
(document.getElementById('modal-produto') as HTMLElement).style.display = 'none';
|
||||
await renderTabProdutos();
|
||||
} catch (err: any) { toast(err.message, 'error'); }
|
||||
});
|
||||
|
||||
// Form Categoria
|
||||
document.getElementById('form-categoria')?.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const nome = (document.getElementById('cat-nome') as HTMLInputElement).value;
|
||||
try {
|
||||
await api.post('/categorias', { nome });
|
||||
toast('Categoria criada!', 'success');
|
||||
(document.getElementById('modal-categoria') as HTMLElement).style.display = 'none';
|
||||
await loadCategorias();
|
||||
await renderTabCategorias();
|
||||
} catch (err: any) { toast(err.message, 'error'); }
|
||||
});
|
||||
|
||||
// Global handlers
|
||||
(window as any).editProduct = (p: any) => {
|
||||
(document.getElementById('produto-id') as HTMLInputElement).value = p.id;
|
||||
(document.getElementById('p-nome') as HTMLInputElement).value = p.nome;
|
||||
(document.getElementById('p-preco') as HTMLInputElement).value = p.preco;
|
||||
(document.getElementById('p-custo') as HTMLInputElement).value = p.custo ?? '';
|
||||
(document.getElementById('p-estoque') as HTMLInputElement).value = p.estoqueAtual;
|
||||
(document.getElementById('p-estoque-min') as HTMLInputElement).value = p.estoqueMinimo;
|
||||
(document.getElementById('p-desc') as HTMLInputElement).value = p.descricao ?? '';
|
||||
(document.getElementById('p-cozinha') as HTMLInputElement).checked = p.itemCozinha;
|
||||
(document.getElementById('p-ativo') as HTMLInputElement).checked = p.ativo;
|
||||
const sel = document.getElementById('p-categoria') as HTMLSelectElement;
|
||||
if (sel) sel.value = p.categoriaId;
|
||||
(document.getElementById('modal-produto-title') as HTMLElement).textContent = 'Editar Produto';
|
||||
(document.getElementById('modal-produto') as HTMLElement).style.display = 'flex';
|
||||
};
|
||||
|
||||
(window as any).deleteProduct = async (id: string, nome: string) => {
|
||||
if (!confirm(`Excluir o produto "${nome}"?`)) return;
|
||||
try {
|
||||
await api.patch(`/produtos/${id}`, { ativo: false });
|
||||
toast('Produto desativado!', 'success');
|
||||
await renderTabProdutos();
|
||||
} catch (err: any) { toast(err.message, 'error'); }
|
||||
};
|
||||
|
||||
(window as any).deleteCategory = async (id: string, nome: string) => {
|
||||
if (!confirm(`Excluir a categoria "${nome}"?`)) return;
|
||||
try {
|
||||
await api.delete(`/categorias/${id}`);
|
||||
toast('Categoria excluída!', 'success');
|
||||
await renderTabCategorias();
|
||||
} catch (err: any) { toast(err.message, 'error'); }
|
||||
};
|
||||
|
||||
await loadCategorias();
|
||||
await renderTabProdutos();
|
||||
}
|
||||
|
||||
function clearProductForm() {
|
||||
(document.getElementById('produto-id') as HTMLInputElement).value = '';
|
||||
(document.getElementById('p-nome') as HTMLInputElement).value = '';
|
||||
(document.getElementById('p-preco') as HTMLInputElement).value = '';
|
||||
(document.getElementById('p-custo') as HTMLInputElement).value = '';
|
||||
(document.getElementById('p-estoque') as HTMLInputElement).value = '0';
|
||||
(document.getElementById('p-estoque-min') as HTMLInputElement).value = '0';
|
||||
(document.getElementById('p-desc') as HTMLInputElement).value = '';
|
||||
(document.getElementById('p-cozinha') as HTMLInputElement).checked = false;
|
||||
(document.getElementById('p-ativo') as HTMLInputElement).checked = true;
|
||||
(document.getElementById('modal-produto-title') as HTMLElement).textContent = 'Novo Produto';
|
||||
}
|
||||
860
web/src/views/orders.ts
Normal file
860
web/src/views/orders.ts
Normal file
@@ -0,0 +1,860 @@
|
||||
import { api } from '../api';
|
||||
import { renderNavbar, toast, formatBRL, getUser, statusBadge, parseDisplayDate } from '../utils';
|
||||
|
||||
let localComandas: any[] = [];
|
||||
|
||||
const FORMAS_PAGAMENTO = [
|
||||
{ value: 'DINHEIRO', label: '💵 Dinheiro' },
|
||||
{ value: 'CARTAO_CREDITO', label: '💳 Cartão Crédito' },
|
||||
{ value: 'CARTAO_DEBITO', label: '💳 Cartão Débito' },
|
||||
{ value: 'PIX', label: '📱 PIX' },
|
||||
];
|
||||
|
||||
export async function renderOrders(container: HTMLElement) {
|
||||
container.innerHTML = `
|
||||
${renderNavbar('/orders')}
|
||||
<div class="container animate-fade-in">
|
||||
<div class="page-header">
|
||||
<h1>Comandas 📋</h1>
|
||||
<button class="btn" id="btn-nova-comanda">+ Nova Comanda</button>
|
||||
</div>
|
||||
|
||||
<form id="form-busca-comandas" class="comandas-search-bar">
|
||||
<div class="comandas-search-field">
|
||||
<label>De</label>
|
||||
<input type="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="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>
|
||||
<button type="button" class="btn btn-sm" id="btn-busca-limpar" style="color:var(--text-secondary);">Limpar</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div id="comandas-list"><p class="card-subtitle">Carregando...</p></div>
|
||||
</div>
|
||||
|
||||
<!-- Modal Nova Comanda -->
|
||||
<div id="modal-nova-comanda" class="modal-overlay" style="display:none;">
|
||||
<div class="modal">
|
||||
<div class="modal-header">
|
||||
<h3>Abrir Nova Comanda</h3>
|
||||
<button class="btn-icon" id="modal-close">✕</button>
|
||||
</div>
|
||||
<form id="form-nova-comanda">
|
||||
<div class="form-group">
|
||||
<label>Identificador (Mesa / Nome)</label>
|
||||
<input type="text" id="identificador" class="form-control" placeholder="Ex: Mesa 5, João Silva" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Nome do Cliente (opcional)</label>
|
||||
<input type="text" id="nomeCliente" class="form-control" placeholder="Nome do cliente">
|
||||
</div>
|
||||
<button type="submit" class="btn" style="width:100%;margin-top:0.5rem;">Abrir Comanda</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal Adicionar Item -->
|
||||
<div id="modal-add-item" class="modal-overlay" style="display:none;">
|
||||
<div class="modal" style="max-width: 500px;">
|
||||
<div class="modal-header">
|
||||
<h3>Adicionar Pedido</h3>
|
||||
<button class="btn-icon" id="modal-item-close">✕</button>
|
||||
</div>
|
||||
<input type="hidden" id="current-comanda-id">
|
||||
<form id="form-add-item">
|
||||
<div class="form-group">
|
||||
<label>Buscar Produto</label>
|
||||
<input type="text" id="modal-produto-busca" class="form-control" placeholder="Digite o nome do produto...">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label id="grid-label">Produtos Sugeridos (Mais Vendidos)</label>
|
||||
<div id="modal-produtos-grid" class="product-mini-grid">
|
||||
</div>
|
||||
</div>
|
||||
<input type="hidden" id="selected-produto-id" required>
|
||||
<div id="selected-produto-preview" class="card-subtitle" style="margin-top: -0.5rem; margin-bottom: 1.5rem; font-weight: 600; color: var(--accent-primary);">
|
||||
Nenhum produto selecionado
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Quantidade</label>
|
||||
<input type="number" id="qtd" class="form-control" value="1" min="1" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Observação</label>
|
||||
<input type="text" id="obs" class="form-control" placeholder="Ex: sem cebola, bem passado...">
|
||||
</div>
|
||||
<button type="submit" class="btn" style="width:100%;margin-top:0.5rem;">Adicionar Pedido</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal Detalhes da Comanda -->
|
||||
<div id="modal-detalhes-comanda" class="modal-overlay" style="display:none;">
|
||||
<div class="modal" style="max-width: 650px;">
|
||||
<div class="modal-header">
|
||||
<h3>Detalhes da Comanda</h3>
|
||||
<button class="btn-icon" id="modal-detalhes-close">✕</button>
|
||||
</div>
|
||||
<input type="hidden" id="detalhes-comanda-id">
|
||||
|
||||
<div class="detalhes-summary" id="detalhes-summary">
|
||||
<div class="detalhes-summary-row">
|
||||
<span class="detalhes-summary-label" id="detalhes-label-ident">—</span>
|
||||
<span class="detalhes-summary-client" id="detalhes-label-client"></span>
|
||||
</div>
|
||||
<div id="detalhes-label-status"></div>
|
||||
<div id="detalhes-label-usuario" style="font-size:0.8rem;color:var(--text-secondary);margin-top:0.25rem;"></div>
|
||||
</div>
|
||||
|
||||
<div class="detalhes-edit-section">
|
||||
<button type="button" class="detalhes-edit-toggle" id="detalhes-edit-toggle">
|
||||
<span>✏️ Editar Informações</span>
|
||||
<span class="detalhes-edit-arrow">▾</span>
|
||||
</button>
|
||||
<div class="detalhes-edit-body" id="detalhes-edit-body">
|
||||
<form id="form-editar-comanda">
|
||||
<div style="display:grid; grid-template-columns: 1fr 1fr; gap: 0.75rem;">
|
||||
<div class="form-group" style="margin:0;">
|
||||
<label>Identificador</label>
|
||||
<input type="text" id="detalhes-identificador" class="form-control" required>
|
||||
</div>
|
||||
<div class="form-group" style="margin:0;">
|
||||
<label>Cliente</label>
|
||||
<input type="text" id="detalhes-cliente" class="form-control">
|
||||
</div>
|
||||
<div class="form-group" style="margin:0;">
|
||||
<label>Status</label>
|
||||
<select id="detalhes-status" class="form-control">
|
||||
<option value="ABERTA">Aberta</option>
|
||||
<option value="FECHADA">Fechada</option>
|
||||
<option value="PAGA">Paga</option>
|
||||
<option value="CANCELADA">Cancelada</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group" style="margin:0;">
|
||||
<label>Forma de Pagamento</label>
|
||||
<select id="detalhes-forma-pagamento" class="form-control">
|
||||
<option value="">Não informado</option>
|
||||
${FORMAS_PAGAMENTO.map(fp => `<option value="${fp.value}">${fp.label}</option>`).join('')}
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group" style="margin:0;">
|
||||
<label>Desconto (R$)</label>
|
||||
<input type="number" id="detalhes-desconto" class="form-control" step="0.01" min="0" value="0">
|
||||
</div>
|
||||
<div class="form-group" style="margin:0;">
|
||||
<label>Acréscimo (R$)</label>
|
||||
<input type="number" id="detalhes-acrescimo" class="form-control" step="0.01" min="0" value="0">
|
||||
</div>
|
||||
<div class="form-group" style="margin:0; grid-column: 1 / -1; display:flex; align-items:center; gap:0.75rem;">
|
||||
<input type="checkbox" id="detalhes-taxa-servico">
|
||||
<label for="detalhes-taxa-servico" style="cursor:pointer;color:var(--text-primary);">Taxa de Serviço (10%)</label>
|
||||
</div>
|
||||
<div class="form-group" style="margin:0; grid-column: 1 / -1;" id="motivo-cancelamento-group" style="display:none;">
|
||||
<label>Motivo do Cancelamento</label>
|
||||
<input type="text" id="detalhes-motivo-cancelamento" class="form-control" placeholder="Motivo (opcional)">
|
||||
</div>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-sm btn-secondary" style="width:100%; margin-top: 1rem;">Salvar Informações</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<hr style="border: 0; border-top: 1px solid var(--border-color); margin: 1.25rem 0;">
|
||||
|
||||
<h4>Itens Consumidos</h4>
|
||||
<div class="table-wrap" style="max-height: 180px; overflow-y: auto; margin-top: 0.5rem; margin-bottom: 1rem;">
|
||||
<table style="font-size: 0.85rem;">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Produto</th>
|
||||
<th style="text-align:center;">Qtd</th>
|
||||
<th style="text-align:right;">Subtotal</th>
|
||||
<th>Obs</th>
|
||||
<th>Adicionado por</th>
|
||||
<th>Status</th>
|
||||
<th>Ações</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="detalhes-itens-tbody">
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div id="detalhes-resumo-financeiro" style="margin-top:0.5rem;">
|
||||
</div>
|
||||
|
||||
<div class="total-bar" style="margin-top:0.5rem; padding: 0.75rem 1rem;">
|
||||
<span style="color:var(--text-secondary); font-size: 0.9rem;">Total Final:</span>
|
||||
<span class="total-value" id="detalhes-total" style="font-size: 1.3rem;">R$ 0,00</span>
|
||||
</div>
|
||||
|
||||
<div style="display: flex; gap: 0.75rem; margin-top: 1.25rem;" id="detalhes-acoes-pagamento">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 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 {
|
||||
let total = c.total || 0;
|
||||
total -= (c.desconto || 0);
|
||||
total += (c.acrescimo || 0);
|
||||
if (c.taxaServico) total += total * 0.10;
|
||||
return Math.max(total, 0);
|
||||
}
|
||||
|
||||
async function loadComandas(params?: { status?: string; dataInicio?: string; dataFim?: string }) {
|
||||
const list = document.getElementById('comandas-list')!;
|
||||
try {
|
||||
const qs = new URLSearchParams();
|
||||
if (params?.status) qs.set('status', params.status);
|
||||
if (params?.dataInicio) qs.set('dataInicio', params.dataInicio);
|
||||
if (params?.dataFim) qs.set('dataFim', params.dataFim);
|
||||
const query = qs.toString();
|
||||
const comandas = await api.get(`/comandas${query ? '?' + query : ''}`);
|
||||
localComandas = comandas;
|
||||
|
||||
if (!comandas.length) {
|
||||
list.innerHTML = `<p class="card-subtitle" style="text-align:center;margin-top:2rem;">Nenhuma comanda aberta no momento.</p>`;
|
||||
return;
|
||||
}
|
||||
list.innerHTML = `
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Identificador</th>
|
||||
<th>Cliente</th>
|
||||
<th>Aberto por</th>
|
||||
<th>Status</th>
|
||||
<th>Total</th>
|
||||
<th>Aberta em</th>
|
||||
<th>Ações</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${comandas.map((c: any) => `
|
||||
<tr>
|
||||
<td data-label="Mesa" class="cmd-ident"><strong>${c.identificador}</strong></td>
|
||||
<td data-label="Cliente" class="cmd-client">${c.nomeCliente ?? ''}</td>
|
||||
<td data-label="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>
|
||||
<td data-label="Ações" class="cmd-acoes">
|
||||
<button class="btn btn-sm btn-secondary" onclick="window.openDetails('${c.id}')">🔍 Ver</button>
|
||||
${c.status === 'ABERTA' ? `
|
||||
<button class="btn btn-sm btn-secondary" onclick="window.openAddItem('${c.id}')">+ Item</button>
|
||||
` : ''}
|
||||
</td>
|
||||
</tr>
|
||||
`).join('')}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
`;
|
||||
} catch (err: any) {
|
||||
list.innerHTML = `<p style="color:var(--accent-primary)">${err.message}</p>`;
|
||||
}
|
||||
}
|
||||
|
||||
function renderProductCards(products: any[]) {
|
||||
const grid = document.getElementById('modal-produtos-grid');
|
||||
if (!grid) return;
|
||||
|
||||
if (products.length === 0) {
|
||||
grid.innerHTML = '<p class="card-subtitle" style="grid-column: 1/-1; text-align: center; margin: 1rem 0;">Nenhum produto encontrado</p>';
|
||||
return;
|
||||
}
|
||||
|
||||
grid.innerHTML = products.map((p: any) => `
|
||||
<div class="product-mini-card" data-id="${p.id}" data-nome="${p.nome}" data-preco="${p.preco}">
|
||||
<div>
|
||||
<div class="product-mini-card-name">${p.nome}</div>
|
||||
<div class="product-mini-card-price">${formatBRL(p.preco)}</div>
|
||||
</div>
|
||||
<div class="product-mini-card-badge">
|
||||
${p.totalVendido !== undefined ? `Vendidos: ${p.totalVendido}` : (p.categoria?.nome ?? '')}
|
||||
</div>
|
||||
</div>
|
||||
`).join('');
|
||||
|
||||
const cards = grid.querySelectorAll('.product-mini-card');
|
||||
cards.forEach(card => {
|
||||
card.addEventListener('click', () => {
|
||||
cards.forEach(c => c.classList.remove('selected'));
|
||||
card.classList.add('selected');
|
||||
|
||||
const id = (card as HTMLElement).dataset.id!;
|
||||
const nome = (card as HTMLElement).dataset.nome!;
|
||||
const preco = parseFloat((card as HTMLElement).dataset.preco!);
|
||||
|
||||
(document.getElementById('selected-produto-id') as HTMLInputElement).value = id;
|
||||
const preview = document.getElementById('selected-produto-preview')!;
|
||||
preview.textContent = `Selecionado: ${nome} (${formatBRL(preco)})`;
|
||||
preview.style.color = 'var(--success)';
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function bindOrderEvents() {
|
||||
document.getElementById('btn-nova-comanda')?.addEventListener('click', () => {
|
||||
(document.getElementById('modal-nova-comanda') as HTMLElement).style.display = 'flex';
|
||||
});
|
||||
document.getElementById('modal-close')?.addEventListener('click', () => {
|
||||
(document.getElementById('modal-nova-comanda') as HTMLElement).style.display = 'none';
|
||||
});
|
||||
document.getElementById('modal-item-close')?.addEventListener('click', () => {
|
||||
(document.getElementById('modal-add-item') as HTMLElement).style.display = 'none';
|
||||
});
|
||||
document.getElementById('modal-detalhes-close')?.addEventListener('click', () => {
|
||||
(document.getElementById('modal-detalhes-comanda') as HTMLElement).style.display = 'none';
|
||||
});
|
||||
|
||||
document.getElementById('form-busca-comandas')?.addEventListener('submit', (e) => {
|
||||
e.preventDefault();
|
||||
const dataInicio = 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 });
|
||||
});
|
||||
|
||||
document.getElementById('btn-busca-limpar')?.addEventListener('click', () => {
|
||||
(document.getElementById('busca-data-inicio') as HTMLInputElement).value = '';
|
||||
(document.getElementById('busca-data-fim') as HTMLInputElement).value = '';
|
||||
loadComandas({ status: 'ABERTA,FECHADA' });
|
||||
});
|
||||
|
||||
document.getElementById('detalhes-edit-toggle')?.addEventListener('click', () => {
|
||||
const section = document.querySelector('.detalhes-edit-section');
|
||||
section?.classList.toggle('expanded');
|
||||
});
|
||||
|
||||
// Toggle motivo cancelamento visibility
|
||||
document.getElementById('detalhes-status')?.addEventListener('change', (e) => {
|
||||
const val = (e.target as HTMLSelectElement).value;
|
||||
const group = document.getElementById('motivo-cancelamento-group') as HTMLElement;
|
||||
if (group) group.style.display = val === 'CANCELADA' ? 'block' : 'none';
|
||||
});
|
||||
|
||||
document.getElementById('form-nova-comanda')?.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const ident = (document.getElementById('identificador') as HTMLInputElement).value;
|
||||
const nome = (document.getElementById('nomeCliente') as HTMLInputElement).value;
|
||||
try {
|
||||
await api.post('/comandas', { identificador: ident, nomeCliente: nome || undefined });
|
||||
toast('Comanda aberta com sucesso!', 'success');
|
||||
(document.getElementById('modal-nova-comanda') as HTMLElement).style.display = 'none';
|
||||
await loadComandas({ status: 'ABERTA,FECHADA' });
|
||||
} catch (err: any) {
|
||||
toast(err.message, 'error');
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById('form-editar-comanda')?.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const id = (document.getElementById('detalhes-comanda-id') as HTMLInputElement).value;
|
||||
const payload: any = {
|
||||
identificador: (document.getElementById('detalhes-identificador') as HTMLInputElement).value,
|
||||
nomeCliente: (document.getElementById('detalhes-cliente') as HTMLInputElement).value || undefined,
|
||||
status: (document.getElementById('detalhes-status') as HTMLSelectElement).value,
|
||||
desconto: parseFloat((document.getElementById('detalhes-desconto') as HTMLInputElement).value) || 0,
|
||||
acrescimo: parseFloat((document.getElementById('detalhes-acrescimo') as HTMLInputElement).value) || 0,
|
||||
taxaServico: (document.getElementById('detalhes-taxa-servico') as HTMLInputElement).checked,
|
||||
motivoCancelamento: (document.getElementById('detalhes-motivo-cancelamento') as HTMLInputElement).value || undefined,
|
||||
};
|
||||
|
||||
try {
|
||||
await api.patch(`/comandas/${id}`, payload);
|
||||
toast('Comanda atualizada!', 'success');
|
||||
(document.getElementById('modal-detalhes-comanda') as HTMLElement).style.display = 'none';
|
||||
await loadComandas({ status: 'ABERTA,FECHADA' });
|
||||
} catch (err: any) {
|
||||
toast(err.message, 'error');
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById('form-add-item')?.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const comandaId = (document.getElementById('current-comanda-id') as HTMLInputElement).value;
|
||||
const produtoId = (document.getElementById('selected-produto-id') as HTMLInputElement).value;
|
||||
if (!produtoId) {
|
||||
toast('Por favor, selecione um produto nos cards acima!', 'error');
|
||||
return;
|
||||
}
|
||||
const quantidade = parseInt((document.getElementById('qtd') as HTMLInputElement).value);
|
||||
const observacao = (document.getElementById('obs') as HTMLInputElement).value;
|
||||
try {
|
||||
await api.post(`/comandas/${comandaId}/itens`, { produtoId, quantidade, observacao: observacao || undefined });
|
||||
toast('Pedido enviado para preparo!', 'success');
|
||||
|
||||
(document.getElementById('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');
|
||||
}
|
||||
});
|
||||
|
||||
const buscaInput = document.getElementById('modal-produto-busca') as HTMLInputElement;
|
||||
let timer: any;
|
||||
buscaInput?.addEventListener('input', () => {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(async () => {
|
||||
const query = buscaInput.value.trim();
|
||||
const gridLabel = document.getElementById('grid-label')!;
|
||||
try {
|
||||
if (query.length > 0) {
|
||||
gridLabel.textContent = 'Resultados da Busca';
|
||||
const products = await api.get(`/produtos/busca?q=${encodeURIComponent(query)}`);
|
||||
renderProductCards(products);
|
||||
} else {
|
||||
gridLabel.textContent = 'Produtos Sugeridos (Mais Vendidos)';
|
||||
const topProducts = await api.get('/produtos/mais-vendidos');
|
||||
renderProductCards(topProducts);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
}, 300);
|
||||
});
|
||||
|
||||
// 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 = '';
|
||||
const buscaInput = document.getElementById('modal-produto-busca') as HTMLInputElement;
|
||||
if (buscaInput) buscaInput.value = '';
|
||||
|
||||
const preview = document.getElementById('selected-produto-preview')!;
|
||||
preview.textContent = 'Nenhum produto selecionado';
|
||||
preview.style.color = 'var(--accent-primary)';
|
||||
|
||||
const gridLabel = document.getElementById('grid-label');
|
||||
if (gridLabel) gridLabel.textContent = 'Produtos Sugeridos (Mais Vendidos)';
|
||||
|
||||
(document.getElementById('modal-add-item') as HTMLElement).style.display = 'flex';
|
||||
|
||||
try {
|
||||
const topProducts = await api.get('/produtos/mais-vendidos');
|
||||
renderProductCards(topProducts);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
};
|
||||
|
||||
(window as any).openDetails = (comandaId: string) => {
|
||||
const c = localComandas.find((x: any) => x.id === comandaId);
|
||||
if (!c) return;
|
||||
|
||||
(document.getElementById('detalhes-comanda-id') as HTMLInputElement).value = c.id;
|
||||
(document.getElementById('detalhes-identificador') as HTMLInputElement).value = c.identificador;
|
||||
(document.getElementById('detalhes-cliente') as HTMLInputElement).value = c.nomeCliente ?? '';
|
||||
(document.getElementById('detalhes-status') as HTMLSelectElement).value = c.status;
|
||||
(document.getElementById('detalhes-forma-pagamento') as HTMLSelectElement).value = c.formaPagamento ?? '';
|
||||
(document.getElementById('detalhes-desconto') as HTMLInputElement).value = c.desconto ?? 0;
|
||||
(document.getElementById('detalhes-acrescimo') as HTMLInputElement).value = c.acrescimo ?? 0;
|
||||
(document.getElementById('detalhes-taxa-servico') as HTMLInputElement).checked = c.taxaServico ?? false;
|
||||
(document.getElementById('detalhes-motivo-cancelamento') as HTMLInputElement).value = c.motivoCancelamento ?? '';
|
||||
|
||||
// Show/hide motivo cancelamento
|
||||
const motivoGroup = document.getElementById('motivo-cancelamento-group') as HTMLElement;
|
||||
if (motivoGroup) motivoGroup.style.display = c.status === 'CANCELADA' ? 'block' : 'none';
|
||||
|
||||
// Summary labels
|
||||
document.getElementById('detalhes-label-ident')!.textContent = c.identificador;
|
||||
document.getElementById('detalhes-label-client')!.textContent = c.nomeCliente ? `· ${c.nomeCliente}` : '';
|
||||
document.getElementById('detalhes-label-status')!.innerHTML = statusBadge(c.status);
|
||||
|
||||
// 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 ?? [];
|
||||
const user = getUser();
|
||||
const canDelete = user && ['ADMIN', 'CAIXA'].includes(user.role) && c.status === 'ABERTA';
|
||||
|
||||
if (itens.length === 0) {
|
||||
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">
|
||||
${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 ? `
|
||||
<button class="btn btn-sm btn-danger btn-delete-item" data-id="${i.id}" data-nome="${i.produto?.nome ?? 'item'}">🗑</button>
|
||||
` : ''}
|
||||
</td>
|
||||
</tr>
|
||||
`).join('');
|
||||
}
|
||||
|
||||
if (canDelete) {
|
||||
tbody.querySelectorAll('.btn-delete-item').forEach(btn => {
|
||||
btn.addEventListener('click', async () => {
|
||||
const itemId = (btn as HTMLElement).dataset.id!;
|
||||
const itemNome = (btn as HTMLElement).dataset.nome!;
|
||||
if (!confirm(`Remover "${itemNome}" da comanda?`)) return;
|
||||
try {
|
||||
await api.delete(`/comandas/itens/${itemId}`);
|
||||
toast('Item removido!', 'success');
|
||||
await loadComandas({ status: 'ABERTA,FECHADA' });
|
||||
(document.getElementById('modal-detalhes-comanda') as HTMLElement).style.display = 'none';
|
||||
(window as any).openDetails(comandaId);
|
||||
} catch (err: any) {
|
||||
toast(err.message, 'error');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// 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
|
||||
const resumoEl = document.getElementById('detalhes-resumo-financeiro')!;
|
||||
const subtotal = c.total || 0;
|
||||
const desconto = c.desconto || 0;
|
||||
const acrescimo = c.acrescimo || 0;
|
||||
const taxaServico = c.taxaServico ? (subtotal - desconto + acrescimo) * 0.10 : 0;
|
||||
const totalFinal = Math.max(subtotal - desconto + acrescimo + taxaServico, 0);
|
||||
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;">
|
||||
<div style="display:flex;justify-content:space-between;margin-bottom:0.25rem;">
|
||||
<span style="color:var(--text-secondary);">Subtotal:</span>
|
||||
<span>${formatBRL(subtotal)}</span>
|
||||
</div>
|
||||
${desconto > 0 ? `<div style="display:flex;justify-content:space-between;margin-bottom:0.25rem;color:var(--warning);">
|
||||
<span>Desconto:</span><span>-${formatBRL(desconto)}</span>
|
||||
</div>` : ''}
|
||||
${acrescimo > 0 ? `<div style="display:flex;justify-content:space-between;margin-bottom:0.25rem;color:var(--accent-secondary);">
|
||||
<span>Acréscimo:</span><span>+${formatBRL(acrescimo)}</span>
|
||||
</div>` : ''}
|
||||
${c.taxaServico ? `<div style="display:flex;justify-content:space-between;margin-bottom:0.25rem;color:var(--text-secondary);">
|
||||
<span>Taxa Serviço (10%):</span><span>+${formatBRL(taxaServico)}</span>
|
||||
</div>` : ''}
|
||||
${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(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' && restante > 0) {
|
||||
acoesContainer.innerHTML = `
|
||||
<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>
|
||||
`;
|
||||
|
||||
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 });
|
||||
toast('Pagamento registrado!', 'success');
|
||||
(document.getElementById('modal-detalhes-comanda') as HTMLElement).style.display = 'none';
|
||||
await loadComandas({ status: 'ABERTA,FECHADA' });
|
||||
} catch (err: any) {
|
||||
toast(err.message, 'error');
|
||||
}
|
||||
});
|
||||
} 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);
|
||||
}
|
||||
}
|
||||
156
web/src/views/users.ts
Normal file
156
web/src/views/users.ts
Normal file
@@ -0,0 +1,156 @@
|
||||
import { api } from '../api';
|
||||
import { renderNavbar, toast, roleBadge } from '../utils';
|
||||
|
||||
const ROLE_OPTIONS = ['ADMIN', 'CAIXA', 'GARCOM', 'COZINHA', 'BARMAN'];
|
||||
|
||||
export async function renderUsers(container: HTMLElement) {
|
||||
container.innerHTML = `
|
||||
${renderNavbar('/users')}
|
||||
<div class="container animate-fade-in">
|
||||
<div class="page-header">
|
||||
<h1>Equipe 👥</h1>
|
||||
<button class="btn" id="btn-novo-usuario">+ Novo Usuário</button>
|
||||
</div>
|
||||
<div id="users-list"><p class="card-subtitle">Carregando...</p></div>
|
||||
</div>
|
||||
|
||||
<!-- Modal Usuário -->
|
||||
<div id="modal-usuario" class="modal-overlay" style="display:none;">
|
||||
<div class="modal">
|
||||
<div class="modal-header">
|
||||
<h3 id="modal-user-title">Novo Usuário</h3>
|
||||
<button class="btn-icon" onclick="document.getElementById('modal-usuario').style.display='none'">✕</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form id="form-usuario">
|
||||
<input type="hidden" id="user-id">
|
||||
<div class="form-group">
|
||||
<label>Nome Completo *</label>
|
||||
<input type="text" id="u-nome" class="form-control" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>E-mail *</label>
|
||||
<input type="email" id="u-email" class="form-control" required>
|
||||
</div>
|
||||
<div class="form-group" id="senha-group">
|
||||
<label>Senha *</label>
|
||||
<input type="password" id="u-senha" class="form-control" placeholder="Mínimo 6 caracteres">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Cargo (Role) *</label>
|
||||
<select id="u-role" class="form-control" required>
|
||||
${ROLE_OPTIONS.map(r => `<option value="${r}">${r}</option>`).join('')}
|
||||
</select>
|
||||
</div>
|
||||
<div style="display:flex;align-items:center;gap:0.75rem;margin-bottom:1.5rem;">
|
||||
<input type="checkbox" id="u-ativo" checked>
|
||||
<label for="u-ativo" style="cursor:pointer;color:var(--text-primary);">Usuário Ativo</label>
|
||||
</div>
|
||||
<button type="submit" class="btn" style="width:100%;">Salvar</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
await loadUsers();
|
||||
bindUserEvents();
|
||||
}
|
||||
|
||||
async function loadUsers() {
|
||||
const list = document.getElementById('users-list')!;
|
||||
try {
|
||||
const users = await api.get('/usuarios');
|
||||
list.innerHTML = `
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr><th>Nome</th><th>E-mail</th><th>Cargo</th><th>Status</th><th>Desde</th><th>Ações</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${users.map((u: any) => `
|
||||
<tr>
|
||||
<td data-label="Nome"><strong>${u.nome}</strong></td>
|
||||
<td data-label="E-mail" style="color:var(--text-secondary)">${u.email}</td>
|
||||
<td data-label="Cargo">${roleBadge(u.role)}</td>
|
||||
<td data-label="Status"><span class="badge ${u.ativo ? 'badge-success' : 'badge-warning'}">${u.ativo ? 'Ativo' : 'Inativo'}</span></td>
|
||||
<td data-label="Desde" style="color:var(--text-secondary)">${new Date(u.criadoEm).toLocaleDateString('pt-BR')}</td>
|
||||
<td data-label="Ações" style="display:flex;gap:0.5rem;flex-wrap:wrap;">
|
||||
<button class="btn btn-sm btn-secondary" onclick="window.editUser(${JSON.stringify(u).replace(/"/g, '"')})">✏️ Editar</button>
|
||||
<button class="btn btn-sm btn-danger" onclick="window.toggleUser('${u.id}','${u.nome}',${u.ativo})">
|
||||
${u.ativo ? '🚫 Desativar' : '✅ Ativar'}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
`).join('')}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
`;
|
||||
} catch (err: any) {
|
||||
list.innerHTML = `<p style="color:var(--accent-primary)">Erro: ${err.message}</p>`;
|
||||
}
|
||||
}
|
||||
|
||||
function bindUserEvents() {
|
||||
document.getElementById('btn-novo-usuario')?.addEventListener('click', () => {
|
||||
clearUserForm();
|
||||
(document.getElementById('modal-usuario') as HTMLElement).style.display = 'flex';
|
||||
(document.getElementById('u-senha') as HTMLInputElement).required = true;
|
||||
(document.getElementById('senha-group') as HTMLElement).style.display = 'block';
|
||||
});
|
||||
|
||||
document.getElementById('form-usuario')?.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const id = (document.getElementById('user-id') as HTMLInputElement).value;
|
||||
const senha = (document.getElementById('u-senha') as HTMLInputElement).value;
|
||||
const payload: any = {
|
||||
nome: (document.getElementById('u-nome') as HTMLInputElement).value,
|
||||
email: (document.getElementById('u-email') as HTMLInputElement).value,
|
||||
role: (document.getElementById('u-role') as HTMLSelectElement).value,
|
||||
ativo: (document.getElementById('u-ativo') as HTMLInputElement).checked,
|
||||
};
|
||||
if (!id) payload.senha = senha;
|
||||
|
||||
try {
|
||||
if (id) await api.patch(`/usuarios/${id}`, payload);
|
||||
else await api.post('/usuarios', { ...payload, senha });
|
||||
toast(id ? 'Usuário atualizado!' : 'Usuário cadastrado!', 'success');
|
||||
(document.getElementById('modal-usuario') as HTMLElement).style.display = 'none';
|
||||
await loadUsers();
|
||||
} catch (err: any) { toast(err.message, 'error'); }
|
||||
});
|
||||
|
||||
(window as any).editUser = (u: any) => {
|
||||
(document.getElementById('user-id') as HTMLInputElement).value = u.id;
|
||||
(document.getElementById('u-nome') as HTMLInputElement).value = u.nome;
|
||||
(document.getElementById('u-email') as HTMLInputElement).value = u.email;
|
||||
(document.getElementById('u-role') as HTMLSelectElement).value = u.role;
|
||||
(document.getElementById('u-ativo') as HTMLInputElement).checked = u.ativo;
|
||||
(document.getElementById('u-senha') as HTMLInputElement).required = false;
|
||||
(document.getElementById('u-senha') as HTMLInputElement).value = '';
|
||||
(document.getElementById('senha-group') as HTMLElement).style.display = 'none';
|
||||
(document.getElementById('modal-user-title') as HTMLElement).textContent = 'Editar Usuário';
|
||||
(document.getElementById('modal-usuario') as HTMLElement).style.display = 'flex';
|
||||
};
|
||||
|
||||
(window as any).toggleUser = async (id: string, nome: string, ativo: boolean) => {
|
||||
const action = ativo ? 'desativar' : 'ativar';
|
||||
if (!confirm(`Deseja ${action} o usuário "${nome}"?`)) return;
|
||||
try {
|
||||
await api.patch(`/usuarios/${id}`, { ativo: !ativo });
|
||||
toast(`Usuário ${ativo ? 'desativado' : 'ativado'}!`, 'success');
|
||||
await loadUsers();
|
||||
} catch (err: any) { toast(err.message, 'error'); }
|
||||
};
|
||||
}
|
||||
|
||||
function clearUserForm() {
|
||||
(document.getElementById('user-id') as HTMLInputElement).value = '';
|
||||
(document.getElementById('u-nome') as HTMLInputElement).value = '';
|
||||
(document.getElementById('u-email') as HTMLInputElement).value = '';
|
||||
(document.getElementById('u-senha') as HTMLInputElement).value = '';
|
||||
(document.getElementById('u-role') as HTMLSelectElement).value = 'GARCOM';
|
||||
(document.getElementById('u-ativo') as HTMLInputElement).checked = true;
|
||||
(document.getElementById('modal-user-title') as HTMLElement).textContent = 'Novo Usuário';
|
||||
}
|
||||
24
web/tsconfig.json
Normal file
24
web/tsconfig.json
Normal file
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es2023",
|
||||
"module": "esnext",
|
||||
"lib": ["ES2023", "DOM"],
|
||||
"types": ["vite/client"],
|
||||
"allowArbitraryExtensions": true,
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
Reference in New Issue
Block a user