Compare commits
No commits in common. "0c41ed4279834aad7910d70601a733141d40b1f5" and "6873b87a85fd924528e942ff85cd59f11772b5aa" have entirely different histories.
0c41ed4279
...
6873b87a85
22 changed files with 225 additions and 1489 deletions
150
.agent
150
.agent
|
|
@ -1,150 +0,0 @@
|
|||
# arquivo: .agent
|
||||
# Agente de desenvolvimento para o projeto e-li.nps
|
||||
#
|
||||
# Projeto:
|
||||
# Widget NPS embutível via 1 arquivo JS + API em Go.
|
||||
# Foco em robustez, segurança, tipagem consistente, observabilidade
|
||||
# e operação simples em ambientes reais (Docker / Proxy / Produção).
|
||||
|
||||
agent_name: "quero_nps"
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
# Descrição do projeto (fonte de verdade)
|
||||
# -------------------------------------------------------------------
|
||||
project_description:
|
||||
- "Widget NPS carregado via 1 arquivo JavaScript (e-li.nps.js)."
|
||||
- "API HTTP escrita em Go."
|
||||
- "PostgreSQL como banco de dados."
|
||||
- "Painel administrativo opcional protegido por senha."
|
||||
- "Uso por aplicações externas via <script>."
|
||||
- "Fail-closed: se a API falhar, o widget não abre."
|
||||
- "CORS liberado para uso amplo."
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
# Stack
|
||||
# -------------------------------------------------------------------
|
||||
project_stack:
|
||||
backend: "Go 1.22+"
|
||||
database: "PostgreSQL 14+"
|
||||
widget: "JavaScript puro (arquivo único)"
|
||||
frontend_internal:
|
||||
- "HTML server-side"
|
||||
- "HTMX (opcional, apenas se já estiver presente no painel)"
|
||||
optional_logic_layer:
|
||||
- "Go → WebAssembly (WASM), apenas se adotado explicitamente no projeto"
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
# Regras gerais
|
||||
# -------------------------------------------------------------------
|
||||
rules:
|
||||
- "Respeitar fielmente o comportamento descrito no README.md."
|
||||
- "Não alterar contratos públicos do widget sem versionamento."
|
||||
- "Evitar mudanças que quebrem widgets já embedados em clientes."
|
||||
- "Mudanças que impactem desenvolvedores OU usuários DEVEM ser documentadas."
|
||||
- "Código deve ser previsível, explícito e fácil de auditar."
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
# Linguagem, nomes e comentários
|
||||
# -------------------------------------------------------------------
|
||||
naming_and_language:
|
||||
- "Nomes de variáveis, funções e arquivos preferencialmente em português."
|
||||
- "Nomes orientados ao domínio NPS (ex: `registrarPedido`, `finalizarResposta`)."
|
||||
- "Comentários SEMPRE em português."
|
||||
- "Comentários devem explicar regras de negócio e decisões técnicas."
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
# Contratos e tipagens
|
||||
# -------------------------------------------------------------------
|
||||
typing_and_contracts:
|
||||
- "Contratos de API devem ser explícitos e estáveis."
|
||||
- "Campos-chave das regras de exibição: produto + inquilino_codigo + usuario_codigo."
|
||||
- "Normalizações técnicas NÃO alteram valores exibidos ao usuário."
|
||||
- "Tipagens JS/TS são auxiliares e não substituem validação no backend."
|
||||
- "Validação SEMPRE no servidor."
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
# Widget JavaScript
|
||||
# -------------------------------------------------------------------
|
||||
widget_policy:
|
||||
- "Widget deve ser carregado via um único <script>."
|
||||
- "Nenhuma dependência externa no cliente."
|
||||
- "Cache controlado exclusivamente pelo servidor via ETag."
|
||||
- "Browser sempre revalida o JS."
|
||||
- "Se a API falhar, o widget NÃO deve abrir (fail-closed)."
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
# Backend Go
|
||||
# -------------------------------------------------------------------
|
||||
backend_policy:
|
||||
- "Servidor Go é a autoridade de regras e persistência."
|
||||
- "Tabelas criadas automaticamente por produto: nps_{produto}."
|
||||
- "Normalização de produto SOMENTE para uso técnico."
|
||||
- "Nunca usar dados não normalizados em SQL."
|
||||
- "Painel só habilita se SENHA_PAINEL estiver definida."
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
# Segurança: prevenção de SQL Injection (OBRIGATÓRIO)
|
||||
# -------------------------------------------------------------------
|
||||
sql_injection_prevention:
|
||||
- "NUNCA concatenar SQL com entrada do usuário."
|
||||
- "Usar queries parametrizadas SEMPRE."
|
||||
- "Identificadores dinâmicos SOMENTE via normalização + regex + allowlist."
|
||||
- "Regex obrigatória: ^[a-z_][a-z0-9_]*$."
|
||||
- "ORDER BY dinâmico apenas com colunas previamente definidas."
|
||||
- "Toda decisão dinâmica de SQL deve ser comentada."
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
# Observabilidade e logs (OBRIGATÓRIO)
|
||||
# -------------------------------------------------------------------
|
||||
logging_policy:
|
||||
- "Registrar logs relevantes em toda a aplicação."
|
||||
- "Logar: inicialização, rotas, chamadas de API, banco e erros."
|
||||
- "Registrar tempo de execução das requisições."
|
||||
- "Incluir IP real do usuário quando disponível."
|
||||
- "Evitar log excessivo ou redundante."
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
# Proteção de segredos nos logs (CRÍTICO)
|
||||
# -------------------------------------------------------------------
|
||||
secrets_policy:
|
||||
- "NUNCA logar senhas, tokens, cookies, Authorization, secrets ou DSN."
|
||||
- "Campos sensíveis devem ser omitidos ou mascarados."
|
||||
- "Na dúvida, NÃO LOGAR."
|
||||
- "Usar '[REDACTED]' quando necessário."
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
# Proxy e IP real
|
||||
# -------------------------------------------------------------------
|
||||
proxy_policy:
|
||||
- "Respeitar X-Forwarded-For e X-Real-IP."
|
||||
- "Uso de middleware RealIP é obrigatório."
|
||||
- "Persistir IP real para auditoria."
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
# README.md — regra OBRIGATÓRIA
|
||||
# -------------------------------------------------------------------
|
||||
readme_policy:
|
||||
- "O README.md é a fonte de verdade operacional do projeto."
|
||||
- "SE a mudança for IMPORTANTE para o DESENVOLVEDOR, atualizar o README.md."
|
||||
- "SE a mudança for IMPORTANTE para o USUÁRIO, atualizar o README.md."
|
||||
- "Considera-se mudança importante:"
|
||||
- "– alteração de API, contrato ou payload"
|
||||
- "– mudança no widget ou forma de embed"
|
||||
- "– cache, ETag ou comportamento de atualização"
|
||||
- "– variáveis de ambiente"
|
||||
- "– segurança, CORS, autenticação ou painel"
|
||||
- "– forma de rodar, build ou deploy"
|
||||
- "O README deve explicar o impacto da mudança e como usar o novo comportamento."
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
# Checklist final
|
||||
# -------------------------------------------------------------------
|
||||
checklist:
|
||||
- "[ ] Compatível com widgets já publicados"
|
||||
- "[ ] SQL 100% parametrizado"
|
||||
- "[ ] Identificadores normalizados e validados"
|
||||
- "[ ] Logs relevantes presentes"
|
||||
- "[ ] Nenhum segredo em logs"
|
||||
- "[ ] Cache do JS controlado por ETag"
|
||||
- "[ ] README.md atualizado se a mudança impacta dev ou usuário"
|
||||
- "[ ] Fluxo principal testado manualmente"
|
||||
|
|
@ -13,13 +13,6 @@ RUN go mod download
|
|||
|
||||
COPY . .
|
||||
|
||||
# Build do WASM do widget (regras de negócio no cliente)
|
||||
# Importante: a compilação do WASM exige GOOS=js/GOARCH=wasm.
|
||||
RUN GOOS=js GOARCH=wasm go build -trimpath -ldflags="-s -w" -o web/static/e-li.nps.wasm ./cmd/widgetwasm
|
||||
|
||||
# Copia o runtime JS do Go para WASM (Go class, polyfills)
|
||||
RUN cp "$(go env GOROOT)/lib/wasm/wasm_exec.js" web/static/wasm_exec.js
|
||||
|
||||
# Build do binário
|
||||
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
|
||||
go build -trimpath -ldflags="-s -w" -o /out/server ./cmd/server
|
||||
|
|
|
|||
47
README.md
47
README.md
|
|
@ -27,38 +27,6 @@ O servidor controla o cache de `/static/e-li.nps.js` via **ETag**.
|
|||
|
||||
Isso evita problemas de clientes com JS antigo em cache após mudanças.
|
||||
|
||||
### WebAssembly (WASM) — regras do widget em Go
|
||||
|
||||
O widget `e-li.nps.js` carrega um módulo WASM compilado em Go, para concentrar
|
||||
as regras de negócio do cliente (pré-validações, cooldown e decisão de abertura
|
||||
com base na resposta do backend).
|
||||
|
||||
Arquivos servidos:
|
||||
|
||||
- `/static/e-li.nps.js` (arquivo único do widget)
|
||||
- `/static/e-li.nps.wasm` (módulo WASM)
|
||||
- `/static/wasm_exec.js` (runtime do Go para WASM)
|
||||
|
||||
Regras importantes:
|
||||
|
||||
- **Fail-closed**: se o WASM não carregar, o widget não abre.
|
||||
- Cache é controlado por **ETag** e o browser sempre **revalida**.
|
||||
- O backend Go continua sendo a **autoridade** das regras e persistência.
|
||||
|
||||
#### Build local do WASM
|
||||
|
||||
Para (re)gerar os arquivos do WASM localmente:
|
||||
|
||||
```bash
|
||||
# gera o módulo WASM
|
||||
GOOS=js GOARCH=wasm go build -o web/static/e-li.nps.wasm ./cmd/widgetwasm
|
||||
|
||||
# copia o runtime JS do Go para WASM
|
||||
cp "$(go env GOROOT)/lib/wasm/wasm_exec.js" web/static/wasm_exec.js
|
||||
```
|
||||
|
||||
> Observação: no build via Docker, esses passos já são executados no `Dockerfile`.
|
||||
|
||||
### Arquivo `.env`
|
||||
|
||||
O servidor carrega automaticamente um arquivo `.env` na raiz do projeto (se existir) usando `godotenv`.
|
||||
|
|
@ -373,18 +341,13 @@ curl -sS -X PATCH http://localhost:8080/api/e-li.nps/elicencie_gov/<id> \
|
|||
- O nome **exibido ao usuário** é o original informado e fica salvo em `produto_nome` na tabela do produto.
|
||||
- O controle de exibição (regras 45 dias / 10 dias) é baseado em: **produto + inquilino_codigo + usuario_codigo**.
|
||||
|
||||
### Observabilidade (logs)
|
||||
## Recomendações (para prompts / manutenção)
|
||||
|
||||
O servidor registra **uma linha por requisição** com:
|
||||
|
||||
- `metodo`, `path`, `status`
|
||||
- `dur_ms` (tempo de execução)
|
||||
- `request_id` (quando disponível)
|
||||
- `ip_real` (após `middleware.RealIP`)
|
||||
|
||||
Regra importante (segurança): o projeto **não** deve logar segredos (senha, tokens,
|
||||
cookies, Authorization, DSN).
|
||||
Alguns cuidados:
|
||||
|
||||
- Nomes de variáveis ou arquivos preferencialmente em português
|
||||
- Sempre adicionar comentários em português que ajudem humanos e IAs na manutenção
|
||||
- Se a mudança for importante, atualizar `README.md`
|
||||
|
||||
---
|
||||
|
||||
|
|
|
|||
|
|
@ -4,7 +4,6 @@ import (
|
|||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
|
|
@ -21,13 +20,8 @@ import (
|
|||
)
|
||||
|
||||
func main() {
|
||||
// Logger estruturado (stdout). Mantemos log.Printf apenas para logs muito
|
||||
// iniciais/críticos e para compatibilidade; o restante deve usar slog.
|
||||
logger := elinps.LoggerPadrao()
|
||||
slog.SetDefault(logger)
|
||||
|
||||
// Carrega .env se existir (conveniência para dev local).
|
||||
// Variáveis definidas no SO têm precedência.
|
||||
// Load .env if present (convenience for local dev). Environment variables
|
||||
// explicitly set in the OS take precedence.
|
||||
_ = godotenv.Load()
|
||||
|
||||
cfg := mustLoadConfig()
|
||||
|
|
@ -41,7 +35,7 @@ func main() {
|
|||
}
|
||||
defer pool.Close()
|
||||
|
||||
// Garante extensões necessárias.
|
||||
// Ensures required extensions exist.
|
||||
if err := db.EnsurePgcrypto(ctx, pool); err != nil {
|
||||
log.Fatalf("ensure pgcrypto: %v", err)
|
||||
}
|
||||
|
|
@ -50,24 +44,23 @@ func main() {
|
|||
r.Use(middleware.RequestID)
|
||||
r.Use(middleware.RealIP)
|
||||
r.Use(middleware.Recoverer)
|
||||
r.Use(elinps.MiddlewareLogRequisicao(logger))
|
||||
r.Use(middleware.Timeout(15 * time.Second))
|
||||
r.Use(middleware.Compress(5))
|
||||
|
||||
// CORS liberado + preflight.
|
||||
// CORS wildcard + preflight
|
||||
r.Use(elinps.CORSMiddleware())
|
||||
|
||||
// Limites básicos.
|
||||
// Basic limits
|
||||
r.Use(elinps.MaxBodyBytesMiddleware(64 * 1024))
|
||||
|
||||
// Health.
|
||||
// Health
|
||||
r.Get("/healthz", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })
|
||||
|
||||
// Home: renderiza README.md
|
||||
// Público (sem senha), para facilitar documentação do serviço.
|
||||
r.Get("/", elinps.NewReadmePage("README.md").ServeHTTP)
|
||||
|
||||
// Widget estático.
|
||||
// Static widget
|
||||
fileServer := http.FileServer(http.Dir("web/static"))
|
||||
// Versão do widget para controle de cache.
|
||||
//
|
||||
|
|
@ -92,52 +85,14 @@ func main() {
|
|||
|
||||
http.ServeFile(w, r, "web/static/e-li.nps.js")
|
||||
})
|
||||
|
||||
// WASM do widget.
|
||||
// Regra: cache controlado por ETag e revalidação obrigatória.
|
||||
// Importante: mantemos o MESMO ETag da inicialização (versaoWidget)
|
||||
// para JS e WASM, garantindo que ambos "andem juntos".
|
||||
r.Get("/e-li.nps.wasm", func(w http.ResponseWriter, r *http.Request) {
|
||||
etag := fmt.Sprintf("\"%s\"", versaoWidget)
|
||||
w.Header().Set("ETag", etag)
|
||||
w.Header().Set("Cache-Control", "no-cache, must-revalidate")
|
||||
w.Header().Set("Content-Type", "application/wasm")
|
||||
|
||||
if r.Header.Get("If-None-Match") == etag {
|
||||
w.WriteHeader(http.StatusNotModified)
|
||||
return
|
||||
}
|
||||
http.ServeFile(w, r, "web/static/e-li.nps.wasm")
|
||||
})
|
||||
|
||||
// Runtime JS do Go para WASM.
|
||||
// Também fica sob ETag + revalidação.
|
||||
r.Get("/wasm_exec.js", func(w http.ResponseWriter, r *http.Request) {
|
||||
etag := fmt.Sprintf("\"%s\"", versaoWidget)
|
||||
w.Header().Set("ETag", etag)
|
||||
w.Header().Set("Cache-Control", "no-cache, must-revalidate")
|
||||
w.Header().Set("Content-Type", "application/javascript")
|
||||
|
||||
if r.Header.Get("If-None-Match") == etag {
|
||||
w.WriteHeader(http.StatusNotModified)
|
||||
return
|
||||
}
|
||||
http.ServeFile(w, r, "web/static/wasm_exec.js")
|
||||
})
|
||||
r.Handle("/*", http.StripPrefix("/static/", fileServer))
|
||||
})
|
||||
// Conveniência: permitir /teste.html
|
||||
// Convenience: allow /teste.html
|
||||
r.Get("/teste.html", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.ServeFile(w, r, "web/static/teste.html")
|
||||
})
|
||||
|
||||
// Conveniência: favicon.
|
||||
// O arquivo fica em web/static/favicon.ico.
|
||||
r.Get("/favicon.ico", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.ServeFile(w, r, "web/static/favicon.ico")
|
||||
})
|
||||
|
||||
// Rotas NPS.
|
||||
// NPS routes
|
||||
h := elinps.NewHandlers(pool)
|
||||
r.Route("/api/e-li.nps", func(r chi.Router) {
|
||||
r.Post("/pedido", h.PostPedido)
|
||||
|
|
@ -148,7 +103,7 @@ func main() {
|
|||
r.Get("/{produto}/{id}/form", h.GetForm)
|
||||
})
|
||||
|
||||
// Painel.
|
||||
// Painel (dashboard)
|
||||
// Protegido por SENHA_PAINEL.
|
||||
// Se SENHA_PAINEL estiver vazia, o painel fica desabilitado.
|
||||
painel := elinps.NewPainelHandlers(pool, cfg.SenhaPainel)
|
||||
|
|
@ -161,7 +116,7 @@ func main() {
|
|||
}
|
||||
|
||||
go func() {
|
||||
logger.Info("servidor_iniciado", "addr", cfg.Addr)
|
||||
log.Printf("listening on %s", cfg.Addr)
|
||||
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
log.Fatalf("listen: %v", err)
|
||||
}
|
||||
|
|
@ -171,9 +126,9 @@ func main() {
|
|||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := srv.Shutdown(shutdownCtx); err != nil {
|
||||
logger.Error("erro_no_shutdown", "err", err)
|
||||
log.Printf("shutdown: %v", err)
|
||||
}
|
||||
logger.Info("servidor_finalizado")
|
||||
log.Printf("bye")
|
||||
}
|
||||
|
||||
type config struct {
|
||||
|
|
|
|||
|
|
@ -1,241 +0,0 @@
|
|||
//go:build js && wasm
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"syscall/js"
|
||||
|
||||
"e-li.nps/internal/contratos"
|
||||
)
|
||||
|
||||
// IMPORTANTE (.agent): o backend Go continua sendo a autoridade das regras.
|
||||
// Este WASM existe para concentrar regras de negócio do widget (cliente) em Go,
|
||||
// mantendo o arquivo JS pequeno e fácil de auditar.
|
||||
|
||||
var dataISORe = regexp.MustCompile(`^([0-9]{4})-([0-9]{2})-([0-9]{2})$`)
|
||||
|
||||
type cfgWidget = contratos.ConfigWidget
|
||||
|
||||
func main() {
|
||||
js.Global().Set("__eli_nps_wasm_preflight", js.FuncOf(preflight))
|
||||
js.Global().Set("__eli_nps_wasm_decidir", js.FuncOf(decidir))
|
||||
js.Global().Set("__eli_nps_wasm_cooldown_ativo", js.FuncOf(cooldownAtivo))
|
||||
js.Global().Set("__eli_nps_wasm_set_cooldown", js.FuncOf(setCooldown))
|
||||
js.Global().Set("__eli_nps_wasm_ready", true)
|
||||
|
||||
// Mantém o módulo vivo.
|
||||
select {}
|
||||
}
|
||||
|
||||
func cooldownAtivo(this js.Value, args []js.Value) any {
|
||||
if len(args) < 1 {
|
||||
return false
|
||||
}
|
||||
chave := strings.TrimSpace(args[0].String())
|
||||
if chave == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
// Best-effort: se der erro, tratamos como não ativo.
|
||||
storage := js.Global().Get("localStorage")
|
||||
if storage.IsUndefined() || storage.IsNull() {
|
||||
return false
|
||||
}
|
||||
|
||||
v := storage.Call("getItem", chave)
|
||||
if v.IsNull() || v.IsUndefined() {
|
||||
return false
|
||||
}
|
||||
|
||||
parsed := js.Global().Get("JSON").Call("parse", v)
|
||||
until := parsed.Get("until")
|
||||
if until.IsUndefined() || until.IsNull() {
|
||||
return false
|
||||
}
|
||||
|
||||
agora := js.Global().Get("Date").Call("now").Int()
|
||||
return int64(agora) < int64(until.Int())
|
||||
}
|
||||
|
||||
func setCooldown(this js.Value, args []js.Value) any {
|
||||
if len(args) < 2 {
|
||||
return nil
|
||||
}
|
||||
chave := strings.TrimSpace(args[0].String())
|
||||
if chave == "" {
|
||||
return nil
|
||||
}
|
||||
ateMs := int64(args[1].Int())
|
||||
if ateMs <= 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
storage := js.Global().Get("localStorage")
|
||||
if storage.IsUndefined() || storage.IsNull() {
|
||||
return nil
|
||||
}
|
||||
|
||||
obj := js.Global().Get("Object").New()
|
||||
obj.Set("until", ateMs)
|
||||
json := js.Global().Get("JSON").Call("stringify", obj)
|
||||
storage.Call("setItem", chave, json)
|
||||
return nil
|
||||
}
|
||||
|
||||
func preflight(this js.Value, args []js.Value) any {
|
||||
if len(args) < 1 {
|
||||
return map[string]any{"ok": false, "motivo": "sem_cfg"}
|
||||
}
|
||||
cfg := lerCfg(args[0])
|
||||
|
||||
// Bloqueio por data mínima.
|
||||
if antesDaDataMinima(cfg.DataMinimaAbertura) {
|
||||
return map[string]any{"ok": false, "motivo": "antes_da_data_minima"}
|
||||
}
|
||||
|
||||
// controle de exibição: produto + inquilino_codigo + usuario_codigo
|
||||
if cfg.ProdutoNome == "" || cfg.InquilinoCodigo == "" || cfg.UsuarioCodigo == "" {
|
||||
return map[string]any{"ok": false, "motivo": "contexto_incompleto"}
|
||||
}
|
||||
|
||||
chaveCooldown := chaveCooldown(cfg.ProdutoNome, cfg.InquilinoCodigo, cfg.UsuarioCodigo)
|
||||
untilMs := calcularCooldownAteMs(cfg.CooldownHours)
|
||||
|
||||
// Enviamos exatamente o produto_nome informado.
|
||||
payload := map[string]any{
|
||||
"produto_nome": cfg.ProdutoNome,
|
||||
"inquilino_codigo": cfg.InquilinoCodigo,
|
||||
"inquilino_nome": cfg.InquilinoNome,
|
||||
"usuario_codigo": cfg.UsuarioCodigo,
|
||||
"usuario_nome": cfg.UsuarioNome,
|
||||
"usuario_telefone": cfg.UsuarioTelefone,
|
||||
"usuario_email": normalizarEmail(cfg.UsuarioEmail),
|
||||
}
|
||||
|
||||
return map[string]any{
|
||||
"ok": true,
|
||||
"chave_cooldown": chaveCooldown,
|
||||
"cooldown_ate_ms": untilMs,
|
||||
"payload": payload,
|
||||
}
|
||||
}
|
||||
|
||||
func decidir(this js.Value, args []js.Value) any {
|
||||
// Entrada:
|
||||
// - args[0] = cfg (para cooldownHours)
|
||||
// - args[1] = resposta JSON do servidor (obj)
|
||||
if len(args) < 2 {
|
||||
return map[string]any{"abrir": false, "motivo": "sem_dados"}
|
||||
}
|
||||
cfg := lerCfg(args[0])
|
||||
data := args[1]
|
||||
|
||||
untilMs := calcularCooldownAteMs(cfg.CooldownHours)
|
||||
|
||||
// Fail-closed.
|
||||
if data.IsUndefined() || data.IsNull() {
|
||||
return map[string]any{"abrir": false, "motivo": "resposta_invalida", "aplicar_cooldown": true, "cooldown_ate_ms": untilMs}
|
||||
}
|
||||
|
||||
// Esperado: {pode_abrir:bool, id:string, produto:string}
|
||||
podeAbrir := data.Get("pode_abrir")
|
||||
if !podeAbrir.Truthy() {
|
||||
return map[string]any{"abrir": false, "motivo": "nao_pode_abrir", "aplicar_cooldown": true, "cooldown_ate_ms": untilMs}
|
||||
}
|
||||
id := strings.TrimSpace(data.Get("id").String())
|
||||
produtoRota := strings.TrimSpace(data.Get("produto").String())
|
||||
if id == "" || produtoRota == "" {
|
||||
// Não dá para montar URL segura.
|
||||
return map[string]any{"abrir": false, "motivo": "sem_produto_ou_id", "aplicar_cooldown": true, "cooldown_ate_ms": untilMs}
|
||||
}
|
||||
|
||||
return map[string]any{
|
||||
"abrir": true,
|
||||
"id": id,
|
||||
"produto_rota": produtoRota,
|
||||
"aplicar_cooldown": true,
|
||||
"cooldown_ate_ms": untilMs,
|
||||
}
|
||||
}
|
||||
|
||||
func lerCfg(v js.Value) cfgWidget {
|
||||
// Leitura defensiva: tudo é best-effort.
|
||||
getStr := func(k string) string {
|
||||
if v.Type() != js.TypeObject {
|
||||
return ""
|
||||
}
|
||||
vv := v.Get(k)
|
||||
if vv.IsUndefined() || vv.IsNull() {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(vv.String())
|
||||
}
|
||||
getNum := func(k string) float64 {
|
||||
if v.Type() != js.TypeObject {
|
||||
return 0
|
||||
}
|
||||
vv := v.Get(k)
|
||||
if vv.IsUndefined() || vv.IsNull() {
|
||||
return 0
|
||||
}
|
||||
return vv.Float()
|
||||
}
|
||||
|
||||
return cfgWidget{
|
||||
ProdutoNome: getStr("produto_nome"),
|
||||
InquilinoCodigo: getStr("inquilino_codigo"),
|
||||
InquilinoNome: getStr("inquilino_nome"),
|
||||
UsuarioCodigo: getStr("usuario_codigo"),
|
||||
UsuarioNome: getStr("usuario_nome"),
|
||||
UsuarioTelefone: getStr("usuario_telefone"),
|
||||
UsuarioEmail: getStr("usuario_email"),
|
||||
CooldownHours: getNum("cooldownHours"),
|
||||
DataMinimaAbertura: getStr("data_minima_abertura"),
|
||||
}
|
||||
}
|
||||
|
||||
func normalizarEmail(email string) string {
|
||||
return strings.ToLower(strings.TrimSpace(email))
|
||||
}
|
||||
|
||||
func chaveCooldown(produto, inquilino, usuarioCodigo string) string {
|
||||
// Prefixo de storage atualizado para o novo nome do projeto.
|
||||
return "eli-nps:cooldown:" + produto + ":" + inquilino + ":" + usuarioCodigo
|
||||
}
|
||||
|
||||
func calcularCooldownAteMs(hours float64) int64 {
|
||||
if hours <= 0 {
|
||||
hours = 24
|
||||
}
|
||||
agora := js.Global().Get("Date").Call("now").Int()
|
||||
return int64(agora) + int64(hours*3600*1000)
|
||||
}
|
||||
|
||||
func antesDaDataMinima(s string) bool {
|
||||
// Aceita somente ISO (data) YYYY-MM-DD.
|
||||
v := strings.TrimSpace(s)
|
||||
if v == "" {
|
||||
return false
|
||||
}
|
||||
m := dataISORe.FindStringSubmatch(v)
|
||||
if m == nil {
|
||||
return false
|
||||
}
|
||||
// new Date(ano, mes-1, dia, 0, 0, 0, 0)
|
||||
ano := m[1]
|
||||
mes := m[2]
|
||||
dia := m[3]
|
||||
|
||||
// Converte para números via JS (simplifica validação e compatibilidade de timezone).
|
||||
nAno := js.Global().Get("Number").Invoke(ano).Int()
|
||||
nMes := js.Global().Get("Number").Invoke(mes).Int()
|
||||
nDia := js.Global().Get("Number").Invoke(dia).Int()
|
||||
if nAno <= 0 || nMes < 1 || nMes > 12 || nDia < 1 || nDia > 31 {
|
||||
return false
|
||||
}
|
||||
dataMin := js.Global().Get("Date").New(nAno, nMes-1, nDia, 0, 0, 0, 0)
|
||||
agora := js.Global().Get("Date").New()
|
||||
return agora.Call("getTime").Int() < dataMin.Call("getTime").Int()
|
||||
}
|
||||
|
|
@ -1,128 +0,0 @@
|
|||
package contratos
|
||||
|
||||
import "time"
|
||||
|
||||
// Tipos centralizados do projeto.
|
||||
//
|
||||
// Regra: este arquivo concentra as tipagens (structs) usadas como contratos de
|
||||
// dados entre camadas (backend, painel e widget/WASM), para manter consistência
|
||||
// e facilitar auditoria.
|
||||
|
||||
// ------------------------------
|
||||
// API do widget
|
||||
// ------------------------------
|
||||
|
||||
type PedidoInput struct {
|
||||
ProdutoNome string `json:"produto_nome"`
|
||||
InquilinoCodigo string `json:"inquilino_codigo"`
|
||||
InquilinoNome string `json:"inquilino_nome"`
|
||||
UsuarioCodigo string `json:"usuario_codigo"`
|
||||
UsuarioNome string `json:"usuario_nome"`
|
||||
UsuarioTelefone string `json:"usuario_telefone"`
|
||||
UsuarioEmail string `json:"usuario_email"`
|
||||
}
|
||||
|
||||
type PedidoResponse struct {
|
||||
PodeAbrir bool `json:"pode_abrir"`
|
||||
Motivo string `json:"motivo,omitempty"`
|
||||
ID string `json:"id,omitempty"`
|
||||
// Produto normalizado retornado pelo backend para montar URL segura.
|
||||
Produto string `json:"produto,omitempty"`
|
||||
}
|
||||
|
||||
type PatchInput struct {
|
||||
Nota *int `json:"nota,omitempty"`
|
||||
Justificativa *string `json:"justificativa,omitempty"`
|
||||
Finalizar bool `json:"finalizar,omitempty"`
|
||||
}
|
||||
|
||||
type Registro struct {
|
||||
// ProdutoNome é o nome original do produto como enviado pela integração/widget.
|
||||
// Ele existe apenas para exibição ao usuário.
|
||||
//
|
||||
// Importante: a normalização (remoção de acentos/símbolos) é usada apenas
|
||||
// para formar o nome da tabela no Postgres e o parâmetro {produto} da rota.
|
||||
ProdutoNome string
|
||||
ID string
|
||||
Status string
|
||||
Nota *int
|
||||
Justificativa *string
|
||||
PedidoCriadoEm time.Time
|
||||
RespondidoEm *time.Time
|
||||
}
|
||||
|
||||
// FormPageData é o payload para renderização do formulário no iframe.
|
||||
type FormPageData struct {
|
||||
Produto string
|
||||
ID string
|
||||
Reg Registro
|
||||
}
|
||||
|
||||
// ------------------------------
|
||||
// Painel
|
||||
// ------------------------------
|
||||
|
||||
// NPSMensal representa o cálculo do NPS agregado por mês.
|
||||
type NPSMensal struct {
|
||||
Mes string
|
||||
Detratores int
|
||||
Neutros int
|
||||
Promotores int
|
||||
Total int
|
||||
NPS int
|
||||
}
|
||||
|
||||
// RespostaPainel representa uma resposta para listagem no painel.
|
||||
type RespostaPainel struct {
|
||||
ID string
|
||||
RespondidoEm *time.Time
|
||||
PedidoCriadoEm time.Time
|
||||
UsuarioCodigo *string
|
||||
UsuarioNome string
|
||||
UsuarioEmail *string
|
||||
Nota *int
|
||||
Justificativa *string
|
||||
}
|
||||
|
||||
type PainelDados struct {
|
||||
Produto string
|
||||
Produtos []string
|
||||
Meses []NPSMensal
|
||||
Respostas []RespostaPainel
|
||||
Pagina int
|
||||
SomenteBaixas bool
|
||||
MsgErro string
|
||||
}
|
||||
|
||||
type ListarRespostasFiltro struct {
|
||||
SomenteNotasBaixas bool
|
||||
Pagina int
|
||||
PorPagina int
|
||||
}
|
||||
|
||||
func (f *ListarRespostasFiltro) Normalizar() {
|
||||
if f.Pagina <= 0 {
|
||||
f.Pagina = 1
|
||||
}
|
||||
if f.PorPagina <= 0 || f.PorPagina > 200 {
|
||||
f.PorPagina = 50
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------
|
||||
// Widget/WASM
|
||||
// ------------------------------
|
||||
|
||||
// ConfigWidget representa as opções passadas para window.ELiNPS.init(...).
|
||||
// No WASM lemos via syscall/js; aqui fica apenas a tipagem centralizada.
|
||||
type ConfigWidget struct {
|
||||
ProdutoNome string
|
||||
InquilinoCodigo string
|
||||
InquilinoNome string
|
||||
UsuarioCodigo string
|
||||
UsuarioNome string
|
||||
UsuarioTelefone string
|
||||
UsuarioEmail string
|
||||
CooldownHours float64
|
||||
DataMinimaAbertura string
|
||||
}
|
||||
|
|
@ -14,7 +14,7 @@ func NewPool(ctx context.Context, databaseURL string) (*pgxpool.Pool, error) {
|
|||
return nil, fmt.Errorf("parse DATABASE_URL: %w", err)
|
||||
}
|
||||
|
||||
// Defaults razoáveis para um serviço pequeno/médio.
|
||||
// Reasonable defaults
|
||||
cfg.MaxConns = 10
|
||||
cfg.MinConns = 0
|
||||
cfg.MaxConnLifetime = 60 * time.Minute
|
||||
|
|
|
|||
|
|
@ -13,22 +13,6 @@ import (
|
|||
|
||||
var produtoRe = regexp.MustCompile(`^[a-z_][a-z0-9_]*$`)
|
||||
|
||||
// TableNameValido valida se o nome de tabela está no formato esperado do projeto:
|
||||
// "nps_" + produto normalizado.
|
||||
//
|
||||
// Motivação (segurança): identificadores não podem ser parametrizados em SQL.
|
||||
// Então, sempre que precisarmos interpolar um nome de tabela, validamos aqui
|
||||
// para evitar SQL injection via identificador.
|
||||
func TableNameValido(tableName string) bool {
|
||||
if !strings.HasPrefix(tableName, "nps_") {
|
||||
return false
|
||||
}
|
||||
produto := strings.TrimPrefix(tableName, "nps_")
|
||||
// produtoRe já garante: ^[a-z_][a-z0-9_]*$
|
||||
// (e a normalização limita tamanho em NormalizeProduto).
|
||||
return produtoRe.MatchString(produto)
|
||||
}
|
||||
|
||||
// NormalizeProduto normaliza e valida um nome de produto para uso em:
|
||||
// - nomes de tabela no Postgres (prefixo nps_)
|
||||
// - rotas/URLs (parâmetro {produto})
|
||||
|
|
@ -96,14 +80,11 @@ func EnsurePgcrypto(ctx context.Context, pool *pgxpool.Pool) error {
|
|||
return err
|
||||
}
|
||||
|
||||
// EnsureNPSTable cria a tabela por produto + índices se não existirem.
|
||||
// Importante: tableName deve ser criada a partir de um produto normalizado.
|
||||
// EnsureNPSTable creates the per-product table + indexes if they do not exist.
|
||||
// IMPORTANT: tableName must be created from a sanitized product name.
|
||||
func EnsureNPSTable(ctx context.Context, pool *pgxpool.Pool, tableName string) error {
|
||||
// Identifiers cannot be passed as $1 parameters, so we must interpolate.
|
||||
// Segurança: tableName deve ser estritamente derivada de NormalizeProduto + prefix.
|
||||
if !TableNameValido(tableName) {
|
||||
return fmt.Errorf("nome de tabela invalido")
|
||||
}
|
||||
// Safety: tableName is strictly derived from NormalizeProduto + prefix.
|
||||
q := fmt.Sprintf(`
|
||||
CREATE TABLE IF NOT EXISTS %s (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
|
|
|
|||
|
|
@ -3,11 +3,9 @@ package elinps
|
|||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"e-li.nps/internal/contratos"
|
||||
"e-li.nps/internal/db"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
|
@ -30,7 +28,7 @@ func NewHandlers(pool *pgxpool.Pool) *Handlers {
|
|||
func (h *Handlers) PostPedido(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
var in contratos.PedidoInput
|
||||
var in PedidoInput
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]any{"error": "json_invalido"})
|
||||
return
|
||||
|
|
@ -40,45 +38,42 @@ func (h *Handlers) PostPedido(w http.ResponseWriter, r *http.Request) {
|
|||
return
|
||||
}
|
||||
|
||||
// Garante a tabela do produto (e normaliza o identificador técnico).
|
||||
// Ensure per-product table exists (also normalizes produto).
|
||||
table, err := h.store.EnsureTableForProduto(ctx, in.ProdutoNome)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]any{"error": "produto_invalido"})
|
||||
return
|
||||
}
|
||||
|
||||
// Mantemos a forma normalizada para o widget montar URLs com segurança.
|
||||
// Keep normalized form for the widget to build URLs safely.
|
||||
// table = "nps_" + produto_normalizado
|
||||
produtoNormalizado := strings.TrimPrefix(table, "nps_")
|
||||
|
||||
// Regras.
|
||||
// Rules
|
||||
respRecente, err := h.store.HasRespostaValidaRecente(ctx, table, in.InquilinoCodigo, in.UsuarioCodigo)
|
||||
if err != nil {
|
||||
slog.Error("erro ao checar resposta recente", "err", err)
|
||||
// Fail-closed.
|
||||
writeJSON(w, http.StatusOK, contratos.PedidoResponse{PodeAbrir: false, Motivo: "erro"})
|
||||
// Fail-closed
|
||||
writeJSON(w, http.StatusOK, PedidoResponse{PodeAbrir: false, Motivo: "erro"})
|
||||
return
|
||||
}
|
||||
if respRecente {
|
||||
writeJSON(w, http.StatusOK, contratos.PedidoResponse{PodeAbrir: false, Motivo: "resposta_recente"})
|
||||
writeJSON(w, http.StatusOK, PedidoResponse{PodeAbrir: false, Motivo: "resposta_recente"})
|
||||
return
|
||||
}
|
||||
|
||||
pedidoAberto, err := h.store.HasPedidoEmAbertoRecente(ctx, table, in.InquilinoCodigo, in.UsuarioCodigo)
|
||||
if err != nil {
|
||||
slog.Error("erro ao checar pedido em aberto", "err", err)
|
||||
writeJSON(w, http.StatusOK, contratos.PedidoResponse{PodeAbrir: false, Motivo: "erro"})
|
||||
writeJSON(w, http.StatusOK, PedidoResponse{PodeAbrir: false, Motivo: "erro"})
|
||||
return
|
||||
}
|
||||
if pedidoAberto {
|
||||
writeJSON(w, http.StatusOK, contratos.PedidoResponse{PodeAbrir: false, Motivo: "pedido_em_aberto"})
|
||||
writeJSON(w, http.StatusOK, PedidoResponse{PodeAbrir: false, Motivo: "pedido_em_aberto"})
|
||||
return
|
||||
}
|
||||
|
||||
id, err := h.store.CreatePedido(ctx, table, in, r)
|
||||
if err != nil {
|
||||
slog.Error("erro ao criar pedido", "err", err)
|
||||
writeJSON(w, http.StatusOK, contratos.PedidoResponse{PodeAbrir: false, Motivo: "erro"})
|
||||
writeJSON(w, http.StatusOK, PedidoResponse{PodeAbrir: false, Motivo: "erro"})
|
||||
return
|
||||
}
|
||||
|
||||
|
|
@ -90,7 +85,7 @@ func (h *Handlers) PatchResposta(w http.ResponseWriter, r *http.Request) {
|
|||
produtoParam := chi.URLParam(r, "produto")
|
||||
id := chi.URLParam(r, "id")
|
||||
|
||||
// produtoParam já está no path; sanitizamos novamente por segurança.
|
||||
// produtoParam already in path; sanitize again.
|
||||
prod, err := db.NormalizeProduto(produtoParam)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]any{"error": "produto_invalido"})
|
||||
|
|
@ -98,12 +93,11 @@ func (h *Handlers) PatchResposta(w http.ResponseWriter, r *http.Request) {
|
|||
}
|
||||
table := db.TableNameForProduto(prod)
|
||||
if err := db.EnsureNPSTable(ctx, h.store.pool, table); err != nil {
|
||||
slog.Error("erro ao garantir tabela", "err", err)
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]any{"error": "db"})
|
||||
return
|
||||
}
|
||||
|
||||
var in contratos.PatchInput
|
||||
var in PatchInput
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]any{"error": "json_invalido"})
|
||||
return
|
||||
|
|
@ -119,21 +113,19 @@ func (h *Handlers) PatchResposta(w http.ResponseWriter, r *http.Request) {
|
|||
}
|
||||
|
||||
if err := h.store.PatchRegistro(ctx, table, id, in); err != nil {
|
||||
slog.Error("erro ao atualizar registro", "err", err)
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]any{"error": "db"})
|
||||
return
|
||||
}
|
||||
|
||||
// Se chamado via HTMX, respondemos com fragmento HTML atualizado.
|
||||
// If called via HTMX, respond with refreshed HTML fragment.
|
||||
if r.Header.Get("HX-Request") == "true" {
|
||||
reg, err := h.store.GetRegistro(ctx, table, id)
|
||||
if err != nil {
|
||||
slog.Error("erro ao buscar registro", "err", err)
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
w.Write([]byte("db"))
|
||||
return
|
||||
}
|
||||
data := contratos.FormPageData{Produto: prod, ID: id, Reg: reg}
|
||||
data := FormPageData{Produto: prod, ID: id, Reg: reg}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
h.tpl.Render(w, "form_inner.html", data)
|
||||
return
|
||||
|
|
@ -155,7 +147,6 @@ func (h *Handlers) GetForm(w http.ResponseWriter, r *http.Request) {
|
|||
}
|
||||
table := db.TableNameForProduto(prod)
|
||||
if err := db.EnsureNPSTable(ctx, h.store.pool, table); err != nil {
|
||||
slog.Error("erro ao garantir tabela", "err", err)
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
w.Write([]byte("db"))
|
||||
return
|
||||
|
|
@ -168,20 +159,19 @@ func (h *Handlers) GetForm(w http.ResponseWriter, r *http.Request) {
|
|||
w.Write([]byte("nao encontrado"))
|
||||
return
|
||||
}
|
||||
slog.Error("erro ao buscar registro", "err", err)
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
w.Write([]byte("db"))
|
||||
return
|
||||
}
|
||||
|
||||
data := contratos.FormPageData{
|
||||
data := FormPageData{
|
||||
Produto: prod,
|
||||
ID: id,
|
||||
Reg: reg,
|
||||
}
|
||||
|
||||
// Sempre retornamos uma página HTML completa para o widget usar iframe.
|
||||
// Porém o container interno também é compatível com HTMX (swap de si mesmo).
|
||||
// Always return a standalone HTML page so the widget can use iframe.
|
||||
// But the inner container is also HTMX-friendly (it swaps itself).
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
h.tpl.Render(w, "form_page.html", data)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,91 +0,0 @@
|
|||
package elinps
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
)
|
||||
|
||||
// LoggerPadrao cria um logger simples (stdout) adequado para Docker.
|
||||
//
|
||||
// Regras do projeto:
|
||||
// - logs relevantes (rotas, tempo de execução, erros)
|
||||
// - NUNCA logar segredos (Authorization/cookies/senha/DSN)
|
||||
func LoggerPadrao() *slog.Logger {
|
||||
return slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))
|
||||
}
|
||||
|
||||
type responseWriterComStatus struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
bytes int
|
||||
}
|
||||
|
||||
func (w *responseWriterComStatus) WriteHeader(status int) {
|
||||
w.status = status
|
||||
w.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func (w *responseWriterComStatus) Write(b []byte) (int, error) {
|
||||
if w.status == 0 {
|
||||
w.status = http.StatusOK
|
||||
}
|
||||
n, err := w.ResponseWriter.Write(b)
|
||||
w.bytes += n
|
||||
return n, err
|
||||
}
|
||||
|
||||
// MiddlewareLogRequisicao registra uma linha por requisição com:
|
||||
// - método, path, status, duração
|
||||
// - request_id (se existir)
|
||||
// - ip_real (após chi/middleware.RealIP)
|
||||
func MiddlewareLogRequisicao(logger *slog.Logger) func(http.Handler) http.Handler {
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ini := time.Now()
|
||||
ww := &responseWriterComStatus{ResponseWriter: w}
|
||||
next.ServeHTTP(ww, r)
|
||||
|
||||
dur := time.Since(ini)
|
||||
attrs := []any{
|
||||
"metodo", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"status", ww.status,
|
||||
"dur_ms", dur.Milliseconds(),
|
||||
"bytes", ww.bytes,
|
||||
"ip_real", ipSomenteHost(r.RemoteAddr),
|
||||
}
|
||||
if reqID := requestIDFromContext(r.Context()); reqID != "" {
|
||||
attrs = append(attrs, "request_id", reqID)
|
||||
}
|
||||
logger.Info("http_request", attrs...)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ipSomenteHost retorna apenas o IP (sem porta). Se o valor não parecer um IP,
|
||||
// devolve string vazia.
|
||||
func ipSomenteHost(remoteAddr string) string {
|
||||
ip := remoteAddr
|
||||
if host, _, err := net.SplitHostPort(remoteAddr); err == nil {
|
||||
ip = host
|
||||
}
|
||||
if net.ParseIP(ip) == nil {
|
||||
return ""
|
||||
}
|
||||
return ip
|
||||
}
|
||||
|
||||
func requestIDFromContext(ctx context.Context) string {
|
||||
// O chi/middleware.RequestID coloca o ID no context.
|
||||
return middleware.GetReqID(ctx)
|
||||
}
|
||||
40
internal/elinps/models.go
Normal file
40
internal/elinps/models.go
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
package elinps
|
||||
|
||||
import "time"
|
||||
|
||||
type PedidoInput struct {
|
||||
ProdutoNome string `json:"produto_nome"`
|
||||
InquilinoCodigo string `json:"inquilino_codigo"`
|
||||
InquilinoNome string `json:"inquilino_nome"`
|
||||
UsuarioCodigo string `json:"usuario_codigo"`
|
||||
UsuarioNome string `json:"usuario_nome"`
|
||||
UsuarioTelefone string `json:"usuario_telefone"`
|
||||
UsuarioEmail string `json:"usuario_email"`
|
||||
}
|
||||
|
||||
type PedidoResponse struct {
|
||||
PodeAbrir bool `json:"pode_abrir"`
|
||||
Motivo string `json:"motivo,omitempty"`
|
||||
ID string `json:"id,omitempty"`
|
||||
}
|
||||
|
||||
type PatchInput struct {
|
||||
Nota *int `json:"nota,omitempty"`
|
||||
Justificativa *string `json:"justificativa,omitempty"`
|
||||
Finalizar bool `json:"finalizar,omitempty"`
|
||||
}
|
||||
|
||||
type Registro struct {
|
||||
// ProdutoNome é o nome original do produto como enviado pela integração/widget.
|
||||
// Ele existe apenas para exibição ao usuário.
|
||||
//
|
||||
// Importante: a normalização (remoção de acentos/símbolos) é usada apenas
|
||||
// para formar o nome da tabela no Postgres e o parâmetro {produto} da rota.
|
||||
ProdutoNome string
|
||||
ID string
|
||||
Status string
|
||||
Nota *int
|
||||
Justificativa *string
|
||||
PedidoCriadoEm time.Time
|
||||
RespondidoEm *time.Time
|
||||
}
|
||||
|
|
@ -9,7 +9,6 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"e-li.nps/internal/contratos"
|
||||
"e-li.nps/internal/db"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
|
@ -58,11 +57,37 @@ func (a AuthPainel) handlerLoginPost(w http.ResponseWriter, r *http.Request) {
|
|||
http.Redirect(w, r, "/painel", http.StatusFound)
|
||||
}
|
||||
|
||||
type NPSMensal = contratos.NPSMensal
|
||||
// NPSMensal representa o cálculo do NPS agregado por mês.
|
||||
type NPSMensal struct {
|
||||
Mes string
|
||||
Detratores int
|
||||
Neutros int
|
||||
Promotores int
|
||||
Total int
|
||||
NPS int
|
||||
}
|
||||
|
||||
type RespostaPainel = contratos.RespostaPainel
|
||||
// RespostaPainel representa uma resposta para listagem no painel.
|
||||
type RespostaPainel struct {
|
||||
ID string
|
||||
RespondidoEm *time.Time
|
||||
PedidoCriadoEm time.Time
|
||||
UsuarioCodigo *string
|
||||
UsuarioNome string
|
||||
UsuarioEmail *string
|
||||
Nota *int
|
||||
Justificativa *string
|
||||
}
|
||||
|
||||
type PainelDados = contratos.PainelDados
|
||||
type PainelDados struct {
|
||||
Produto string
|
||||
Produtos []string
|
||||
Meses []NPSMensal
|
||||
Respostas []RespostaPainel
|
||||
Pagina int
|
||||
SomenteBaixas bool
|
||||
MsgErro string
|
||||
}
|
||||
|
||||
func (a AuthPainel) handlerPainel(w http.ResponseWriter, r *http.Request, store *Store) {
|
||||
ctx := r.Context()
|
||||
|
|
@ -120,7 +145,7 @@ func (a AuthPainel) handlerPainel(w http.ResponseWriter, r *http.Request, store
|
|||
if err != nil {
|
||||
// Se a tabela ainda não tem coluna ip_real/ etc, EnsureNPSTable deveria ajustar.
|
||||
if err == pgx.ErrNoRows {
|
||||
respostas = []contratos.RespostaPainel{}
|
||||
respostas = []RespostaPainel{}
|
||||
} else {
|
||||
dados.MsgErro = "erro ao listar respostas"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,9 +6,6 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"e-li.nps/internal/contratos"
|
||||
"e-li.nps/internal/db"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
|
|
@ -44,11 +41,8 @@ ORDER BY tablename`)
|
|||
// - 1–6 detratores
|
||||
// - 7–8 neutros
|
||||
// - 9–10 promotores
|
||||
func (s *Store) NPSMesAMes(ctx context.Context, tabela string, meses int) ([]contratos.NPSMensal, error) {
|
||||
// Segurança: a tabela é um identificador interpolado. Validamos sempre.
|
||||
if !db.TableNameValido(tabela) {
|
||||
return nil, fmt.Errorf("tabela invalida")
|
||||
}
|
||||
func (s *Store) NPSMesAMes(ctx context.Context, tabela string, meses int) ([]NPSMensal, error) {
|
||||
// Segurança: tabela deve ser derivada de NormalizeProduto + prefixo.
|
||||
q := fmt.Sprintf(`
|
||||
WITH base AS (
|
||||
SELECT
|
||||
|
|
@ -76,9 +70,9 @@ ORDER BY mes ASC`, tabela)
|
|||
}
|
||||
defer rows.Close()
|
||||
|
||||
out := []contratos.NPSMensal{}
|
||||
out := []NPSMensal{}
|
||||
for rows.Next() {
|
||||
var m contratos.NPSMensal
|
||||
var m NPSMensal
|
||||
if err := rows.Scan(&m.Mes, &m.Detratores, &m.Neutros, &m.Promotores, &m.Total); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -98,15 +92,17 @@ type ListarRespostasFiltro struct {
|
|||
PorPagina int
|
||||
}
|
||||
|
||||
func (f *ListarRespostasFiltro) normalizar() { (*contratos.ListarRespostasFiltro)(f).Normalizar() }
|
||||
|
||||
// ListarRespostas retorna respostas respondidas, com paginação e filtro.
|
||||
func (s *Store) ListarRespostas(ctx context.Context, tabela string, filtro ListarRespostasFiltro) ([]contratos.RespostaPainel, error) {
|
||||
// Segurança: a tabela é um identificador interpolado. Validamos sempre.
|
||||
if !db.TableNameValido(tabela) {
|
||||
return nil, fmt.Errorf("tabela invalida")
|
||||
func (f *ListarRespostasFiltro) normalizar() {
|
||||
if f.Pagina <= 0 {
|
||||
f.Pagina = 1
|
||||
}
|
||||
if f.PorPagina <= 0 || f.PorPagina > 200 {
|
||||
f.PorPagina = 50
|
||||
}
|
||||
}
|
||||
|
||||
// ListarRespostas retorna respostas respondidas, com paginação e filtro.
|
||||
func (s *Store) ListarRespostas(ctx context.Context, tabela string, filtro ListarRespostasFiltro) ([]RespostaPainel, error) {
|
||||
filtro.normalizar()
|
||||
offset := (filtro.Pagina - 1) * filtro.PorPagina
|
||||
|
||||
|
|
@ -115,9 +111,6 @@ func (s *Store) ListarRespostas(ctx context.Context, tabela string, filtro Lista
|
|||
cond += " AND nota BETWEEN 1 AND 6"
|
||||
}
|
||||
|
||||
// Importante (segurança): apesar do cond ser construído em string, ele NÃO usa
|
||||
// entrada do usuário diretamente. O filtro "SomenteNotasBaixas" é booleano.
|
||||
// A tabela também é validada por regex (TableNameValido).
|
||||
q := fmt.Sprintf(`
|
||||
SELECT
|
||||
id,
|
||||
|
|
@ -139,9 +132,9 @@ LIMIT $1 OFFSET $2`, tabela, cond)
|
|||
}
|
||||
defer rows.Close()
|
||||
|
||||
respostas := []contratos.RespostaPainel{}
|
||||
respostas := []RespostaPainel{}
|
||||
for rows.Next() {
|
||||
var r contratos.RespostaPainel
|
||||
var r RespostaPainel
|
||||
if err := rows.Scan(
|
||||
&r.ID,
|
||||
&r.RespondidoEm,
|
||||
|
|
|
|||
|
|
@ -7,7 +7,6 @@ import (
|
|||
"net/http"
|
||||
"time"
|
||||
|
||||
"e-li.nps/internal/contratos"
|
||||
"e-li.nps/internal/db"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
|
@ -53,10 +52,6 @@ func (s *Store) EnsureTableForProduto(ctx context.Context, produtoNome string) (
|
|||
}
|
||||
|
||||
func (s *Store) HasRespostaValidaRecente(ctx context.Context, table, inquilinoCodigo, usuarioCodigo string) (bool, error) {
|
||||
// Segurança: a tabela é um identificador interpolado. Validamos sempre.
|
||||
if !db.TableNameValido(table) {
|
||||
return false, fmt.Errorf("tabela invalida")
|
||||
}
|
||||
q := fmt.Sprintf(`
|
||||
SELECT 1
|
||||
FROM %s
|
||||
|
|
@ -77,10 +72,6 @@ LIMIT 1`, table)
|
|||
}
|
||||
|
||||
func (s *Store) HasPedidoEmAbertoRecente(ctx context.Context, table, inquilinoCodigo, usuarioCodigo string) (bool, error) {
|
||||
// Segurança: a tabela é um identificador interpolado. Validamos sempre.
|
||||
if !db.TableNameValido(table) {
|
||||
return false, fmt.Errorf("tabela invalida")
|
||||
}
|
||||
q := fmt.Sprintf(`
|
||||
SELECT 1
|
||||
FROM %s
|
||||
|
|
@ -99,11 +90,7 @@ LIMIT 1`, table)
|
|||
return true, nil
|
||||
}
|
||||
|
||||
func (s *Store) CreatePedido(ctx context.Context, table string, in contratos.PedidoInput, r *http.Request) (string, error) {
|
||||
// Segurança: a tabela é um identificador interpolado. Validamos sempre.
|
||||
if !db.TableNameValido(table) {
|
||||
return "", fmt.Errorf("tabela invalida")
|
||||
}
|
||||
func (s *Store) CreatePedido(ctx context.Context, table string, in PedidoInput, r *http.Request) (string, error) {
|
||||
q := fmt.Sprintf(`
|
||||
INSERT INTO %s (
|
||||
produto_nome,
|
||||
|
|
@ -123,28 +110,20 @@ RETURNING id`, table)
|
|||
return id, err
|
||||
}
|
||||
|
||||
func (s *Store) GetRegistro(ctx context.Context, table, id string) (contratos.Registro, error) {
|
||||
// Segurança: a tabela é um identificador interpolado. Validamos sempre.
|
||||
if !db.TableNameValido(table) {
|
||||
return contratos.Registro{}, fmt.Errorf("tabela invalida")
|
||||
}
|
||||
func (s *Store) GetRegistro(ctx context.Context, table, id string) (Registro, error) {
|
||||
q := fmt.Sprintf(`
|
||||
SELECT id, produto_nome, status, nota, justificativa, pedido_criado_em, respondido_em
|
||||
FROM %s
|
||||
WHERE id=$1`, table)
|
||||
|
||||
var reg contratos.Registro
|
||||
var reg Registro
|
||||
err := s.pool.QueryRow(ctx, q, id).Scan(
|
||||
®.ID, ®.ProdutoNome, ®.Status, ®.Nota, ®.Justificativa, ®.PedidoCriadoEm, ®.RespondidoEm,
|
||||
)
|
||||
return reg, err
|
||||
}
|
||||
|
||||
func (s *Store) PatchRegistro(ctx context.Context, table, id string, in contratos.PatchInput) error {
|
||||
// Segurança: a tabela é um identificador interpolado. Validamos sempre.
|
||||
if !db.TableNameValido(table) {
|
||||
return fmt.Errorf("tabela invalida")
|
||||
}
|
||||
func (s *Store) PatchRegistro(ctx context.Context, table, id string, in PatchInput) error {
|
||||
// UPDATE único com campos opcionais.
|
||||
q := fmt.Sprintf(`
|
||||
UPDATE %s
|
||||
|
|
@ -161,16 +140,12 @@ WHERE id=$1`, table)
|
|||
}
|
||||
|
||||
func (s *Store) TouchAtualizadoEm(ctx context.Context, table, id string) error {
|
||||
// Segurança: a tabela é um identificador interpolado. Validamos sempre.
|
||||
if !db.TableNameValido(table) {
|
||||
return fmt.Errorf("tabela invalida")
|
||||
}
|
||||
q := fmt.Sprintf(`UPDATE %s SET atualizado_em=now() WHERE id=$1`, table)
|
||||
_, err := s.pool.Exec(ctx, q, id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) CooldownSuggested(reg contratos.Registro) time.Duration {
|
||||
func (s *Store) CooldownSuggested(reg Registro) time.Duration {
|
||||
// Não é usado pelo servidor hoje; fica como helper se precisarmos.
|
||||
if reg.Status == "respondido" {
|
||||
return 45 * 24 * time.Hour
|
||||
|
|
|
|||
|
|
@ -2,10 +2,7 @@ package elinps
|
|||
|
||||
import (
|
||||
"html/template"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"e-li.nps/internal/contratos"
|
||||
)
|
||||
|
||||
type TemplateRenderer struct {
|
||||
|
|
@ -15,15 +12,11 @@ type TemplateRenderer struct {
|
|||
func NewTemplateRenderer(t *template.Template) *TemplateRenderer { return &TemplateRenderer{t: t} }
|
||||
|
||||
func (r *TemplateRenderer) Render(w http.ResponseWriter, name string, data any) {
|
||||
if err := r.t.ExecuteTemplate(w, name, data); err != nil {
|
||||
// Não expomos detalhes do erro para o usuário (pode conter paths/etc).
|
||||
// Mas registramos para depuração.
|
||||
slog.Error("erro ao renderizar template", "template", name, "err", err)
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
w.Write([]byte("erro ao renderizar"))
|
||||
return
|
||||
}
|
||||
_ = r.t.ExecuteTemplate(w, name, data)
|
||||
}
|
||||
|
||||
// Alias para manter as chamadas concisas dentro do pacote elinps.
|
||||
type FormPageData = contratos.FormPageData
|
||||
type FormPageData struct {
|
||||
Produto string
|
||||
ID string
|
||||
Reg Registro
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,8 +7,9 @@ import (
|
|||
)
|
||||
|
||||
func mustParseTemplates() *template.Template {
|
||||
// Parse de templates via filesystem local (mantém o repositório simples).
|
||||
// Se precisarmos de deploy single-binary, podemos migrar para go:embed.
|
||||
// Local filesystem parsing (keeps the repo simple).
|
||||
// If you want a single-binary deploy, we can switch to go:embed by moving
|
||||
// templates into internal/elinps and embedding without "..".
|
||||
funcs := template.FuncMap{
|
||||
"seq": func(start, end int) []int {
|
||||
if end < start {
|
||||
|
|
@ -24,7 +25,7 @@ func mustParseTemplates() *template.Template {
|
|||
return ptr != nil && *ptr == v
|
||||
},
|
||||
"produtoLabel": func(produto string) string {
|
||||
// Label "amigável" a partir do produto normalizado.
|
||||
// Best-effort label from normalized produto.
|
||||
p := strings.ReplaceAll(produto, "_", " ")
|
||||
parts := strings.Fields(p)
|
||||
for i := range parts {
|
||||
|
|
|
|||
|
|
@ -4,8 +4,6 @@ import (
|
|||
"errors"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"e-li.nps/internal/contratos"
|
||||
)
|
||||
|
||||
var emailRe = regexp.MustCompile(`^[^\s@]+@[^\s@]+\.[^\s@]+$`)
|
||||
|
|
@ -14,7 +12,7 @@ func normalizeEmail(s string) string {
|
|||
return strings.ToLower(strings.TrimSpace(s))
|
||||
}
|
||||
|
||||
func ValidatePedidoInput(in *contratos.PedidoInput) error {
|
||||
func ValidatePedidoInput(in *PedidoInput) error {
|
||||
in.ProdutoNome = strings.TrimSpace(in.ProdutoNome)
|
||||
in.InquilinoCodigo = strings.TrimSpace(in.InquilinoCodigo)
|
||||
in.InquilinoNome = strings.TrimSpace(in.InquilinoNome)
|
||||
|
|
@ -51,7 +49,7 @@ func ValidatePedidoInput(in *contratos.PedidoInput) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func ValidatePatchInput(in *contratos.PatchInput) error {
|
||||
func ValidatePatchInput(in *PatchInput) error {
|
||||
if in.Nota != nil {
|
||||
if *in.Nota < 1 || *in.Nota > 10 {
|
||||
return errors.New("nota invalida")
|
||||
|
|
|
|||
|
|
@ -1,14 +1,4 @@
|
|||
(function(){
|
||||
// Widget NPS (arquivo único).
|
||||
//
|
||||
// Regras do projeto (.agent):
|
||||
// - sem dependências externas
|
||||
// - fail-closed
|
||||
// - contratos públicos estáveis
|
||||
//
|
||||
// Evolução: regras de negócio do cliente foram movidas para WASM (Go)
|
||||
// sempre que possível. O backend continua sendo a autoridade.
|
||||
|
||||
const DEFAULTS = {
|
||||
apiBase: '',
|
||||
cooldownHours: 24,
|
||||
|
|
@ -18,55 +8,51 @@
|
|||
data_minima_abertura: '',
|
||||
};
|
||||
|
||||
function parseDataMinima(s){
|
||||
// Aceita somente ISO (data) YYYY-MM-DD.
|
||||
// Retorna um Date no início do dia (00:00) no horário local.
|
||||
const v = String(s || '').trim();
|
||||
if(!v) return null;
|
||||
const m = /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/.exec(v);
|
||||
if(!m) return null;
|
||||
const ano = Number(m[1]);
|
||||
const mes = Number(m[2]);
|
||||
const dia = Number(m[3]);
|
||||
if(!ano || mes < 1 || mes > 12 || dia < 1 || dia > 31) return null;
|
||||
return new Date(ano, mes-1, dia, 0, 0, 0, 0);
|
||||
}
|
||||
|
||||
function antesDaDataMinima(cfg){
|
||||
const d = parseDataMinima(cfg.data_minima_abertura);
|
||||
if(!d) return false;
|
||||
return new Date() < d;
|
||||
}
|
||||
|
||||
function normalizeEmail(email){
|
||||
return String(email || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function cooldownKey(produto, inquilino, usuarioCodigo){
|
||||
// Prefixo de storage atualizado para o novo nome do projeto.
|
||||
return `eli-nps:cooldown:${produto}:${inquilino}:${usuarioCodigo}`;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// WASM (Go)
|
||||
// ------------------------------------------------------------------
|
||||
function nowMs(){ return Date.now(); }
|
||||
|
||||
async function carregarWasm(apiBase){
|
||||
// fail-closed: se o WASM não carregar, o widget não abre.
|
||||
if(window.__eli_nps_wasm_ready) return true;
|
||||
if(window.__eli_nps_wasm_loading) return window.__eli_nps_wasm_loading;
|
||||
|
||||
window.__eli_nps_wasm_loading = (async function(){
|
||||
function withinCooldown(key){
|
||||
try{
|
||||
// wasm_exec.js expõe global `Go`.
|
||||
if(!window.Go){
|
||||
await carregarScript(`${apiBase}/static/wasm_exec.js`);
|
||||
const v = localStorage.getItem(key);
|
||||
if(!v) return false;
|
||||
const obj = JSON.parse(v);
|
||||
return obj && obj.until && nowMs() < obj.until;
|
||||
}catch(e){ return false; }
|
||||
}
|
||||
|
||||
const go = new Go();
|
||||
const res = await fetch(`${apiBase}/static/e-li.nps.wasm`, {cache: 'no-cache'});
|
||||
if(!res.ok) return false;
|
||||
const bytes = await res.arrayBuffer();
|
||||
const {instance} = await WebAssembly.instantiate(bytes, go.importObject);
|
||||
go.run(instance);
|
||||
return !!window.__eli_nps_wasm_ready;
|
||||
}catch(e){
|
||||
return false;
|
||||
}
|
||||
})();
|
||||
|
||||
return window.__eli_nps_wasm_loading;
|
||||
}
|
||||
|
||||
function carregarScript(src){
|
||||
return new Promise(function(resolve, reject){
|
||||
function setCooldown(key, hours){
|
||||
try{
|
||||
const s = document.createElement('script');
|
||||
s.src = src;
|
||||
s.async = true;
|
||||
s.onload = function(){ resolve(); };
|
||||
s.onerror = function(){ reject(new Error('script_fail')); };
|
||||
document.head.appendChild(s);
|
||||
}catch(e){
|
||||
reject(e);
|
||||
}
|
||||
});
|
||||
const until = nowMs() + hours*3600*1000;
|
||||
localStorage.setItem(key, JSON.stringify({until}));
|
||||
}catch(e){}
|
||||
}
|
||||
|
||||
function createModal(){
|
||||
|
|
@ -147,43 +133,71 @@
|
|||
init: async function(opts){
|
||||
const cfg = Object.assign({}, DEFAULTS, opts || {});
|
||||
|
||||
// Carrega WASM (Go). Sem WASM, não abrimos o widget (fail-closed).
|
||||
const okWasm = await carregarWasm(cfg.apiBase);
|
||||
if(!okWasm) return;
|
||||
// Bloqueio por data mínima (feature flag simples).
|
||||
// Ex.: não abrir modal antes de 2026-01-01.
|
||||
if(antesDaDataMinima(cfg)){
|
||||
return;
|
||||
}
|
||||
|
||||
// Pré-validação e preparação do payload no WASM.
|
||||
const pre = window.__eli_nps_wasm_preflight(cfg);
|
||||
if(!pre || !pre.ok) return;
|
||||
// produto_nome pode ser qualquer string (ex.: "e-licencie", "Cachaça & Churras").
|
||||
// Regra do projeto: o tratamento/normalização de caracteres deve ser feito
|
||||
// apenas no backend, exclusivamente para nome de tabela/rotas.
|
||||
const produtoNome = String(cfg.produto_nome || '').trim();
|
||||
const inquilino = String(cfg.inquilino_codigo || '').trim();
|
||||
const usuarioCodigo = String(cfg.usuario_codigo || '').trim();
|
||||
const email = normalizeEmail(cfg.usuario_email);
|
||||
|
||||
// Cooldown visual no browser (WASM faz storage best-effort).
|
||||
// A chave do cooldown é best-effort e não participa de regra de segurança.
|
||||
if(window.__eli_nps_wasm_cooldown_ativo(pre.chave_cooldown)) return;
|
||||
// controle de exibição: produto + inquilino_codigo + usuario_codigo
|
||||
if(!produtoNome || !inquilino || !usuarioCodigo){
|
||||
return; // missing required context
|
||||
}
|
||||
|
||||
// A chave do cooldown é “best-effort” e não participa de nenhuma regra
|
||||
// de segurança. Mantemos o produto como foi informado.
|
||||
const chaveCooldown = cooldownKey(produtoNome, inquilino, usuarioCodigo);
|
||||
if(withinCooldown(chaveCooldown)) return;
|
||||
|
||||
// Enviamos exatamente o produto_nome informado.
|
||||
const payload = {
|
||||
produto_nome: produtoNome,
|
||||
inquilino_codigo: inquilino,
|
||||
inquilino_nome: String(cfg.inquilino_nome || '').trim(),
|
||||
usuario_codigo: usuarioCodigo,
|
||||
usuario_nome: String(cfg.usuario_nome || '').trim(),
|
||||
usuario_telefone: String(cfg.usuario_telefone || '').trim(),
|
||||
usuario_email: email,
|
||||
};
|
||||
|
||||
let data;
|
||||
try{
|
||||
const res = await postJSON(`${cfg.apiBase}/api/e-li.nps/pedido`, pre.payload);
|
||||
const res = await postJSON(`${cfg.apiBase}/api/e-li.nps/pedido`, payload);
|
||||
if(!res.ok) return; // fail-closed
|
||||
data = await res.json();
|
||||
}catch(e){
|
||||
return; // fail-closed
|
||||
}
|
||||
|
||||
const dec = window.__eli_nps_wasm_decidir(cfg, data);
|
||||
if(!dec || !dec.abrir){
|
||||
// cooldown para evitar flicker se o backend seguir rejeitando.
|
||||
if(dec && dec.aplicar_cooldown){
|
||||
window.__eli_nps_wasm_set_cooldown(pre.chave_cooldown, dec.cooldown_ate_ms);
|
||||
if(!data || !data.pode_abrir || !data.id){
|
||||
// small cooldown to avoid flicker if backend keeps rejecting
|
||||
setCooldown(chaveCooldown, cfg.cooldownHours);
|
||||
return;
|
||||
}
|
||||
|
||||
// Backend can return normalized product; use it for building iframe URL.
|
||||
const produtoRota = data.produto;
|
||||
if(!produtoRota){
|
||||
// fail-closed (não dá pra montar URL segura)
|
||||
setCooldown(chaveCooldown, cfg.cooldownHours);
|
||||
return;
|
||||
}
|
||||
|
||||
const modal = createModal();
|
||||
const iframe = document.createElement('iframe');
|
||||
iframe.src = `${cfg.apiBase}/e-li.nps/${dec.produto_rota}/${dec.id}/form`;
|
||||
iframe.src = `${cfg.apiBase}/e-li.nps/${produtoRota}/${data.id}/form`;
|
||||
modal.panel.appendChild(iframe);
|
||||
|
||||
// Visual cooldown so it doesn't keep popping (even if user closes).
|
||||
window.__eli_nps_wasm_set_cooldown(pre.chave_cooldown, dec.cooldown_ate_ms);
|
||||
setCooldown(chaveCooldown, cfg.cooldownHours);
|
||||
}
|
||||
};
|
||||
})();
|
||||
|
|
|
|||
Binary file not shown.
Binary file not shown.
|
Before Width: | Height: | Size: 97 KiB |
|
|
@ -1,575 +0,0 @@
|
|||
// Copyright 2018 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
"use strict";
|
||||
|
||||
(() => {
|
||||
const enosys = () => {
|
||||
const err = new Error("not implemented");
|
||||
err.code = "ENOSYS";
|
||||
return err;
|
||||
};
|
||||
|
||||
if (!globalThis.fs) {
|
||||
let outputBuf = "";
|
||||
globalThis.fs = {
|
||||
constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1, O_DIRECTORY: -1 }, // unused
|
||||
writeSync(fd, buf) {
|
||||
outputBuf += decoder.decode(buf);
|
||||
const nl = outputBuf.lastIndexOf("\n");
|
||||
if (nl != -1) {
|
||||
console.log(outputBuf.substring(0, nl));
|
||||
outputBuf = outputBuf.substring(nl + 1);
|
||||
}
|
||||
return buf.length;
|
||||
},
|
||||
write(fd, buf, offset, length, position, callback) {
|
||||
if (offset !== 0 || length !== buf.length || position !== null) {
|
||||
callback(enosys());
|
||||
return;
|
||||
}
|
||||
const n = this.writeSync(fd, buf);
|
||||
callback(null, n);
|
||||
},
|
||||
chmod(path, mode, callback) { callback(enosys()); },
|
||||
chown(path, uid, gid, callback) { callback(enosys()); },
|
||||
close(fd, callback) { callback(enosys()); },
|
||||
fchmod(fd, mode, callback) { callback(enosys()); },
|
||||
fchown(fd, uid, gid, callback) { callback(enosys()); },
|
||||
fstat(fd, callback) { callback(enosys()); },
|
||||
fsync(fd, callback) { callback(null); },
|
||||
ftruncate(fd, length, callback) { callback(enosys()); },
|
||||
lchown(path, uid, gid, callback) { callback(enosys()); },
|
||||
link(path, link, callback) { callback(enosys()); },
|
||||
lstat(path, callback) { callback(enosys()); },
|
||||
mkdir(path, perm, callback) { callback(enosys()); },
|
||||
open(path, flags, mode, callback) { callback(enosys()); },
|
||||
read(fd, buffer, offset, length, position, callback) { callback(enosys()); },
|
||||
readdir(path, callback) { callback(enosys()); },
|
||||
readlink(path, callback) { callback(enosys()); },
|
||||
rename(from, to, callback) { callback(enosys()); },
|
||||
rmdir(path, callback) { callback(enosys()); },
|
||||
stat(path, callback) { callback(enosys()); },
|
||||
symlink(path, link, callback) { callback(enosys()); },
|
||||
truncate(path, length, callback) { callback(enosys()); },
|
||||
unlink(path, callback) { callback(enosys()); },
|
||||
utimes(path, atime, mtime, callback) { callback(enosys()); },
|
||||
};
|
||||
}
|
||||
|
||||
if (!globalThis.process) {
|
||||
globalThis.process = {
|
||||
getuid() { return -1; },
|
||||
getgid() { return -1; },
|
||||
geteuid() { return -1; },
|
||||
getegid() { return -1; },
|
||||
getgroups() { throw enosys(); },
|
||||
pid: -1,
|
||||
ppid: -1,
|
||||
umask() { throw enosys(); },
|
||||
cwd() { throw enosys(); },
|
||||
chdir() { throw enosys(); },
|
||||
}
|
||||
}
|
||||
|
||||
if (!globalThis.path) {
|
||||
globalThis.path = {
|
||||
resolve(...pathSegments) {
|
||||
return pathSegments.join("/");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!globalThis.crypto) {
|
||||
throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)");
|
||||
}
|
||||
|
||||
if (!globalThis.performance) {
|
||||
throw new Error("globalThis.performance is not available, polyfill required (performance.now only)");
|
||||
}
|
||||
|
||||
if (!globalThis.TextEncoder) {
|
||||
throw new Error("globalThis.TextEncoder is not available, polyfill required");
|
||||
}
|
||||
|
||||
if (!globalThis.TextDecoder) {
|
||||
throw new Error("globalThis.TextDecoder is not available, polyfill required");
|
||||
}
|
||||
|
||||
const encoder = new TextEncoder("utf-8");
|
||||
const decoder = new TextDecoder("utf-8");
|
||||
|
||||
globalThis.Go = class {
|
||||
constructor() {
|
||||
this.argv = ["js"];
|
||||
this.env = {};
|
||||
this.exit = (code) => {
|
||||
if (code !== 0) {
|
||||
console.warn("exit code:", code);
|
||||
}
|
||||
};
|
||||
this._exitPromise = new Promise((resolve) => {
|
||||
this._resolveExitPromise = resolve;
|
||||
});
|
||||
this._pendingEvent = null;
|
||||
this._scheduledTimeouts = new Map();
|
||||
this._nextCallbackTimeoutID = 1;
|
||||
|
||||
const setInt64 = (addr, v) => {
|
||||
this.mem.setUint32(addr + 0, v, true);
|
||||
this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true);
|
||||
}
|
||||
|
||||
const setInt32 = (addr, v) => {
|
||||
this.mem.setUint32(addr + 0, v, true);
|
||||
}
|
||||
|
||||
const getInt64 = (addr) => {
|
||||
const low = this.mem.getUint32(addr + 0, true);
|
||||
const high = this.mem.getInt32(addr + 4, true);
|
||||
return low + high * 4294967296;
|
||||
}
|
||||
|
||||
const loadValue = (addr) => {
|
||||
const f = this.mem.getFloat64(addr, true);
|
||||
if (f === 0) {
|
||||
return undefined;
|
||||
}
|
||||
if (!isNaN(f)) {
|
||||
return f;
|
||||
}
|
||||
|
||||
const id = this.mem.getUint32(addr, true);
|
||||
return this._values[id];
|
||||
}
|
||||
|
||||
const storeValue = (addr, v) => {
|
||||
const nanHead = 0x7FF80000;
|
||||
|
||||
if (typeof v === "number" && v !== 0) {
|
||||
if (isNaN(v)) {
|
||||
this.mem.setUint32(addr + 4, nanHead, true);
|
||||
this.mem.setUint32(addr, 0, true);
|
||||
return;
|
||||
}
|
||||
this.mem.setFloat64(addr, v, true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (v === undefined) {
|
||||
this.mem.setFloat64(addr, 0, true);
|
||||
return;
|
||||
}
|
||||
|
||||
let id = this._ids.get(v);
|
||||
if (id === undefined) {
|
||||
id = this._idPool.pop();
|
||||
if (id === undefined) {
|
||||
id = this._values.length;
|
||||
}
|
||||
this._values[id] = v;
|
||||
this._goRefCounts[id] = 0;
|
||||
this._ids.set(v, id);
|
||||
}
|
||||
this._goRefCounts[id]++;
|
||||
let typeFlag = 0;
|
||||
switch (typeof v) {
|
||||
case "object":
|
||||
if (v !== null) {
|
||||
typeFlag = 1;
|
||||
}
|
||||
break;
|
||||
case "string":
|
||||
typeFlag = 2;
|
||||
break;
|
||||
case "symbol":
|
||||
typeFlag = 3;
|
||||
break;
|
||||
case "function":
|
||||
typeFlag = 4;
|
||||
break;
|
||||
}
|
||||
this.mem.setUint32(addr + 4, nanHead | typeFlag, true);
|
||||
this.mem.setUint32(addr, id, true);
|
||||
}
|
||||
|
||||
const loadSlice = (addr) => {
|
||||
const array = getInt64(addr + 0);
|
||||
const len = getInt64(addr + 8);
|
||||
return new Uint8Array(this._inst.exports.mem.buffer, array, len);
|
||||
}
|
||||
|
||||
const loadSliceOfValues = (addr) => {
|
||||
const array = getInt64(addr + 0);
|
||||
const len = getInt64(addr + 8);
|
||||
const a = new Array(len);
|
||||
for (let i = 0; i < len; i++) {
|
||||
a[i] = loadValue(array + i * 8);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
const loadString = (addr) => {
|
||||
const saddr = getInt64(addr + 0);
|
||||
const len = getInt64(addr + 8);
|
||||
return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len));
|
||||
}
|
||||
|
||||
const testCallExport = (a, b) => {
|
||||
this._inst.exports.testExport0();
|
||||
return this._inst.exports.testExport(a, b);
|
||||
}
|
||||
|
||||
const timeOrigin = Date.now() - performance.now();
|
||||
this.importObject = {
|
||||
_gotest: {
|
||||
add: (a, b) => a + b,
|
||||
callExport: testCallExport,
|
||||
},
|
||||
gojs: {
|
||||
// Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters)
|
||||
// may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported
|
||||
// function. A goroutine can switch to a new stack if the current stack is too small (see morestack function).
|
||||
// This changes the SP, thus we have to update the SP used by the imported function.
|
||||
|
||||
// func wasmExit(code int32)
|
||||
"runtime.wasmExit": (sp) => {
|
||||
sp >>>= 0;
|
||||
const code = this.mem.getInt32(sp + 8, true);
|
||||
this.exited = true;
|
||||
delete this._inst;
|
||||
delete this._values;
|
||||
delete this._goRefCounts;
|
||||
delete this._ids;
|
||||
delete this._idPool;
|
||||
this.exit(code);
|
||||
},
|
||||
|
||||
// func wasmWrite(fd uintptr, p unsafe.Pointer, n int32)
|
||||
"runtime.wasmWrite": (sp) => {
|
||||
sp >>>= 0;
|
||||
const fd = getInt64(sp + 8);
|
||||
const p = getInt64(sp + 16);
|
||||
const n = this.mem.getInt32(sp + 24, true);
|
||||
fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n));
|
||||
},
|
||||
|
||||
// func resetMemoryDataView()
|
||||
"runtime.resetMemoryDataView": (sp) => {
|
||||
sp >>>= 0;
|
||||
this.mem = new DataView(this._inst.exports.mem.buffer);
|
||||
},
|
||||
|
||||
// func nanotime1() int64
|
||||
"runtime.nanotime1": (sp) => {
|
||||
sp >>>= 0;
|
||||
setInt64(sp + 8, (timeOrigin + performance.now()) * 1000000);
|
||||
},
|
||||
|
||||
// func walltime() (sec int64, nsec int32)
|
||||
"runtime.walltime": (sp) => {
|
||||
sp >>>= 0;
|
||||
const msec = (new Date).getTime();
|
||||
setInt64(sp + 8, msec / 1000);
|
||||
this.mem.setInt32(sp + 16, (msec % 1000) * 1000000, true);
|
||||
},
|
||||
|
||||
// func scheduleTimeoutEvent(delay int64) int32
|
||||
"runtime.scheduleTimeoutEvent": (sp) => {
|
||||
sp >>>= 0;
|
||||
const id = this._nextCallbackTimeoutID;
|
||||
this._nextCallbackTimeoutID++;
|
||||
this._scheduledTimeouts.set(id, setTimeout(
|
||||
() => {
|
||||
this._resume();
|
||||
while (this._scheduledTimeouts.has(id)) {
|
||||
// for some reason Go failed to register the timeout event, log and try again
|
||||
// (temporary workaround for https://github.com/golang/go/issues/28975)
|
||||
console.warn("scheduleTimeoutEvent: missed timeout event");
|
||||
this._resume();
|
||||
}
|
||||
},
|
||||
getInt64(sp + 8),
|
||||
));
|
||||
this.mem.setInt32(sp + 16, id, true);
|
||||
},
|
||||
|
||||
// func clearTimeoutEvent(id int32)
|
||||
"runtime.clearTimeoutEvent": (sp) => {
|
||||
sp >>>= 0;
|
||||
const id = this.mem.getInt32(sp + 8, true);
|
||||
clearTimeout(this._scheduledTimeouts.get(id));
|
||||
this._scheduledTimeouts.delete(id);
|
||||
},
|
||||
|
||||
// func getRandomData(r []byte)
|
||||
"runtime.getRandomData": (sp) => {
|
||||
sp >>>= 0;
|
||||
crypto.getRandomValues(loadSlice(sp + 8));
|
||||
},
|
||||
|
||||
// func finalizeRef(v ref)
|
||||
"syscall/js.finalizeRef": (sp) => {
|
||||
sp >>>= 0;
|
||||
const id = this.mem.getUint32(sp + 8, true);
|
||||
this._goRefCounts[id]--;
|
||||
if (this._goRefCounts[id] === 0) {
|
||||
const v = this._values[id];
|
||||
this._values[id] = null;
|
||||
this._ids.delete(v);
|
||||
this._idPool.push(id);
|
||||
}
|
||||
},
|
||||
|
||||
// func stringVal(value string) ref
|
||||
"syscall/js.stringVal": (sp) => {
|
||||
sp >>>= 0;
|
||||
storeValue(sp + 24, loadString(sp + 8));
|
||||
},
|
||||
|
||||
// func valueGet(v ref, p string) ref
|
||||
"syscall/js.valueGet": (sp) => {
|
||||
sp >>>= 0;
|
||||
const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16));
|
||||
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
||||
storeValue(sp + 32, result);
|
||||
},
|
||||
|
||||
// func valueSet(v ref, p string, x ref)
|
||||
"syscall/js.valueSet": (sp) => {
|
||||
sp >>>= 0;
|
||||
Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32));
|
||||
},
|
||||
|
||||
// func valueDelete(v ref, p string)
|
||||
"syscall/js.valueDelete": (sp) => {
|
||||
sp >>>= 0;
|
||||
Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16));
|
||||
},
|
||||
|
||||
// func valueIndex(v ref, i int) ref
|
||||
"syscall/js.valueIndex": (sp) => {
|
||||
sp >>>= 0;
|
||||
storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16)));
|
||||
},
|
||||
|
||||
// valueSetIndex(v ref, i int, x ref)
|
||||
"syscall/js.valueSetIndex": (sp) => {
|
||||
sp >>>= 0;
|
||||
Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24));
|
||||
},
|
||||
|
||||
// func valueCall(v ref, m string, args []ref) (ref, bool)
|
||||
"syscall/js.valueCall": (sp) => {
|
||||
sp >>>= 0;
|
||||
try {
|
||||
const v = loadValue(sp + 8);
|
||||
const m = Reflect.get(v, loadString(sp + 16));
|
||||
const args = loadSliceOfValues(sp + 32);
|
||||
const result = Reflect.apply(m, v, args);
|
||||
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
||||
storeValue(sp + 56, result);
|
||||
this.mem.setUint8(sp + 64, 1);
|
||||
} catch (err) {
|
||||
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
||||
storeValue(sp + 56, err);
|
||||
this.mem.setUint8(sp + 64, 0);
|
||||
}
|
||||
},
|
||||
|
||||
// func valueInvoke(v ref, args []ref) (ref, bool)
|
||||
"syscall/js.valueInvoke": (sp) => {
|
||||
sp >>>= 0;
|
||||
try {
|
||||
const v = loadValue(sp + 8);
|
||||
const args = loadSliceOfValues(sp + 16);
|
||||
const result = Reflect.apply(v, undefined, args);
|
||||
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
||||
storeValue(sp + 40, result);
|
||||
this.mem.setUint8(sp + 48, 1);
|
||||
} catch (err) {
|
||||
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
||||
storeValue(sp + 40, err);
|
||||
this.mem.setUint8(sp + 48, 0);
|
||||
}
|
||||
},
|
||||
|
||||
// func valueNew(v ref, args []ref) (ref, bool)
|
||||
"syscall/js.valueNew": (sp) => {
|
||||
sp >>>= 0;
|
||||
try {
|
||||
const v = loadValue(sp + 8);
|
||||
const args = loadSliceOfValues(sp + 16);
|
||||
const result = Reflect.construct(v, args);
|
||||
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
||||
storeValue(sp + 40, result);
|
||||
this.mem.setUint8(sp + 48, 1);
|
||||
} catch (err) {
|
||||
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
||||
storeValue(sp + 40, err);
|
||||
this.mem.setUint8(sp + 48, 0);
|
||||
}
|
||||
},
|
||||
|
||||
// func valueLength(v ref) int
|
||||
"syscall/js.valueLength": (sp) => {
|
||||
sp >>>= 0;
|
||||
setInt64(sp + 16, parseInt(loadValue(sp + 8).length));
|
||||
},
|
||||
|
||||
// valuePrepareString(v ref) (ref, int)
|
||||
"syscall/js.valuePrepareString": (sp) => {
|
||||
sp >>>= 0;
|
||||
const str = encoder.encode(String(loadValue(sp + 8)));
|
||||
storeValue(sp + 16, str);
|
||||
setInt64(sp + 24, str.length);
|
||||
},
|
||||
|
||||
// valueLoadString(v ref, b []byte)
|
||||
"syscall/js.valueLoadString": (sp) => {
|
||||
sp >>>= 0;
|
||||
const str = loadValue(sp + 8);
|
||||
loadSlice(sp + 16).set(str);
|
||||
},
|
||||
|
||||
// func valueInstanceOf(v ref, t ref) bool
|
||||
"syscall/js.valueInstanceOf": (sp) => {
|
||||
sp >>>= 0;
|
||||
this.mem.setUint8(sp + 24, (loadValue(sp + 8) instanceof loadValue(sp + 16)) ? 1 : 0);
|
||||
},
|
||||
|
||||
// func copyBytesToGo(dst []byte, src ref) (int, bool)
|
||||
"syscall/js.copyBytesToGo": (sp) => {
|
||||
sp >>>= 0;
|
||||
const dst = loadSlice(sp + 8);
|
||||
const src = loadValue(sp + 32);
|
||||
if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) {
|
||||
this.mem.setUint8(sp + 48, 0);
|
||||
return;
|
||||
}
|
||||
const toCopy = src.subarray(0, dst.length);
|
||||
dst.set(toCopy);
|
||||
setInt64(sp + 40, toCopy.length);
|
||||
this.mem.setUint8(sp + 48, 1);
|
||||
},
|
||||
|
||||
// func copyBytesToJS(dst ref, src []byte) (int, bool)
|
||||
"syscall/js.copyBytesToJS": (sp) => {
|
||||
sp >>>= 0;
|
||||
const dst = loadValue(sp + 8);
|
||||
const src = loadSlice(sp + 16);
|
||||
if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) {
|
||||
this.mem.setUint8(sp + 48, 0);
|
||||
return;
|
||||
}
|
||||
const toCopy = src.subarray(0, dst.length);
|
||||
dst.set(toCopy);
|
||||
setInt64(sp + 40, toCopy.length);
|
||||
this.mem.setUint8(sp + 48, 1);
|
||||
},
|
||||
|
||||
"debug": (value) => {
|
||||
console.log(value);
|
||||
},
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async run(instance) {
|
||||
if (!(instance instanceof WebAssembly.Instance)) {
|
||||
throw new Error("Go.run: WebAssembly.Instance expected");
|
||||
}
|
||||
this._inst = instance;
|
||||
this.mem = new DataView(this._inst.exports.mem.buffer);
|
||||
this._values = [ // JS values that Go currently has references to, indexed by reference id
|
||||
NaN,
|
||||
0,
|
||||
null,
|
||||
true,
|
||||
false,
|
||||
globalThis,
|
||||
this,
|
||||
];
|
||||
this._goRefCounts = new Array(this._values.length).fill(Infinity); // number of references that Go has to a JS value, indexed by reference id
|
||||
this._ids = new Map([ // mapping from JS values to reference ids
|
||||
[0, 1],
|
||||
[null, 2],
|
||||
[true, 3],
|
||||
[false, 4],
|
||||
[globalThis, 5],
|
||||
[this, 6],
|
||||
]);
|
||||
this._idPool = []; // unused ids that have been garbage collected
|
||||
this.exited = false; // whether the Go program has exited
|
||||
|
||||
// Pass command line arguments and environment variables to WebAssembly by writing them to the linear memory.
|
||||
let offset = 4096;
|
||||
|
||||
const strPtr = (str) => {
|
||||
const ptr = offset;
|
||||
const bytes = encoder.encode(str + "\0");
|
||||
new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes);
|
||||
offset += bytes.length;
|
||||
if (offset % 8 !== 0) {
|
||||
offset += 8 - (offset % 8);
|
||||
}
|
||||
return ptr;
|
||||
};
|
||||
|
||||
const argc = this.argv.length;
|
||||
|
||||
const argvPtrs = [];
|
||||
this.argv.forEach((arg) => {
|
||||
argvPtrs.push(strPtr(arg));
|
||||
});
|
||||
argvPtrs.push(0);
|
||||
|
||||
const keys = Object.keys(this.env).sort();
|
||||
keys.forEach((key) => {
|
||||
argvPtrs.push(strPtr(`${key}=${this.env[key]}`));
|
||||
});
|
||||
argvPtrs.push(0);
|
||||
|
||||
const argv = offset;
|
||||
argvPtrs.forEach((ptr) => {
|
||||
this.mem.setUint32(offset, ptr, true);
|
||||
this.mem.setUint32(offset + 4, 0, true);
|
||||
offset += 8;
|
||||
});
|
||||
|
||||
// The linker guarantees global data starts from at least wasmMinDataAddr.
|
||||
// Keep in sync with cmd/link/internal/ld/data.go:wasmMinDataAddr.
|
||||
const wasmMinDataAddr = 4096 + 8192;
|
||||
if (offset >= wasmMinDataAddr) {
|
||||
throw new Error("total length of command line and environment variables exceeds limit");
|
||||
}
|
||||
|
||||
this._inst.exports.run(argc, argv);
|
||||
if (this.exited) {
|
||||
this._resolveExitPromise();
|
||||
}
|
||||
await this._exitPromise;
|
||||
}
|
||||
|
||||
_resume() {
|
||||
if (this.exited) {
|
||||
throw new Error("Go program has already exited");
|
||||
}
|
||||
this._inst.exports.resume();
|
||||
if (this.exited) {
|
||||
this._resolveExitPromise();
|
||||
}
|
||||
}
|
||||
|
||||
_makeFuncWrapper(id) {
|
||||
const go = this;
|
||||
return function () {
|
||||
const event = { id: id, this: this, args: arguments };
|
||||
go._pendingEvent = event;
|
||||
go._resume();
|
||||
return event.result;
|
||||
};
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
{{define "form_inner.html"}}
|
||||
{{/* Este bloco pode ser trocado pelo HTMX (target #eli-nps-modal-body) */}}
|
||||
{{/* This block can be swapped by HTMX (target #eli-nps-modal-body) */}}
|
||||
{{if eq .Reg.Status "respondido"}}
|
||||
<div class="eli-nps-ok">
|
||||
<p class="eli-nps-title">Obrigado!</p>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue