Skip to content

feat(languages): canonical pt-br translation applied on every migration - #31

Open
lbrunofidelis wants to merge 9 commits into
devfrom
feat/#29-improve-pt-br-translations
Open

lbrunofidelis wants to merge 9 commits into
devfrom
feat/#29-improve-pt-br-translations

Conversation

@lbrunofidelis

@lbrunofidelis lbrunofidelis commented Oct 9, 2026 •

Copy link
Copy Markdown
Collaborator

PR atrelado

  • Frontend #32: troca os textos que estavam fixos no código (diálogo "Consulta via API" da lista de contatos e o aviso de erro na criação de relacionamento) por tokens de idioma, e corrige o arquivo local de português para PT-BR. Os tokens novos que ele usa são criados por este PR (migração 2.58.3), então um não funciona sem o outro.

Por que

O idioma Português do Go.Data estava incompleto e misturado. Numa cópia do banco real, 6.020 tokens portuguese_pt ainda mostravam o texto em inglês e 113 tinham sobras em espanhol (por exemplo "Tablero principal" no menu e "Copia de seguridade" em Backups), além de textos em português de Portugal ("utilizador", "equipa", "Tem a certeza"). Os questionários dos modelos padrão de surto estavam quase todos em inglês. Cada versão trazia uma migração portuguese.json própria, aplicada uma única vez, e qualquer correção feita direto no banco se perdia ou divergia entre instâncias.

Causa

O português não tinha fonte única. Os textos vinham das migrações versionadas (migrations/<versão>/data/portuguese/), executadas uma vez cada, e do que cada instância editou no banco. Nada garantia cobertura dos tokens novos nem corrigia textos antigos. Além disso, as ações da 2.51.0 estão registradas mais de uma vez no migrateModelData.js (buildNo 2, 5, 6 e 7) e rodam de novo a cada migração, regravando 13 tokens com o texto antigo do 2.51.0/data/portuguese/portuguese.json.

O que muda

  1. Arquivo canônico do PT-BR em server/install/scripts/languages/portuguese_pt/: system.json (interface, permissões, erros da API, dados de referência e os 183 itens de ajuda), templates.json (questionários dos 11 modelos padrão) e identical-to-english.json (231 tokens que ficam iguais ao inglês de propósito: siglas, números, nomes de países, Latitude, Status...). São 9.344 tokens, revisados um a um com o glossário validado pela equipe (cluster = grupo, follow-up = acompanhamento, outcome = evolução, deceased = óbito, hospitalization = hospitalização).
  2. applyPortugueseTranslations.js: passo que roda no fim do migrate-database e do init-database (install.js, migrateDatabase.js). Grava o texto canônico só nos tokens portuguese_pt existentes e não excluídos cujo texto difere, com updatedAt/dbUpdatedAt = agora (o frontend busca os tokens alterados depois do LANGUAGE_UPDATE_LAST, então basta recarregar a página). Nunca cria nem restaura tokens. Uma segunda execução não grava nada. Resumo em logs/application.log: Portuguese translations: N checked, N updated, N absent or deleted.
  3. npm run check-pt-translations (server/scripts/checkPortugueseTranslations.js): lê os dados de idioma do repositório, sem banco, e falha quando um token sem PT, com PT vazio, com PT igual ao inglês fora da allowlist, com {{placeholders}} diferentes do inglês ou desconhecido no repositório. Roda no CI depois do Build (.github/workflows/ci.yml).
  4. Migração 2.58.3: tokens em inglês do diálogo "Consulta via API" e do aviso de erro da criação de relacionamento, usados pelo PR do Frontend.
  5. 2.51.0/data/portuguese/portuguese.json: dois textos alinhados ao canônico, para que a reexecução da 2.51.0 não desfaça o PT-BR a cada migração.

Importante para quem opera instâncias: a partir deste PR, o arquivo canônico vence. Textos em português editados direto no banco ou importados por planilha voltam ao canônico no próximo deploy. Toda correção passa a ser feita por PR no canônico.

