Redator de SD - preparado para deploy
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
# Copie este arquivo para ".env" (na mesma pasta) e preencha a chave.
|
||||
# O arquivo .env NUNCA deve ser versionado nem compartilhado.
|
||||
|
||||
# Chave da API da Anthropic (crie em https://console.anthropic.com -> API Keys)
|
||||
ANTHROPIC_API_KEY=
|
||||
|
||||
# Provedor de LLM (por enquanto apenas "anthropic"; adaptador OpenAI previsto para a fase 1.1)
|
||||
LLM_PROVIDER=anthropic
|
||||
|
||||
# Modelo padrão
|
||||
LLM_MODEL=claude-opus-5
|
||||
|
||||
# Modelos oferecidos nos seletores da interface (Nova SD e Base de Conhecimento),
|
||||
# separados por vírgula. O LLM_MODEL acima sempre entra na lista, como padrão.
|
||||
# Obs.: o custo estimado no rodapé usa a tabela de preços do Opus.
|
||||
LLM_MODELOS=claude-sonnet-5,claude-haiku-4-5-20251001
|
||||
|
||||
# Esforço de raciocínio do modelo: low | medium | high | xhigh | max
|
||||
# (vazio = padrão da API, que é high). "medium" acelera bem a entrevista
|
||||
# com perda mínima de qualidade; suba para high se notar respostas rasas.
|
||||
LLM_EFFORT=medium
|
||||
|
||||
# Porta do servidor local
|
||||
PORT=3344
|
||||
|
||||
# Login do app (usuário único). Enquanto os dois campos estiverem vazios,
|
||||
# o app roda SEM login e mostra um aviso.
|
||||
APP_USUARIO=
|
||||
APP_SENHA=
|
||||
@@ -0,0 +1,3 @@
|
||||
node_modules/
|
||||
.env
|
||||
data/
|
||||
@@ -0,0 +1,88 @@
|
||||
# Redator de SD — RMDS / SES-MG × Isis Saúde
|
||||
|
||||
App local que conduz a entrevista de redação de Solicitações de Demanda (SD) com um LLM,
|
||||
valida em código contra as regras do contrato (PE 29/2025) e mantém a base de conhecimento.
|
||||
|
||||
## Primeira execução
|
||||
|
||||
1. **Chave de API** — crie em https://console.anthropic.com → *API Keys* e coloque um crédito
|
||||
inicial pequeno (US$ 5–10 rendem dezenas de SDs).
|
||||
2. **Configuração** — copie `.env.example` para `.env` (nesta pasta) e preencha
|
||||
`ANTHROPIC_API_KEY`. Defina também `APP_USUARIO` e `APP_SENHA` para ativar a
|
||||
tela de login (enquanto vazios, o app roda aberto e mostra um aviso).
|
||||
O `.env` nunca deve ser versionado nem compartilhado.
|
||||
3. **Dependências** (só na primeira vez):
|
||||
```
|
||||
cd D:\IasisSaude\app
|
||||
npm install
|
||||
```
|
||||
4. **Rodar**:
|
||||
```
|
||||
npm start
|
||||
```
|
||||
e abra http://localhost:3344 no navegador.
|
||||
|
||||
## Como funciona
|
||||
|
||||
- **Nova SD**: cole a demanda bruta → o redator entrevista você (uma pergunta por turno,
|
||||
opções viram botões) enquanto o painel do documento se atualiza ao vivo.
|
||||
- **Validação**: os itens `codigo` do checklist são recalculados em JavaScript a cada
|
||||
atualização — e o resultado é realimentado ao modelo, que se corrige sozinho.
|
||||
- **Trava de integridade**: exportação e envio ficam bloqueados até todos os artefatos
|
||||
serem confirmados (checkbox + data) e nenhuma falha de código restar.
|
||||
- **Envio**: atribui o número definitivo (SD-NN) e registra a SD em
|
||||
`..\base-conhecimento.json` — saldo de pools e precedentes ficam atualizados
|
||||
para as próximas entrevistas.
|
||||
- **Documento / impressão**: o botão "Documento / imprimir (PDF)" abre a SD formatada
|
||||
como documento oficial em uma aba pronta para Ctrl+P → salvar como PDF. Com pendências
|
||||
bloqueantes abertas, o documento sai com marca de RASCUNHO.
|
||||
- **Validar JSON externo** (menu no topo): cole o JSON de uma SD que não nasceu no app —
|
||||
o validador recalcula tudo, roda o checklist e libera documento/download, sem salvar nada.
|
||||
- **Alimentar base** (menu no topo): envie o documento de uma SD real (`.pdf`, `.md` ou `.txt`;
|
||||
`.docx` deve ser exportado como PDF). Uma chamada de LLM extrai o registro estruturado
|
||||
(itens, UST por item, período, status) e sugere capacidades reutilizáveis; a conferência
|
||||
determinística em código checa somas, itens, status e impacto nos pools. **Nada é gravado
|
||||
sem revisão**: você edita o registro, marca/desmarca capacidades e só então grava em
|
||||
`..\base-conhecimento.json`. Erros de conferência bloqueiam a gravação; regravar o mesmo
|
||||
SD-NN substitui o registro anterior (capacidades, porém, são sempre acrescentadas — ao
|
||||
regravar uma SD, desmarque as que já entraram na primeira vez).
|
||||
- **Login**: usuário único definido no `.env`. As sessões vivem na memória do servidor —
|
||||
reiniciar o servidor exige novo login.
|
||||
|
||||
## Arquivos de configuração (raiz do projeto, `D:\IasisSaude`)
|
||||
|
||||
| Arquivo | Papel |
|
||||
|---|---|
|
||||
| `prompt-redator-sd.md` | Comportamento do redator (system prompt) |
|
||||
| `regras-sd.json` | Regras duras do contrato — fonte única |
|
||||
| `schema-sd.json` | Formato da SD |
|
||||
| `base-conhecimento.json` | Histórico: SDs enviadas e capacidades da plataforma |
|
||||
|
||||
Editar qualquer um deles muda o app na próxima reinicialização — não é preciso mexer em código.
|
||||
|
||||
## Custos
|
||||
|
||||
O rodapé do chat mostra tokens e custo estimado em tempo real. O system prompt
|
||||
(prompt + regras + base) é cacheado pela API — turnos seguintes da mesma conversa
|
||||
pagam ~10% do preço no prefixo repetido.
|
||||
|
||||
## Dados
|
||||
|
||||
- `data/sds.json` — SDs e conversas (criado automaticamente; fora do versionamento).
|
||||
- Provedor/modelo/esforço configuráveis no `.env` (`LLM_PROVIDER`, `LLM_MODEL`,
|
||||
`LLM_EFFORT` — low/medium/high/xhigh/max; medium recomendado para a entrevista).
|
||||
Adaptador OpenAI previsto para a fase 1.1 (`src/llm/provider.js`).
|
||||
- **Seletor de modelo**: `LLM_MODELOS` (lista separada por vírgula) define os modelos
|
||||
oferecidos nos seletores das telas Nova SD e Base de Conhecimento; o `LLM_MODEL`
|
||||
sempre entra como padrão. O modelo escolhido fica fixo para a SD inteira — trocar
|
||||
no meio da conversa descartaria o cache de prompt. O custo do rodapé usa a tabela
|
||||
de preços do Opus (a observação ao lado do valor lembra isso).
|
||||
|
||||
## Atualização dos arquivos de configuração
|
||||
|
||||
O prompt do redator é remontado automaticamente quando `base-conhecimento.json`,
|
||||
`prompt-redator-sd.md`, `regras-sd.json` ou `schema-sd.json` mudam no disco —
|
||||
vale a partir da PRÓXIMA conversa, sem reiniciar o servidor. Exceção: mudanças em
|
||||
`regras-sd.json`/`schema-sd.json` também alimentam o validador em código e a
|
||||
ferramenta do modelo, que carregam na subida — para essas duas, reinicie.
|
||||
Mudanças no `.env` sempre exigem reinício.
|
||||
@@ -0,0 +1,3 @@
|
||||
Subir Aplicação
|
||||
|
||||
cd D:\IasisSaude\app && npm start
|
||||
Generated
+890
@@ -0,0 +1,890 @@
|
||||
{
|
||||
"name": "redator-sd",
|
||||
"version": "0.1.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "redator-sd",
|
||||
"version": "0.1.0",
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "^0.74.0",
|
||||
"dotenv": "^16.4.5",
|
||||
"express": "^4.21.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@anthropic-ai/sdk": {
|
||||
"version": "0.74.0",
|
||||
"resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.74.0.tgz",
|
||||
"integrity": "sha512-srbJV7JKsc5cQ6eVuFzjZO7UR3xEPJqPamHFIe29bs38Ij2IripoAhC0S5NslNbaFUYqBKypmmpzMTpqfHEUDw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"json-schema-to-ts": "^3.1.1"
|
||||
},
|
||||
"bin": {
|
||||
"anthropic-ai-sdk": "bin/cli"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"zod": "^3.25.0 || ^4.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"zod": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/runtime": {
|
||||
"version": "7.29.7",
|
||||
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz",
|
||||
"integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/accepts": {
|
||||
"version": "1.3.8",
|
||||
"resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
|
||||
"integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"mime-types": "~2.1.34",
|
||||
"negotiator": "0.6.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/array-flatten": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
|
||||
"integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/body-parser": {
|
||||
"version": "1.20.6",
|
||||
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.6.tgz",
|
||||
"integrity": "sha512-p5tAzS57i5MV9fZFDj9LeIiTZEufbSe2eDozP+ElheSUq1m74CRq1jI4mYNDdVs9vQztXFLuk/Gd6BWTdwRJ5g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"bytes": "~3.1.2",
|
||||
"content-type": "~1.0.5",
|
||||
"debug": "2.6.9",
|
||||
"depd": "2.0.0",
|
||||
"destroy": "~1.2.0",
|
||||
"http-errors": "~2.0.1",
|
||||
"iconv-lite": "~0.4.24",
|
||||
"on-finished": "~2.4.1",
|
||||
"qs": "~6.15.1",
|
||||
"raw-body": "~2.5.3",
|
||||
"type-is": "~1.6.18",
|
||||
"unpipe": "~1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8",
|
||||
"npm": "1.2.8000 || >= 1.4.16"
|
||||
}
|
||||
},
|
||||
"node_modules/bytes": {
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
|
||||
"integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/call-bind-apply-helpers": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
|
||||
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"es-errors": "^1.3.0",
|
||||
"function-bind": "^1.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/call-bound": {
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",
|
||||
"integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"call-bind-apply-helpers": "^1.0.2",
|
||||
"get-intrinsic": "^1.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/content-disposition": {
|
||||
"version": "0.5.4",
|
||||
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
|
||||
"integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"safe-buffer": "5.2.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/content-type": {
|
||||
"version": "1.0.5",
|
||||
"resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
|
||||
"integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/cookie": {
|
||||
"version": "0.7.2",
|
||||
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
|
||||
"integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/cookie-signature": {
|
||||
"version": "1.0.7",
|
||||
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz",
|
||||
"integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/debug": {
|
||||
"version": "2.6.9",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
|
||||
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ms": "2.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/depd": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
|
||||
"integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/destroy": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz",
|
||||
"integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.8",
|
||||
"npm": "1.2.8000 || >= 1.4.16"
|
||||
}
|
||||
},
|
||||
"node_modules/dotenv": {
|
||||
"version": "16.6.1",
|
||||
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz",
|
||||
"integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==",
|
||||
"license": "BSD-2-Clause",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://dotenvx.com"
|
||||
}
|
||||
},
|
||||
"node_modules/dunder-proto": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
|
||||
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"call-bind-apply-helpers": "^1.0.1",
|
||||
"es-errors": "^1.3.0",
|
||||
"gopd": "^1.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/ee-first": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
|
||||
"integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/encodeurl": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
|
||||
"integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/es-define-property": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
|
||||
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/es-errors": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
|
||||
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/es-object-atoms": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz",
|
||||
"integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"es-errors": "^1.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/escape-html": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
|
||||
"integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/etag": {
|
||||
"version": "1.8.1",
|
||||
"resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
|
||||
"integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/express": {
|
||||
"version": "4.22.2",
|
||||
"resolved": "https://registry.npmjs.org/express/-/express-4.22.2.tgz",
|
||||
"integrity": "sha512-IuL+Elrou2ZvCFHs18/CIzy2Nzvo25nZ1/D2eIZlz7c+QUayAcYoiM2BthCjs+EBHVpjYjcuLDAiCWgeIX3X1Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"accepts": "~1.3.8",
|
||||
"array-flatten": "1.1.1",
|
||||
"body-parser": "~1.20.5",
|
||||
"content-disposition": "~0.5.4",
|
||||
"content-type": "~1.0.4",
|
||||
"cookie": "~0.7.1",
|
||||
"cookie-signature": "~1.0.6",
|
||||
"debug": "2.6.9",
|
||||
"depd": "2.0.0",
|
||||
"encodeurl": "~2.0.0",
|
||||
"escape-html": "~1.0.3",
|
||||
"etag": "~1.8.1",
|
||||
"finalhandler": "~1.3.1",
|
||||
"fresh": "~0.5.2",
|
||||
"http-errors": "~2.0.0",
|
||||
"merge-descriptors": "1.0.3",
|
||||
"methods": "~1.1.2",
|
||||
"on-finished": "~2.4.1",
|
||||
"parseurl": "~1.3.3",
|
||||
"path-to-regexp": "~0.1.12",
|
||||
"proxy-addr": "~2.0.7",
|
||||
"qs": "~6.15.1",
|
||||
"range-parser": "~1.2.1",
|
||||
"safe-buffer": "5.2.1",
|
||||
"send": "~0.19.0",
|
||||
"serve-static": "~1.16.2",
|
||||
"setprototypeof": "1.2.0",
|
||||
"statuses": "~2.0.1",
|
||||
"type-is": "~1.6.18",
|
||||
"utils-merge": "1.0.1",
|
||||
"vary": "~1.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.10.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/finalhandler": {
|
||||
"version": "1.3.2",
|
||||
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz",
|
||||
"integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"debug": "2.6.9",
|
||||
"encodeurl": "~2.0.0",
|
||||
"escape-html": "~1.0.3",
|
||||
"on-finished": "~2.4.1",
|
||||
"parseurl": "~1.3.3",
|
||||
"statuses": "~2.0.2",
|
||||
"unpipe": "~1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/forwarded": {
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
|
||||
"integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/fresh": {
|
||||
"version": "0.5.2",
|
||||
"resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
|
||||
"integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/function-bind": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
|
||||
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/get-intrinsic": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
|
||||
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"call-bind-apply-helpers": "^1.0.2",
|
||||
"es-define-property": "^1.0.1",
|
||||
"es-errors": "^1.3.0",
|
||||
"es-object-atoms": "^1.1.1",
|
||||
"function-bind": "^1.1.2",
|
||||
"get-proto": "^1.0.1",
|
||||
"gopd": "^1.2.0",
|
||||
"has-symbols": "^1.1.0",
|
||||
"hasown": "^2.0.2",
|
||||
"math-intrinsics": "^1.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/get-proto": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
|
||||
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"dunder-proto": "^1.0.1",
|
||||
"es-object-atoms": "^1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/gopd": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
|
||||
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/has-symbols": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
|
||||
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/hasown": {
|
||||
"version": "2.0.4",
|
||||
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",
|
||||
"integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"function-bind": "^1.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/http-errors": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
|
||||
"integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"depd": "~2.0.0",
|
||||
"inherits": "~2.0.4",
|
||||
"setprototypeof": "~1.2.0",
|
||||
"statuses": "~2.0.2",
|
||||
"toidentifier": "~1.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/iconv-lite": {
|
||||
"version": "0.4.24",
|
||||
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",
|
||||
"integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"safer-buffer": ">= 2.1.2 < 3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/inherits": {
|
||||
"version": "2.0.4",
|
||||
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
|
||||
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/ipaddr.js": {
|
||||
"version": "1.9.1",
|
||||
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
|
||||
"integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.10"
|
||||
}
|
||||
},
|
||||
"node_modules/json-schema-to-ts": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz",
|
||||
"integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.18.3",
|
||||
"ts-algebra": "^2.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
}
|
||||
},
|
||||
"node_modules/math-intrinsics": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
|
||||
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/media-typer": {
|
||||
"version": "0.3.0",
|
||||
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
|
||||
"integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/merge-descriptors": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz",
|
||||
"integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/methods": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz",
|
||||
"integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/mime": {
|
||||
"version": "1.6.0",
|
||||
"resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz",
|
||||
"integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==",
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"mime": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/mime-db": {
|
||||
"version": "1.52.0",
|
||||
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
|
||||
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/mime-types": {
|
||||
"version": "2.1.35",
|
||||
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
|
||||
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"mime-db": "1.52.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/ms": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
|
||||
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/negotiator": {
|
||||
"version": "0.6.3",
|
||||
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
|
||||
"integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/object-inspect": {
|
||||
"version": "1.13.4",
|
||||
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
|
||||
"integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/on-finished": {
|
||||
"version": "2.4.1",
|
||||
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
|
||||
"integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ee-first": "1.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/parseurl": {
|
||||
"version": "1.3.3",
|
||||
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
|
||||
"integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/path-to-regexp": {
|
||||
"version": "0.1.13",
|
||||
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.13.tgz",
|
||||
"integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/proxy-addr": {
|
||||
"version": "2.0.7",
|
||||
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
|
||||
"integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"forwarded": "0.2.0",
|
||||
"ipaddr.js": "1.9.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.10"
|
||||
}
|
||||
},
|
||||
"node_modules/qs": {
|
||||
"version": "6.15.3",
|
||||
"resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz",
|
||||
"integrity": "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"es-define-property": "^1.0.1",
|
||||
"side-channel": "^1.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.6"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/range-parser": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
|
||||
"integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/raw-body": {
|
||||
"version": "2.5.3",
|
||||
"resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz",
|
||||
"integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"bytes": "~3.1.2",
|
||||
"http-errors": "~2.0.1",
|
||||
"iconv-lite": "~0.4.24",
|
||||
"unpipe": "~1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/safe-buffer": {
|
||||
"version": "5.2.1",
|
||||
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
|
||||
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
],
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/safer-buffer": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
|
||||
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/send": {
|
||||
"version": "0.19.2",
|
||||
"resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz",
|
||||
"integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"debug": "2.6.9",
|
||||
"depd": "2.0.0",
|
||||
"destroy": "1.2.0",
|
||||
"encodeurl": "~2.0.0",
|
||||
"escape-html": "~1.0.3",
|
||||
"etag": "~1.8.1",
|
||||
"fresh": "~0.5.2",
|
||||
"http-errors": "~2.0.1",
|
||||
"mime": "1.6.0",
|
||||
"ms": "2.1.3",
|
||||
"on-finished": "~2.4.1",
|
||||
"range-parser": "~1.2.1",
|
||||
"statuses": "~2.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/send/node_modules/ms": {
|
||||
"version": "2.1.3",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
||||
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/serve-static": {
|
||||
"version": "1.16.3",
|
||||
"resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.3.tgz",
|
||||
"integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"encodeurl": "~2.0.0",
|
||||
"escape-html": "~1.0.3",
|
||||
"parseurl": "~1.3.3",
|
||||
"send": "~0.19.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/setprototypeof": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
|
||||
"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/side-channel": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz",
|
||||
"integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"es-errors": "^1.3.0",
|
||||
"object-inspect": "^1.13.4",
|
||||
"side-channel-list": "^1.0.1",
|
||||
"side-channel-map": "^1.0.1",
|
||||
"side-channel-weakmap": "^1.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/side-channel-list": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz",
|
||||
"integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"es-errors": "^1.3.0",
|
||||
"object-inspect": "^1.13.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/side-channel-map": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",
|
||||
"integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"call-bound": "^1.0.2",
|
||||
"es-errors": "^1.3.0",
|
||||
"get-intrinsic": "^1.2.5",
|
||||
"object-inspect": "^1.13.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/side-channel-weakmap": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
|
||||
"integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"call-bound": "^1.0.2",
|
||||
"es-errors": "^1.3.0",
|
||||
"get-intrinsic": "^1.2.5",
|
||||
"object-inspect": "^1.13.3",
|
||||
"side-channel-map": "^1.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/statuses": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
|
||||
"integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/toidentifier": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
|
||||
"integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/ts-algebra": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz",
|
||||
"integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/type-is": {
|
||||
"version": "1.6.18",
|
||||
"resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
|
||||
"integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"media-typer": "0.3.0",
|
||||
"mime-types": "~2.1.24"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/unpipe": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
|
||||
"integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/utils-merge": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
|
||||
"integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/vary": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
|
||||
"integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"name": "redator-sd",
|
||||
"version": "0.1.0",
|
||||
"description": "Redator de Solicitações de Demanda (SD) — RMDS / SES-MG × Isis Saúde",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"start": "node src/server.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "^0.74.0",
|
||||
"dotenv": "^16.4.5",
|
||||
"express": "^4.21.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,980 @@
|
||||
"use strict";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const esc = (s) =>
|
||||
String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
|
||||
const fmtD = (iso) => {
|
||||
const m = String(iso || "").match(/^(\d{4})-(\d{2})-(\d{2})/);
|
||||
return m ? `${m[3]}/${m[2]}/${m[1]}` : "—";
|
||||
};
|
||||
const dayNum = (iso) => {
|
||||
const m = String(iso || "").match(/^(\d{4})-(\d{2})-(\d{2})/);
|
||||
return m ? Date.UTC(+m[1], +m[2] - 1, +m[3]) / 86400000 : NaN;
|
||||
};
|
||||
|
||||
// Preços do claude-opus-5 (USD por 1M tokens) para o custo estimado no rodapé.
|
||||
const PRECO = { input: 5, output: 25, cache_read: 0.5, cache_write: 6.25 };
|
||||
|
||||
let statusApp = null;
|
||||
let sdAtual = null; // { id, numero, status, chat, rascunho, validacao, bloqueios, uso }
|
||||
let ocupado = false;
|
||||
let modoExterno = false; // tela "Validar JSON externo"
|
||||
let externo = null; // { sd, exportado, validacao, bloqueios }
|
||||
let ultimosBloqueios = [];
|
||||
|
||||
// ---------- Markdown mínimo (negrito, código, títulos, listas, OPCAO:) ----------
|
||||
function renderMd(texto) {
|
||||
const linhas = String(texto || "").split("\n");
|
||||
const out = [];
|
||||
let lista = null; // "ul" | "ol"
|
||||
const fechaLista = () => { if (lista) { out.push(`</${lista}>`); lista = null; } };
|
||||
const inline = (s) =>
|
||||
esc(s)
|
||||
.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>")
|
||||
.replace(/`([^`]+)`/g, "<code>$1</code>");
|
||||
for (const raw of linhas) {
|
||||
const l = raw.trimEnd();
|
||||
if (/^OPCAO:/i.test(l.trim())) continue; // vira botão, não texto
|
||||
const h = l.match(/^(#{1,4})\s+(.*)/);
|
||||
const ul = l.match(/^\s*[-•]\s+(.*)/);
|
||||
const ol = l.match(/^\s*\d+[.)]\s+(.*)/);
|
||||
if (h) { fechaLista(); out.push(`<h3>${inline(h[2])}</h3>`); }
|
||||
else if (ul) { if (lista !== "ul") { fechaLista(); out.push("<ul>"); lista = "ul"; } out.push(`<li>${inline(ul[1])}</li>`); }
|
||||
else if (ol) { if (lista !== "ol") { fechaLista(); out.push("<ol>"); lista = "ol"; } out.push(`<li>${inline(ol[1])}</li>`); }
|
||||
else if (l.trim() === "") { fechaLista(); }
|
||||
else { fechaLista(); out.push(`<p>${inline(l)}</p>`); }
|
||||
}
|
||||
fechaLista();
|
||||
return out.join("");
|
||||
}
|
||||
|
||||
function extrairOpcoes(texto) {
|
||||
return String(texto || "")
|
||||
.split("\n")
|
||||
.map((l) => l.trim())
|
||||
.filter((l) => /^OPCAO:/i.test(l))
|
||||
.map((l) => l.replace(/^OPCAO:\s*/i, "").trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
// ---------- Tema (automático → claro → escuro; escolha guardada no navegador) ----------
|
||||
const TEMAS = ["auto", "claro", "escuro"];
|
||||
const TEMA_ICONE = { auto: "🌗", claro: "☀️", escuro: "🌙" };
|
||||
const TEMA_ROTULO = { auto: "automático (segue o sistema)", claro: "claro", escuro: "escuro" };
|
||||
let temaAtual = localStorage.getItem("sd_tema");
|
||||
if (!TEMAS.includes(temaAtual)) temaAtual = "auto";
|
||||
|
||||
function aplicarTema(t) {
|
||||
const raiz = document.documentElement;
|
||||
if (t === "claro") raiz.dataset.theme = "light";
|
||||
else if (t === "escuro") raiz.dataset.theme = "dark";
|
||||
else delete raiz.dataset.theme; // automático: quem manda é o sistema
|
||||
$("btnTema").textContent = TEMA_ICONE[t];
|
||||
$("btnTema").title = `Tema: ${TEMA_ROTULO[t]} — clique para alternar`;
|
||||
}
|
||||
aplicarTema(temaAtual);
|
||||
|
||||
$("btnTema").addEventListener("click", () => {
|
||||
temaAtual = TEMAS[(TEMAS.indexOf(temaAtual) + 1) % TEMAS.length];
|
||||
localStorage.setItem("sd_tema", temaAtual);
|
||||
aplicarTema(temaAtual);
|
||||
});
|
||||
|
||||
// ---------- Autenticação + navegação ----------
|
||||
window.addEventListener("hashchange", rotear);
|
||||
window.addEventListener("DOMContentLoaded", iniciar);
|
||||
|
||||
async function iniciar() {
|
||||
let sess = null;
|
||||
try { sess = await (await fetch("/api/sessao")).json(); } catch {}
|
||||
if (!sess) { $("statusChip").textContent = "servidor indisponível"; return; }
|
||||
$("btnSair").hidden = !sess.precisa_login;
|
||||
if (sess.precisa_login && !sess.logado) { mostrarLogin(); return; }
|
||||
await entrar();
|
||||
}
|
||||
|
||||
async function entrar() {
|
||||
esconderTodas();
|
||||
await carregarStatus();
|
||||
rotear();
|
||||
}
|
||||
|
||||
function esconderTodas() {
|
||||
for (const id of ["telaLogin", "telaHome", "telaConversa", "telaValidar", "telaBase"]) $(id).hidden = true;
|
||||
}
|
||||
|
||||
function mostrarLogin() {
|
||||
esconderTodas();
|
||||
$("telaLogin").hidden = false;
|
||||
$("loginErro").hidden = true;
|
||||
$("loginUsuario").focus();
|
||||
}
|
||||
|
||||
$("formLogin").addEventListener("submit", async (ev) => {
|
||||
ev.preventDefault();
|
||||
$("btnLogin").disabled = true;
|
||||
const r = await fetch("/api/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ usuario: $("loginUsuario").value, senha: $("loginSenha").value }),
|
||||
}).catch(() => null);
|
||||
$("btnLogin").disabled = false;
|
||||
if (r?.ok) { $("loginSenha").value = ""; await entrar(); }
|
||||
else {
|
||||
$("loginErro").textContent = "Usuário ou senha inválidos.";
|
||||
$("loginErro").hidden = false;
|
||||
}
|
||||
});
|
||||
|
||||
$("btnSair").addEventListener("click", async () => {
|
||||
await fetch("/api/logout", { method: "POST" }).catch(() => {});
|
||||
location.hash = "#/";
|
||||
mostrarLogin();
|
||||
});
|
||||
|
||||
function exigirLogin(resp) {
|
||||
// Sessão expirada/servidor reiniciado: volta para a tela de login.
|
||||
if (resp && resp.status === 401) { mostrarLogin(); return true; }
|
||||
return false;
|
||||
}
|
||||
|
||||
async function carregarStatus() {
|
||||
try {
|
||||
const r = await fetch("/api/status");
|
||||
if (exigirLogin(r)) return;
|
||||
statusApp = await r.json();
|
||||
$("statusChip").textContent = statusApp.configurado
|
||||
? `${statusApp.provider} · ${statusApp.model} · próxima: SD-${statusApp.proximo_numero}`
|
||||
: "sem chave de API";
|
||||
$("avisoConfig").hidden = statusApp.configurado;
|
||||
popularSeletoresModelo();
|
||||
} catch {
|
||||
$("statusChip").textContent = "servidor indisponível";
|
||||
}
|
||||
}
|
||||
|
||||
// Seletores de modelo (Nova SD e Base de Conhecimento) — lista do .env (LLM_MODEL + LLM_MODELOS).
|
||||
function popularSeletoresModelo() {
|
||||
const modelos = statusApp?.modelos || [];
|
||||
for (const id of ["selModelo", "selModeloBase"]) {
|
||||
const sel = $(id);
|
||||
const anterior = sel.value;
|
||||
sel.innerHTML = modelos
|
||||
.map((m) => `<option value="${esc(m)}">${esc(m)}${m === statusApp.model ? " (padrão)" : ""}</option>`)
|
||||
.join("");
|
||||
// preserva a escolha do usuário entre recargas de status; senão, usa o padrão
|
||||
sel.value = modelos.includes(anterior) ? anterior : statusApp.model;
|
||||
}
|
||||
}
|
||||
|
||||
function moverPainel(slotId) {
|
||||
const painel = $("painel");
|
||||
const slot = $(slotId);
|
||||
if (painel.parentElement !== slot) slot.appendChild(painel);
|
||||
}
|
||||
|
||||
function rotear() {
|
||||
if ($("telaLogin") && !$("telaLogin").hidden) return; // aguardando login
|
||||
const m = location.hash.match(/^#\/sd\/(.+)$/);
|
||||
if (location.hash === "#/validar") mostrarValidar();
|
||||
else if (location.hash === "#/base") mostrarBase();
|
||||
else if (m) abrirConversa(m[1]);
|
||||
else mostrarHome();
|
||||
}
|
||||
|
||||
// ---------- Home ----------
|
||||
async function mostrarHome() {
|
||||
esconderTodas();
|
||||
$("telaHome").hidden = false;
|
||||
sdAtual = null;
|
||||
modoExterno = false;
|
||||
const rList = await fetch("/api/sds");
|
||||
if (exigirLogin(rList)) return;
|
||||
const lista = await rList.json();
|
||||
$("listaSds").innerHTML = lista.length
|
||||
? lista
|
||||
.sort((a, b) => (a.criadaEm < b.criadaEm ? 1 : -1))
|
||||
.map(
|
||||
(s) => `<a class="sd-item" href="#/sd/${s.id}">
|
||||
<span class="num">SD-${s.numero}</span>
|
||||
<span class="tit">${esc(s.titulo)}</span>
|
||||
<span class="st st-${s.status}">${s.status}</span>
|
||||
<button type="button" class="btn-excluir" data-id="${s.id}" data-status="${s.status}"
|
||||
data-titulo="${esc(s.titulo)}" title="Excluir da lista">✕</button></a>`
|
||||
)
|
||||
.join("")
|
||||
: '<p class="hint">Nenhuma SD ainda — cole a primeira demanda acima.</p>';
|
||||
$("listaSds").querySelectorAll(".btn-excluir").forEach((b) =>
|
||||
b.addEventListener("click", async (ev) => {
|
||||
ev.preventDefault(); // o botão vive dentro do link da SD
|
||||
ev.stopPropagation();
|
||||
const { id, status, titulo } = ev.currentTarget.dataset;
|
||||
const aviso = status === "enviada"
|
||||
? `Excluir a conversa de "${titulo}" da lista?\n\nEla já foi ENVIADA: o registro na base de conhecimento (saldos e precedentes) NÃO será apagado — só a conversa aqui do app.`
|
||||
: `Excluir o rascunho "${titulo}"?\n\nA conversa e o rascunho serão apagados de vez.`;
|
||||
if (!confirm(aviso)) return;
|
||||
const r = await fetch(`/api/sds/${id}`, { method: "DELETE" });
|
||||
if (exigirLogin(r)) return;
|
||||
if (!r.ok) { alert("Não foi possível excluir."); return; }
|
||||
await carregarStatus(); // numeração provisória pode mudar
|
||||
await mostrarHome();
|
||||
})
|
||||
);
|
||||
if (statusApp?.saldos) {
|
||||
$("saldosBox").innerHTML = Object.entries(statusApp.saldos)
|
||||
.map(
|
||||
([item, v]) => `<div class="saldo-chip">
|
||||
<div class="label">${esc(item)}</div>
|
||||
<div class="value">${v.saldo.toLocaleString("pt-BR")} UST</div>
|
||||
<div class="sub">de ${v.pool_total.toLocaleString("pt-BR")} · consumido ${v.consumido.toLocaleString("pt-BR")}</div>
|
||||
</div>`
|
||||
)
|
||||
.join("");
|
||||
}
|
||||
}
|
||||
|
||||
$("btnIniciar").addEventListener("click", async () => {
|
||||
const demanda = $("demandaInput").value.trim();
|
||||
if (!demanda || ocupado) return;
|
||||
$("btnIniciar").disabled = true;
|
||||
// Prepara a tela de conversa e transmite o primeiro turno
|
||||
esconderTodas();
|
||||
$("telaConversa").hidden = false;
|
||||
modoExterno = false;
|
||||
moverPainel("slotPainelConversa");
|
||||
$("mensagens").innerHTML = "";
|
||||
$("opcoes").innerHTML = "";
|
||||
resetPainel();
|
||||
addMsgUser(demanda);
|
||||
const resp = await fetch("/api/sds", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ demanda, modelo: $("selModelo").value }),
|
||||
});
|
||||
if (exigirLogin(resp)) return;
|
||||
const sdId = resp.headers.get("X-Sd-Id");
|
||||
history.replaceState(null, "", `#/sd/${sdId}`);
|
||||
sdAtual = { id: sdId, chat: [], rascunho: null };
|
||||
$("demandaInput").value = "";
|
||||
$("btnIniciar").disabled = false;
|
||||
await consumirStream(resp);
|
||||
await recarregarSd(); // pega numero/status/uso consolidados
|
||||
});
|
||||
|
||||
// ---------- Conversa ----------
|
||||
async function abrirConversa(id) {
|
||||
if (sdAtual?.id === id && ocupado) return; // já está na tela, streaming em curso
|
||||
esconderTodas();
|
||||
$("telaConversa").hidden = false;
|
||||
modoExterno = false;
|
||||
moverPainel("slotPainelConversa");
|
||||
sdAtual = { id };
|
||||
await recarregarSd(true);
|
||||
}
|
||||
|
||||
async function recarregarSd(renderChat = false) {
|
||||
const r = await fetch(`/api/sds/${sdAtual.id}`);
|
||||
if (exigirLogin(r)) return;
|
||||
if (!r.ok) { location.hash = "#/"; return; }
|
||||
const d = await r.json();
|
||||
sdAtual = d;
|
||||
if (renderChat) {
|
||||
$("mensagens").innerHTML = "";
|
||||
$("opcoes").innerHTML = "";
|
||||
for (const m of d.chat || []) {
|
||||
if (m.role === "user") addMsgUser(m.texto);
|
||||
else addMsgAssistant(m.texto, true);
|
||||
}
|
||||
const ultimo = (d.chat || []).filter((m) => m.role === "assistant").pop();
|
||||
if (ultimo) renderOpcoes(extrairOpcoes(ultimo.texto));
|
||||
}
|
||||
renderPainel(d.rascunho, d.validacao, d.bloqueios);
|
||||
renderUso(d.uso);
|
||||
const soLeitura = d.status === "enviada";
|
||||
$("msgInput").disabled = soLeitura;
|
||||
$("btnEnviarMsg").disabled = soLeitura;
|
||||
if (soLeitura) $("msgInput").placeholder = "SD enviada — somente leitura.";
|
||||
rolarChat();
|
||||
}
|
||||
|
||||
function addMsgUser(texto) {
|
||||
const div = document.createElement("div");
|
||||
div.className = "msg user";
|
||||
div.textContent = texto;
|
||||
$("mensagens").appendChild(div);
|
||||
rolarChat();
|
||||
}
|
||||
|
||||
function addMsgAssistant(texto, pronto = false) {
|
||||
const div = document.createElement("div");
|
||||
div.className = "msg assistant";
|
||||
div.innerHTML = pronto ? renderMd(texto) : '<span class="digitando">▍</span>';
|
||||
$("mensagens").appendChild(div);
|
||||
rolarChat();
|
||||
return div;
|
||||
}
|
||||
|
||||
function renderOpcoes(opcoes) {
|
||||
$("opcoes").innerHTML = "";
|
||||
for (const o of opcoes) {
|
||||
const b = document.createElement("button");
|
||||
b.type = "button";
|
||||
b.textContent = o;
|
||||
b.addEventListener("click", () => enviarMensagem(o));
|
||||
$("opcoes").appendChild(b);
|
||||
}
|
||||
}
|
||||
|
||||
function rolarChat() {
|
||||
const el = $("mensagens");
|
||||
el.scrollTop = el.scrollHeight;
|
||||
}
|
||||
|
||||
$("formMsg").addEventListener("submit", (ev) => {
|
||||
ev.preventDefault();
|
||||
const t = $("msgInput").value.trim();
|
||||
if (t) enviarMensagem(t);
|
||||
});
|
||||
$("msgInput").addEventListener("keydown", (ev) => {
|
||||
if (ev.key === "Enter" && !ev.shiftKey) {
|
||||
ev.preventDefault();
|
||||
$("formMsg").requestSubmit();
|
||||
}
|
||||
});
|
||||
|
||||
async function enviarMensagem(texto) {
|
||||
if (ocupado || !sdAtual?.id) return;
|
||||
$("msgInput").value = "";
|
||||
$("opcoes").innerHTML = "";
|
||||
addMsgUser(texto);
|
||||
const resp = await fetch(`/api/sds/${sdAtual.id}/mensagem`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ texto }),
|
||||
});
|
||||
if (exigirLogin(resp)) return;
|
||||
if (!resp.ok && !resp.body) {
|
||||
addMsgAssistant("⚠ Erro ao enviar a mensagem.", true);
|
||||
return;
|
||||
}
|
||||
await consumirStream(resp);
|
||||
}
|
||||
|
||||
async function consumirStream(resp) {
|
||||
ocupado = true;
|
||||
$("btnEnviarMsg").disabled = true;
|
||||
const bolha = addMsgAssistant("");
|
||||
let texto = "";
|
||||
// "pensando…" cobre o silêncio do raciocínio interno do modelo: antes da
|
||||
// primeira palavra e entre as chamadas de ferramenta (validação do rascunho).
|
||||
let pensando = true;
|
||||
const pinta = () => {
|
||||
bolha.innerHTML =
|
||||
renderMd(texto) +
|
||||
(pensando ? '<span class="pensando">pensando…</span>' : '<span class="digitando">▍</span>');
|
||||
rolarChat();
|
||||
};
|
||||
pinta();
|
||||
try {
|
||||
const reader = resp.body.getReader();
|
||||
const dec = new TextDecoder();
|
||||
let buf = "";
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
buf += dec.decode(value, { stream: true });
|
||||
let nl;
|
||||
while ((nl = buf.indexOf("\n")) >= 0) {
|
||||
const linha = buf.slice(0, nl).trim();
|
||||
buf = buf.slice(nl + 1);
|
||||
if (!linha) continue;
|
||||
let ev;
|
||||
try { ev = JSON.parse(linha); } catch { continue; }
|
||||
if (ev.t === "delta") {
|
||||
texto += ev.text;
|
||||
pensando = false;
|
||||
pinta();
|
||||
} else if (ev.t === "rascunho") {
|
||||
renderPainel(ev.sd, ev.validacao, ev.bloqueios);
|
||||
pensando = true; // o modelo volta a raciocinar sobre o resultado da validação
|
||||
pinta();
|
||||
} else if (ev.t === "uso") {
|
||||
renderUso(ev.uso);
|
||||
} else if (ev.t === "erro") {
|
||||
texto += `\n\n⚠ ${ev.msg}`;
|
||||
pensando = false;
|
||||
pinta();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
texto += "\n\n⚠ Conexão interrompida — recarregue a página para retomar.";
|
||||
}
|
||||
bolha.innerHTML = renderMd(texto);
|
||||
renderOpcoes(extrairOpcoes(texto));
|
||||
ocupado = false;
|
||||
$("btnEnviarMsg").disabled = false;
|
||||
rolarChat();
|
||||
}
|
||||
|
||||
// ---------- Painel do documento ----------
|
||||
function resetPainel() {
|
||||
$("painelVazio").hidden = false;
|
||||
$("painelConteudo").hidden = true;
|
||||
}
|
||||
|
||||
function renderPainel(sd, validacao, bloqueios) {
|
||||
if (!sd) { resetPainel(); return; }
|
||||
ultimosBloqueios = bloqueios || [];
|
||||
if (!modoExterno && sdAtual) { sdAtual.rascunho = sd; }
|
||||
$("painelVazio").hidden = true;
|
||||
$("painelConteudo").hidden = false;
|
||||
const E = sd.entregaveis || [];
|
||||
const cab = sd.cabecalho || {};
|
||||
const R = validacao?.resultados || {};
|
||||
const totais = validacao?.totais || {};
|
||||
|
||||
// Resumo
|
||||
$("pResumo").innerHTML = `
|
||||
<div class="ptitulo">${esc(cab.titulo || cab.projeto || "SD em elaboração")}</div>
|
||||
<div class="resumo-chips">
|
||||
<div class="rchip"><div class="label">Nº</div><div class="value">${esc(cab.numero_sd || (sdAtual?.numero ? "SD-" + sdAtual.numero : "—"))}</div></div>
|
||||
<div class="rchip"><div class="label">Total</div><div class="value">${validacao?.soma_ust ?? "—"} UST</div></div>
|
||||
<div class="rchip"><div class="label">Prazo</div><div class="value">${esc(cab.prazo_execucao_semanas ?? "—")} sem.</div></div>
|
||||
<div class="rchip"><div class="label">Itens</div><div class="value" style="font-size:12px">${(cab.itens_tr || []).join(" + ") || "—"}</div></div>
|
||||
<div class="rchip"><div class="label">✓/!/✗/○</div><div class="value" style="font-size:12px">${totais.ok ?? 0}/${totais.alerta ?? 0}/${totais.falha ?? 0}/${totais.pendente ?? 0}</div></div>
|
||||
</div>`;
|
||||
|
||||
// Quadro
|
||||
let linhas = E.map((e) => {
|
||||
const par = (e.paralelo_com || []).length ? " ∥" : "";
|
||||
return `<tr><td class="num">${e.n ?? ""}</td><td>${esc(e.nome)}${par}</td><td>${esc(e.tipo || "")}</td>
|
||||
<td>${esc(e.item_tr || "")}</td><td class="num">${e.semanas ?? ""}</td><td class="num">${e.ust ?? ""}</td>
|
||||
<td>${fmtD(e.periodo?.inicio)}–${fmtD(e.periodo?.fim)}</td></tr>`;
|
||||
}).join("");
|
||||
const porItem = validacao?.soma_por_item || {};
|
||||
if (Object.keys(porItem).length > 1) {
|
||||
linhas += Object.keys(porItem).sort()
|
||||
.map((i) => `<tr class="subtotal"><td colspan="5">Subtotal ${esc(i)}</td><td class="num">${porItem[i]}</td><td></td></tr>`)
|
||||
.join("");
|
||||
}
|
||||
linhas += `<tr class="total"><td colspan="5">TOTAL</td><td class="num">${validacao?.soma_ust ?? ""}</td><td></td></tr>`;
|
||||
$("pQuadro").innerHTML = `<table class="quadro">
|
||||
<tr><th>#</th><th>Entregável</th><th>Tipo</th><th>Item</th><th>Sem</th><th>UST</th><th>Período</th></tr>${linhas}</table>`;
|
||||
|
||||
// Artefatos (trava de integridade)
|
||||
$("pArtefatos").innerHTML = E.map((e, ei) => {
|
||||
const arts = (e.artefatos || []).map((a, ai) => {
|
||||
const bad = a.data && e.periodo?.fim && dayNum(a.data) > dayNum(e.periodo.fim);
|
||||
return `<div class="art-row ${a.confirmado_pelo_usuario ? "confirmed" : "unconfirmed"}">
|
||||
<input type="checkbox" data-e="${ei}" data-a="${ai}" ${a.confirmado_pelo_usuario ? "checked" : ""} aria-label="Confirmar artefato">
|
||||
<div class="art-main">
|
||||
<label>${esc(a.nome)}</label>
|
||||
<input type="date" data-e="${ei}" data-a="${ai}" value="${esc(a.data || "")}" aria-label="Data do artefato">
|
||||
${bad ? `<div class="flag bad">data posterior ao fim do entregável (${fmtD(e.periodo.fim)})</div>`
|
||||
: a.confirmado_pelo_usuario && !a.data ? `<div class="flag miss">confirmado sem data</div>` : ""}
|
||||
</div></div>`;
|
||||
}).join("");
|
||||
return arts ? `<div class="art-entr"><h4>E${e.n} — ${esc(e.nome)}</h4>${arts}</div>` : "";
|
||||
}).join("") || '<p class="hint">Ainda sem artefatos registrados.</p>';
|
||||
|
||||
$("pArtefatos").querySelectorAll("input[type=checkbox]").forEach((cb) =>
|
||||
cb.addEventListener("change", (ev) =>
|
||||
atualizarArtefato(+ev.target.dataset.e, +ev.target.dataset.a, { confirmado: ev.target.checked })
|
||||
)
|
||||
);
|
||||
$("pArtefatos").querySelectorAll("input[type=date]").forEach((di) =>
|
||||
di.addEventListener("change", (ev) =>
|
||||
atualizarArtefato(+ev.target.dataset.e, +ev.target.dataset.a, { data: ev.target.value || "" })
|
||||
)
|
||||
);
|
||||
|
||||
// Checklist
|
||||
const ICONS = { ok: "✓", alerta: "!", falha: "✗", pendente: "○" };
|
||||
const checklist = statusApp?.checklist || [];
|
||||
$("pChecklist").innerHTML = checklist.map((c) => {
|
||||
const r = R[c.id] || { status: "pendente", obs: "" };
|
||||
return `<div class="check-item st-${r.status}">
|
||||
<span class="icon">${ICONS[r.status]}</span>
|
||||
<span class="id">${c.id}</span>
|
||||
<span>${esc(c.regra)}${r.obs ? `<span class="obs">${esc(r.obs)}</span>` : ""}</span></div>`;
|
||||
}).join("");
|
||||
|
||||
// Pendências
|
||||
const pend = [...(sd.pendencias || [])];
|
||||
(bloqueios || []).forEach((b) => pend.push("Bloqueante: " + b));
|
||||
$("pPendencias").innerHTML = pend.length
|
||||
? pend.map((p) => `<li>${esc(p)}</li>`).join("")
|
||||
: "<li>Nenhuma pendência registrada.</li>";
|
||||
|
||||
// Fechamento
|
||||
const bloqueado = (bloqueios || []).length > 0;
|
||||
const lock = $("pBloqueios");
|
||||
lock.className = "lock-msg " + (bloqueado ? "locked" : "open");
|
||||
lock.textContent = bloqueado
|
||||
? "Exportação bloqueada — " + bloqueios.join("; ") + "."
|
||||
: "SD liberada: artefatos confirmados e nenhuma falha de código.";
|
||||
$("btnBaixar").disabled = bloqueado;
|
||||
$("btnEnviarSd").hidden = modoExterno;
|
||||
$("btnEnviarSd").disabled = bloqueado || sdAtual?.status === "enviada";
|
||||
}
|
||||
|
||||
async function atualizarArtefato(e, a, corpo) {
|
||||
if (modoExterno) {
|
||||
const art = externo?.sd?.entregaveis?.[e]?.artefatos?.[a];
|
||||
if (!art) return;
|
||||
if (typeof corpo.confirmado === "boolean") art.confirmado_pelo_usuario = corpo.confirmado;
|
||||
if (corpo.data !== undefined) {
|
||||
if (corpo.data) art.data = corpo.data;
|
||||
else delete art.data;
|
||||
}
|
||||
await validarExterno(false);
|
||||
return;
|
||||
}
|
||||
const r = await fetch(`/api/sds/${sdAtual.id}/artefato`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ e, a, ...corpo }),
|
||||
});
|
||||
if (exigirLogin(r)) return;
|
||||
if (r.ok) {
|
||||
const d = await r.json();
|
||||
renderPainel(d.sd, d.validacao, d.bloqueios);
|
||||
}
|
||||
}
|
||||
|
||||
$("btnBaixar").addEventListener("click", () => {
|
||||
if (modoExterno) {
|
||||
if (externo?.exportado) baixarJsonLocal(externo.exportado);
|
||||
return;
|
||||
}
|
||||
window.location.href = `/api/sds/${sdAtual.id}/export`;
|
||||
});
|
||||
|
||||
function baixarJsonLocal(obj) {
|
||||
const nome = (obj.cabecalho?.numero_sd || "sd").toLowerCase().replace(/[^a-z0-9-]+/g, "-") + ".json";
|
||||
const blob = new Blob([JSON.stringify(obj, null, 2)], { type: "application/json" });
|
||||
const a = document.createElement("a");
|
||||
a.href = URL.createObjectURL(blob);
|
||||
a.download = nome;
|
||||
a.click();
|
||||
URL.revokeObjectURL(a.href);
|
||||
}
|
||||
|
||||
$("btnEnviarSd").addEventListener("click", async () => {
|
||||
if (!confirm("Marcar como enviada? O número definitivo será atribuído e a SD entra na base de conhecimento.")) return;
|
||||
const r = await fetch(`/api/sds/${sdAtual.id}/enviar`, { method: "POST" });
|
||||
const d = await r.json();
|
||||
if (r.ok) {
|
||||
alert(`SD registrada na base como ${d.registro_na_base.id}.`);
|
||||
await carregarStatus();
|
||||
await recarregarSd();
|
||||
} else {
|
||||
alert(d.erro + (d.bloqueios ? "\n- " + d.bloqueios.join("\n- ") : ""));
|
||||
}
|
||||
});
|
||||
|
||||
// ---------- Documento formatado + impressão/PDF ----------
|
||||
const CSS_IMPRESSAO = `
|
||||
body{margin:0; padding:32px 40px; background:#fff; color:#000;
|
||||
font-family:Georgia,"Times New Roman",serif; font-size:12.5pt; line-height:1.6;}
|
||||
h1{font-size:16pt; margin:0 0 2px; line-height:1.3;}
|
||||
.doc-sub{font-family:"Segoe UI",Arial,sans-serif; font-size:8.5pt; color:#555;
|
||||
text-transform:uppercase; letter-spacing:.08em; margin-bottom:18px;}
|
||||
.marca-rascunho{font-family:"Segoe UI",Arial,sans-serif; font-size:9pt; color:#B3362B;
|
||||
border:1px solid #B3362B; display:inline-block; padding:2px 10px; margin-bottom:14px;}
|
||||
h2{font-size:12.5pt; margin:22px 0 8px; border-bottom:2px solid #0B6B70; padding-bottom:3px;}
|
||||
h3{font-size:11pt; margin:16px 0 5px;}
|
||||
p{margin:0 0 10px;}
|
||||
table{border-collapse:collapse; width:100%; font-size:9.5pt;}
|
||||
th,td{border:1px solid #999; padding:4px 7px; text-align:left; vertical-align:top;}
|
||||
th{font-family:"Segoe UI",Arial,sans-serif; font-size:8pt; text-transform:uppercase;
|
||||
letter-spacing:.04em; background:#E1EFEF;}
|
||||
tr.subtotal td{font-weight:700; background:#E1EFEF;}
|
||||
tr.total td{font-weight:700; border-top:2px solid #0B6B70;}
|
||||
td.num,th.num{text-align:right;}
|
||||
.nota{font-size:10pt; font-style:italic; color:#444; margin-top:6px;}
|
||||
ul,ol{margin:0 0 10px; padding-left:20px;}
|
||||
li{margin-bottom:3px;}
|
||||
.cab-table td:first-child{font-family:"Segoe UI",Arial,sans-serif; font-size:8.5pt;
|
||||
text-transform:uppercase; letter-spacing:.04em; color:#555; width:170px;}
|
||||
.art-status{font-family:"Segoe UI",Arial,sans-serif; font-size:8pt; border-radius:8px;
|
||||
padding:1px 7px; margin-left:6px; white-space:nowrap; border:1px solid #999;}
|
||||
.art-status.sim{background:#E3F2E9; color:#1E7B47;}
|
||||
.art-status.nao{background:#F8EFDB; color:#A8730B;}
|
||||
.enq-desc{font-size:10pt; color:#444;}
|
||||
h2,h3{page-break-after:avoid;} tr{page-break-inside:avoid;}
|
||||
@page{margin:18mm 15mm;}`;
|
||||
|
||||
function minArtCli(ust) {
|
||||
const faixas = statusApp?.regras?.artefatos_minimos || [];
|
||||
const f = faixas.find((b) => b.ust_max === null || ust <= b.ust_max);
|
||||
return f ? f.artefatos : 1;
|
||||
}
|
||||
|
||||
function documentoHtml(sdX, rascunho) {
|
||||
const cab = sdX.cabecalho || {};
|
||||
const E = sdX.entregaveis || [];
|
||||
const infoItem = (i) => statusApp?.regras?.itens?.[i] || {};
|
||||
const soma = E.reduce((a, e) => a + (e.ust || 0), 0);
|
||||
const porItem = {};
|
||||
E.forEach((e) => (porItem[e.item_tr] = (porItem[e.item_tr] || 0) + (e.ust || 0)));
|
||||
const multi = Object.keys(porItem).length > 1;
|
||||
|
||||
let quadro = E.map((e) =>
|
||||
`<tr><td class="num">${e.n ?? ""}</td><td>${esc(e.nome)}</td><td>${esc(e.tipo || "")}</td>
|
||||
<td>${esc(e.item_tr || "")}</td><td class="num">${e.semanas ?? ""}</td>
|
||||
<td class="num">${e.timebox_h ?? ""}h</td><td class="num">${e.ust ?? ""}</td>
|
||||
<td>${fmtD(e.periodo?.inicio)} – ${fmtD(e.periodo?.fim)}</td></tr>`
|
||||
).join("");
|
||||
if (multi)
|
||||
quadro += Object.keys(porItem).sort()
|
||||
.map((i) => `<tr class="subtotal"><td colspan="6">Subtotal ${esc(i)}</td><td class="num">${porItem[i]}</td><td></td></tr>`)
|
||||
.join("");
|
||||
quadro += `<tr class="total"><td colspan="6">TOTAL</td><td class="num">${soma}</td><td></td></tr>`;
|
||||
|
||||
const notas = E.filter((e) => (e.nota_paralelismo || "").trim())
|
||||
.map((e) => `<p class="nota"><strong>Nota de paralelismo (E${e.n}):</strong> ${esc(e.nota_paralelismo)}</p>`)
|
||||
.join("");
|
||||
|
||||
const det = E.map((e) =>
|
||||
`<h3>E${e.n} · ${esc(e.tipo || "")} — ${esc(e.nome)} (${e.ust ?? "?"} UST)</h3>
|
||||
<p><strong>Resumo:</strong> ${esc(e.resumo || "")}</p>
|
||||
<p style="margin-bottom:4px"><strong>Atividades:</strong></p>
|
||||
<ol>${(e.atividades || []).map((a) => `<li>${esc(a)}</li>`).join("")}</ol>
|
||||
<p style="margin-bottom:4px"><strong>Artefatos</strong> (mínimo ${minArtCli(e.ust || 0)} pela faixa de UST):</p>
|
||||
<ul>${(e.artefatos || []).map((a) =>
|
||||
`<li>${esc(a.nome)}${a.data ? ` — ${fmtD(a.data)}` : ""}
|
||||
<span class="art-status ${a.confirmado_pelo_usuario ? "sim" : "nao"}">${a.confirmado_pelo_usuario ? "confirmado" : "a confirmar"}</span></li>`
|
||||
).join("")}</ul>
|
||||
<p style="margin-bottom:4px"><strong>Critérios de aceite:</strong></p>
|
||||
<ul>${(e.criterios_aceite || []).map((c) => `<li>${esc(c)}</li>`).join("")}</ul>`
|
||||
).join("");
|
||||
|
||||
const enq = (sdX.enquadramento_tr || []).map((q) => {
|
||||
const inf = infoItem(q.item_tr);
|
||||
return `<h3>Item ${inf.numero ?? "?"} — “${esc(q.titulo_literal)}” (CATMAS ${esc(inf.catmas || "—")}) — entregáveis ${(q.entregaveis_n || []).join(", ")}</h3>
|
||||
<p class="enq-desc">${esc(q.descricao_item || "")}</p>
|
||||
<ul>${(q.aderencia || []).map((b) => `<li>${esc(b)}</li>`).join("")}</ul>`;
|
||||
}).join("");
|
||||
|
||||
const titulo = esc(cab.numero_sd || "SD") + " — " + esc(cab.projeto || "Solicitação de Demanda");
|
||||
return `<!DOCTYPE html><html lang="pt-BR"><head><meta charset="utf-8"><title>${titulo}</title>` +
|
||||
`<style>${CSS_IMPRESSAO}</style></head><body>` +
|
||||
`<h1>${esc(cab.titulo || cab.projeto || "Solicitação de Demanda")}</h1>` +
|
||||
`<div class="doc-sub">Solicitação de Demanda · ${esc(cab.numero_sd || "SD-__")} · ${esc(cab.versao || "V1")} · RMDS / SES-MG</div>` +
|
||||
(rascunho ? `<div class="marca-rascunho">RASCUNHO — há pendências bloqueantes abertas</div>` : "") +
|
||||
`<table class="cab-table">
|
||||
<tr><td>Projeto</td><td>${esc(cab.projeto || "")}</td></tr>
|
||||
<tr><td>Data de abertura</td><td>${fmtD(cab.data_abertura)}</td></tr>
|
||||
<tr><td>Período de execução</td><td>${fmtD(cab.periodo_execucao?.inicio)} a ${fmtD(cab.periodo_execucao?.fim)}</td></tr>
|
||||
<tr><td>Itens do TR</td><td>${(cab.itens_tr || []).map(esc).join(" e ")}</td></tr>
|
||||
<tr><td>Total</td><td>${soma} UST${cab.total_ust_extenso ? ` (${esc(cab.total_ust_extenso)})` : ""}</td></tr>
|
||||
<tr><td>Prazo de execução</td><td>${esc(cab.prazo_execucao_semanas ?? "—")} semanas (calendário)</td></tr>
|
||||
<tr><td>Entregáveis</td><td>${E.length}</td></tr>
|
||||
</table>
|
||||
<h2>1. Objetivo</h2><p>${esc(sdX.objetivo || "")}</p>
|
||||
<h2>2. Contexto e escopo</h2>${(sdX.contexto || []).map((p) => `<p>${esc(p)}</p>`).join("")}
|
||||
<h2>3. Quadro de entregáveis</h2><table>
|
||||
<tr><th class="num">#</th><th>Entregável</th><th>Tipo</th><th>Item</th><th class="num">Sem.</th><th class="num">Timebox</th><th class="num">UST</th><th>Período</th></tr>
|
||||
${quadro}</table>${notas}
|
||||
<h2>4. Detalhamento por entregável</h2>${det}
|
||||
<h2>5. Enquadramento no TR</h2>${enq}` +
|
||||
`<scr` + `ipt>window.addEventListener("load",()=>setTimeout(()=>window.print(),350));</scr` + `ipt></body></html>`;
|
||||
}
|
||||
|
||||
function abrirDocumento(sdX, rascunho) {
|
||||
const html = documentoHtml(sdX, rascunho);
|
||||
try {
|
||||
const w = window.open("", "_blank");
|
||||
if (w && w.document) {
|
||||
w.document.open();
|
||||
w.document.write(html);
|
||||
w.document.close();
|
||||
return;
|
||||
}
|
||||
} catch { /* pop-up bloqueado */ }
|
||||
const nome = (sdX.cabecalho?.numero_sd || "sd").toLowerCase().replace(/[^a-z0-9-]+/g, "-") + "-impressao.html";
|
||||
const blob = new Blob([html], { type: "text/html" });
|
||||
const a = document.createElement("a");
|
||||
a.href = URL.createObjectURL(blob);
|
||||
a.download = nome;
|
||||
a.click();
|
||||
URL.revokeObjectURL(a.href);
|
||||
}
|
||||
|
||||
$("btnDocumento").addEventListener("click", async () => {
|
||||
if (modoExterno) {
|
||||
if (externo?.exportado) abrirDocumento(externo.exportado, (externo.bloqueios || []).length > 0);
|
||||
return;
|
||||
}
|
||||
if (!sdAtual?.id) return;
|
||||
const r = await fetch(`/api/sds/${sdAtual.id}/export?forcar=1`);
|
||||
if (exigirLogin(r)) return;
|
||||
if (!r.ok) { alert("Não foi possível gerar o documento."); return; }
|
||||
abrirDocumento(await r.json(), ultimosBloqueios.length > 0);
|
||||
});
|
||||
|
||||
// ---------- Validar JSON externo ----------
|
||||
function mostrarValidar() {
|
||||
esconderTodas();
|
||||
$("telaValidar").hidden = false;
|
||||
modoExterno = true;
|
||||
sdAtual = null;
|
||||
moverPainel("slotPainelValidar");
|
||||
if (externo?.exportado) renderPainel(externo.exportado, externo.validacao, externo.bloqueios);
|
||||
else resetPainel();
|
||||
}
|
||||
|
||||
async function validarExterno(lerTextarea = true) {
|
||||
const erroBox = $("validarErro");
|
||||
erroBox.hidden = true;
|
||||
let sdIn = externo?.sd;
|
||||
if (lerTextarea) {
|
||||
try {
|
||||
sdIn = JSON.parse($("jsonExterno").value);
|
||||
} catch (e) {
|
||||
erroBox.textContent = "JSON inválido: " + e.message;
|
||||
erroBox.hidden = false;
|
||||
return;
|
||||
}
|
||||
}
|
||||
const r = await fetch("/api/validar", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ sd: sdIn }),
|
||||
});
|
||||
if (exigirLogin(r)) return;
|
||||
const d = await r.json();
|
||||
if (!r.ok) {
|
||||
erroBox.textContent = d.erro || "Erro ao validar.";
|
||||
erroBox.hidden = false;
|
||||
return;
|
||||
}
|
||||
externo = { sd: sdIn, exportado: d.exportado, validacao: d.validacao, bloqueios: d.bloqueios };
|
||||
renderPainel(d.exportado, d.validacao, d.bloqueios);
|
||||
}
|
||||
|
||||
$("btnValidarJson").addEventListener("click", () => validarExterno(true));
|
||||
|
||||
$("btnImportarJson").addEventListener("click", () => $("arquivoJson").click());
|
||||
$("arquivoJson").addEventListener("change", async (ev) => {
|
||||
const arquivo = ev.target.files?.[0];
|
||||
ev.target.value = ""; // permite reimportar o mesmo arquivo depois
|
||||
if (!arquivo) return;
|
||||
const erroBox = $("validarErro");
|
||||
if (arquivo.size > 2 * 1024 * 1024) {
|
||||
erroBox.textContent = "Arquivo muito grande (máx. 2 MB).";
|
||||
erroBox.hidden = false;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const texto = await arquivo.text();
|
||||
JSON.parse(texto); // valida a sintaxe antes de preencher
|
||||
$("jsonExterno").value = texto;
|
||||
erroBox.hidden = true;
|
||||
await validarExterno(true); // já valida a SD importada
|
||||
} catch (e) {
|
||||
erroBox.textContent = `O arquivo "${arquivo.name}" não contém JSON válido: ${e.message}`;
|
||||
erroBox.hidden = false;
|
||||
}
|
||||
});
|
||||
|
||||
$("btnLimparJson").addEventListener("click", () => {
|
||||
$("jsonExterno").value = "";
|
||||
externo = null;
|
||||
$("validarErro").hidden = true;
|
||||
resetPainel();
|
||||
});
|
||||
|
||||
$("btnVoltarValidar").addEventListener("click", () => { location.hash = "#/"; });
|
||||
|
||||
// ---------- Alimentar base de conhecimento (upload de SD real) ----------
|
||||
|
||||
function mostrarBase() {
|
||||
esconderTodas();
|
||||
$("telaBase").hidden = false;
|
||||
modoExterno = false;
|
||||
sdAtual = null;
|
||||
}
|
||||
|
||||
$("btnVoltarBase").addEventListener("click", () => { location.hash = "#/"; });
|
||||
$("btnEscolherDoc").addEventListener("click", () => $("arquivoDoc").click());
|
||||
|
||||
function baseErro(msg) {
|
||||
const box = $("baseErro");
|
||||
box.textContent = msg || "";
|
||||
box.hidden = !msg;
|
||||
}
|
||||
|
||||
$("arquivoDoc").addEventListener("change", async (ev) => {
|
||||
const arquivo = ev.target.files?.[0];
|
||||
ev.target.value = ""; // permite reenviar o mesmo arquivo
|
||||
if (!arquivo) return;
|
||||
baseErro("");
|
||||
$("baseOk").hidden = true;
|
||||
const ext = (arquivo.name.toLowerCase().match(/\.([a-z0-9]+)$/) || [])[1] || "";
|
||||
if (!["pdf", "md", "txt", "markdown"].includes(ext)) {
|
||||
baseErro(`Formato .${ext || "?"} não suportado — envie .pdf, .md ou .txt (para .docx, exporte como PDF).`);
|
||||
return;
|
||||
}
|
||||
if (arquivo.size > 15 * 1024 * 1024) {
|
||||
baseErro("Arquivo muito grande (máx. 15 MB).");
|
||||
return;
|
||||
}
|
||||
$("btnEscolherDoc").disabled = true;
|
||||
$("baseExtraindo").hidden = false;
|
||||
$("baseRevisao").hidden = true;
|
||||
try {
|
||||
const base64 = await new Promise((resolve, reject) => {
|
||||
const fr = new FileReader();
|
||||
fr.onload = () => resolve(String(fr.result).split(",")[1] || "");
|
||||
fr.onerror = () => reject(new Error("Falha ao ler o arquivo."));
|
||||
fr.readAsDataURL(arquivo);
|
||||
});
|
||||
const r = await fetch("/api/base/extrair", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ nome: arquivo.name, base64, modelo: $("selModeloBase").value }),
|
||||
});
|
||||
if (exigirLogin(r)) return;
|
||||
const d = await r.json();
|
||||
if (!r.ok) { baseErro(d.erro || "Erro na extração."); return; }
|
||||
renderRevisaoBase(d);
|
||||
if (d.uso) {
|
||||
const custo = ((d.uso.input_tokens || 0) * PRECO.input + (d.uso.output_tokens || 0) * PRECO.output) / 1e6;
|
||||
$("baseUso").textContent =
|
||||
`extração: ${(d.uso.input_tokens || 0).toLocaleString("pt-BR")} tokens lidos · ` +
|
||||
`${(d.uso.output_tokens || 0).toLocaleString("pt-BR")} gerados · custo estimado US$ ${custo.toFixed(3)} ` +
|
||||
`(estimativa válida para o modelo Opus)`;
|
||||
}
|
||||
} catch (e) {
|
||||
baseErro("Erro na extração: " + e.message);
|
||||
} finally {
|
||||
$("btnEscolherDoc").disabled = false;
|
||||
$("baseExtraindo").hidden = true;
|
||||
}
|
||||
});
|
||||
|
||||
function renderRevisaoBase(d) {
|
||||
$("baseRevisao").hidden = false;
|
||||
$("baseSdJson").value = JSON.stringify(d.sd || {}, null, 2);
|
||||
renderConferenciaBase(d.conferencia || []);
|
||||
|
||||
const obs = d.observacoes || [];
|
||||
$("baseObsBloco").hidden = !obs.length;
|
||||
$("baseObs").innerHTML = obs.map((o) => `<li>${esc(o)}</li>`).join("");
|
||||
|
||||
$("baseCaps").innerHTML = (d.capacidades || []).length
|
||||
? (d.capacidades || []).map((c, i) => `
|
||||
<div class="cap-card" data-i="${i}">
|
||||
<input type="checkbox" checked aria-label="Incluir capacidade">
|
||||
<div class="cap-main">
|
||||
<input type="text" class="cap-titulo" value="${esc(c.titulo || "")}" aria-label="Título da capacidade">
|
||||
<textarea class="cap-desc" rows="3" aria-label="Descrição da capacidade">${esc(c.descricao || "")}</textarea>
|
||||
<div class="cap-meta">
|
||||
<input type="text" class="cap-item" value="${esc(c.item_tr || "")}" aria-label="Item do TR" placeholder="item do TR (ex.: I-02)">
|
||||
<input type="text" class="cap-tags" value="${esc((c.tags || []).join(", "))}" aria-label="Tags" placeholder="tags separadas por vírgula">
|
||||
</div>
|
||||
</div>
|
||||
</div>`).join("")
|
||||
: '<p class="hint">Nenhuma capacidade reutilizável identificada no documento.</p>';
|
||||
$("baseCaps").querySelectorAll(".cap-card input[type=checkbox]").forEach((cb) =>
|
||||
cb.addEventListener("change", (ev) =>
|
||||
ev.target.closest(".cap-card").classList.toggle("excluida", !ev.target.checked)
|
||||
)
|
||||
);
|
||||
$("baseRevisao").scrollIntoView({ behavior: "smooth" });
|
||||
}
|
||||
|
||||
function renderConferenciaBase(lista) {
|
||||
const temErro = lista.some((c) => c.nivel === "erro");
|
||||
$("baseConferencia").innerHTML = lista.length
|
||||
? lista.map((c) => `<div class="check-item st-${c.nivel === "erro" ? "falha" : "alerta"}">
|
||||
<span class="icon">${c.nivel === "erro" ? "✗" : "!"}</span>
|
||||
<span class="id">${c.nivel}</span><span>${esc(c.msg)}</span></div>`).join("")
|
||||
: '<div class="check-item st-ok"><span class="icon">✓</span><span class="id">ok</span><span>Nenhuma inconsistência encontrada.</span></div>';
|
||||
$("btnGravarBase").disabled = temErro;
|
||||
return temErro;
|
||||
}
|
||||
|
||||
function lerSdRevisada() {
|
||||
try {
|
||||
return JSON.parse($("baseSdJson").value);
|
||||
} catch (e) {
|
||||
baseErro("JSON do registro inválido: " + e.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function lerCapsRevisadas() {
|
||||
return [...$("baseCaps").querySelectorAll(".cap-card")]
|
||||
.filter((card) => card.querySelector("input[type=checkbox]").checked)
|
||||
.map((card) => ({
|
||||
titulo: card.querySelector(".cap-titulo").value.trim(),
|
||||
descricao: card.querySelector(".cap-desc").value.trim(),
|
||||
item_tr: card.querySelector(".cap-item").value.trim(),
|
||||
tags: card.querySelector(".cap-tags").value.split(",").map((t) => t.trim()).filter(Boolean),
|
||||
}))
|
||||
.filter((c) => c.titulo);
|
||||
}
|
||||
|
||||
$("btnReconferir").addEventListener("click", async () => {
|
||||
baseErro("");
|
||||
const sd = lerSdRevisada();
|
||||
if (!sd) return;
|
||||
const r = await fetch("/api/base/conferir", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ sd }),
|
||||
});
|
||||
if (exigirLogin(r)) return;
|
||||
const d = await r.json();
|
||||
renderConferenciaBase(d.conferencia || []);
|
||||
});
|
||||
|
||||
$("btnGravarBase").addEventListener("click", async () => {
|
||||
baseErro("");
|
||||
const sd = lerSdRevisada();
|
||||
if (!sd) return;
|
||||
const caps = lerCapsRevisadas();
|
||||
if (!confirm(`Gravar ${sd.id || "a SD"} na base de conhecimento` +
|
||||
(caps.length ? ` com ${caps.length} capacidade(s)` : "") +
|
||||
"? Saldos de pool e precedentes passam a valer nas próximas entrevistas.")) return;
|
||||
$("btnGravarBase").disabled = true;
|
||||
try {
|
||||
const r = await fetch("/api/base/gravar", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ sd, capacidades: caps }),
|
||||
});
|
||||
if (exigirLogin(r)) return;
|
||||
const d = await r.json();
|
||||
if (!r.ok) {
|
||||
if (d.conferencia) renderConferenciaBase(d.conferencia);
|
||||
baseErro(d.erro || "Erro ao gravar.");
|
||||
return;
|
||||
}
|
||||
const okBox = $("baseOk");
|
||||
okBox.textContent = `✓ ${d.sd.id} gravada na base` +
|
||||
(d.capacidades.length ? ` com ${d.capacidades.map((c) => c.id).join(", ")}` : "") +
|
||||
". Vale a partir da próxima conversa.";
|
||||
okBox.hidden = false;
|
||||
await carregarStatus(); // atualiza próxima numeração e saldos no topo
|
||||
} finally {
|
||||
$("btnGravarBase").disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
function renderUso(uso) {
|
||||
if (!uso) return;
|
||||
const custo =
|
||||
(uso.input_tokens * PRECO.input +
|
||||
uso.output_tokens * PRECO.output +
|
||||
uso.cache_read_input_tokens * PRECO.cache_read +
|
||||
uso.cache_creation_input_tokens * PRECO.cache_write) / 1e6;
|
||||
$("usoBox").textContent =
|
||||
`tokens: ${uso.input_tokens.toLocaleString("pt-BR")} in · ${uso.output_tokens.toLocaleString("pt-BR")} out · ` +
|
||||
`cache ${uso.cache_read_input_tokens.toLocaleString("pt-BR")} lidos / ${uso.cache_creation_input_tokens.toLocaleString("pt-BR")} gravados · ` +
|
||||
`custo estimado US$ ${custo.toFixed(3)} (estimativa válida para o modelo Opus)`;
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="pt-BR">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Redator de SD — RMDS / SES-MG</title>
|
||||
<link rel="stylesheet" href="styles.css" />
|
||||
<link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>📋</text></svg>" />
|
||||
</head>
|
||||
<body>
|
||||
<header class="appbar">
|
||||
<h1>Redator de SD</h1>
|
||||
<span class="sub">RMDS · PE 29/2025 — SES-MG × Isis Saúde</span>
|
||||
<span class="spacer"></span>
|
||||
<span id="statusChip" class="chip-status">carregando…</span>
|
||||
<a href="#/" id="navHome" class="btn btn-sm">Nova SD</a>
|
||||
<a href="#/validar" id="navValidar" class="btn btn-sm">Validar JSON</a>
|
||||
<a href="#/base" id="navBase" class="btn btn-sm">Base de Conhecimento</a>
|
||||
<button id="btnTema" class="btn btn-sm" type="button" title="Tema">🌗</button>
|
||||
<button id="btnSair" class="btn btn-sm" hidden>Sair</button>
|
||||
</header>
|
||||
|
||||
<!-- Aviso de configuração -->
|
||||
<div id="avisoConfig" class="aviso" hidden>
|
||||
⚠ Chave de API não configurada. Copie <code>app\.env.example</code> para <code>app\.env</code>,
|
||||
preencha <code>ANTHROPIC_API_KEY</code> e reinicie o servidor.
|
||||
</div>
|
||||
|
||||
<!-- Login (usuário único) -->
|
||||
<main id="telaLogin" hidden>
|
||||
<form id="formLogin" class="panel login-box">
|
||||
<h2>Entrar</h2>
|
||||
<label>Usuário<br><input type="text" id="loginUsuario" autocomplete="username" required></label>
|
||||
<label>Senha<br><input type="password" id="loginSenha" autocomplete="current-password" required></label>
|
||||
<div id="loginErro" class="login-erro" hidden></div>
|
||||
<button type="submit" class="btn btn-primary" id="btnLogin">Entrar</button>
|
||||
</form>
|
||||
</main>
|
||||
|
||||
<!-- Tela inicial: lista + nova demanda -->
|
||||
<main id="telaHome" hidden>
|
||||
<section class="panel nova-demanda">
|
||||
<h2>Nova SD</h2>
|
||||
<p class="hint">Cole a demanda do jeito que ela chegou — trecho de ata, e-mail encaminhado, mensagem.
|
||||
Não precisa organizar. O redator lê, compara com a base e pergunta só o que faltar.</p>
|
||||
<textarea id="demandaInput" rows="5" placeholder="Ex.: a secretaria quer implementar um sistema de..."></textarea>
|
||||
<div class="btnrow">
|
||||
<button id="btnIniciar" class="btn btn-primary">Iniciar entrevista</button>
|
||||
<label class="sel-modelo">Modelo
|
||||
<select id="selModelo"></select>
|
||||
</label>
|
||||
</div>
|
||||
<p class="hint" style="margin:8px 0 0">O modelo fica fixo para a SD inteira (trocar no meio
|
||||
descartaria o cache da conversa). Lista configurável em <code>LLM_MODELOS</code> no .env.</p>
|
||||
</section>
|
||||
<section class="panel">
|
||||
<h2>SDs em andamento</h2>
|
||||
<div id="listaSds" class="lista-sds"></div>
|
||||
</section>
|
||||
<section class="panel">
|
||||
<h2>Saldo dos pools de UST</h2>
|
||||
<div id="saldosBox" class="saldos"></div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<!-- Tela da entrevista: chat + painel -->
|
||||
<main id="telaConversa" class="conversa" hidden>
|
||||
<section class="coluna-chat">
|
||||
<div id="mensagens" class="mensagens"></div>
|
||||
<div id="opcoes" class="opcoes"></div>
|
||||
<form id="formMsg" class="form-msg">
|
||||
<textarea id="msgInput" rows="2" placeholder="Responda ao redator… (Enter envia, Shift+Enter quebra linha)"></textarea>
|
||||
<button type="submit" class="btn btn-primary" id="btnEnviarMsg">Enviar</button>
|
||||
</form>
|
||||
<div id="usoBox" class="uso"></div>
|
||||
</section>
|
||||
<aside class="coluna-painel" id="slotPainelConversa">
|
||||
<div id="painel">
|
||||
<div class="painel-vazio" id="painelVazio">O painel do documento aparece aqui assim que o redator
|
||||
registrar os primeiros campos da SD.</div>
|
||||
<div id="painelConteudo" hidden>
|
||||
<section class="pbloco" id="pResumo"></section>
|
||||
<section class="pbloco">
|
||||
<h3>Quadro de entregáveis</h3>
|
||||
<div id="pQuadro" class="twrap"></div>
|
||||
</section>
|
||||
<section class="pbloco">
|
||||
<h3>Trava de integridade — artefatos</h3>
|
||||
<div id="pArtefatos"></div>
|
||||
</section>
|
||||
<section class="pbloco">
|
||||
<h3>Checklist de validação</h3>
|
||||
<div id="pChecklist"></div>
|
||||
</section>
|
||||
<section class="pbloco">
|
||||
<h3>Pendências</h3>
|
||||
<ul id="pPendencias" class="pend-list"></ul>
|
||||
</section>
|
||||
<section class="pbloco" id="pExport">
|
||||
<h3>Fechamento</h3>
|
||||
<div id="pBloqueios" class="lock-msg"></div>
|
||||
<div class="btnrow">
|
||||
<button class="btn" id="btnDocumento">Documento / imprimir (PDF)</button>
|
||||
<button class="btn" id="btnBaixar">Baixar .json</button>
|
||||
<button class="btn btn-primary" id="btnEnviarSd">Marcar como enviada</button>
|
||||
</div>
|
||||
<p class="hint" style="margin-top:8px">O documento abre em uma aba pronta para imprimir
|
||||
(Ctrl+P → salvar como PDF). Enquanto houver pendência bloqueante, ele sai com marca de rascunho.</p>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
</main>
|
||||
|
||||
<!-- Validação de JSON externo -->
|
||||
<main id="telaValidar" class="conversa" hidden>
|
||||
<section class="coluna-chat">
|
||||
<div class="panel">
|
||||
<h2>Validar JSON externo</h2>
|
||||
<p class="hint">Cole aqui o JSON de uma SD que não nasceu neste app (ex.: redigida no Claude ou
|
||||
recebida de um colega). O app recalcula UST e datas, roda o checklist do contrato e libera o
|
||||
documento para impressão — sem salvar nada.</p>
|
||||
<textarea id="jsonExterno" rows="14" spellcheck="false"
|
||||
placeholder='Cole o JSON da SD (formato schema-sd.json)…'></textarea>
|
||||
<div id="validarErro" class="login-erro" hidden></div>
|
||||
<div class="btnrow" style="margin-top:10px">
|
||||
<button class="btn btn-primary" id="btnValidarJson">Validar</button>
|
||||
<button class="btn" id="btnImportarJson">Importar JSON</button>
|
||||
<button class="btn" id="btnLimparJson">Limpar</button>
|
||||
<button class="btn" id="btnVoltarValidar">Voltar</button>
|
||||
</div>
|
||||
<input type="file" id="arquivoJson" accept=".json,application/json" hidden>
|
||||
</div>
|
||||
</section>
|
||||
<aside class="coluna-painel" id="slotPainelValidar"></aside>
|
||||
</main>
|
||||
|
||||
<!-- Alimentar base de conhecimento: upload de SD real → extração → revisão → gravação -->
|
||||
<main id="telaBase" hidden>
|
||||
<section class="panel">
|
||||
<h2>Alimentar base de conhecimento</h2>
|
||||
<p class="hint">Envie o documento de uma SD real (<strong>.pdf</strong>, <strong>.md</strong> ou <strong>.txt</strong> —
|
||||
se estiver em .docx, exporte como PDF). O app lê o documento, extrai o registro estruturado
|
||||
(itens, UST por item, período, status) e sugere capacidades reutilizáveis. Nada é gravado
|
||||
sem a sua revisão abaixo.</p>
|
||||
<div class="btnrow">
|
||||
<button class="btn btn-primary" id="btnEscolherDoc">Enviar documento</button>
|
||||
<label class="sel-modelo">Modelo
|
||||
<select id="selModeloBase"></select>
|
||||
</label>
|
||||
<button class="btn" id="btnVoltarBase">Voltar</button>
|
||||
</div>
|
||||
<input type="file" id="arquivoDoc" accept=".pdf,.md,.txt,application/pdf,text/markdown,text/plain" hidden>
|
||||
<div id="baseErro" class="login-erro" hidden style="margin-top:10px"></div>
|
||||
<div id="baseExtraindo" class="hint" hidden style="margin-top:10px">⏳ Lendo o documento e extraindo o registro… isso leva de 30 segundos a 2 minutos.</div>
|
||||
<div id="baseUso" class="uso" style="margin-top:6px"></div>
|
||||
</section>
|
||||
|
||||
<section class="panel" id="baseRevisao" hidden>
|
||||
<h2>Revisão antes de gravar</h2>
|
||||
<div class="pbloco">
|
||||
<h3>Conferência (em código)</h3>
|
||||
<div id="baseConferencia"></div>
|
||||
</div>
|
||||
<div class="pbloco" id="baseObsBloco" hidden>
|
||||
<h3>Observações do extrator</h3>
|
||||
<ul id="baseObs" class="pend-list"></ul>
|
||||
</div>
|
||||
<div class="pbloco">
|
||||
<h3>Registro da SD (edite se necessário e reconfira)</h3>
|
||||
<textarea id="baseSdJson" rows="16" spellcheck="false"></textarea>
|
||||
</div>
|
||||
<div class="pbloco">
|
||||
<h3>Capacidades sugeridas (desmarque as que não devem entrar)</h3>
|
||||
<div id="baseCaps"></div>
|
||||
</div>
|
||||
<div class="btnrow">
|
||||
<button class="btn" id="btnReconferir">Reconferir</button>
|
||||
<button class="btn btn-primary" id="btnGravarBase">Gravar na base</button>
|
||||
</div>
|
||||
<div id="baseOk" class="lock-msg open" hidden style="margin-top:10px"></div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<script src="app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,168 @@
|
||||
/* Tema: claro é o padrão; o escuro vale quando o usuário escolhe (data-theme="dark")
|
||||
ou quando o sistema está escuro e o usuário não forçou o claro (data-theme="light").
|
||||
O botão 🌗 do topo alterna automático → claro → escuro (persistido em localStorage). */
|
||||
:root{
|
||||
color-scheme:light;
|
||||
--bg:#F2F6F5; --surface:#FFFFFF; --ink:#1C2A2D; --muted:#5C6B6E;
|
||||
--line:#D7E1DF; --accent:#0B6B70; --accent-soft:#E1EFEF; --accent-ink:#FFFFFF;
|
||||
--ok:#1E7B47; --ok-bg:#E3F2E9; --warn:#A8730B; --warn-bg:#F8EFDB;
|
||||
--err:#B3362B; --err-bg:#F9E4E1; --pend:#5E6E78; --pend-bg:#E8EDF0;
|
||||
--shadow:0 1px 3px rgba(28,42,45,.08);
|
||||
--sans:"Segoe UI",system-ui,-apple-system,sans-serif;
|
||||
--mono:Consolas,"Cascadia Mono",ui-monospace,monospace;
|
||||
}
|
||||
:root[data-theme="dark"]{
|
||||
color-scheme:dark;
|
||||
--bg:#0E191B; --surface:#152325; --ink:#E3EDEB; --muted:#94A6A4;
|
||||
--line:#25393C; --accent:#56C4CA; --accent-soft:#123B3E; --accent-ink:#08282A;
|
||||
--ok:#54C88A; --ok-bg:#123626; --warn:#E2AC42; --warn-bg:#3A2D0F;
|
||||
--err:#E3705F; --err-bg:#41201C; --pend:#9AA8B2; --pend-bg:#22313A;
|
||||
--shadow:0 1px 3px rgba(0,0,0,.35);
|
||||
}
|
||||
@media (prefers-color-scheme: dark){
|
||||
:root:not([data-theme="light"]){
|
||||
color-scheme:dark;
|
||||
--bg:#0E191B; --surface:#152325; --ink:#E3EDEB; --muted:#94A6A4;
|
||||
--line:#25393C; --accent:#56C4CA; --accent-soft:#123B3E; --accent-ink:#08282A;
|
||||
--ok:#54C88A; --ok-bg:#123626; --warn:#E2AC42; --warn-bg:#3A2D0F;
|
||||
--err:#E3705F; --err-bg:#41201C; --pend:#9AA8B2; --pend-bg:#22313A;
|
||||
--shadow:0 1px 3px rgba(0,0,0,.35);
|
||||
}
|
||||
}
|
||||
*{box-sizing:border-box}
|
||||
[hidden]{display:none !important}
|
||||
html,body{height:100%}
|
||||
body{margin:0; background:var(--bg); color:var(--ink); font-family:var(--sans); line-height:1.5; display:flex; flex-direction:column;}
|
||||
button{font-family:var(--sans); cursor:pointer;}
|
||||
button:focus-visible, a:focus-visible, textarea:focus-visible, input:focus-visible{outline:2px solid var(--accent); outline-offset:2px;}
|
||||
textarea, select, input[type=date], input[type=text]{font-family:var(--sans); font-size:14px; background:var(--surface); color:var(--ink); border:1px solid var(--line); border-radius:6px; padding:8px 10px;}
|
||||
.sel-modelo{display:inline-flex; align-items:center; gap:8px; font-size:13px; color:var(--muted);}
|
||||
.sel-modelo select{font-family:var(--mono); font-size:12.5px; padding:7px 8px;}
|
||||
textarea{width:100%; resize:vertical;}
|
||||
|
||||
.appbar{background:var(--surface); border-bottom:1px solid var(--line); padding:10px 20px; display:flex; align-items:center; gap:12px; flex-wrap:wrap;}
|
||||
.appbar h1{font-size:16px; margin:0;}
|
||||
.appbar .sub{color:var(--muted); font-size:12px;}
|
||||
.appbar .spacer{flex:1;}
|
||||
.chip-status{font-size:12px; color:var(--muted); font-family:var(--mono);}
|
||||
|
||||
.aviso{background:var(--warn-bg); color:var(--warn); padding:10px 20px; font-size:14px;}
|
||||
.aviso code{font-family:var(--mono);}
|
||||
|
||||
.btn{border:1px solid var(--line); background:var(--surface); color:var(--ink); border-radius:6px; padding:8px 16px; font-size:14px; font-weight:600; text-decoration:none; display:inline-block;}
|
||||
.btn:hover{border-color:var(--accent);}
|
||||
.btn-sm{padding:4px 12px; font-size:13px;}
|
||||
.btn-primary{background:var(--accent); border-color:var(--accent); color:var(--accent-ink);}
|
||||
.btn-primary:hover{filter:brightness(1.08);}
|
||||
.btn:disabled{opacity:.45; cursor:not-allowed;}
|
||||
.btnrow{display:flex; gap:10px; flex-wrap:wrap;}
|
||||
|
||||
.panel{background:var(--surface); border:1px solid var(--line); border-radius:8px; box-shadow:var(--shadow); padding:16px 20px;}
|
||||
.panel h2{font-size:14px; margin:0 0 10px; text-transform:uppercase; letter-spacing:.06em; color:var(--muted);}
|
||||
.hint{font-size:13px; color:var(--muted); margin:0 0 10px;}
|
||||
|
||||
/* --- Login --- */
|
||||
#telaLogin{flex:1; display:flex; align-items:center; justify-content:center; padding:20px;}
|
||||
.login-box{width:100%; max-width:340px; display:flex; flex-direction:column; gap:12px;}
|
||||
.login-box label{font-size:13px; color:var(--muted);}
|
||||
.login-box input{width:100%; margin-top:4px;}
|
||||
.login-erro{background:var(--err-bg); color:var(--err); border-radius:6px; padding:8px 12px; font-size:13px;}
|
||||
|
||||
/* --- Home --- */
|
||||
#telaHome, #telaBase{max-width:860px; width:100%; margin:0 auto; padding:20px; display:flex; flex-direction:column; gap:16px;}
|
||||
.nova-demanda textarea{margin-bottom:10px;}
|
||||
.lista-sds{display:flex; flex-direction:column; gap:6px;}
|
||||
.sd-item{display:flex; gap:12px; align-items:baseline; padding:8px 10px; border:1px solid var(--line); border-radius:6px; text-decoration:none; color:var(--ink);}
|
||||
.sd-item:hover{border-color:var(--accent); background:var(--accent-soft);}
|
||||
.sd-item .num{font-family:var(--mono); font-size:12px; color:var(--accent); white-space:nowrap;}
|
||||
.sd-item .tit{flex:1; font-size:14px; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;}
|
||||
.sd-item .st{font-size:11px; border-radius:10px; padding:1px 8px;}
|
||||
.sd-item .btn-excluir{border:1px solid var(--line); background:var(--surface); color:var(--muted);
|
||||
border-radius:6px; font-size:12px; line-height:1; padding:4px 8px; align-self:center; flex:0 0 auto;}
|
||||
.sd-item .btn-excluir:hover{border-color:var(--err); color:var(--err); background:var(--err-bg);}
|
||||
.st-rascunho{background:var(--warn-bg); color:var(--warn);}
|
||||
.st-enviada{background:var(--ok-bg); color:var(--ok);}
|
||||
.saldos{display:flex; gap:10px; flex-wrap:wrap;}
|
||||
.saldo-chip{border:1px solid var(--line); border-radius:8px; padding:8px 14px; min-width:130px;}
|
||||
.saldo-chip .label{font-size:11px; text-transform:uppercase; letter-spacing:.06em; color:var(--muted);}
|
||||
.saldo-chip .value{font-size:17px; font-weight:700; font-variant-numeric:tabular-nums;}
|
||||
.saldo-chip .sub{font-size:11px; color:var(--muted);}
|
||||
|
||||
/* --- Conversa --- */
|
||||
.conversa{flex:1; display:grid; grid-template-columns:minmax(0,1fr) 420px; gap:0; min-height:0;}
|
||||
@media (max-width: 980px){ .conversa{grid-template-columns:1fr;} .coluna-painel{border-left:none; border-top:1px solid var(--line);} }
|
||||
.coluna-chat{display:flex; flex-direction:column; min-height:0; padding:16px 20px; gap:10px;}
|
||||
.mensagens{flex:1; overflow-y:auto; display:flex; flex-direction:column; gap:12px; padding-right:4px; min-height:200px;}
|
||||
.msg{max-width:92%; padding:10px 14px; border-radius:10px; font-size:14px;}
|
||||
.msg.user{align-self:flex-end; background:var(--accent-soft); border:1px solid var(--line); white-space:pre-wrap;}
|
||||
.msg.assistant{align-self:flex-start; background:var(--surface); border:1px solid var(--line); box-shadow:var(--shadow);}
|
||||
.msg.assistant p{margin:0 0 8px;} .msg.assistant p:last-child{margin-bottom:0;}
|
||||
.msg.assistant ul,.msg.assistant ol{margin:4px 0 8px; padding-left:20px;}
|
||||
.msg.assistant li{margin-bottom:2px;}
|
||||
.msg.assistant h1,.msg.assistant h2,.msg.assistant h3{font-size:14.5px; margin:10px 0 4px;}
|
||||
.msg.assistant code{font-family:var(--mono); font-size:12.5px; background:var(--bg); padding:0 4px; border-radius:4px;}
|
||||
.msg.assistant strong{color:var(--accent);}
|
||||
.msg .digitando{display:inline-block; animation:pulse 1s infinite;}
|
||||
.msg .pensando{display:inline-block; color:var(--muted); font-style:italic; font-size:13px; animation:pulse 1.4s infinite;}
|
||||
@keyframes pulse{50%{opacity:.3}}
|
||||
@media (prefers-reduced-motion: reduce){ .msg .digitando{animation:none;} }
|
||||
.opcoes{display:flex; flex-direction:column; gap:6px;}
|
||||
.opcoes button{text-align:left; background:var(--surface); border:1px solid var(--accent); color:var(--ink); border-radius:8px; padding:8px 14px; font-size:13.5px;}
|
||||
.opcoes button:hover{background:var(--accent-soft);}
|
||||
.form-msg{display:flex; gap:8px; align-items:flex-end;}
|
||||
.form-msg textarea{flex:1;}
|
||||
.uso{font-size:11.5px; color:var(--muted); font-family:var(--mono);}
|
||||
|
||||
/* --- Painel --- */
|
||||
.coluna-painel{border-left:1px solid var(--line); background:var(--surface); overflow-y:auto; padding:16px 18px;}
|
||||
.painel-vazio{color:var(--muted); font-size:13.5px; padding:30px 10px; text-align:center;}
|
||||
.pbloco{margin-bottom:18px;}
|
||||
.pbloco h3{font-size:12px; text-transform:uppercase; letter-spacing:.07em; color:var(--muted); margin:0 0 8px;}
|
||||
.resumo-chips{display:flex; gap:8px; flex-wrap:wrap; margin-bottom:6px;}
|
||||
.rchip{border:1px solid var(--line); border-radius:8px; padding:6px 12px;}
|
||||
.rchip .label{font-size:10px; text-transform:uppercase; letter-spacing:.06em; color:var(--muted);}
|
||||
.rchip .value{font-size:15px; font-weight:700; font-variant-numeric:tabular-nums;}
|
||||
.ptitulo{font-size:14.5px; font-weight:700; margin-bottom:8px;}
|
||||
.twrap{overflow-x:auto;}
|
||||
table.quadro{border-collapse:collapse; width:100%; font-size:12px; font-variant-numeric:tabular-nums;}
|
||||
table.quadro th, table.quadro td{border:1px solid var(--line); padding:4px 7px; text-align:left; vertical-align:top;}
|
||||
table.quadro th{font-size:10.5px; text-transform:uppercase; letter-spacing:.04em; background:var(--accent-soft);}
|
||||
table.quadro td.num{text-align:right;}
|
||||
table.quadro tr.total td{font-weight:700; border-top:2px solid var(--accent);}
|
||||
table.quadro tr.subtotal td{font-weight:600; background:var(--accent-soft);}
|
||||
|
||||
.check-item{display:grid; grid-template-columns:18px 56px 1fr; gap:6px; padding:4px 0; border-top:1px solid var(--line); font-size:12.5px; align-items:start;}
|
||||
.check-item:first-child{border-top:none;}
|
||||
.check-item .icon{font-weight:700; text-align:center;}
|
||||
.check-item .id{font-family:var(--mono); font-size:10.5px; color:var(--muted); padding-top:2px;}
|
||||
.check-item .obs{display:block; color:var(--muted); font-size:11.5px;}
|
||||
.st-ok .icon{color:var(--ok);} .st-alerta .icon{color:var(--warn);}
|
||||
.st-falha .icon{color:var(--err);} .st-pendente .icon{color:var(--pend);}
|
||||
|
||||
.art-entr{margin-bottom:10px;}
|
||||
.art-entr h4{font-size:12px; margin:0 0 4px;}
|
||||
.art-row{display:flex; gap:8px; align-items:flex-start; padding:5px 8px; border-radius:6px; font-size:12.5px; margin-bottom:3px;}
|
||||
.art-row.confirmed{background:var(--ok-bg);}
|
||||
.art-row.unconfirmed{background:var(--warn-bg);}
|
||||
.art-row input[type=checkbox]{margin-top:3px; accent-color:var(--accent); width:15px; height:15px; flex:0 0 auto;}
|
||||
.art-row .art-main{flex:1; min-width:0;}
|
||||
.art-row label{cursor:pointer; display:block;}
|
||||
.art-row input[type=date]{font-family:var(--mono); font-size:11.5px; margin-top:3px; padding:2px 6px;}
|
||||
.art-row .flag{font-size:11px; margin-top:2px;}
|
||||
.flag.bad{color:var(--err);} .flag.miss{color:var(--warn);}
|
||||
|
||||
/* --- Alimentar base --- */
|
||||
.cap-card{border:1px solid var(--line); border-radius:8px; padding:10px 12px; margin-bottom:8px;
|
||||
display:flex; gap:10px; align-items:flex-start;}
|
||||
.cap-card input[type=checkbox]{margin-top:4px; accent-color:var(--accent); width:16px; height:16px; flex:0 0 auto;}
|
||||
.cap-card .cap-main{flex:1; min-width:0; display:flex; flex-direction:column; gap:6px;}
|
||||
.cap-card input[type=text]{width:100%; font-weight:600;}
|
||||
.cap-card textarea{font-size:13px;}
|
||||
.cap-card .cap-meta{display:flex; gap:8px; flex-wrap:wrap;}
|
||||
.cap-card .cap-meta input{flex:1; min-width:120px; font-size:12.5px; font-family:var(--mono);}
|
||||
.cap-card.excluida{opacity:.45;}
|
||||
|
||||
.pend-list{margin:0; padding-left:18px; font-size:12.5px; display:flex; flex-direction:column; gap:5px;}
|
||||
.lock-msg{font-size:12.5px; border-radius:6px; padding:8px 11px; margin-bottom:10px;}
|
||||
.lock-msg.locked{background:var(--warn-bg); color:var(--warn);}
|
||||
.lock-msg.open{background:var(--ok-bg); color:var(--ok);}
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
// Base de conhecimento: numeração sequencial, saldo de pools e registro de SDs enviadas.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { PROJETO_DIR } from "./config.js";
|
||||
import { REGRAS } from "./validador.js";
|
||||
|
||||
const BASE_PATH = path.join(PROJETO_DIR, "base-conhecimento.json");
|
||||
|
||||
export function lerBase() {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(BASE_PATH, "utf8"));
|
||||
} catch {
|
||||
return { sds: [], capacidades: [], convencoes: {} };
|
||||
}
|
||||
}
|
||||
|
||||
function registrosReais(base) {
|
||||
// Ignora os registros de exemplo que vieram no esqueleto do arquivo.
|
||||
return (base.sds || []).filter((s) => !String(s.id).includes("EXEMPLO"));
|
||||
}
|
||||
|
||||
export function proximoNumero(base, numerosEmUso = []) {
|
||||
const nums = registrosReais(base)
|
||||
.map((s) => Number(String(s.id).match(/^SD-(\d+)/)?.[1]))
|
||||
.filter((n) => !isNaN(n));
|
||||
const max = Math.max(0, ...nums, ...numerosEmUso);
|
||||
return max + 1;
|
||||
}
|
||||
|
||||
export function saldos(base) {
|
||||
const consumo = {};
|
||||
const consomem = new Set(
|
||||
base.convencoes?.status_que_consomem_pool || [
|
||||
"enviada", "aprovada", "em_execucao", "concluida", "faturada",
|
||||
]
|
||||
);
|
||||
registrosReais(base).forEach((s) => {
|
||||
if (!consomem.has(s.status)) return;
|
||||
Object.entries(s.ust_por_item || {}).forEach(([item, ust]) => {
|
||||
consumo[item] = (consumo[item] || 0) + (ust || 0);
|
||||
});
|
||||
});
|
||||
const out = {};
|
||||
Object.entries(REGRAS.itens).forEach(([item, def]) => {
|
||||
out[item] = {
|
||||
pool_total: def.pool_ust_total,
|
||||
consumido: consumo[item] || 0,
|
||||
saldo: def.pool_ust_total - (consumo[item] || 0),
|
||||
};
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Bloco de contexto injetado na primeira mensagem de cada conversa. */
|
||||
export function contextoParaConversa(numeroProvisorio) {
|
||||
const base = lerBase();
|
||||
const s = saldos(base);
|
||||
const reais = registrosReais(base);
|
||||
const caps = (base.capacidades || []).filter((c) => !String(c.id).includes("EXEMPLO"));
|
||||
const linhas = [
|
||||
`Número provisório desta SD: SD-${numeroProvisorio} (o app confirma no envio).`,
|
||||
`Data de hoje: ${new Date().toISOString().slice(0, 10)}.`,
|
||||
"Saldo dos pools de UST (pool total − SDs que consomem pool):",
|
||||
...Object.entries(s).map(
|
||||
([i, v]) => ` ${i}: saldo ${v.saldo} UST (total ${v.pool_total}, consumido ${v.consumido})`
|
||||
),
|
||||
reais.length
|
||||
? `SDs anteriores na base: ${reais.map((r) => `${r.id} (${r.titulo}, ${r.status})`).join("; ")}`
|
||||
: "Base de SDs anteriores vazia — não cite precedentes.",
|
||||
caps.length
|
||||
? `Capacidades já entregues: ${caps.map((c) => `${c.id} (${c.titulo})`).join("; ")}`
|
||||
: "Nenhuma capacidade registrada na base — dimensione como construção do zero, mas pergunte ao usuário se algo já existe quando for relevante.",
|
||||
];
|
||||
return linhas.join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Grava uma SD REAL (extraída de documento e revisada pelo usuário) na base.
|
||||
* Substitui o registro se o id já existir; capacidades novas recebem CAP-NN sequencial.
|
||||
*/
|
||||
export function gravarSdReal(sd, capacidades = []) {
|
||||
const base = lerBase();
|
||||
const registro = {
|
||||
id: sd.id,
|
||||
titulo: String(sd.titulo || "").trim(),
|
||||
projeto: String(sd.projeto || "").trim(),
|
||||
itens_tr: sd.itens_tr || Object.keys(sd.ust_por_item || {}),
|
||||
ust_total: sd.ust_total,
|
||||
ust_por_item: sd.ust_por_item || {},
|
||||
status: sd.status,
|
||||
periodo: sd.periodo || null,
|
||||
resumo: String(sd.resumo || "").trim(),
|
||||
tags: Array.isArray(sd.tags) ? sd.tags : [],
|
||||
fonte: String(sd.fonte || "").trim(),
|
||||
};
|
||||
base.sds = (base.sds || []).filter((s) => s.id !== registro.id);
|
||||
base.sds.push(registro);
|
||||
|
||||
const capsGravadas = [];
|
||||
base.capacidades = base.capacidades || [];
|
||||
let n = Math.max(
|
||||
0,
|
||||
...base.capacidades
|
||||
.map((c) => Number(String(c.id).match(/^CAP-(\d+)/)?.[1]))
|
||||
.filter((x) => !isNaN(x))
|
||||
);
|
||||
for (const c of capacidades) {
|
||||
if (!String(c?.titulo || "").trim()) continue;
|
||||
const cap = {
|
||||
id: `CAP-${String(++n).padStart(2, "0")}`,
|
||||
titulo: String(c.titulo).trim(),
|
||||
descricao: String(c.descricao || "").trim(),
|
||||
origem_sd: registro.id,
|
||||
item_tr: String(c.item_tr || "").trim(),
|
||||
status: "entregue",
|
||||
tags: Array.isArray(c.tags) ? c.tags : [],
|
||||
};
|
||||
base.capacidades.push(cap);
|
||||
capsGravadas.push(cap);
|
||||
}
|
||||
|
||||
base.atualizado_em = new Date().toISOString().slice(0, 10);
|
||||
fs.writeFileSync(BASE_PATH, JSON.stringify(base, null, 2), "utf8");
|
||||
return { sd: registro, capacidades: capsGravadas };
|
||||
}
|
||||
|
||||
/** Acrescenta a SD enviada à base de conhecimento (uma linha por SD, como planejado). */
|
||||
export function registrarEnvio(sdExport) {
|
||||
const base = lerBase();
|
||||
const cab = sdExport.cabecalho || {};
|
||||
const porItem = {};
|
||||
(sdExport.entregaveis || []).forEach((e) => {
|
||||
porItem[e.item_tr] = (porItem[e.item_tr] || 0) + (e.ust || 0);
|
||||
});
|
||||
const registro = {
|
||||
id: cab.numero_sd,
|
||||
titulo: cab.titulo || cab.projeto || "",
|
||||
projeto: cab.projeto || "",
|
||||
itens_tr: cab.itens_tr || Object.keys(porItem),
|
||||
ust_total: cab.total_ust,
|
||||
ust_por_item: porItem,
|
||||
status: "enviada",
|
||||
periodo: cab.periodo_execucao || null,
|
||||
resumo: String(sdExport.objetivo || "").slice(0, 300),
|
||||
tags: [],
|
||||
};
|
||||
base.sds = (base.sds || []).filter((s) => s.id !== registro.id);
|
||||
base.sds.push(registro);
|
||||
base.atualizado_em = new Date().toISOString().slice(0, 10);
|
||||
fs.writeFileSync(BASE_PATH, JSON.stringify(base, null, 2), "utf8");
|
||||
return registro;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import dotenv from "dotenv";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
// Raiz do app (D:\IasisSaude\app) e raiz do projeto (D:\IasisSaude),
|
||||
// onde vivem regras-sd.json, schema-sd.json, base-conhecimento.json e o prompt.
|
||||
export const APP_DIR = path.resolve(here, "..");
|
||||
export const PROJETO_DIR = path.resolve(APP_DIR, "..");
|
||||
export const DATA_DIR = path.join(APP_DIR, "data");
|
||||
|
||||
dotenv.config({ path: path.join(APP_DIR, ".env") });
|
||||
|
||||
const EFFORTS_VALIDOS = ["low", "medium", "high", "xhigh", "max"];
|
||||
let effort = (process.env.LLM_EFFORT || "").trim().toLowerCase();
|
||||
if (effort && !EFFORTS_VALIDOS.includes(effort)) {
|
||||
console.warn(
|
||||
`⚠ LLM_EFFORT="${process.env.LLM_EFFORT}" inválido (use ${EFFORTS_VALIDOS.join("/")}) — usando o padrão da API.`
|
||||
);
|
||||
effort = "";
|
||||
}
|
||||
|
||||
const model = process.env.LLM_MODEL || "claude-opus-5";
|
||||
|
||||
// Modelos oferecidos nos seletores da interface (Nova SD e Base de Conhecimento).
|
||||
// LLM_MODELOS: lista separada por vírgula; o LLM_MODEL padrão sempre entra.
|
||||
const modelos = [
|
||||
...new Set(
|
||||
[model, ...(process.env.LLM_MODELOS || "").split(",").map((m) => m.trim()).filter(Boolean)]
|
||||
),
|
||||
];
|
||||
|
||||
export const config = {
|
||||
provider: process.env.LLM_PROVIDER || "anthropic",
|
||||
model,
|
||||
modelos,
|
||||
apiKey: process.env.ANTHROPIC_API_KEY || "",
|
||||
effort, // "" = padrão da API (high)
|
||||
port: Number(process.env.PORT || 3344),
|
||||
usuario: process.env.APP_USUARIO || "",
|
||||
senha: process.env.APP_SENHA || "",
|
||||
};
|
||||
|
||||
export function configOk() {
|
||||
return Boolean(config.apiKey);
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
// Extração de uma SD REAL (documento .pdf/.md/.txt) para o formato da base de conhecimento.
|
||||
// O LLM lê o documento e devolve o registro estruturado; a conferência determinística
|
||||
// roda em código; a gravação só acontece depois da revisão humana na tela.
|
||||
import { REGRAS } from "./validador.js";
|
||||
import { lerBase, saldos } from "./base.js";
|
||||
|
||||
const STATUS_SD = ["rascunho", "enviada", "aprovada", "em_execucao", "concluida", "faturada", "cancelada"];
|
||||
const STATUS_CONSOMEM = ["enviada", "aprovada", "em_execucao", "concluida", "faturada"];
|
||||
|
||||
// ---------- Ferramenta de extração (saída estruturada) ----------
|
||||
|
||||
export const TOOL_EXTRACAO = {
|
||||
name: "registrar_extracao",
|
||||
description:
|
||||
"Registra o resultado da extração do documento da SD no formato da base de conhecimento. " +
|
||||
"Chame exatamente uma vez, com todos os fatos que o documento sustenta.",
|
||||
input_schema: {
|
||||
type: "object",
|
||||
required: ["sd"],
|
||||
properties: {
|
||||
sd: {
|
||||
type: "object",
|
||||
required: ["id", "titulo", "projeto", "itens_tr", "ust_total", "ust_por_item", "status", "resumo", "tags"],
|
||||
properties: {
|
||||
id: { type: "string", pattern: "^SD-\\d+$", description: "Número oficial da SD no contrato, ex.: SD-8" },
|
||||
titulo: { type: "string" },
|
||||
projeto: { type: "string", description: "Programa/projeto a que a SD pertence, ex.: 'P2 — Vacinação'" },
|
||||
itens_tr: { type: "array", items: { type: "string", enum: Object.keys(REGRAS.itens) } },
|
||||
ust_total: { type: "integer", description: "Total de UST da SD" },
|
||||
ust_por_item: {
|
||||
type: "object",
|
||||
description: "Soma das UST do quadro de entregáveis, por item do TR. As chaves devem ser as mesmas de itens_tr e a soma deve bater com ust_total.",
|
||||
additionalProperties: { type: "integer" },
|
||||
},
|
||||
status: { type: "string", enum: STATUS_SD },
|
||||
periodo: {
|
||||
type: ["object", "null"],
|
||||
properties: {
|
||||
inicio: { type: "string", description: "AAAA-MM-DD" },
|
||||
fim: { type: "string", description: "AAAA-MM-DD" },
|
||||
},
|
||||
},
|
||||
resumo: { type: "string", description: "Resumo factual em até ~600 caracteres: o que foi entregue e o que ficou de reutilizável." },
|
||||
tags: { type: "array", items: { type: "string" }, description: "minúsculas, sem acento, singular" },
|
||||
fonte: { type: "string", description: "Nome do arquivo enviado" },
|
||||
},
|
||||
},
|
||||
capacidades: {
|
||||
type: "array",
|
||||
description: "Capacidades REUTILIZÁVEIS que esta SD entregou (integrações, motores, componentes, dicionários de dados) — aquilo que uma SD futura reaproveitaria em vez de reconstruir.",
|
||||
items: {
|
||||
type: "object",
|
||||
required: ["titulo", "descricao", "item_tr"],
|
||||
properties: {
|
||||
titulo: { type: "string" },
|
||||
descricao: { type: "string", description: "Padrão: o que existe hoje + o que uma nova SD NÃO precisa refazer." },
|
||||
item_tr: { type: "string", enum: Object.keys(REGRAS.itens) },
|
||||
tags: { type: "array", items: { type: "string" } },
|
||||
},
|
||||
},
|
||||
},
|
||||
observacoes: {
|
||||
type: "array",
|
||||
items: { type: "string" },
|
||||
description: "Tudo que ficou ambíguo no documento ou merece revisão humana (status incerto, valores conflitantes, campos ausentes).",
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export function montarSystemExtracao() {
|
||||
const itens = Object.entries(REGRAS.itens)
|
||||
.map(([k, v]) => ` ${k} — item ${v.item_tr_numero} do TR, "${v.titulo_literal}" (CATMAS ${v.codigo_catmas})`)
|
||||
.join("\n");
|
||||
return [
|
||||
"Você extrai, de um documento oficial de Solicitação de Demanda (SD) do contrato PE 29/2025",
|
||||
"(programa RMDS — SES-MG × Isis Saúde), o registro estruturado para a base de conhecimento do redator de SDs.",
|
||||
"",
|
||||
"Regras de extração:",
|
||||
"- Registre APENAS fatos presentes no documento. A base só serve se for verdadeira — nunca estime valores que o documento não sustenta.",
|
||||
"- ust_por_item: some as UST do quadro de entregáveis por item do TR. A soma por item deve bater com o total da SD; confira antes de responder.",
|
||||
"- Itens do TR deste contrato:",
|
||||
itens,
|
||||
`- status: use a convenção [${STATUS_SD.join(", ")}]. Se o documento não permitir concluir o status, escolha o mais provável e registre a dúvida em observacoes.`,
|
||||
"- capacidades: só o que é genuinamente reutilizável por SDs futuras. Prefira poucas e bem descritas a muitas e vagas.",
|
||||
"- tags: minúsculas, sem acento, singular quando possível (ex.: vacinacao, integracao, dashboard).",
|
||||
"- fonte: repita o nome do arquivo informado na mensagem.",
|
||||
"",
|
||||
"Chame a ferramenta registrar_extracao exatamente uma vez. Não escreva texto além da chamada.",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
/** Monta o conteúdo da mensagem do usuário a partir do arquivo enviado (base64). */
|
||||
export function montarConteudoDocumento({ nome, base64 }) {
|
||||
const ext = String(nome || "").toLowerCase().match(/\.([a-z0-9]+)$/)?.[1] || "";
|
||||
const instrucao = `Arquivo: ${nome}\nExtraia o registro desta SD para a base de conhecimento e chame registrar_extracao.`;
|
||||
if (ext === "pdf") {
|
||||
return [
|
||||
{ type: "document", source: { type: "base64", media_type: "application/pdf", data: base64 } },
|
||||
{ type: "text", text: instrucao },
|
||||
];
|
||||
}
|
||||
const texto = Buffer.from(base64, "base64").toString("utf8");
|
||||
return [{ type: "text", text: `${instrucao}\n\n<documento nome="${nome}">\n${texto}\n</documento>` }];
|
||||
}
|
||||
|
||||
// ---------- Conferência determinística (roda em código, sem LLM) ----------
|
||||
|
||||
/** Devolve a lista de inconsistências: nivel "erro" bloqueia a gravação; "alerta" só avisa. */
|
||||
export function conferirExtracao(sd) {
|
||||
const avisos = [];
|
||||
const erro = (msg) => avisos.push({ nivel: "erro", msg });
|
||||
const alerta = (msg) => avisos.push({ nivel: "alerta", msg });
|
||||
if (!sd || typeof sd !== "object") {
|
||||
erro("Registro da SD ausente ou inválido.");
|
||||
return avisos;
|
||||
}
|
||||
const base = lerBase();
|
||||
|
||||
if (!/^SD-\d+$/.test(String(sd.id || ""))) erro(`id "${sd.id ?? ""}" fora do padrão SD-NN.`);
|
||||
if (!String(sd.titulo || "").trim()) erro("Título vazio.");
|
||||
|
||||
const porItem = sd.ust_por_item && typeof sd.ust_por_item === "object" ? sd.ust_por_item : {};
|
||||
const soma = Object.values(porItem).reduce((a, b) => a + (Number(b) || 0), 0);
|
||||
if (!Number.isFinite(sd.ust_total) || sd.ust_total <= 0) erro("ust_total ausente ou inválido.");
|
||||
else if (soma !== sd.ust_total)
|
||||
erro(`Soma de ust_por_item (${soma}) difere de ust_total (${sd.ust_total}).`);
|
||||
|
||||
Object.keys(porItem).forEach((i) => {
|
||||
if (!REGRAS.itens[i]) erro(`Item "${i}" em ust_por_item não existe no contrato (${Object.keys(REGRAS.itens).join(", ")}).`);
|
||||
});
|
||||
const setItens = new Set(Array.isArray(sd.itens_tr) ? sd.itens_tr : []);
|
||||
const setPor = new Set(Object.keys(porItem));
|
||||
if (setItens.size !== setPor.size || [...setItens].some((i) => !setPor.has(i)))
|
||||
erro(`itens_tr (${[...setItens].join(", ") || "vazio"}) não bate com as chaves de ust_por_item (${[...setPor].join(", ") || "vazio"}).`);
|
||||
|
||||
if (!STATUS_SD.includes(sd.status)) erro(`status "${sd.status ?? ""}" fora da convenção (${STATUS_SD.join(", ")}).`);
|
||||
|
||||
const p = sd.periodo;
|
||||
if (p?.inicio && p?.fim && p.inicio > p.fim) erro(`Período invertido: início ${p.inicio} posterior ao fim ${p.fim}.`);
|
||||
else if (!p?.inicio || !p?.fim) alerta("Período de execução incompleto — confirme início e fim.");
|
||||
|
||||
const existente = (base.sds || []).find((s) => s.id === sd.id);
|
||||
if (existente) alerta(`${sd.id} já existe na base ("${existente.titulo}") — gravar vai SUBSTITUIR esse registro.`);
|
||||
|
||||
// Impacto no saldo dos pools (descontando o que o registro antigo já consumia).
|
||||
const consomem = new Set(base.convencoes?.status_que_consomem_pool || STATUS_CONSOMEM);
|
||||
if (consomem.has(sd.status)) {
|
||||
const s = saldos(base);
|
||||
Object.entries(porItem).forEach(([item, ust]) => {
|
||||
if (!s[item]) return;
|
||||
const jaContava = existente && consomem.has(existente.status) ? existente.ust_por_item?.[item] || 0 : 0;
|
||||
const novoSaldo = s[item].saldo + jaContava - (Number(ust) || 0);
|
||||
if (novoSaldo < 0) alerta(`Saldo do pool ${item} ficaria negativo (${novoSaldo} UST) — confira os valores.`);
|
||||
});
|
||||
}
|
||||
|
||||
if (!String(sd.resumo || "").trim()) alerta("Resumo vazio — o redator usa o resumo para citar precedentes.");
|
||||
return avisos;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* Repara históricos em que um tool_use ficou sem o tool_result seguinte
|
||||
* (ex.: turno truncado por max_tokens). Sem isso, a API rejeita TODAS as
|
||||
* mensagens seguintes da conversa com erro 400
|
||||
* ("tool_use ids were found without tool_result blocks immediately after").
|
||||
*/
|
||||
export function repararHistorico(mensagens) {
|
||||
const saida = [];
|
||||
for (let i = 0; i < mensagens.length; i++) {
|
||||
const m = mensagens[i];
|
||||
saida.push(m);
|
||||
if (m.role !== "assistant" || !Array.isArray(m.content)) continue;
|
||||
const ids = m.content.filter((b) => b.type === "tool_use").map((b) => b.id);
|
||||
if (!ids.length) continue;
|
||||
const prox = mensagens[i + 1];
|
||||
const respondidos = new Set(
|
||||
prox && prox.role === "user" && Array.isArray(prox.content)
|
||||
? prox.content.filter((b) => b.type === "tool_result").map((b) => b.tool_use_id)
|
||||
: []
|
||||
);
|
||||
const faltantes = ids.filter((id) => !respondidos.has(id));
|
||||
if (!faltantes.length) continue;
|
||||
const resultados = faltantes.map((id) => ({
|
||||
type: "tool_result",
|
||||
tool_use_id: id,
|
||||
content:
|
||||
"Esta chamada foi interrompida antes de ser processada (turno truncado). " +
|
||||
"O estado NÃO foi aplicado — se necessário, chame atualizar_rascunho novamente com a SD completa.",
|
||||
is_error: true,
|
||||
}));
|
||||
if (respondidos.size) {
|
||||
prox.content = [...resultados, ...prox.content]; // completa o tool_result parcial existente
|
||||
} else {
|
||||
saida.push({ role: "user", content: resultados }); // insere a resposta que faltava
|
||||
}
|
||||
}
|
||||
return saida;
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
// Adaptador Anthropic — implementa a interface ProviderLLM do app.
|
||||
// Interface: executarTurno({ system, messages, tools, onText }) -> mensagem final da API.
|
||||
import Anthropic from "@anthropic-ai/sdk";
|
||||
|
||||
export function criarAnthropicProvider(config) {
|
||||
const client = new Anthropic({ apiKey: config.apiKey });
|
||||
|
||||
// Fallback server-side: se um classificador de segurança recusar a requisição,
|
||||
// a própria API re-executa em um modelo alternativo recomendado. Se a conta não
|
||||
// tiver o beta disponível, o adaptador detecta o 400 e passa a chamar sem fallback.
|
||||
let fallbackDisponivel = true;
|
||||
|
||||
async function chamar({ system, messages, tools, onText, model }) {
|
||||
const params = {
|
||||
model: model || config.model,
|
||||
// Atenção: max_tokens cobre raciocínio interno + texto + JSON da ferramenta.
|
||||
// O rascunho completo da SD é grande; 16k estourava em turnos avançados.
|
||||
max_tokens: 32000,
|
||||
system,
|
||||
messages,
|
||||
tools,
|
||||
cache_control: { type: "ephemeral" }, // auto-cache do último bloco (histórico da conversa)
|
||||
};
|
||||
if (config.effort) params.output_config = { effort: config.effort };
|
||||
if (fallbackDisponivel) {
|
||||
params.betas = ["server-side-fallback-2026-07-01"];
|
||||
params.fallbacks = "default";
|
||||
}
|
||||
const stream = client.beta.messages.stream(params);
|
||||
for await (const event of stream) {
|
||||
if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
|
||||
onText?.(event.delta.text);
|
||||
}
|
||||
}
|
||||
return await stream.finalMessage();
|
||||
}
|
||||
|
||||
return {
|
||||
nome: "anthropic",
|
||||
modelo: config.model,
|
||||
|
||||
/**
|
||||
* Chamada única (sem streaming) com saída estruturada forçada — usada pela
|
||||
* extração de SD real. Aceita PDF via bloco document na mensagem.
|
||||
*/
|
||||
async executarExtracao({ system, messages, tools, toolName, model }) {
|
||||
const params = {
|
||||
model: model || config.model,
|
||||
max_tokens: 8000,
|
||||
system,
|
||||
messages,
|
||||
tools,
|
||||
tool_choice: { type: "tool", name: toolName },
|
||||
};
|
||||
let resp;
|
||||
try {
|
||||
resp = await client.messages.create(params);
|
||||
} catch (err) {
|
||||
// tool_choice forçado é incompatível com raciocínio estendido em algumas
|
||||
// configurações — repete deixando o modelo decidir (o prompt já obriga a chamada).
|
||||
if (err?.status === 400 && /tool_choice|thinking/i.test(String(err?.message || err))) {
|
||||
resp = await client.messages.create({ ...params, tool_choice: { type: "auto" } });
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
const tu = (resp.content || []).find((b) => b.type === "tool_use" && b.name === toolName);
|
||||
if (!tu) {
|
||||
const texto = (resp.content || []).filter((b) => b.type === "text").map((b) => b.text).join(" ");
|
||||
throw new Error("O modelo não retornou a extração estruturada." + (texto ? ` Resposta: ${texto.slice(0, 300)}` : ""));
|
||||
}
|
||||
return { input: tu.input, usage: resp.usage };
|
||||
},
|
||||
|
||||
async executarTurno(args) {
|
||||
try {
|
||||
return await chamar(args);
|
||||
} catch (err) {
|
||||
const msg = String(err?.message || err);
|
||||
if (
|
||||
fallbackDisponivel &&
|
||||
err?.status === 400 &&
|
||||
/fallback/i.test(msg)
|
||||
) {
|
||||
// Conta sem o beta de fallback: repete sem ele e não tenta de novo.
|
||||
fallbackDisponivel = false;
|
||||
return await chamar(args);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// Camada de abstração de provedor de LLM.
|
||||
// MVP: adaptador Anthropic. Fase 1.1: adaptador OpenAI implementando a mesma interface.
|
||||
import { criarAnthropicProvider } from "./anthropic.js";
|
||||
|
||||
export function criarProvider(config) {
|
||||
switch (config.provider) {
|
||||
case "anthropic":
|
||||
return criarAnthropicProvider(config);
|
||||
case "openai":
|
||||
throw new Error(
|
||||
"Adaptador OpenAI ainda não implementado (previsto para a fase 1.1). Use LLM_PROVIDER=anthropic."
|
||||
);
|
||||
default:
|
||||
throw new Error(`Provedor desconhecido: ${config.provider}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
// Monta o system prompt do redator: prompt-redator-sd.md + regras + schema + base,
|
||||
// mais a seção <app> que adapta o comportamento ao aplicativo (tool em vez de bloco de texto).
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { PROJETO_DIR } from "./../config.js";
|
||||
|
||||
const SECAO_APP = `
|
||||
<app>
|
||||
Você está rodando dentro do aplicativo Redator de SD. Ajustes ao <modo_de_conducao> e à <saida>:
|
||||
|
||||
1. NÃO escreva o bloco "RASCUNHO ATÉ AQUI" em texto. Em vez disso, ao final de CADA turno em que
|
||||
algum campo da SD mudou, chame a ferramenta atualizar_rascunho com o estado COMPLETO da SD até
|
||||
aqui (campos ainda desconhecidos podem ficar ausentes, mas envie tudo o que já foi definido —
|
||||
a ferramenta substitui o estado anterior por inteiro). É essa chamada que alimenta o painel do
|
||||
documento que o usuário vê ao lado do chat.
|
||||
2. O resultado da ferramenta traz a validação DETERMINÍSTICA do app (os itens "codigo" do checklist,
|
||||
recalculados em código). Trate esse resultado como autoridade: se apontar falha, corrija a SD e
|
||||
chame a ferramenta de novo no mesmo turno antes de responder ao usuário.
|
||||
3. Na <saida> final (Passo 6), entregue apenas o rascunho legível no chat — NÃO cole o JSON em bloco
|
||||
de código; o JSON vai pela ferramenta. Preencha também o array "validacao" da SD com o seu parecer
|
||||
sobre os itens de "julgamento" (ENQ-02..05, DOC-01, DOC-04..06, DOC-10, DOC-11).
|
||||
4. A confirmação de artefatos (DOC-08) acontece na interface, fora do chat: o usuário marca checkbox
|
||||
e data no painel. Não insista em pedir confirmação textual; registre os artefatos como tipos com
|
||||
confirmado_pelo_usuario=false e siga.
|
||||
5. No texto do chat, não use tabelas markdown — use listas. As opções de resposta que você oferece
|
||||
devem vir em linhas iniciadas por "OPCAO:" (ex.: "OPCAO: 1. Ciclo completo → 4 entregáveis"),
|
||||
uma por linha, que o app transforma em botões clicáveis.
|
||||
6. A primeira mensagem do usuário traz um bloco <contexto-do-app> com o número provisório da SD,
|
||||
a data de hoje e o saldo real dos pools — use esses valores; não os recalcule nem os questione.
|
||||
</app>`;
|
||||
|
||||
const ARQUIVOS = [
|
||||
"prompt-redator-sd.md",
|
||||
"regras-sd.json",
|
||||
"schema-sd.json",
|
||||
"base-conhecimento.json",
|
||||
];
|
||||
|
||||
let cache = null;
|
||||
let assinatura = "";
|
||||
|
||||
// Assinatura por data de modificação: se qualquer arquivo-fonte mudou no disco,
|
||||
// o prompt é remontado na próxima conversa — sem precisar reiniciar o servidor.
|
||||
function assinaturaArquivos() {
|
||||
return ARQUIVOS.map((f) => {
|
||||
try {
|
||||
return fs.statSync(path.join(PROJETO_DIR, f)).mtimeMs;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}).join("|");
|
||||
}
|
||||
|
||||
export function montarSystem() {
|
||||
const atual = assinaturaArquivos();
|
||||
if (cache && assinatura === atual) return cache;
|
||||
assinatura = atual;
|
||||
cache = null;
|
||||
const prompt = fs.readFileSync(path.join(PROJETO_DIR, "prompt-redator-sd.md"), "utf8");
|
||||
const regras = fs.readFileSync(path.join(PROJETO_DIR, "regras-sd.json"), "utf8");
|
||||
const schema = fs.readFileSync(path.join(PROJETO_DIR, "schema-sd.json"), "utf8");
|
||||
let baseTexto;
|
||||
try {
|
||||
baseTexto = fs.readFileSync(path.join(PROJETO_DIR, "base-conhecimento.json"), "utf8");
|
||||
} catch {
|
||||
baseTexto = '{"sds": [], "capacidades": []}';
|
||||
}
|
||||
|
||||
// Injeta a base no bloco <base_consultada> do prompt (substitui o comentário de injeção).
|
||||
const promptComBase = prompt.replace(
|
||||
/<base_consultada>[\s\S]*?<\/base_consultada>/,
|
||||
`<base_consultada>\nConteúdo de base-conhecimento.json (registros com "EXEMPLO" no id devem ser ignorados):\n${baseTexto}\n</base_consultada>`
|
||||
);
|
||||
|
||||
const texto = [
|
||||
promptComBase,
|
||||
`<regras>\nConteúdo de regras-sd.json:\n${regras}\n</regras>`,
|
||||
`<schema>\nConteúdo de schema-sd.json (formato da SD e da ferramenta atualizar_rascunho):\n${schema}\n</schema>`,
|
||||
SECAO_APP,
|
||||
].join("\n\n");
|
||||
|
||||
// Um único bloco com cache_control: o prefixo inteiro (estável) é cacheado;
|
||||
// o que varia por conversa vai na primeira mensagem do usuário.
|
||||
cache = [{ type: "text", text: texto, cache_control: { type: "ephemeral" } }];
|
||||
return cache;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// Ferramenta atualizar_rascunho: o input é a própria SD, no formato de schema-sd.json.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { PROJETO_DIR } from "./../config.js";
|
||||
|
||||
function limparSchema(node) {
|
||||
// Remove chaves de metadado que não pertencem a um input_schema de ferramenta.
|
||||
if (Array.isArray(node)) return node.map(limparSchema);
|
||||
if (node && typeof node === "object") {
|
||||
const out = {};
|
||||
for (const [k, v] of Object.entries(node)) {
|
||||
if (["$schema", "$id", "$comment", "title"].includes(k)) continue;
|
||||
out[k] = limparSchema(v);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
let cache = null;
|
||||
|
||||
export function ferramentas() {
|
||||
if (cache) return cache;
|
||||
const schema = JSON.parse(
|
||||
fs.readFileSync(path.join(PROJETO_DIR, "schema-sd.json"), "utf8")
|
||||
);
|
||||
const inputSchema = limparSchema(schema);
|
||||
// O rascunho parcial não tem todos os campos obrigatórios ainda — relaxa o required
|
||||
// do nível raiz para a ferramenta aceitar estados intermediários da entrevista.
|
||||
delete inputSchema.required;
|
||||
|
||||
cache = [
|
||||
{
|
||||
name: "atualizar_rascunho",
|
||||
description:
|
||||
"Atualiza o painel do documento com o estado COMPLETO e atual da SD (substitui o estado " +
|
||||
"anterior por inteiro — envie todos os campos já definidos, não apenas o que mudou). " +
|
||||
"Chame ao final de cada turno em que algum campo da SD mudou, e novamente no mesmo turno " +
|
||||
"se o resultado da validação apontar falha que você consiga corrigir. O resultado retorna " +
|
||||
"a validação determinística do app (itens 'codigo' do checklist, UST recalculada, subtotais).",
|
||||
input_schema: inputSchema,
|
||||
},
|
||||
];
|
||||
return cache;
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
import express from "express";
|
||||
import path from "node:path";
|
||||
import crypto from "node:crypto";
|
||||
import { APP_DIR, config, configOk } from "./config.js";
|
||||
import { criarProvider } from "./llm/provider.js";
|
||||
import { montarSystem } from "./redator/prompt.js";
|
||||
import { ferramentas } from "./redator/tools.js";
|
||||
import {
|
||||
validar,
|
||||
resumoParaRedator,
|
||||
construirExport,
|
||||
bloqueiosDeExportacao,
|
||||
CHECKLIST,
|
||||
REGRAS,
|
||||
} from "./validador.js";
|
||||
import { lerBase, proximoNumero, saldos, contextoParaConversa, registrarEnvio, gravarSdReal } from "./base.js";
|
||||
import { TOOL_EXTRACAO, montarSystemExtracao, montarConteudoDocumento, conferirExtracao } from "./extrator.js";
|
||||
import { repararHistorico } from "./historico.js";
|
||||
import { listarSds, obterSd, criarSd, salvarSd, excluirSd, numerosEmUso } from "./store.js";
|
||||
|
||||
const app = express();
|
||||
// 25mb comporta um PDF de SD em base64 (rota /api/base/extrair); as demais rotas têm corpos pequenos.
|
||||
app.use(express.json({ limit: "25mb" }));
|
||||
app.use(express.static(path.join(APP_DIR, "public")));
|
||||
|
||||
let provider = null;
|
||||
function getProvider() {
|
||||
if (!configOk()) throw new Error("ANTHROPIC_API_KEY não configurada. Copie .env.example para .env e preencha a chave.");
|
||||
if (!provider) provider = criarProvider(config);
|
||||
return provider;
|
||||
}
|
||||
|
||||
function somarUso(acc, usage) {
|
||||
if (!usage) return;
|
||||
acc.input_tokens += usage.input_tokens || 0;
|
||||
acc.output_tokens += usage.output_tokens || 0;
|
||||
acc.cache_read_input_tokens += usage.cache_read_input_tokens || 0;
|
||||
acc.cache_creation_input_tokens += usage.cache_creation_input_tokens || 0;
|
||||
acc.turnos += 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executa um turno do redator (com loop de ferramenta) e transmite o progresso
|
||||
* ao navegador como NDJSON: {t:"delta"|"rascunho"|"uso"|"erro"|"fim", ...}
|
||||
*/
|
||||
async function rodarTurno(registro, res) {
|
||||
res.setHeader("Content-Type", "application/x-ndjson; charset=utf-8");
|
||||
res.setHeader("Cache-Control", "no-cache");
|
||||
const send = (obj) => res.write(JSON.stringify(obj) + "\n");
|
||||
|
||||
try {
|
||||
const prov = getProvider();
|
||||
const system = montarSystem();
|
||||
const tools = ferramentas();
|
||||
let textoDoTurno = "";
|
||||
let iteracoes = 0;
|
||||
let truncamentos = 0;
|
||||
|
||||
// Cura históricos quebrados por versões anteriores (tool_use sem tool_result).
|
||||
registro.mensagens = repararHistorico(registro.mensagens);
|
||||
|
||||
while (iteracoes++ < 8) {
|
||||
const final = await prov.executarTurno({
|
||||
system,
|
||||
messages: registro.mensagens,
|
||||
tools,
|
||||
model: registro.modelo || undefined,
|
||||
onText: (t) => {
|
||||
textoDoTurno += t;
|
||||
send({ t: "delta", text: t });
|
||||
},
|
||||
});
|
||||
somarUso(registro.uso, final.usage);
|
||||
registro.mensagens.push({ role: "assistant", content: final.content });
|
||||
|
||||
const truncado = final.stop_reason === "max_tokens";
|
||||
const toolUses = (final.content || []).filter((b) => b.type === "tool_use");
|
||||
|
||||
// Regra de ouro da API: TODO tool_use recebe tool_result na mensagem seguinte,
|
||||
// seja qual for o stop_reason — senão o histórico fica inválido para sempre.
|
||||
if (toolUses.length) {
|
||||
const results = [];
|
||||
for (const tu of toolUses) {
|
||||
if (truncado) {
|
||||
results.push({
|
||||
type: "tool_result",
|
||||
tool_use_id: tu.id,
|
||||
content:
|
||||
"A chamada foi truncada pelo limite de tokens e NÃO foi aplicada. " +
|
||||
"Chame atualizar_rascunho novamente com a SD completa.",
|
||||
is_error: true,
|
||||
});
|
||||
} else if (tu.name === "atualizar_rascunho") {
|
||||
registro.rascunho = tu.input;
|
||||
const v = validar(tu.input);
|
||||
send({ t: "rascunho", sd: tu.input, validacao: v, bloqueios: bloqueiosDeExportacao(v) });
|
||||
results.push({
|
||||
type: "tool_result",
|
||||
tool_use_id: tu.id,
|
||||
content: JSON.stringify(resumoParaRedator(v)),
|
||||
});
|
||||
} else {
|
||||
results.push({
|
||||
type: "tool_result",
|
||||
tool_use_id: tu.id,
|
||||
content: `Ferramenta desconhecida: ${tu.name}`,
|
||||
is_error: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
registro.mensagens.push({ role: "user", content: results });
|
||||
}
|
||||
|
||||
if (final.stop_reason === "refusal") {
|
||||
send({ t: "erro", msg: "A requisição foi recusada pelos classificadores de segurança do modelo. Reformule a mensagem e tente de novo." });
|
||||
break;
|
||||
}
|
||||
if (truncado) {
|
||||
// Dá uma chance de o modelo retomar; se truncar de novo, encerra com aviso.
|
||||
if (++truncamentos <= 1 && toolUses.length) continue;
|
||||
send({ t: "erro", msg: "A resposta excedeu o limite de tokens do turno. Envie 'continue' para retomar." });
|
||||
break;
|
||||
}
|
||||
if (final.stop_reason === "pause_turn") continue;
|
||||
if (final.stop_reason !== "tool_use" || !toolUses.length) break;
|
||||
}
|
||||
|
||||
registro.chat.push({ role: "assistant", texto: textoDoTurno });
|
||||
salvarSd(registro);
|
||||
send({ t: "uso", uso: registro.uso });
|
||||
send({ t: "fim" });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
send({ t: "erro", msg: String(err?.message || err) });
|
||||
salvarSd(registro);
|
||||
} finally {
|
||||
res.end();
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Autenticação (usuário único via .env) ----------
|
||||
|
||||
const sessoes = new Set(); // tokens ativos (memória — reiniciar o servidor exige novo login)
|
||||
const authAtivo = () => Boolean(config.usuario && config.senha);
|
||||
const tokenDe = (req) => /(?:^|;\s*)sd_token=([^;]+)/.exec(req.headers.cookie || "")?.[1] || null;
|
||||
const logado = (req) => !authAtivo() || sessoes.has(tokenDe(req));
|
||||
|
||||
app.get("/api/sessao", (req, res) => {
|
||||
res.json({ precisa_login: authAtivo(), logado: logado(req), configurado: configOk() });
|
||||
});
|
||||
|
||||
app.post("/api/login", (req, res) => {
|
||||
if (!authAtivo()) return res.json({ ok: true });
|
||||
const { usuario, senha } = req.body || {};
|
||||
const okU = typeof usuario === "string" &&
|
||||
usuario.length === config.usuario.length &&
|
||||
crypto.timingSafeEqual(Buffer.from(usuario), Buffer.from(config.usuario));
|
||||
const okS = typeof senha === "string" &&
|
||||
senha.length === config.senha.length &&
|
||||
crypto.timingSafeEqual(Buffer.from(senha), Buffer.from(config.senha));
|
||||
if (okU && okS) {
|
||||
const t = crypto.randomUUID();
|
||||
sessoes.add(t);
|
||||
res.setHeader("Set-Cookie", `sd_token=${t}; HttpOnly; SameSite=Lax; Path=/; Max-Age=2592000`);
|
||||
return res.json({ ok: true });
|
||||
}
|
||||
setTimeout(() => res.status(401).json({ erro: "Usuário ou senha inválidos." }), 700);
|
||||
});
|
||||
|
||||
app.post("/api/logout", (req, res) => {
|
||||
sessoes.delete(tokenDe(req));
|
||||
res.setHeader("Set-Cookie", "sd_token=; Path=/; Max-Age=0");
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
// Tudo abaixo desta guarda exige sessão (quando o login estiver configurado).
|
||||
app.use("/api", (req, res, next) => {
|
||||
if (logado(req)) return next();
|
||||
res.status(401).json({ erro: "nao_autenticado" });
|
||||
});
|
||||
|
||||
// ---------- Rotas ----------
|
||||
|
||||
app.get("/api/status", (_req, res) => {
|
||||
const base = lerBase();
|
||||
res.json({
|
||||
configurado: configOk(),
|
||||
provider: config.provider,
|
||||
model: config.model,
|
||||
modelos: config.modelos,
|
||||
proximo_numero: proximoNumero(base, numerosEmUso()),
|
||||
saldos: saldos(base),
|
||||
checklist: CHECKLIST,
|
||||
login_ativo: authAtivo(),
|
||||
regras: {
|
||||
artefatos_minimos: REGRAS.artefatos_minimos,
|
||||
itens: Object.fromEntries(
|
||||
Object.entries(REGRAS.itens).map(([k, v]) => [
|
||||
k,
|
||||
{ numero: v.item_tr_numero, catmas: v.codigo_catmas, titulo_literal: v.titulo_literal },
|
||||
])
|
||||
),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
// Validação de uma SD externa (JSON colado — não nasceu de uma entrevista do app).
|
||||
app.post("/api/validar", (req, res) => {
|
||||
const sd = req.body?.sd;
|
||||
if (!sd || typeof sd !== "object" || !sd.cabecalho || !Array.isArray(sd.entregaveis))
|
||||
return res.status(400).json({
|
||||
erro: "O JSON não parece uma SD: faltam os campos obrigatórios 'cabecalho' e 'entregaveis' (schema-sd.json).",
|
||||
});
|
||||
const exportado = construirExport(sd);
|
||||
const validacao = validar(exportado);
|
||||
res.json({ exportado, validacao, bloqueios: bloqueiosDeExportacao(validacao) });
|
||||
});
|
||||
|
||||
// ---------- Alimentar a base de conhecimento com uma SD real ----------
|
||||
|
||||
const EXT_ACEITAS = new Set(["pdf", "md", "txt", "markdown"]);
|
||||
|
||||
// Extrai o registro estruturado de um documento de SD (uma chamada de LLM, sem streaming).
|
||||
app.post("/api/base/extrair", async (req, res) => {
|
||||
try {
|
||||
const { nome, base64 } = req.body || {};
|
||||
if (!nome || !base64) return res.status(400).json({ erro: "Envie o arquivo (nome + conteúdo)." });
|
||||
const ext = String(nome).toLowerCase().match(/\.([a-z0-9]+)$/)?.[1] || "";
|
||||
if (!EXT_ACEITAS.has(ext))
|
||||
return res.status(400).json({
|
||||
erro: `Formato .${ext || "?"} não suportado. Envie .pdf, .md ou .txt (para .docx, exporte como PDF).`,
|
||||
});
|
||||
const prov = getProvider();
|
||||
const out = await prov.executarExtracao({
|
||||
system: montarSystemExtracao(),
|
||||
messages: [{ role: "user", content: montarConteudoDocumento({ nome, base64 }) }],
|
||||
tools: [TOOL_EXTRACAO],
|
||||
toolName: TOOL_EXTRACAO.name,
|
||||
model: modeloValido(req.body?.modelo) || undefined,
|
||||
});
|
||||
const { sd, capacidades = [], observacoes = [] } = out.input || {};
|
||||
if (sd && !sd.fonte) sd.fonte = nome;
|
||||
res.json({ sd, capacidades, observacoes, conferencia: conferirExtracao(sd), uso: out.usage });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.status(500).json({ erro: String(err?.message || err) });
|
||||
}
|
||||
});
|
||||
|
||||
// Reconfere um registro editado na tela de revisão (só código, sem LLM).
|
||||
app.post("/api/base/conferir", (req, res) => {
|
||||
res.json({ conferencia: conferirExtracao(req.body?.sd) });
|
||||
});
|
||||
|
||||
// Grava o registro revisado. Erros de conferência bloqueiam; alertas passam (o usuário revisou).
|
||||
app.post("/api/base/gravar", (req, res) => {
|
||||
const { sd, capacidades } = req.body || {};
|
||||
const conferencia = conferirExtracao(sd);
|
||||
if (conferencia.some((c) => c.nivel === "erro"))
|
||||
return res.status(409).json({ erro: "Há erros de conferência — corrija o registro antes de gravar.", conferencia });
|
||||
const r = gravarSdReal(sd, Array.isArray(capacidades) ? capacidades : []);
|
||||
res.json({ ok: true, ...r, saldos: saldos(lerBase()) });
|
||||
});
|
||||
|
||||
app.get("/api/sds", (_req, res) => res.json(listarSds()));
|
||||
|
||||
app.get("/api/sds/:id", (req, res) => {
|
||||
const registro = obterSd(req.params.id);
|
||||
if (!registro) return res.status(404).json({ erro: "SD não encontrada" });
|
||||
const validacao = registro.rascunho ? validar(registro.rascunho) : null;
|
||||
res.json({
|
||||
id: registro.id,
|
||||
numero: registro.numero,
|
||||
modelo: registro.modelo || "",
|
||||
status: registro.status,
|
||||
criadaEm: registro.criadaEm,
|
||||
demanda: registro.demanda,
|
||||
chat: registro.chat,
|
||||
rascunho: registro.rascunho,
|
||||
uso: registro.uso,
|
||||
validacao,
|
||||
bloqueios: validacao ? bloqueiosDeExportacao(validacao) : null,
|
||||
});
|
||||
});
|
||||
|
||||
// Modelo vindo da interface: só aceita os da lista configurada (LLM_MODEL + LLM_MODELOS).
|
||||
function modeloValido(m) {
|
||||
return typeof m === "string" && config.modelos.includes(m) ? m : "";
|
||||
}
|
||||
|
||||
// Exclui um rascunho da lista. Uma SD "enviada" pode ser excluída da lista também —
|
||||
// o registro dela na base de conhecimento NÃO é afetado (a base é a memória oficial).
|
||||
app.delete("/api/sds/:id", (req, res) => {
|
||||
if (!excluirSd(req.params.id)) return res.status(404).json({ erro: "SD não encontrada" });
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
// Nova SD: cria o registro e roda o primeiro turno (streaming).
|
||||
app.post("/api/sds", async (req, res) => {
|
||||
const demanda = String(req.body?.demanda || "").trim();
|
||||
if (!demanda) return res.status(400).json({ erro: "Informe a demanda bruta." });
|
||||
const numero = proximoNumero(lerBase(), numerosEmUso());
|
||||
const registro = criarSd(demanda, numero, modeloValido(req.body?.modelo));
|
||||
registro.chat = [{ role: "user", texto: demanda }];
|
||||
registro.mensagens.push({
|
||||
role: "user",
|
||||
content: `<contexto-do-app>\n${contextoParaConversa(numero)}\n</contexto-do-app>\n\nDemanda bruta:\n${demanda}`,
|
||||
});
|
||||
res.setHeader("X-Sd-Id", registro.id);
|
||||
await rodarTurno(registro, res);
|
||||
});
|
||||
|
||||
// Turno seguinte da entrevista (streaming).
|
||||
app.post("/api/sds/:id/mensagem", async (req, res) => {
|
||||
const registro = obterSd(req.params.id);
|
||||
if (!registro) return res.status(404).json({ erro: "SD não encontrada" });
|
||||
if (registro.status === "enviada") return res.status(409).json({ erro: "SD já enviada — somente leitura." });
|
||||
const texto = String(req.body?.texto || "").trim();
|
||||
if (!texto) return res.status(400).json({ erro: "Mensagem vazia." });
|
||||
registro.chat.push({ role: "user", texto });
|
||||
registro.mensagens.push({ role: "user", content: texto });
|
||||
await rodarTurno(registro, res);
|
||||
});
|
||||
|
||||
// Trava de integridade: confirmação/data de artefato pelo usuário (fora do chat).
|
||||
app.post("/api/sds/:id/artefato", (req, res) => {
|
||||
const registro = obterSd(req.params.id);
|
||||
if (!registro?.rascunho) return res.status(404).json({ erro: "SD sem rascunho" });
|
||||
const { e, a, confirmado, data, nome } = req.body || {};
|
||||
const art = registro.rascunho.entregaveis?.[e]?.artefatos?.[a];
|
||||
if (!art) return res.status(400).json({ erro: "Artefato não encontrado" });
|
||||
if (typeof confirmado === "boolean") art.confirmado_pelo_usuario = confirmado;
|
||||
if (data !== undefined) {
|
||||
if (data) art.data = data;
|
||||
else delete art.data;
|
||||
}
|
||||
if (typeof nome === "string" && nome.trim()) art.nome = nome.trim();
|
||||
salvarSd(registro);
|
||||
const validacao = validar(registro.rascunho);
|
||||
res.json({ sd: registro.rascunho, validacao, bloqueios: bloqueiosDeExportacao(validacao) });
|
||||
});
|
||||
|
||||
// Exportação do JSON final (bloqueada enquanto houver pendência bloqueante).
|
||||
app.get("/api/sds/:id/export", (req, res) => {
|
||||
const registro = obterSd(req.params.id);
|
||||
if (!registro?.rascunho) return res.status(404).json({ erro: "SD sem rascunho" });
|
||||
const exportado = construirExport(registro.rascunho);
|
||||
const v = validar(exportado);
|
||||
const bloqueios = bloqueiosDeExportacao(v);
|
||||
if (bloqueios.length && req.query.forcar !== "1")
|
||||
return res.status(409).json({ erro: "Exportação bloqueada", bloqueios });
|
||||
const nome = (exportado.cabecalho?.numero_sd || "sd").toLowerCase().replace(/[^a-z0-9-]+/g, "-");
|
||||
res.setHeader("Content-Disposition", `attachment; filename="${nome}.json"`);
|
||||
res.json(exportado);
|
||||
});
|
||||
|
||||
// Marca como enviada: número definitivo + registro na base de conhecimento.
|
||||
app.post("/api/sds/:id/enviar", (req, res) => {
|
||||
const registro = obterSd(req.params.id);
|
||||
if (!registro?.rascunho) return res.status(404).json({ erro: "SD sem rascunho" });
|
||||
if (registro.status === "enviada") return res.status(409).json({ erro: "SD já enviada." });
|
||||
const exportado = construirExport(registro.rascunho);
|
||||
const v = validar(exportado);
|
||||
const bloqueios = bloqueiosDeExportacao(v);
|
||||
if (bloqueios.length) return res.status(409).json({ erro: "Envio bloqueado", bloqueios });
|
||||
exportado.cabecalho.numero_sd = `SD-${registro.numero}`;
|
||||
registro.rascunho.cabecalho.numero_sd = `SD-${registro.numero}`;
|
||||
const reg = registrarEnvio(exportado);
|
||||
registro.status = "enviada";
|
||||
salvarSd(registro);
|
||||
res.json({ ok: true, registro_na_base: reg });
|
||||
});
|
||||
|
||||
app.listen(config.port, () => {
|
||||
console.log(`\nRedator de SD rodando em http://localhost:${config.port}`);
|
||||
if (!configOk()) {
|
||||
console.log("⚠ ANTHROPIC_API_KEY não configurada — copie .env.example para .env e preencha a chave.");
|
||||
} else {
|
||||
console.log(`Provedor: ${config.provider} · Modelo: ${config.model}`);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
// Persistência simples em arquivo (data/sds.json). SQLite fica para uma fase futura.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import crypto from "node:crypto";
|
||||
import { DATA_DIR } from "./config.js";
|
||||
|
||||
const FILE = path.join(DATA_DIR, "sds.json");
|
||||
|
||||
function lerTudo() {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(FILE, "utf8"));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function gravarTudo(lista) {
|
||||
fs.mkdirSync(DATA_DIR, { recursive: true });
|
||||
const tmp = FILE + ".tmp";
|
||||
fs.writeFileSync(tmp, JSON.stringify(lista, null, 2), "utf8");
|
||||
fs.renameSync(tmp, FILE);
|
||||
}
|
||||
|
||||
export function listarSds() {
|
||||
return lerTudo().map((s) => ({
|
||||
id: s.id,
|
||||
numero: s.numero,
|
||||
titulo: s.rascunho?.cabecalho?.titulo || s.demanda.slice(0, 80),
|
||||
status: s.status,
|
||||
criadaEm: s.criadaEm,
|
||||
turnos: (s.mensagens || []).filter((m) => m.role === "user").length,
|
||||
}));
|
||||
}
|
||||
|
||||
export function obterSd(id) {
|
||||
return lerTudo().find((s) => s.id === id) || null;
|
||||
}
|
||||
|
||||
export function criarSd(demanda, numero, modelo = "") {
|
||||
const registro = {
|
||||
id: crypto.randomUUID(),
|
||||
numero,
|
||||
modelo, // modelo de LLM fixado na criação ("" = padrão do .env)
|
||||
status: "rascunho", // rascunho -> enviada
|
||||
criadaEm: new Date().toISOString(),
|
||||
demanda,
|
||||
chat: [], // histórico legível para a interface [{role, texto}]
|
||||
mensagens: [], // histórico no formato da API (role/content)
|
||||
rascunho: null, // último estado da SD vindo da tool atualizar_rascunho
|
||||
uso: { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0, turnos: 0 },
|
||||
};
|
||||
const lista = lerTudo();
|
||||
lista.push(registro);
|
||||
gravarTudo(lista);
|
||||
return registro;
|
||||
}
|
||||
|
||||
export function salvarSd(registro) {
|
||||
const lista = lerTudo();
|
||||
const i = lista.findIndex((s) => s.id === registro.id);
|
||||
if (i === -1) lista.push(registro);
|
||||
else lista[i] = registro;
|
||||
gravarTudo(lista);
|
||||
return registro;
|
||||
}
|
||||
|
||||
export function excluirSd(id) {
|
||||
const lista = lerTudo();
|
||||
const i = lista.findIndex((s) => s.id === id);
|
||||
if (i === -1) return false;
|
||||
lista.splice(i, 1);
|
||||
gravarTudo(lista);
|
||||
return true;
|
||||
}
|
||||
|
||||
export function numerosEmUso() {
|
||||
return lerTudo()
|
||||
.map((s) => Number(s.numero))
|
||||
.filter((n) => !isNaN(n));
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
// Validador determinístico da SD — mesma lógica do painel (artefato) publicado.
|
||||
// Fonte das regras: regras-sd.json na raiz do projeto.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { PROJETO_DIR } from "./config.js";
|
||||
|
||||
export const REGRAS = JSON.parse(
|
||||
fs.readFileSync(path.join(PROJETO_DIR, "regras-sd.json"), "utf8")
|
||||
);
|
||||
|
||||
const TIPO_KEY = {
|
||||
Descoberta: "descoberta",
|
||||
Design: "design",
|
||||
Arquitetura: "arquitetura",
|
||||
"Construção": "construcao",
|
||||
};
|
||||
|
||||
export const CHECKLIST = REGRAS.checklist;
|
||||
|
||||
const dayNum = (iso) => {
|
||||
const m = String(iso || "").match(/^(\d{4})-(\d{2})-(\d{2})/);
|
||||
return m ? Date.UTC(+m[1], +m[2] - 1, +m[3]) / 86400000 : NaN;
|
||||
};
|
||||
const fmtD = (iso) => {
|
||||
const m = String(iso || "").match(/^(\d{4})-(\d{2})-(\d{2})/);
|
||||
return m ? `${m[3]}/${m[2]}/${m[1]}` : String(iso || "—");
|
||||
};
|
||||
const weeksCal = (i, f) => {
|
||||
const a = dayNum(i), b = dayNum(f);
|
||||
return isNaN(a) || isNaN(b) ? NaN : Math.ceil((b - a + 1) / 7);
|
||||
};
|
||||
|
||||
export function timeboxDe(e) {
|
||||
const it = REGRAS.itens[e.item_tr];
|
||||
const k = TIPO_KEY[e.tipo];
|
||||
return it && k ? it.timebox_h[k] : NaN;
|
||||
}
|
||||
export function ustDe(e) {
|
||||
const t = timeboxDe(e);
|
||||
return isNaN(t) ? NaN : t * (e.semanas || 0);
|
||||
}
|
||||
export function minArtefatos(ust) {
|
||||
const faixa = REGRAS.artefatos_minimos.find(
|
||||
(b) => b.ust_max === null || ust <= b.ust_max
|
||||
);
|
||||
return faixa ? faixa.artefatos : 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Roda os itens `codigo` e `usuario` do checklist sobre a SD.
|
||||
* Itens `julgamento` são herdados do array validacao produzido pelo redator.
|
||||
* Retorna { resultados: {id: {status, obs}}, totais: {ok, alerta, falha, pendente} }
|
||||
*/
|
||||
export function validar(sd) {
|
||||
const E = sd.entregaveis || [];
|
||||
const cab = sd.cabecalho || {};
|
||||
const byN = {};
|
||||
E.forEach((e) => (byN[e.n] = e));
|
||||
const R = {};
|
||||
const set = (id, status, obs) => (R[id] = { status, obs });
|
||||
|
||||
const semItem = E.filter((e) => !REGRAS.itens[e.item_tr]);
|
||||
set(
|
||||
"ENQ-01",
|
||||
semItem.length ? "falha" : "ok",
|
||||
semItem.length
|
||||
? "Sem item válido: linhas " + semItem.map((e) => e.n).join(", ")
|
||||
: `${E.length} entregáveis, todos com item válido.`
|
||||
);
|
||||
|
||||
set(
|
||||
"ENQ-06",
|
||||
semItem.length ? "alerta" : "ok",
|
||||
"Cada linha do quadro tem um único item_tr (garantido pela estrutura)."
|
||||
);
|
||||
|
||||
const somaPorItem = {};
|
||||
E.forEach((e) => {
|
||||
somaPorItem[e.item_tr] = (somaPorItem[e.item_tr] || 0) + (ustDe(e) || 0);
|
||||
});
|
||||
const itensUsados = Object.keys(somaPorItem);
|
||||
|
||||
if (itensUsados.length <= 1) {
|
||||
set("ENQ-07", "ok", "SD de item único — subtotal dispensado.");
|
||||
} else {
|
||||
const st = sd.subtotais_por_item || [];
|
||||
const faltam = itensUsados.filter((i) => !st.some((s) => s.item_tr === i));
|
||||
const errados = st.filter(
|
||||
(s) => somaPorItem[s.item_tr] !== undefined && s.ust !== somaPorItem[s.item_tr]
|
||||
);
|
||||
if (faltam.length)
|
||||
set("ENQ-07", "falha", "Sem subtotal declarado para: " + faltam.join(", "));
|
||||
else if (errados.length)
|
||||
set(
|
||||
"ENQ-07",
|
||||
"falha",
|
||||
"Subtotal divergente do recálculo em: " + errados.map((s) => s.item_tr).join(", ")
|
||||
);
|
||||
else
|
||||
set(
|
||||
"ENQ-07",
|
||||
"ok",
|
||||
itensUsados.map((i) => `${i}: ${somaPorItem[i]} UST`).join(" · ")
|
||||
);
|
||||
}
|
||||
|
||||
const lim = REGRAS.limites;
|
||||
const foraSem = E.filter(
|
||||
(e) => !(e.semanas >= lim.semanas_min && e.semanas <= lim.semanas_max)
|
||||
);
|
||||
set(
|
||||
"CAL-01",
|
||||
foraSem.length ? "falha" : "ok",
|
||||
foraSem.length
|
||||
? "Fora de 2–4 semanas: linhas " + foraSem.map((e) => `${e.n} (${e.semanas})`).join(", ")
|
||||
: "Semanas: " + E.map((e) => e.semanas).join(", ") + " — todas entre 2 e 4."
|
||||
);
|
||||
|
||||
const contas = [], erros02 = [];
|
||||
E.forEach((e) => {
|
||||
const exp = ustDe(e);
|
||||
contas.push(`${timeboxDe(e)}×${e.semanas}=${exp}`);
|
||||
if (e.ust !== exp) erros02.push(`linha ${e.n}: declarado ${e.ust}, correto ${exp}`);
|
||||
});
|
||||
set(
|
||||
"CAL-02",
|
||||
erros02.length ? "falha" : "ok",
|
||||
erros02.length ? erros02.join("; ") : "Conta refeita: " + contas.join("; ")
|
||||
);
|
||||
|
||||
const err03 = E.filter((e) => e.tipo === "Construção" && e.timebox_h !== timeboxDe(e));
|
||||
set(
|
||||
"CAL-03",
|
||||
err03.length ? "falha" : "ok",
|
||||
err03.length
|
||||
? "Timebox de Construção errado: linhas " +
|
||||
err03.map((e) => `${e.n} (${e.timebox_h}h, correto ${timeboxDe(e)}h)`).join(", ")
|
||||
: "Construção com timebox correto por item."
|
||||
);
|
||||
|
||||
const soma = E.reduce((a, e) => a + (ustDe(e) || 0), 0);
|
||||
set(
|
||||
"CAL-04",
|
||||
cab.total_ust === soma ? "ok" : "falha",
|
||||
`Σ linhas (recalculado) = ${soma} UST; cabeçalho declara ${cab.total_ust ?? "—"}.`
|
||||
);
|
||||
|
||||
const overl = [];
|
||||
E.forEach((e) =>
|
||||
(e.depende_de || []).forEach((dn) => {
|
||||
const d = byN[dn];
|
||||
if (d && e.periodo && d.periodo && !(dayNum(e.periodo.inicio) > dayNum(d.periodo.fim)))
|
||||
overl.push(`linha ${e.n} sobrepõe a linha ${dn}`);
|
||||
})
|
||||
);
|
||||
set(
|
||||
"CAL-05",
|
||||
overl.length ? "falha" : "ok",
|
||||
overl.length ? overl.join("; ") : "Nenhuma sobreposição entre encadeados (depende_de)."
|
||||
);
|
||||
|
||||
const semNota = E.filter(
|
||||
(e) => (e.paralelo_com || []).length && !(e.nota_paralelismo || "").trim()
|
||||
);
|
||||
const temPar = E.some((e) => (e.paralelo_com || []).length);
|
||||
set(
|
||||
"CAL-06",
|
||||
semNota.length ? "falha" : "ok",
|
||||
semNota.length
|
||||
? "Paralelo sem nota: linhas " + semNota.map((e) => e.n).join(", ")
|
||||
: temPar
|
||||
? "Paralelismo declarado em nota."
|
||||
: "Não há paralelismo na SD."
|
||||
);
|
||||
|
||||
const inicios = E.map((e) => e.periodo?.inicio).filter(Boolean).sort();
|
||||
const fins = E.map((e) => e.periodo?.fim).filter(Boolean).sort();
|
||||
const pi = cab.periodo_execucao?.inicio, pf = cab.periodo_execucao?.fim;
|
||||
const wCal = weeksCal(pi, pf);
|
||||
const probs07 = [];
|
||||
if (inicios.length && pi !== inicios[0])
|
||||
probs07.push(`início do cabeçalho (${fmtD(pi)}) ≠ 1º entregável (${fmtD(inicios[0])})`);
|
||||
if (fins.length && pf !== fins[fins.length - 1])
|
||||
probs07.push(`fim do cabeçalho (${fmtD(pf)}) ≠ último entregável (${fmtD(fins[fins.length - 1])})`);
|
||||
if (!isNaN(wCal) && cab.prazo_execucao_semanas !== wCal)
|
||||
probs07.push(`calendário = ${wCal} semanas; cabeçalho declara ${cab.prazo_execucao_semanas}`);
|
||||
set(
|
||||
"CAL-07",
|
||||
probs07.length ? "falha" : "ok",
|
||||
probs07.length
|
||||
? probs07.join("; ")
|
||||
: `${fmtD(pi)} a ${fmtD(pf)} = ${wCal} semanas de calendário — confere.`
|
||||
);
|
||||
|
||||
const declarados = cab.itens_tr || [];
|
||||
const probs02d = [];
|
||||
itensUsados.forEach((i) => {
|
||||
if (!declarados.includes(i)) probs02d.push(`${i} usado no quadro mas ausente do cabeçalho`);
|
||||
});
|
||||
declarados.forEach((i) => {
|
||||
if (!itensUsados.includes(i)) probs02d.push(`${i} declarado no cabeçalho sem entregável`);
|
||||
});
|
||||
(sd.enquadramento_tr || []).forEach((q) => {
|
||||
if (!itensUsados.includes(q.item_tr))
|
||||
probs02d.push(`Seção 5 traz ${q.item_tr} sem entregável correspondente`);
|
||||
});
|
||||
set(
|
||||
"DOC-02",
|
||||
probs02d.length ? "falha" : "ok",
|
||||
probs02d.length ? probs02d.join("; ") : "Itens do cabeçalho, quadro e Seção 5 correspondem."
|
||||
);
|
||||
|
||||
const err03t = (sd.enquadramento_tr || []).filter(
|
||||
(q) => REGRAS.itens[q.item_tr] && q.titulo_literal !== REGRAS.itens[q.item_tr].titulo_literal
|
||||
);
|
||||
set(
|
||||
"DOC-03",
|
||||
err03t.length ? "falha" : "ok",
|
||||
err03t.length
|
||||
? "Título divergente do TR em: " + err03t.map((q) => q.item_tr).join(", ")
|
||||
: "Títulos literais conferem com regras-sd.json."
|
||||
);
|
||||
|
||||
const err07 = E.filter((e) => (e.artefatos || []).length < minArtefatos(ustDe(e) || 0));
|
||||
set(
|
||||
"DOC-07",
|
||||
err07.length ? "falha" : "ok",
|
||||
err07.length
|
||||
? "Abaixo do mínimo: linhas " +
|
||||
err07.map((e) => `${e.n} (${(e.artefatos || []).length}/${minArtefatos(ustDe(e) || 0)})`).join(", ")
|
||||
: E.map((e) => `E${e.n}: ${(e.artefatos || []).length}/${minArtefatos(ustDe(e) || 0)}`).join(" · ")
|
||||
);
|
||||
|
||||
const todos = E.flatMap((e) => e.artefatos || []);
|
||||
const naoConf = todos.filter((a) => !a.confirmado_pelo_usuario).length;
|
||||
set(
|
||||
"DOC-08",
|
||||
naoConf ? "pendente" : todos.length ? "ok" : "pendente",
|
||||
naoConf
|
||||
? `${naoConf} de ${todos.length} artefatos ainda não confirmados — bloqueante para exportação.`
|
||||
: todos.length
|
||||
? `Todos os ${todos.length} artefatos confirmados pelo usuário.`
|
||||
: "SD ainda sem artefatos."
|
||||
);
|
||||
|
||||
const errData = [], semData = [];
|
||||
E.forEach((e) =>
|
||||
(e.artefatos || []).forEach((a) => {
|
||||
if (a.data) {
|
||||
if (e.periodo?.fim && dayNum(a.data) > dayNum(e.periodo.fim))
|
||||
errData.push(`E${e.n}: "${a.nome}" datado ${fmtD(a.data)} > fim ${fmtD(e.periodo.fim)}`);
|
||||
} else if (a.confirmado_pelo_usuario) {
|
||||
semData.push(`E${e.n}: "${a.nome}" confirmado sem data`);
|
||||
}
|
||||
})
|
||||
);
|
||||
if (errData.length) set("DOC-09", "falha", errData.join("; "));
|
||||
else if (semData.length) set("DOC-09", "alerta", semData.join("; "));
|
||||
else if (todos.some((a) => a.data))
|
||||
set("DOC-09", "ok", "Datas informadas são ≤ ao fim do respectivo entregável.");
|
||||
else set("DOC-09", "alerta", "Nenhum artefato tem data informada ainda.");
|
||||
|
||||
// Itens de julgamento: herdados do parecer do redator (array validacao da SD)
|
||||
const orig = {};
|
||||
(sd.validacao || []).forEach((v) => (orig[v.id] = v));
|
||||
CHECKLIST.filter((c) => c.verificador === "julgamento").forEach((c) => {
|
||||
const o = orig[c.id];
|
||||
set(
|
||||
c.id,
|
||||
o?.status || "pendente",
|
||||
o?.observacao || (o ? "Revisão do redator: sem ressalvas." : "Sem parecer do redator ainda.")
|
||||
);
|
||||
});
|
||||
|
||||
const totais = { ok: 0, alerta: 0, falha: 0, pendente: 0 };
|
||||
Object.values(R).forEach((r) => (totais[r.status] = (totais[r.status] || 0) + 1));
|
||||
return { resultados: R, totais, soma_ust: soma, soma_por_item: somaPorItem };
|
||||
}
|
||||
|
||||
/** Resumo compacto (só o que não está ok) para realimentar o redator via tool_result. */
|
||||
export function resumoParaRedator(validacao) {
|
||||
const pend = Object.entries(validacao.resultados)
|
||||
.filter(([, r]) => r.status !== "ok")
|
||||
.map(([id, r]) => `${id} [${r.status}]: ${r.obs}`);
|
||||
return {
|
||||
validador_do_app: {
|
||||
total_ust_recalculado: validacao.soma_ust,
|
||||
subtotais: validacao.soma_por_item,
|
||||
itens_nao_ok: pend.length ? pend : "todos os checks de código passaram",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Reconstrói a SD com valores recalculados pelo app + array validacao completo (para exportação). */
|
||||
export function construirExport(sd) {
|
||||
const copy = JSON.parse(JSON.stringify(sd));
|
||||
const E = copy.entregaveis || [];
|
||||
E.forEach((e) => {
|
||||
e.timebox_h = timeboxDe(e);
|
||||
e.ust = ustDe(e);
|
||||
});
|
||||
const soma = E.reduce((a, e) => a + (e.ust || 0), 0);
|
||||
copy.cabecalho = copy.cabecalho || {};
|
||||
copy.cabecalho.total_ust = soma;
|
||||
const porItem = {};
|
||||
E.forEach((e) => (porItem[e.item_tr] = (porItem[e.item_tr] || 0) + (e.ust || 0)));
|
||||
if (Object.keys(porItem).length > 1)
|
||||
copy.subtotais_por_item = Object.keys(porItem)
|
||||
.sort()
|
||||
.map((i) => ({ item_tr: i, ust: porItem[i] }));
|
||||
const v = validar(copy);
|
||||
copy.validacao = CHECKLIST.map((c) => {
|
||||
const r = v.resultados[c.id];
|
||||
const o = { id: c.id, status: r?.status || "pendente" };
|
||||
if (r?.obs && o.status !== "ok") o.observacao = r.obs;
|
||||
return o;
|
||||
});
|
||||
return copy;
|
||||
}
|
||||
|
||||
/** Exportação é bloqueada enquanto houver artefato não confirmado ou falha de código. */
|
||||
export function bloqueiosDeExportacao(validacao) {
|
||||
const razoes = [];
|
||||
if (validacao.resultados["DOC-08"]?.status !== "ok")
|
||||
razoes.push("artefatos não confirmados (DOC-08)");
|
||||
const falhas = Object.entries(validacao.resultados)
|
||||
.filter(([, r]) => r.status === "falha")
|
||||
.map(([id]) => id);
|
||||
if (falhas.length) razoes.push("falhas no checklist: " + falhas.join(", "));
|
||||
return razoes;
|
||||
}
|
||||
Reference in New Issue
Block a user