adicionado 0 na escal de nota

This commit is contained in:
Luiz Silva 2026-01-05 08:57:14 -03:00
parent 0bbd04ee45
commit e8ca410b94
8 changed files with 72 additions and 15 deletions

View file

@ -120,7 +120,8 @@ CREATE TABLE IF NOT EXISTS %s (
pedido_criado_em timestamptz NOT NULL DEFAULT now(),
respondido_em timestamptz NULL,
atualizado_em timestamptz NOT NULL DEFAULT now(),
nota int NULL CHECK (nota BETWEEN 1 AND 10),
-- Escala NPS do projeto: 010.
nota int NULL CHECK (nota BETWEEN 0 AND 10),
justificativa text NULL,
valida bool NOT NULL DEFAULT true,
origem text NOT NULL DEFAULT 'widget_iframe',
@ -135,6 +136,43 @@ ALTER TABLE %s ADD COLUMN IF NOT EXISTS usuario_codigo text;
ALTER TABLE %s ADD COLUMN IF NOT EXISTS produto_nome text NOT NULL DEFAULT '';
ALTER TABLE %s ADD COLUMN IF NOT EXISTS ip_real text;
-- Migração defensiva (em runtime) da constraint de nota.
--
-- Motivação:
-- - Em versões anteriores a escala era 110.
-- - As tabelas por produto são criadas automaticamente; portanto, podem existir
-- tabelas antigas com CHECK antigo em nota.
--
-- Estratégia:
-- - Remover qualquer CHECK existente que mencione a coluna nota.
-- - Recriar uma constraint nomeada ck_nota_0_10 com a regra atual (010).
--
-- Segurança: tableName é validado por TableNameValido (regex) antes de ser
-- interpolado e usado como regclass/identificador.
DO $$
DECLARE c record;
BEGIN
FOR c IN
SELECT conname
FROM pg_constraint
WHERE conrelid = '%s'::regclass
AND contype='c'
AND pg_get_constraintdef(oid) ILIKE '%%nota%%'
LOOP
EXECUTE format('ALTER TABLE %%I DROP CONSTRAINT %%I', '%s', c.conname);
END LOOP;
IF NOT EXISTS (
SELECT 1
FROM pg_constraint
WHERE conrelid = '%s'::regclass
AND contype='c'
AND conname='ck_nota_0_10'
) THEN
EXECUTE format('ALTER TABLE %%I ADD CONSTRAINT ck_nota_0_10 CHECK (nota BETWEEN 0 AND 10)', '%s');
END IF;
END$$;
-- NOTE: controle de exibição é por (produto + inquilino_codigo + usuario_codigo)
-- então os índices são baseados em usuario_codigo.
@ -145,7 +183,20 @@ CREATE INDEX IF NOT EXISTS idx_nps_resp_recente_%s
CREATE INDEX IF NOT EXISTS idx_nps_pedido_aberto_%s
ON %s (inquilino_codigo, usuario_codigo, pedido_criado_em DESC)
WHERE status='pedido';
`, tableName, tableName, tableName, tableName, tableName, tableName, tableName, tableName)
`,
tableName, // CREATE TABLE
tableName, // ALTER TABLE add usuario_codigo
tableName, // ALTER TABLE add produto_nome
tableName, // ALTER TABLE add ip_real
tableName, // DO block: conrelid (1)
tableName, // DO block: DROP CONSTRAINT (identificador)
tableName, // DO block: conrelid (2)
tableName, // DO block: ADD CONSTRAINT (identificador)
tableName, // idx_nps_resp_recente_%s
tableName, // ON %s
tableName, // idx_nps_pedido_aberto_%s
tableName, // ON %s
)
_, err := pool.Exec(ctx, q)
return err

View file

@ -40,8 +40,8 @@ ORDER BY tablename`)
// NPSMesAMes calcula o NPS por mês para um produto (tabela `nps_{produto}`).
//
// Regra NPS (110):
// - 16 detratores
// Regra NPS (010):
// - 06 detratores
// - 78 neutros
// - 910 promotores
func (s *Store) NPSMesAMes(ctx context.Context, tabela string, meses int) ([]contratos.NPSMensal, error) {
@ -62,7 +62,7 @@ WITH base AS (
)
SELECT
to_char(mes, 'YYYY-MM') AS mes,
SUM(CASE WHEN nota BETWEEN 1 AND 6 THEN 1 ELSE 0 END)::int AS detratores,
SUM(CASE WHEN nota BETWEEN 0 AND 6 THEN 1 ELSE 0 END)::int AS detratores,
SUM(CASE WHEN nota BETWEEN 7 AND 8 THEN 1 ELSE 0 END)::int AS neutros,
SUM(CASE WHEN nota BETWEEN 9 AND 10 THEN 1 ELSE 0 END)::int AS promotores,
COUNT(*)::int AS total
@ -116,7 +116,7 @@ func (s *Store) ListarRespostas(ctx context.Context, tabela string, filtro Lista
cond := "status='respondido' AND valida=true"
if filtro.SomenteNotasBaixas {
cond += " AND nota BETWEEN 1 AND 6"
cond += " AND nota BETWEEN 0 AND 6"
}
// Importante (segurança): apesar do cond ser construído em string, ele NÃO usa
@ -180,7 +180,7 @@ func (s *Store) ExportarRespostas(ctx context.Context, tabela string, filtro Exp
cond := "status='respondido' AND valida=true"
if filtro.SomenteNotasBaixas {
cond += " AND nota BETWEEN 1 AND 6"
cond += " AND nota BETWEEN 0 AND 6"
}
// Sem LIMIT/OFFSET (export completo).

View file

@ -53,7 +53,8 @@ func ValidatePedidoInput(in *contratos.PedidoInput) error {
func ValidatePatchInput(in *contratos.PatchInput) error {
if in.Nota != nil {
if *in.Nota < 1 || *in.Nota > 10 {
// Regra do produto: escala NPS é 010.
if *in.Nota < 0 || *in.Nota > 10 {
return errors.New("nota invalida")
}
}