Como validar

  1. npm run check-pt-translations deve terminar com portuguese_pt check passed: 9344 tokens in scope.
  2. Numa cópia do banco, rode npm run migrate-database e procure a linha Portuguese translations: em logs/application.log.
  3. Rode npm run migrate-database de novo: a linha deve dizer 0 updated.
  4. Com o navegador já aberto em Português antes da migração, recarregue a página depois dela: o menu passa de "Tablero principal" para "Painel de controle" sem limpar o localStorage.
  5. Crie um surto a partir de um modelo padrão (Modelos de surto, Gerar surto) com a interface em Português: o questionário vem em PT-BR.

Validado

  • npm run check-pt-translations: passed, 9.344 tokens no escopo, 0 findings.
  • Cópia do banco real, antes: 6.020 tokens PT iguais ao inglês fora da allowlist, 7.442 diferentes do canônico, 113 sobras em espanhol. migrate-database: 9344 checked, 7442 updated, 64 absent or deleted. Depois: 0, 0 e 0.
  • Segunda e terceira execução: 0 updated. Antes da correção da 2.51.0 eram 2 updated a cada execução.
  • Token voltado para o inglês no Mongo (LNG_LAYOUT_MENU_ITEM_DASHBOARD_LABEL = "Dashboard"): restaurado para "Painel de controle" pelo migrate-database.
  • init-database em banco vazio: 9344 checked, 7473 updated, 0 absent or deleted, e a varredura dá 0 tokens iguais ao inglês ou diferentes do canônico.
  • Navegador com o idioma em cache: "Tablero principal" virou "Painel de controle" depois do reload; o LANGUAGE_UPDATE_LAST avançou sozinho para o horário da migração.
  • Surto criado pela tela a partir do modelo de febre amarela: 111 de 111 textos do questionário iguais ao canônico em PT-BR.
  • Script de prova do passo de aplicação: só o token diferente é atualizado; token igual, excluído e ausente ficam como estão; english_us intacto; segunda execução com zero gravações. Script de prova do check: cada tipo de problema faz o script sair com 1.
  • Todas as tags HTML e entidades dos 183 itens de ajuda são idênticas às do inglês.
  • npm run build ok. eslint nos .js tocados: só os 2 erros de indentação já existentes em migrateModelData.js:482-483, que não são deste PR.

Fora do escopo

  • Idioma padrão: continua english_us.
  • Reexecução da 2.51.0 a cada migração: o defeito no migrateModelData.js continua, e merece card próprio. Aqui só os textos foram alinhados.
  • Tokens ausentes no banco local: 64 tokens do canônico não existem no banco local (60 deles da 2.58.0, das notificações de equipe), porque a migração foi editada depois de executada. Por isso o formulário de surto mostra LNG_PAGE_CREATE_OUTBREAK_LABEL_NOTIFY_TEAM cru. O passo canônico não cria tokens, de propósito. Num init-database limpo os 9.344 existem.
  • Termos de saúde em aberto: "burial" (adotado "sepultamento"), "strain" ("cepa"), "targeted" ("direcionado"), "conjunctival suffusion" e "endemic". Ajustar depois é só uma linha no canônico.

Linked PR

  • Frontend #32: replaces hardcoded texts (the contacts "API query" dialog and the relationship creation error) with language tokens and fixes the local Portuguese file to Brazilian Portuguese. The new tokens it uses are created here (migration 2.58.3), so neither works alone.

Why (English)

The Portuguese language was incomplete and mixed. On a copy of the real database, 6,020 portuguese_pt tokens still showed English, 113 had Spanish leftovers ("Tablero principal" in the menu, "Copia de seguridade" for Backups), and others were European Portuguese ("utilizador", "equipa"). The default outbreak template questionnaires were almost all in English. Each version shipped its own portuguese.json migration, applied once, and fixes made directly in a database were lost or diverged between instances.

Cause

Portuguese had no single source. Texts came from versioned migrations, each run once, and from whatever each instance edited in its database; nothing ensured coverage of new tokens or fixed old ones. Also, the 2.51.0 language actions are registered several times in migrateModelData.js (buildNo 2, 5, 6, 7) and run again on every migration, rewriting 13 tokens with the old text of 2.51.0/data/portuguese/portuguese.json.

