Balcão+

Arquitetura do sistema

Modelo do banco, organização do projeto e fluxo de tempo real.

-- Esquema do banco (PostgreSQL / Supabase) — Realtime ligado em pedidos, itens_pedido, mesas e tickets_kds

create table lojas (
  id uuid primary key default gen_random_uuid(),
  nome text not null, cnpj text, taxa_servico numeric(5,2) default 10,
  couvert numeric(10,2) default 0, regra_pizza text check (regra_pizza in ('media','maior')) default 'maior',
  kds_amarelo_min int default 8, kds_vermelho_min int default 15
);

create table usuarios (
  id uuid primary key references auth.users, loja_id uuid references lojas,
  nome text not null, papel text check (papel in ('dono','gerente','caixa','garcom','cozinha','entregador'))
);

create table categorias (id uuid primary key default gen_random_uuid(), loja_id uuid references lojas, nome text, ordem int);
create table pracas (id uuid primary key default gen_random_uuid(), loja_id uuid references lojas, nome text); -- Forno, Bar, Chapa

create table produtos (
  id uuid primary key default gen_random_uuid(), loja_id uuid references lojas,
  categoria_id uuid references categorias, praca_id uuid references pracas,
  nome text not null, ean text, sku text,
  tipo text check (tipo in ('simples','pizza','combo','insumo')) default 'simples',
  unidade text check (unidade in ('un','kg','g','ml','l')) default 'un',
  preco numeric(10,2), custo numeric(10,4), controla_estoque bool default true,
  estoque_minimo numeric(12,3) default 0, ativo bool default true
);
create unique index on produtos (loja_id, ean) where ean is not null;

-- Pizzas: sabores são produtos tipo 'pizza'; tamanhos e opções configuráveis
create table tamanhos_pizza (id uuid primary key default gen_random_uuid(), loja_id uuid references lojas, nome text, fatias int, max_sabores int, fator_preco numeric(5,3));
create table opcoes_produto (id uuid primary key default gen_random_uuid(), loja_id uuid references lojas, grupo text check (grupo in ('borda','massa','adicional')), nome text, preco numeric(10,2), insumo_id uuid references produtos, qtd_insumo numeric(12,3));

-- Ficha técnica e combos (baixa automática)
create table fichas_tecnicas (produto_id uuid references produtos, insumo_id uuid references produtos, quantidade numeric(12,3), primary key (produto_id, insumo_id));
create table combo_itens (combo_id uuid references produtos, produto_id uuid references produtos, quantidade numeric(12,3), primary key (combo_id, produto_id));

create table lotes (
  id uuid primary key default gen_random_uuid(), produto_id uuid references produtos,
  codigo text, validade date, quantidade numeric(12,3), custo_unit numeric(10,4), criado_em timestamptz default now()
);
create table movimentos_estoque (
  id bigserial primary key, produto_id uuid references produtos, lote_id uuid references lotes,
  tipo text check (tipo in ('entrada','venda','perda','ajuste','producao')), quantidade numeric(12,3),
  item_pedido_id uuid, usuario_id uuid references usuarios, criado_em timestamptz default now()
);

create table mesas (
  id uuid primary key default gen_random_uuid(), loja_id uuid references lojas, numero int, lugares int,
  forma text, pos_x int, pos_y int,
  status text check (status in ('livre','ocupada','pagamento','reservada')) default 'livre'
);
create table reservas (id uuid primary key default gen_random_uuid(), mesa_id uuid references mesas, cliente text, telefone text, para timestamptz, pessoas int);

create table clientes (id uuid primary key default gen_random_uuid(), loja_id uuid references lojas, nome text, telefone text, endereco text, bairro text, lat numeric, lng numeric);
create table entregadores (id uuid primary key default gen_random_uuid(), loja_id uuid references lojas, usuario_id uuid references usuarios, nome text, placa text, diaria numeric(10,2), ativo bool default true);
create table taxas_entrega (id uuid primary key default gen_random_uuid(), loja_id uuid references lojas, bairro text, km_ate numeric(5,2), valor numeric(10,2));

create table pedidos (
  id uuid primary key default gen_random_uuid(), loja_id uuid references lojas, numero serial,
  canal text check (canal in ('balcao','mesa','delivery')),
  origem text check (origem in ('balcao','ifood','rappi','whatsapp','proprio')),
  id_externo text, codigo_coleta text, payload_externo jsonb,          -- webhook iFood/Rappi
  mesa_id uuid references mesas, cliente_id uuid references clientes, entregador_id uuid references entregadores,
  etapa text check (etapa in ('novo','preparo','pronto','rota','concluido','cancelado')) default 'novo',
  subtotal numeric(10,2), desconto numeric(10,2) default 0, taxa_servico numeric(10,2) default 0,
  couvert numeric(10,2) default 0, taxa_entrega numeric(10,2) default 0, total numeric(10,2),
  caixa_id uuid, criado_em timestamptz default now(), aceito_em timestamptz, concluido_em timestamptz
);
create unique index on pedidos (loja_id, origem, id_externo) where id_externo is not null;

create table comandas (id uuid primary key default gen_random_uuid(), pedido_id uuid references pedidos, nome text, fechada bool default false);

create table itens_pedido (
  id uuid primary key default gen_random_uuid(), pedido_id uuid references pedidos, comanda_id uuid references comandas,
  produto_id uuid references produtos, tamanho_id uuid references tamanhos_pizza,
  descricao text, quantidade numeric(12,3), preco_unit numeric(10,2), obs text,
  praca_id uuid references pracas, status_kds text check (status_kds in ('fila','preparo','pronto','entregue')) default 'fila',
  enviado_em timestamptz default now(), pronto_em timestamptz
);
create table itens_pedido_sabores (item_id uuid references itens_pedido, sabor_id uuid references produtos, fracao numeric(4,3)); -- 0.5, 0.333, 0.25
create table itens_pedido_opcoes (item_id uuid references itens_pedido, opcao_id uuid references opcoes_produto, preco numeric(10,2));

create table caixas (
  id uuid primary key default gen_random_uuid(), loja_id uuid references lojas, operador_id uuid references usuarios,
  aberto_em timestamptz default now(), fundo numeric(10,2), fechado_em timestamptz,
  valor_informado numeric(10,2), valor_esperado numeric(10,2), diferenca numeric(10,2)  -- fechamento cego
);
create table movimentos_caixa (id bigserial primary key, caixa_id uuid references caixas, tipo text check (tipo in ('sangria','suprimento')), valor numeric(10,2), motivo text, criado_em timestamptz default now());
create table pagamentos (id uuid primary key default gen_random_uuid(), pedido_id uuid references pedidos, caixa_id uuid references caixas, forma text check (forma in ('dinheiro','pix','credito','debito','online','voucher')), valor numeric(10,2), troco numeric(10,2) default 0, comanda_id uuid references comandas, criado_em timestamptz default now());

-- Gatilho: ao inserir item_pedido, baixa estoque pela ficha técnica / combo
-- create function baixar_estoque() returns trigger ... ;