What changes

  1. Canonical PT-BR files in server/install/scripts/languages/portuguese_pt/: system.json (UI, permissions, API errors, reference data, 183 help items), templates.json (questionnaires of the 11 default templates) and identical-to-english.json (231 tokens intentionally equal to English). 9,344 tokens, reviewed one by one against the team-validated glossary.
  2. applyPortugueseTranslations.js, run at the end of migrate-database and init-database: writes the canonical text only into existing, non-deleted portuguese_pt tokens whose text differs, setting updatedAt/dbUpdatedAt to now so a page reload is enough. Never creates or restores tokens; a second run writes nothing. Summary line in logs/application.log.
  3. npm run check-pt-translations: reads the repository language data (no database) and fails on missing, empty, equal-to-English-not-allowlisted, placeholder-mismatch or unknown tokens. CI runs it after Build.
  4. Migration 2.58.3: English tokens used by the Frontend PR.
  5. 2.51.0/data/portuguese/portuguese.json: two texts aligned with the canonical file so the 2.51.0 re-execution no longer undoes them.

Operators note: the canonical file wins from now on. Portuguese texts edited in a database or imported from a spreadsheet go back to the canonical text on the next deploy; corrections go through a pull request.

How to validate

  1. npm run check-pt-translations → portuguese_pt check passed: 9344 tokens in scope.
  2. On a database copy, npm run migrate-database, then look for Portuguese translations: in logs/application.log.
  3. Run it again: 0 updated.
  4. With a browser already open in Portuguese before the migration, reload after it: the menu goes from "Tablero principal" to "Painel de controle" without clearing localStorage.
  5. Generate an outbreak from a default template with the UI in Portuguese: the questionnaire is in PT-BR.

Validated

  • Check: passed, 9,344 tokens, 0 findings.
  • Real database copy, before: 6,020 equal to English outside the allowlist, 7,442 different from canonical, 113 Spanish leftovers. Migration: 9344 checked, 7442 updated, 64 absent or deleted. After: 0, 0, 0.
  • Second and third runs: 0 updated (it was 2 updated per run before the 2.51.0 fix).
  • A token set back to English in Mongo is restored by migrate-database.
  • init-database on an empty database: 9344 checked, 7473 updated, 0 absent or deleted; scan 0 equal to English, 0 different from canonical.
  • Cached browser: "Tablero principal" became "Painel de controle" after a reload; LANGUAGE_UPDATE_LAST advanced by itself.
  • Outbreak generated through the UI from the yellow fever template: 111 of 111 questionnaire texts equal to the canonical PT-BR.
  • Apply step proof script and check script self-test: all cases pass. Help items: HTML tags and entities identical to English.
  • npm run build ok; eslint on touched .js files: only the two pre-existing indentation errors at migrateModelData.js:482-483.

Out of scope

  • Default language: stays english_us.
  • 2.51.0 re-execution: the migrateModelData.js defect stays and deserves its own card.
  • Tokens absent from the local database: 64 canonical tokens (60 from 2.58.0, team notifications) were never created because the migration was edited after it ran. The outbreak form therefore shows LNG_PAGE_CREATE_OUTBREAK_LABEL_NOTIFY_TEAM raw. The canonical step does not create tokens by design.
  • Open health terms: "burial", "strain", "targeted", "conjunctival suffusion" and "endemic". Each is a one-line change in the canonical file later.

…ions

Upstream and template migrations write english text into portuguese_pt. The step writes the canonical text over the existing, non-deleted tokens and moves updatedAt forward so cached browsers fetch it.
Builds the tokens in scope from the repository language data only, so it runs without a database. Fails on missing, empty or english text, on placeholders that differ from the english ones and on tokens unknown to the repository.
Also covers the warning of the relationship creation page. The texts were hardcoded in the front end.
…translation

The 2.51.0 language actions run again on every migration, so their older texts were rewritten and corrected back each time.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant