From 6e93d9746ea89b054a9759257f363d7e783250e5 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 17:37:56 +0000 Subject: [PATCH 01/24] docs: RFC for application status model and migration (#108) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GfjfbQseka7Y3pN4sK32Pe --- ...2026-11-30-application-status-model-rfc.md | 335 ++++++++++++++++++ 1 file changed, 335 insertions(+) create mode 100644 docs/superpowers/specs/2026-11-30-application-status-model-rfc.md diff --git a/docs/superpowers/specs/2026-11-30-application-status-model-rfc.md b/docs/superpowers/specs/2026-11-30-application-status-model-rfc.md new file mode 100644 index 00000000..3ba1dda3 --- /dev/null +++ b/docs/superpowers/specs/2026-11-30-application-status-model-rfc.md @@ -0,0 +1,335 @@ +# RFC — Reavaliação dos status e transições do funil de candidaturas + +- **Issue:** hugoalves-dev/SpringBoot-JobApplyTracker#108 +- **Tipo:** análise / RFC. Não autoriza implementação nem migração de dados. +- **Data:** 2026-11-30 +- **Base do inventário:** `main` do backend (último commit 2026-11-23), `main` do frontend React, workflow n8n `Candidaturas enviadas → Applywell` (`V8fLB09X5wjN6ZeY`). + +--- + +## 0. Resumo executivo + +1. **O vocabulário gravável hoje é só o da `V29`** (`application_statuses`, 9 nomes, case-sensitive via `existsByName`). `ApplicationStatus.java` é código morto: não é referenciado em lugar nenhum, mas os rótulos PT-BR dele ainda aparecem no Swagger (`allowableValues` de `ApplicationRequest` e `UpdateStatusRequest`) — que anuncia valores que a API **rejeita** com 400. +2. **Os nomes `ENTREVISTA_MARCADA`, `REJEITADO`, `GHOSTING`, `RH_NEGOCIACAO` etc. (nomes de constante do enum) são tratados como valores legados persistidos** em `InterviewMetricsService`, `GamificationService`, `DashboardService`, `McpAnalyticsTools` e `src/lib/interviews.ts`. Ou seja: há (ou houve) linhas com o *nome da constante* gravado, não o *displayName*. Os rótulos PT-BR (`Entrevista marcada`, `Tarde demais`…) **não são reconhecidos por nenhum consumidor** — se existirem no banco, caem no `familyOf → 'sent'` do frontend e somem das métricas. +3. **O scheduler noturno (`StaleApplicationsScheduler`) já corrompe semântica hoje**, antes de qualquer refatoração: + - Rascunho (`status IS NULL`) sem update há 7 dias → vira **`Rejected`** (sem `previous_status`). Rascunho não enviado vira "rejeição". + - **Qualquer** status ≠ `Ghosting` sem update há 1 mês → vira **`Ghosting`**, inclusive `Rejected`, `Approved` e registros **arquivados**. Uma rejeição de 2 meses atrás hoje é contabilizada como ghosting, e um `Approved` também. + - Não há teste cobrindo o scheduler. +4. **A causa do incidente de 09/11 é estrutural:** o workflow n8n instrui o agente a "use a valid status from its result" de `List-Statuses`. O catálogo não tem semântica nem ordem de entrada; o LLM escolheu `Pending HR Response`. Paralelamente, `McpApplicationCreationRulesResource` diz "omit (null) for a fresh cold outreach. Use `RH` only when already in process" e `McpPromptsConfig` diz "Use status `RH` for a standard LinkedIn/HR cold outreach". **Três fontes, três semânticas diferentes para `RH`.** +5. **"Entrevista" está inflada por status:** entrar em `Pending HR Response`, `Technical Test` etc. grava linha em `interview_events` e dispara XP de "interview progress" e o prompt de confirmação de entrevista no frontend. O `interviewCount` explícito já corrige o número exibido, mas `interview_events` e gamificação continuam contando transição como entrevista. +6. **Recomendação:** antes de qualquer migração de modelo, abrir uma issue de **hotfix do scheduler** (parar de sobrescrever terminais/arquivados e parar de rejeitar rascunhos). Isso estanca a perda de informação que a própria migração depois precisaria desfazer. + +--- + +## 1. Inventário + +### 1.1 Fontes de vocabulário + +| Fonte | Valores | Papel real | +|---|---|---| +| `V29__add_application_status_table.sql` (`application_statuses`) | `RH`, `Pending HR Response`, `Pending Hiring Manager Response`, `Technical Test`, `Pending Technical Test Response`, `Offer Negotiation`, `Ghosting`, `Rejected`, `Approved` | **Autoritativo para escrita** (`ApplicationService.validateStatus`), `List-Statuses`, `GET /applications/statuses`, recurso MCP `Application Statuses` | +| `entity/enums/ApplicationStatus.java` | `RH`, `Entrevista marcada`, `Fiz a RH - Aguardando Atualização`, `Fiz a Hiring Manager - Aguardando Atualização`, `Teste Técnico`, `Fiz teste Técnico - aguardando atualização`, `RH (Negociação)`, `Rejeitado`, `Tarde demais`, `Ghosting` | **Sem uso.** Só sobrevive no Swagger e nas descrições | +| Nomes de constante (`ENTREVISTA_MARCADA`, `REJEITADO`, `GHOSTING`, `RH_NEGOCIACAO`, `FIZ_*`, `TESTE_TECNICO`) | — | Lidos como "legado persistido" por métricas, dashboard, gamificação, MCP analytics, frontend `interviews.ts` | +| `NULL` + `to_send_later=true` | pseudo-status `TO_SEND_LATER` | Rascunho. API aceita `TO_SEND_LATER`/vazio e grava `NULL` | +| `previous_status` | qualquer um dos acima | Só preenchido ao entrar em `Rejected`/`Ghosting`; zerado em qualquer outra transição | +| `interview_events.old_status/new_status` | qualquer um dos acima | Histórico **parcial**: só transições que "entram" num status de entrevista | + +> **Não há tabela de histórico de status completa.** `updated_at` é o único carimbo temporal, e muda em qualquer edição (nota, link, reminder). Isso limita o que a migração pode inferir — ver §5. + +### 1.2 Valores persistidos (pendente — não tenho acesso ao banco de produção) + +Inventário somente leitura a rodar antes de fechar a matriz: + +```sql +-- Distribuição real, incluindo grafias/caixas antigas +SELECT status, to_send_later, archived, COUNT(*) AS n, + COUNT(application_date) AS with_date, + COUNT(previous_status) AS with_prev, + SUM(CASE WHEN interview_scheduled THEN 1 ELSE 0 END) AS sched, + SUM(CASE WHEN interview_count > 0 THEN 1 ELSE 0 END) AS with_interviews, + MIN(updated_at), MAX(updated_at) +FROM job_applications +GROUP BY status, to_send_later, archived +ORDER BY n DESC; + +-- De onde vieram Ghosting/Rejected +SELECT status, previous_status, COUNT(*) +FROM job_applications +WHERE previous_status IS NOT NULL OR status IN ('Ghosting','GHOSTING','Rejected','REJEITADO','Rejeitado') +GROUP BY status, previous_status ORDER BY 3 DESC; + +-- Candidatos a "rejeitado pelo scheduler" (rascunho expirado): Rejected sem previous_status e sem data +SELECT COUNT(*) FROM job_applications +WHERE status = 'Rejected' AND previous_status IS NULL AND application_date IS NULL; + +-- Notas que sugerem cancelamento (caso Vetta) +SELECT id, organization, status, previous_status, note FROM job_applications +WHERE note ~* '(cancel|encerr|congel|suspens|sem vaga|vaga fechada|hiring freeze)'; + +-- Valores fora do catálogo atual +SELECT status, COUNT(*) FROM job_applications +WHERE status IS NOT NULL AND status NOT IN (SELECT name FROM application_statuses) +GROUP BY status; +``` + + +**Hipóteses a confirmar com esse inventário:** + +- H1: existem linhas com nomes de constante (`REJEITADO`, `GHOSTING`…) — os consumidores sugerem que sim. +- H2: existem `Rejected` sem `previous_status` e sem `application_date` gerados pelo scheduler de rascunho. +- H3: existem `Ghosting` com `previous_status IN ('Rejected','Approved')` gerados pelo scheduler mensal. +- H4: existem `Ghosting` com `archived=true`. + +### 1.3 Consumidores e acoplamento + +| Camada | Arquivo | O que faz com status | Impacto da mudança | +|---|---|---|---| +| Escrita | `service/ApplicationService.java` | `validateStatus` contra `application_statuses`; `applyStatusChange` mantém `previous_status` só para Rejected/Ghosting; `NULL` ⇒ rascunho e zera `application_date` | Alto — ponto central de transição | +| Job | `tasks/StaleApplicationsScheduler.java` | Rascunho 7d ⇒ `Rejected`; tudo 30d ⇒ `Ghosting` | **Alto e urgente** (§0.3) | +| Métrica | `service/InterviewMetricsService.java` | Grava `interview_events` ao entrar num conjunto de 11 status | Alto — conceito "entrevista" acoplado a status | +| Gamificação | `service/GamificationService.java` | XP de interview progress por status; `OFFER_WON` por `Offer Negotiation`; conquista `GHOSTBUSTER` por `Ghosting` | Médio | +| Dashboard | `service/DashboardService.java` | `waitingResponses` = 3 status "Pending *"; rejected/ghosting por string | Alto — vira `waitingOn` | +| MCP | `mcp/tools/McpAnalyticsTools.java` | rejection/ghosting rate, `averageDaysToResponse` (usa `updated_at` — mede "última edição", não resposta), breakdown por string bruta | Médio | +| MCP | `McpApplicationTools` (`Update-Application-Status`, `Patch-Application`), `McpApplicationStatusesResource`, `McpApplicationCreationRulesResource`, `McpPromptsConfig` | Contrato "status display name"; regras divergentes para `RH` | Alto — contrato externo (ChatGPT, n8n) | +| Filtro/busca | `repository/ApplicationSpecifications.java`, `AssistantApplicationQueryService` | Igualdade exata + `LIKE` em `status` | Médio | +| Export | `service/export/ExportColumn.java` | Exporta string bruta; `NULL` ⇒ `TO_SEND_LATER` | Baixo — mas é contrato de arquivo | +| Seed | `config/FakeDataSeeder.java` | 9 valores da V29 | Baixo | +| Docs | `ApplicationRequest`, `UpdateStatusRequest` (Swagger) | `allowableValues` errado (enum morto) | Baixo, mas engana integrações hoje | +| Front | `src/types/index.ts` | `APPLICATION_STATUSES` hardcoded (fallback) | Médio | +| Front | `src/lib/statuses.ts` | 6 famílias; `Pending HR Response` ⇒ `replied` rotulado "Post-Interview"; desconhecido ⇒ `sent` silencioso | Alto — funil e board | +| Front | `src/lib/interviews.ts` | Mesmo conjunto de 11 para pedir confirmação de entrevista | Médio | +| Front | `ApplicationForm.tsx` | Default `RH` / primeiro do catálogo | Médio | +| Front | `ApplicationsBoard.tsx`, `Metrics.tsx`, `ApplicationsList.tsx`, `Exports.tsx` | Colunas/funil/filtros por status bruto ou família | Médio | +| Automação | n8n `Candidaturas enviadas → Applywell` | LLM escolhe status livre de `List-Statuses` | **Causa do incidente de 09/11** | +| Testes | 18 arquivos (backend IT/unit, front unit/e2e, `data.sql`, `mockApi.ts`) | Strings hardcoded | Custo de manutenção da migração | + +--- + +## 2. Matriz atual vs. proposta + +Modelo aprovado na issue: **etapa** (`stage`) + **pendência** (`waitingOn`) + **resultado** (`outcome`) + **atividades** + `archived` independente. + +### 2.1 Status da V29 (os nove) + +| Status atual | Semântica *observada no código* | Problema | Proposta | Exemplo / caso-limite | +|---|---|---|---|---| +| `RH` | Três versões: "Initial HR outreach" (enum), "já em processo" (regras MCP), "cold outreach padrão" (prompt MCP). Frontend: família `sent` = "Applied (RH)" | Nome é um ator, não uma etapa. Ambíguo entre "enviei" e "o RH falou comigo" | `stage=APPLIED` | DevScout envia 30 e-mails ⇒ `APPLIED`. DM para recrutador sem candidatura formal ⇒ ainda `APPLIED` (atividade `CONTACT_SENT`), nunca `RECRUITER_SCREEN` | +| `Pending HR Response` | Frontend: `replied`/"Post-RH"; conta como entrevista em métricas e gamificação; conta em `waitingResponses` | Confunde "esperando o RH responder minha candidatura" (= APPLIED + waiting) com "fiz a triagem e espero retorno" (= RECRUITER_SCREEN + waiting) | `APPLIED`+`waitingOn=COMPANY` **ou** `RECRUITER_SCREEN`+`waitingOn=COMPANY`, decidido por evidência | Foi o valor errado do incidente de 09/11 | +| `Pending Hiring Manager Response` | Já falou com HM, aguarda | Mistura etapa e pendência | `HIRING_MANAGER`+`waitingOn=COMPANY` | — | +| `Technical Test` | Teste recebido/em andamento | Não distingue recebido × entregue | `ASSESSMENT` (+ atividade `ASSESSMENT_RECEIVED` quando houver evidência) | — | +| `Pending Technical Test Response` | Teste entregue, aguarda | Etapa+pendência | `ASSESSMENT`+`waitingOn=COMPANY` | Não criar `ASSESSMENT_SUBMITTED` sem data | +| `Offer Negotiation` | Proposta/negociação. `OFFER_WON` na gamificação | Usado como "oferta ganha" | `stage=OFFER` | Aceite ⇒ atividade `OFFER_ACCEPTED`; recusa ⇒ `outcome=WITHDREW` (motivo `OFFER_DECLINED`) | +| `Ghosting` | Setado manualmente **ou** pelo scheduler após 30 dias sem *edição* | Terminal falso; sobrescreve terminais e arquivados; mede edição, não resposta | **Indicador calculado** (`isPossiblyGhosted`), não status nem outcome | Empresa calada 45 dias após teste ⇒ `ASSESSMENT`+`waitingOn=COMPANY`+indicador ligado. Usuário desiste ⇒ `outcome=WITHDREW` (motivo `NO_RESPONSE`) | +| `Rejected` | Rejeição **e** rascunho expirado (scheduler) **e** vaga cancelada (Vetta) | Três significados | `outcome=REJECTED` só para rejeição; cancelamento ⇒ `ROLE_CANCELLED`; rascunho expirado ⇒ volta a `DRAFT` ou `NEEDS_REVIEW` | Incompatibilidade geográfica (caso 09/11) ⇒ `REJECTED` motivo `NOT_ELIGIBLE` | +| `Approved` | Nenhum consumidor além do front (família `offer`) | Indefinido: aprovado em etapa? proposta? contratado? | `outcome=HIRED` só com contratação confirmada; senão `NEEDS_REVIEW` | — | + +### 2.2 Valores legados fora da V29 (enum e nomes de constante) + +| Legado | Proposta | Confiança | +|---|---|---| +| `Entrevista marcada` / `ENTREVISTA_MARCADA` | `INTERVIEW` | Determinístico para etapa; **não** criar `INTERVIEW_SCHEDULED` sem data | +| `Fiz a RH - Aguardando Atualização` / `FIZ_A_RH_…` | `RECRUITER_SCREEN`+`waitingOn=COMPANY` | Determinístico | +| `Fiz a Hiring Manager - …` / `FIZ_A_HIRING_MANAGER_…` | `HIRING_MANAGER`+`waitingOn=COMPANY` | Determinístico | +| `Teste Técnico` / `TESTE_TECNICO` | `ASSESSMENT` | Determinístico | +| `Fiz teste Técnico - …` / `FIZ_TESTE_TECNICO_…` | `ASSESSMENT`+`waitingOn=COMPANY` | Determinístico | +| `RH (Negociação)` / `RH_NEGOCIACAO` | `OFFER` só com evidência; senão `NEEDS_REVIEW` | Ambíguo (descrição: "negotiation **or** offer discussion") | +| `Rejeitado` / `REJEITADO` | `outcome=REJECTED` | Determinístico salvo nota de cancelamento | +| `Tarde demais` | `ROLE_CANCELLED` só com evidência; senão `NEEDS_REVIEW` | Ambíguo ("missed **or** closed too late") | +| `GHOSTING` | igual a `Ghosting` | — | + +### 2.3 Resultado (`outcome`) — catálogo + +| Chave | Rótulo PT-BR | Entra quando | Conta como rejeição pessoal? | +|---|---|---|---| +| `REJECTED` | Rejeitada | Resposta explícita negativa da empresa (inclui "não elegível") | Sim | +| `ROLE_CANCELLED` | Vaga cancelada | Empresa encerrou/congelou a vaga por motivo interno | **Não** | +| `WITHDREW` | Desisti | Candidato encerra (sem retorno, recusou proposta, perdeu interesse) | Não | +| `HIRED` | Contratado | Contratação confirmada (aceite + início/contrato) | Não | + +Motivo opcional (`outcomeReason`, texto livre ou enum curto: `NOT_ELIGIBLE`, `NO_RESPONSE`, `OFFER_DECLINED`, `ROLE_FILLED`…) — fica fora do contrato estável inicialmente para não inflar o catálogo. + +--- + +## 3. Semântica, grupos e critérios de entrada/saída + +| Grupo | Etapa | Entra com evidência | Sai para | +|---|---|---|---| +| Pré-candidatura | `DRAFT` | Registro criado sem envio | `APPLIED` (envio confirmado) ou exclusão | +| Seleção | `APPLIED` | E-mail/formulário enviado, confirmação de plataforma, envio automático (DevScout). **Auto-reply "recebemos sua candidatura" não muda etapa** | `RECRUITER_SCREEN`, `HIRING_MANAGER`, `ASSESSMENT`, `INTERVIEW` (empresas pulam etapas), ou outcome | +| Seleção | `RECRUITER_SCREEN` | Contato **humano** do RH: call, mensagem pedindo disponibilidade, questionário de triagem enviado por pessoa | `HIRING_MANAGER`, `ASSESSMENT`, `INTERVIEW`, outcome | +| Seleção | `HIRING_MANAGER` | Convite/conversa com gestor da área | `ASSESSMENT`, `INTERVIEW`, `OFFER`, outcome | +| Seleção | `ASSESSMENT` | Teste/case recebido | `INTERVIEW`, `HIRING_MANAGER`, `OFFER`, outcome | +| Seleção | `INTERVIEW` | Convite para rodada de entrevistas (técnica/painel/final). Cada entrevista é **atividade** | `OFFER`, outcome | +| Proposta | `OFFER` | Proposta formal (verbal explícita ou escrita) | outcome (`HIRED`, `WITHDREW`, `REJECTED` se retirada pela empresa, `ROLE_CANCELLED`) | +| Encerramento | *(etapa congelada)* + `outcome` | Ver §2.3 | Reabertura (limpa `outcome`, registra atividade `REOPENED`) | + +**Regras de transição:** + +- Avanço entre etapas **pode pular** (ordem é monotônica por padrão; retrocesso permitido só com atividade explicando — ex.: empresa volta para triagem após troca de vaga). Validar como *warning*, não erro, na primeira versão: o produto é pessoal e o usuário é a fonte de verdade. +- `outcome` **não** altera `stage`. A etapa fica congelada na última conhecida — é o que permite "rejeitado em ASSESSMENT" nos relatórios. +- `DRAFT` não aceita `outcome` exceto exclusão (ou `WITHDREW` se o usuário quiser manter registro). +- `archived` é ortogonal: arquivar não encerra, encerrar não arquiva (já é a regra atual do MCP — manter). +- Nenhuma automação avança etapa só por envio ou confirmação automática. Automação de e-mail só pode: criar `APPLIED`, registrar atividade, ou propor transição para confirmação. + +### 3.1 Distinção `APPLIED` × `RECRUITER_SCREEN` × `HIRING_MANAGER` (critério objetivo) + +| Evento | Etapa resultante | +|---|---| +| Candidatura enviada (manual, plataforma, DevScout, e-mail) | `APPLIED` | +| Auto-reply / ATS "recebemos" / "em análise" | `APPLIED` (atividade `ACK_RECEIVED`, opcional) | +| DM ao recrutador / conexão aceita no LinkedIn | `APPLIED` (atividade; `rhAcceptedConnection` já existe) | +| Recrutador humano responde com pergunta, pedido de call, pretensão salarial | `RECRUITER_SCREEN` | +| Call de triagem realizada | `RECRUITER_SCREEN` (atividade `SCREEN_DONE`) | +| Convite para conversar com gestor/líder técnico | `HIRING_MANAGER` | + +### 3.2 Entrevistas + +- `INTERVIEW` é etapa; cada entrevista é atividade (`INTERVIEW_SCHEDULED{at}`, `INTERVIEW_DONE{at}`, `INTERVIEW_CANCELLED`). +- `interviewCount` passa a ser derivável de `INTERVIEW_DONE`; enquanto atividades não existirem, manter o campo explícito atual (que já é a fonte da métrica exibida). +- **Parar** de gravar `interview_events` por mudança de status. Triagem de RH com call é entrevista? Decisão sugerida: **não** para `interviewCount`; sim para "contatos humanos" em outra métrica. + +### 3.3 Ghosting como indicador + +``` +isPossiblyGhosted = outcome IS NULL + AND waitingOn = COMPANY + AND lastCompanyContactAt (ou stageEnteredAt) < now - threshold(stage) + AND followUpsSentSinceLastContact >= N +``` + +Thresholds iniciais sugeridos (configuráveis): `APPLIED` 21 dias, demais 10 dias úteis, `N=1`. Enquanto não houver `lastCompanyContactAt`, usar `stageEnteredAt` — **nunca** `updated_at`, que muda ao editar a nota. + +--- + +## 4. Identificadores estáveis + +| Camada | Hoje | Proposta | +|---|---|---| +| Banco | `status VARCHAR` com display name | `stage VARCHAR(32)` com chave (`APPLIED`), `outcome VARCHAR(32) NULL`, `waiting_on VARCHAR(16) NULL`, `waiting_since TIMESTAMP NULL`, `legacy_status VARCHAR(100) NULL`, `status_migration VARCHAR(16) NULL` (`MAPPED`/`NEEDS_REVIEW`) | +| Catálogo | `application_statuses(name, display_order)` | `application_stages(key, label_pt, label_en, display_order, group)` + `application_outcomes(key, label_pt, label_en, counts_as_rejection)`; ou enums Java + labels no front. **Recomendação:** enum Java (é catálogo fechado, versionado com o código) e manter tabela só se precisar de i18n server-side | +| API REST | `status: "Pending HR Response"` | `stage`, `outcome`, `waitingOn` como chaves; `status` legado continua **lido e escrito** por compat (§5.2) | +| MCP | `Update-Application-Status(status displayName)` | Novas tools `Set-Application-Stage`, `Close-Application(outcome, reason)`, `Log-Application-Activity`. `List-Statuses` passa a devolver **chave + rótulo + critério de entrada** (o texto é o que impede o LLM de chutar) | +| UI | rótulo = valor | Rótulo PT-BR vindo de mapa no front; nunca persistir rótulo | + +Por que não manter display name como identificador: hoje já existem **três** grafias para o mesmo conceito (`Rejected`/`Rejeitado`/`REJEITADO`) e cada consumidor carrega sua própria lista de aliases. Chave estável elimina essa classe de bug. + +--- + +## 5. Migração retrocompatível + +### 5.0 Pré-requisito: hotfix do scheduler (issue separada) + +Sem isso, cada noite gera dados que a migração terá de marcar `NEEDS_REVIEW`. + +- Rascunho expirado: **não** mudar status. No máximo notificar/lembrar. +- Ghosting automático: só para `status` não terminal (`Rejected`, `Approved`, `Ghosting`, legados equivalentes) **e** `archived=false`. Melhor ainda: desligar e deixar o indicador calculado (§3.3) substituir. +- Testes de unidade para ambos os ramos. + +### 5.1 Fases + +1. **Inventário somente leitura** (§1.2). Saída: tabela `status × contagem × evidência disponível`. +2. **Expand:** adicionar colunas novas (nullable) + `legacy_status` (cópia exata de `status`) + `legacy_previous_status`. Não tocar em `status`. +3. **Dry run:** job/SQL que gera relatório por registro: `id, status, previous_status, destino(stage/outcome/waitingOn), regra, evidência, MAPPED|NEEDS_REVIEW`. Nenhuma escrita. +4. **Apply determinístico:** grava só linhas `MAPPED`. `NEEDS_REVIEW` ficam com colunas novas nulas e `status` intacto; UI exibe rótulo legado + badge "revisar". +5. **Dual-write:** backend escreve `status` legado **e** campos novos (mapa reverso: `stage/outcome → status` mais próximo, ex.: `ROLE_CANCELLED → Rejected` só no campo legado, para clientes antigos). Leitura passa a preferir campos novos. +6. **Migrar consumidores** (§6), na ordem: scheduler → métricas/dashboard → MCP → n8n → frontend → export. +7. **Contract:** remover dual-write e colunas legadas só quando `COUNT(status_migration='NEEDS_REVIEW')=0` e nenhum cliente usa `status` (verificar logs de MCP audit/`@AuditMcpOperation`). + +Rollback: até a fase 7, `status` e `legacy_status` preservam o original; reverter = ignorar colunas novas. + +### 5.2 Regras de mapeamento (dry run) + +| Legado | Condição | Destino | Senão | +|---|---|---|---| +| `NULL`, `to_send_later=true`, `application_date IS NULL` | — | `DRAFT` | `NEEDS_REVIEW` (inconsistente) | +| `RH` | `application_date IS NOT NULL` | `APPLIED` | `NEEDS_REVIEW` | +| `Pending HR Response` | nota/atividade comprova contato humano | `RECRUITER_SCREEN`+`COMPANY` | Sem evidência ⇒ `NEEDS_REVIEW`. **Exceção sugerida:** registros criados pelo workflow n8n (identificáveis por auditoria MCP/`created_at` em lote) ⇒ `APPLIED` | +| `Pending Hiring Manager Response`, `FIZ_A_HIRING_MANAGER_*` | — | `HIRING_MANAGER`+`COMPANY` | — | +| `FIZ_A_RH_*` | — | `RECRUITER_SCREEN`+`COMPANY` | — | +| `Technical Test`, `TESTE_TECNICO`, `Teste Técnico` | — | `ASSESSMENT` | — | +| `Pending Technical Test Response`, `FIZ_TESTE_TECNICO_*` | — | `ASSESSMENT`+`COMPANY` | — | +| `ENTREVISTA_MARCADA`, `Entrevista marcada` | — | `INTERVIEW` | — | +| `Offer Negotiation` | — | `OFFER` | — | +| `RH_NEGOCIACAO`, `RH (Negociação)` | nota comprova oferta | `OFFER` | `NEEDS_REVIEW` | +| `Rejected`/`REJEITADO`/`Rejeitado` | `previous_status IS NULL AND application_date IS NULL` (**assinatura do scheduler de rascunho**) | `DRAFT` | — | +| idem | nota casa regex de cancelamento | `ROLE_CANCELLED`, stage = map(`previous_status`) | — | +| idem | caso geral | `REJECTED`, stage = map(`previous_status`) ou `NEEDS_REVIEW` p/ stage se desconhecido | — | +| `Ghosting`/`GHOSTING` | `previous_status` terminal (`Rejected`, `Approved`…) | Aplicar regra do `previous_status` (**desfaz o scheduler**) | — | +| idem | `previous_status` mapeável não terminal | stage = map(`previous_status`), `waitingOn=COMPANY`, sem outcome | — | +| idem | `previous_status IS NULL` | `NEEDS_REVIEW` | — | +| `Tarde demais` | evidência de vaga encerrada | `ROLE_CANCELLED` | `NEEDS_REVIEW` | +| `Approved` | evidência de contratação | `HIRED` | `NEEDS_REVIEW` | + +Nunca criar: datas de contato, atividades de entrevista/teste/oferta, `waiting_since` (fica `NULL` = desconhecido), `outcome` para registro que não tinha terminal. + +--- + +## 6. Impactos por componente + +| Componente | Mudança | Risco / custo | +|---|---|---| +| `StaleApplicationsScheduler` | Hotfix (§5.0), depois substituído pelo indicador | Baixo esforço, alto ganho | +| `ApplicationService` | `applyStatusChange` ⇒ `applyStageChange`/`close`/`reopen`; dual-write; `previous_status` deixa de ser necessário (stage congelado cumpre o papel) | Médio. Cuidado com a regra "status vazio ⇒ rascunho ⇒ zera data" — hoje um PATCH com `status:null` apaga `application_date` | +| `InterviewMetricsService` | Parar de derivar entrevista de status | `interview_events` histórico fica como está (não apagar) | +| `GamificationService` | XP por **entrada em etapa** (`RECRUITER_SCREEN`+), `OFFER_WON` por `stage=OFFER`, `GHOSTBUSTER` por indicador | Idempotência: não reconceder XP em dual-write | +| `DashboardService` | `waitingResponses` = `waitingOn=COMPANY`; rejected = `outcome=REJECTED`; nova contagem `ROLE_CANCELLED` | Números do dashboard **vão mudar** — comunicar | +| `McpAnalyticsTools` | Rates por outcome; `averageDaysToResponse` precisa de atividade de contato (hoje mede `updated_at`, está errado) | Mudança de contrato de saída | +| MCP tools/resources/prompts | Novas tools; `List-Statuses` com critério; unificar regra de `RH`/`APPLIED` num lugar só | Clientes ChatGPT/n8n cacheiam descrições | +| Swagger DTOs | Corrigir `allowableValues` **já** (trivial, independe do RFC) | — | +| `ApplicationStatus.java` | Remover (código morto) | — | +| Export | Colunas `stage`, `outcome`, `waiting_on`, `legacy_status` | Arquivos antigos continuam válidos | +| Frontend `statuses.ts` | Famílias = grupos de etapa; outcome vira badge separado; `familyOf` não pode mais cair em `sent` silenciosamente | Funil muda de definição | +| Frontend `interviews.ts` | Confirmação de entrevista só ao entrar em `INTERVIEW` | — | +| Frontend board | Colunas por etapa; encerrados em coluna/filtro próprio | UX | +| Frontend form | Default `APPLIED` se tem data, `DRAFT` se não | — | +| n8n `Candidaturas enviadas → Applywell` | Trocar "use a valid status from its result" por **`stage=APPLIED` fixo**, ou, antes da migração, `status="RH"` fixo | **Fazer já** — evita repetir o 09/11 | + +--- + +## 7. Testes a especificar + +- **Scheduler:** terminal não vira Ghosting; arquivado não é tocado; rascunho não vira Rejected; idempotência entre execuções. +- **Transições:** pular etapa permitido; retrocesso gera warning; `outcome` não altera `stage`; reabrir limpa `outcome`; `DRAFT → outcome` bloqueado. +- **Dual-write:** escrever `status` legado popula novos campos e vice-versa; ida-e-volta estável. +- **Migração:** fixture com cada linha de §5.2 ⇒ destino esperado; rodar duas vezes ⇒ mesmo resultado; contagem antes = depois; `legacy_status` sempre igual ao original. +- **Importação de e-mail / n8n:** envio automático ⇒ `APPLIED`; auto-reply não avança; duplicata (empresa+recrutador+data) não cria; resposta humana gera *proposta* de transição, não transição. +- **Rejeição × cancelamento:** "a vaga foi cancelada" ⇒ `ROLE_CANCELLED`, não entra em rejection rate; "seguimos com outro candidato" ⇒ `REJECTED`. +- **Métricas:** entrar em `RECRUITER_SCREEN` não incrementa `interviewCount`; ghosting indicador usa `stageEnteredAt`, não `updated_at`. +- **Múltiplas candidaturas na mesma empresa:** são registros independentes; dedupe continua por empresa+recrutador+data (regra MCP atual). + +--- + +## 8. Respostas às perguntas da issue + +| Pergunta | Resposta | +|---|---| +| Renomear `RH`? Estado anterior? | Sim ⇒ `APPLIED`. `DRAFT` já existe de fato (`NULL`+`to_send_later`); formalizar. Prospecção (vaga salva, ainda não decidida) = `DRAFT` também; não criar terceiro estado sem demanda | +| Contato efetivo × triagem × espera × HM | §3.1 | +| Teste recebido/andamento/enviado/aguardando | Uma etapa `ASSESSMENT` + `waitingOn` + atividades. Status separados multiplicariam o catálogo por 4 em cada etapa | +| Entrevistas múltiplas | Atividades; contagem derivada (§3.2) | +| `Approved` | Ambíguo, sem consumidor ⇒ aposentar; `OFFER` (etapa) e `HIRED` (outcome) cobrem | +| Rejected × Cancelled × desistência × Ghosting | §2.3 e §3.3. Ghosting não é terminal | +| `archived` | Já é ortogonal no código; manter. Único violador hoje é o scheduler | +| Candidaturas automáticas / múltiplas na mesma empresa | `APPLIED` fixo; registros independentes | + +--- + +## 9. Desdobramento sugerido em issues + +1. **Hotfix:** scheduler não sobrescreve terminais/arquivados nem rejeita rascunhos (+ testes). *Independe do RFC.* +2. **Hotfix:** workflow n8n usa status fixo `RH` em vez de escolher do catálogo; unificar regras de `RH` em `McpApplicationCreationRulesResource`/`McpPromptsConfig`. *Independe do RFC.* +3. **Limpeza:** remover `ApplicationStatus.java`, corrigir `allowableValues` do Swagger. +4. **Inventário de produção** (§1.2) + dry run (§5.1 fases 1 e 3). +5. Expand schema + dual-write. +6. Apply determinístico + UI de `NEEDS_REVIEW`. +7. Métricas/dashboard/gamificação no novo modelo. +8. MCP v2 (tools novas, `List-Statuses` com critérios). +9. Frontend (famílias, board, funil, form). +10. Atividades (contato, teste, entrevista, oferta) + indicador de ghosting. +11. Contract (remoção do legado). + +## 10. Incertezas declaradas + +- Não consultei o banco de produção: todas as afirmações sobre *valores persistidos* são hipóteses (H1–H4) derivadas dos aliases que o código trata. O SQL de §1.2 resolve. +- Não verifiquei se há outros workflows n8n/GPT Actions escrevendo status além do listado; só um workflow ativo usa o Applywell MCP. +- Thresholds de ghosting (§3.3) são palpite razoável, não dado — calibrar com o inventário (tempo mediano até primeira resposta humana). From 1a909a4f26f3753fd3e9142c0fd4e30d6bc4a05c Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 18:34:49 +0000 Subject: [PATCH 02/24] feat(applications): add stage/outcome/waitingOn columns alongside legacy status Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GfjfbQseka7Y3pN4sK32Pe --- .../com/jobtracker/entity/JobApplication.java | 38 ++++++++++++++++++ .../entity/enums/ApplicationOutcome.java | 5 +++ .../entity/enums/ApplicationStage.java | 5 +++ .../entity/enums/ApplicationStatus.java | 39 ------------------- .../entity/enums/StatusMigrationState.java | 5 +++ .../jobtracker/entity/enums/WaitingOn.java | 5 +++ .../V40__add_application_stage_outcome.sql | 8 ++++ 7 files changed, 66 insertions(+), 39 deletions(-) create mode 100644 src/main/java/com/jobtracker/entity/enums/ApplicationOutcome.java create mode 100644 src/main/java/com/jobtracker/entity/enums/ApplicationStage.java delete mode 100644 src/main/java/com/jobtracker/entity/enums/ApplicationStatus.java create mode 100644 src/main/java/com/jobtracker/entity/enums/StatusMigrationState.java create mode 100644 src/main/java/com/jobtracker/entity/enums/WaitingOn.java create mode 100644 src/main/resources/db/migration/postgresql/V40__add_application_stage_outcome.sql diff --git a/src/main/java/com/jobtracker/entity/JobApplication.java b/src/main/java/com/jobtracker/entity/JobApplication.java index 517ee241..e03d3da5 100644 --- a/src/main/java/com/jobtracker/entity/JobApplication.java +++ b/src/main/java/com/jobtracker/entity/JobApplication.java @@ -5,6 +5,10 @@ import java.time.LocalDateTime; import java.util.UUID; +import com.jobtracker.entity.enums.ApplicationOutcome; +import com.jobtracker.entity.enums.ApplicationStage; +import com.jobtracker.entity.enums.StatusMigrationState; +import com.jobtracker.entity.enums.WaitingOn; import org.hibernate.annotations.UuidGenerator; @Entity @@ -54,6 +58,25 @@ public class JobApplication { @Column(name = "previous_status", nullable = true, length = 100, columnDefinition = "varchar(100)") private String previousStatus; + @Enumerated(EnumType.STRING) + @Column(name = "stage", length = 32) + private ApplicationStage stage; + + @Enumerated(EnumType.STRING) + @Column(name = "outcome", length = 32) + private ApplicationOutcome outcome; + + @Enumerated(EnumType.STRING) + @Column(name = "waiting_on", length = 16) + private WaitingOn waitingOn; + + @Column(name = "legacy_status", length = 100) + private String legacyStatus; + + @Enumerated(EnumType.STRING) + @Column(name = "status_migration", length = 16) + private StatusMigrationState statusMigration; + @Column(name = "to_send_later", nullable = false) private boolean toSendLater; @@ -171,6 +194,21 @@ protected void onUpdate() { public String getPreviousStatus() { return previousStatus; } public void setPreviousStatus(String previousStatus) { this.previousStatus = previousStatus; } + public ApplicationStage getStage() { return stage; } + public void setStage(ApplicationStage stage) { this.stage = stage; } + + public ApplicationOutcome getOutcome() { return outcome; } + public void setOutcome(ApplicationOutcome outcome) { this.outcome = outcome; } + + public WaitingOn getWaitingOn() { return waitingOn; } + public void setWaitingOn(WaitingOn waitingOn) { this.waitingOn = waitingOn; } + + public String getLegacyStatus() { return legacyStatus; } + public void setLegacyStatus(String legacyStatus) { this.legacyStatus = legacyStatus; } + + public StatusMigrationState getStatusMigration() { return statusMigration; } + public void setStatusMigration(StatusMigrationState statusMigration) { this.statusMigration = statusMigration; } + public boolean isToSendLater() { return toSendLater; } public void setToSendLater(boolean toSendLater) { this.toSendLater = toSendLater; } diff --git a/src/main/java/com/jobtracker/entity/enums/ApplicationOutcome.java b/src/main/java/com/jobtracker/entity/enums/ApplicationOutcome.java new file mode 100644 index 00000000..64278745 --- /dev/null +++ b/src/main/java/com/jobtracker/entity/enums/ApplicationOutcome.java @@ -0,0 +1,5 @@ +package com.jobtracker.entity.enums; + +public enum ApplicationOutcome { + HIRED, REJECTED, ROLE_CANCELLED, WITHDREW +} diff --git a/src/main/java/com/jobtracker/entity/enums/ApplicationStage.java b/src/main/java/com/jobtracker/entity/enums/ApplicationStage.java new file mode 100644 index 00000000..9ed43f5b --- /dev/null +++ b/src/main/java/com/jobtracker/entity/enums/ApplicationStage.java @@ -0,0 +1,5 @@ +package com.jobtracker.entity.enums; + +public enum ApplicationStage { + DRAFT, APPLIED, RECRUITER_SCREEN, HIRING_MANAGER, ASSESSMENT, INTERVIEW, OFFER +} diff --git a/src/main/java/com/jobtracker/entity/enums/ApplicationStatus.java b/src/main/java/com/jobtracker/entity/enums/ApplicationStatus.java deleted file mode 100644 index c0728d13..00000000 --- a/src/main/java/com/jobtracker/entity/enums/ApplicationStatus.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.jobtracker.entity.enums; - -public enum ApplicationStatus { - RH("RH", "Initial HR outreach stage."), - ENTREVISTA_MARCADA("Entrevista marcada", "An interview has been scheduled."), - FIZ_A_RH_AGUARDANDO_ATUALIZACAO("Fiz a RH - Aguardando Atualização", "HR contact has happened and a reply is pending."), - FIZ_A_HIRING_MANAGER_AGUARDANDO_ATUALIZACAO("Fiz a Hiring Manager - Aguardando Atualização", "Hiring manager contact has happened and a reply is pending."), - TESTE_TECNICO("Teste Técnico", "Technical test phase."), - FIZ_TESTE_TECNICO_AGUARDANDO_ATUALIZACAO("Fiz teste Técnico - aguardando atualização", "Technical test has been sent and feedback is pending."), - RH_NEGOCIACAO("RH (Negociação)", "Recruiter negotiation or offer discussion."), - REJEITADO("Rejeitado", "Application was rejected."), - TARDE_DEMAIS("Tarde demais", "The opportunity was missed or closed too late."), - GHOSTING("Ghosting", "No response after follow-up attempts."); - - private final String displayName; - private final String description; - - ApplicationStatus(String displayName, String description) { - this.displayName = displayName; - this.description = description; - } - - public String getDisplayName() { - return displayName; - } - - public String getDescription() { - return description; - } - - public static ApplicationStatus fromDisplayName(String displayName) { - for (ApplicationStatus status : values()) { - if (status.displayName.equalsIgnoreCase(displayName)) { - return status; - } - } - throw new IllegalArgumentException("Unknown status: " + displayName); - } -} diff --git a/src/main/java/com/jobtracker/entity/enums/StatusMigrationState.java b/src/main/java/com/jobtracker/entity/enums/StatusMigrationState.java new file mode 100644 index 00000000..7b776f13 --- /dev/null +++ b/src/main/java/com/jobtracker/entity/enums/StatusMigrationState.java @@ -0,0 +1,5 @@ +package com.jobtracker.entity.enums; + +public enum StatusMigrationState { + MAPPED, NEEDS_REVIEW +} diff --git a/src/main/java/com/jobtracker/entity/enums/WaitingOn.java b/src/main/java/com/jobtracker/entity/enums/WaitingOn.java new file mode 100644 index 00000000..60eea93b --- /dev/null +++ b/src/main/java/com/jobtracker/entity/enums/WaitingOn.java @@ -0,0 +1,5 @@ +package com.jobtracker.entity.enums; + +public enum WaitingOn { + COMPANY, CANDIDATE +} diff --git a/src/main/resources/db/migration/postgresql/V40__add_application_stage_outcome.sql b/src/main/resources/db/migration/postgresql/V40__add_application_stage_outcome.sql new file mode 100644 index 00000000..d762b66d --- /dev/null +++ b/src/main/resources/db/migration/postgresql/V40__add_application_stage_outcome.sql @@ -0,0 +1,8 @@ +ALTER TABLE job_applications + ADD COLUMN stage VARCHAR(32) NULL, + ADD COLUMN outcome VARCHAR(32) NULL, + ADD COLUMN waiting_on VARCHAR(16) NULL, + ADD COLUMN legacy_status VARCHAR(100) NULL, + ADD COLUMN status_migration VARCHAR(16) NULL; + +CREATE INDEX idx_app_status_migration ON job_applications (status_migration); From 6b282696657669455779a445add92db7c4a70e70 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 18:35:53 +0000 Subject: [PATCH 03/24] feat(applications): map legacy status values to stage/outcome/waitingOn Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GfjfbQseka7Y3pN4sK32Pe --- .../service/status/LegacyStatusMapper.java | 122 +++++++++++++ .../service/status/StatusMapping.java | 27 +++ .../unit/status/LegacyStatusMapperTest.java | 166 ++++++++++++++++++ 3 files changed, 315 insertions(+) create mode 100644 src/main/java/com/jobtracker/service/status/LegacyStatusMapper.java create mode 100644 src/main/java/com/jobtracker/service/status/StatusMapping.java create mode 100644 src/test/java/com/jobtracker/unit/status/LegacyStatusMapperTest.java diff --git a/src/main/java/com/jobtracker/service/status/LegacyStatusMapper.java b/src/main/java/com/jobtracker/service/status/LegacyStatusMapper.java new file mode 100644 index 00000000..13375719 --- /dev/null +++ b/src/main/java/com/jobtracker/service/status/LegacyStatusMapper.java @@ -0,0 +1,122 @@ +package com.jobtracker.service.status; + +import com.jobtracker.entity.JobApplication; +import com.jobtracker.entity.enums.ApplicationOutcome; +import com.jobtracker.entity.enums.ApplicationStage; +import com.jobtracker.entity.enums.WaitingOn; + +import java.time.LocalDate; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +/** + * Derives the stage/outcome/waitingOn model from the legacy free-text status. Only mappings the legacy data + * proves on its own are MAPPED; anything ambiguous is NEEDS_REVIEW so nothing is inferred silently. + * See docs/superpowers/specs/2026-11-30-application-status-model-rfc.md, section 5.2. + */ +public final class LegacyStatusMapper { + + private static final Set REJECTED = keys("Rejected", "REJEITADO", "Rejeitado"); + private static final Set GHOSTING = keys("Ghosting"); + + private static final Map OPEN_STAGES = Map.ofEntries( + stage("RH", ApplicationStage.APPLIED, null), + stage("Pending Hiring Manager Response", ApplicationStage.HIRING_MANAGER, WaitingOn.COMPANY), + stage("FIZ_A_HIRING_MANAGER_AGUARDANDO_ATUALIZACAO", ApplicationStage.HIRING_MANAGER, WaitingOn.COMPANY), + stage("Fiz a Hiring Manager - Aguardando Atualização", ApplicationStage.HIRING_MANAGER, WaitingOn.COMPANY), + stage("FIZ_A_RH_AGUARDANDO_ATUALIZACAO", ApplicationStage.RECRUITER_SCREEN, WaitingOn.COMPANY), + stage("Fiz a RH - Aguardando Atualização", ApplicationStage.RECRUITER_SCREEN, WaitingOn.COMPANY), + stage("Technical Test", ApplicationStage.ASSESSMENT, null), + stage("TESTE_TECNICO", ApplicationStage.ASSESSMENT, null), + stage("Teste Técnico", ApplicationStage.ASSESSMENT, null), + stage("Pending Technical Test Response", ApplicationStage.ASSESSMENT, WaitingOn.COMPANY), + stage("FIZ_TESTE_TECNICO_AGUARDANDO_ATUALIZACAO", ApplicationStage.ASSESSMENT, WaitingOn.COMPANY), + stage("Fiz teste Técnico - aguardando atualização", ApplicationStage.ASSESSMENT, WaitingOn.COMPANY), + stage("ENTREVISTA_MARCADA", ApplicationStage.INTERVIEW, null), + stage("Entrevista marcada", ApplicationStage.INTERVIEW, null), + stage("Offer Negotiation", ApplicationStage.OFFER, null) + ); + + private LegacyStatusMapper() {} + + public static StatusMapping map(String status, String previousStatus, boolean toSendLater, LocalDate applicationDate) { + String key = key(status); + if (key == null) { + return toSendLater && applicationDate == null + ? StatusMapping.mapped(ApplicationStage.DRAFT, null, null, "draft") + : StatusMapping.needsReview("null-status-inconsistent-draft"); + } + if (REJECTED.contains(key)) { + return mapRejected(previousStatus, applicationDate); + } + if (GHOSTING.contains(key)) { + return mapGhosting(previousStatus, applicationDate); + } + return openStage(key, applicationDate); + } + + public static void apply(JobApplication app) { + StatusMapping mapping = map(app.getStatus(), app.getPreviousStatus(), app.isToSendLater(), app.getApplicationDate()); + app.setStage(mapping.stage()); + app.setOutcome(mapping.outcome()); + app.setWaitingOn(mapping.waitingOn()); + app.setLegacyStatus(app.getStatus()); + app.setStatusMigration(mapping.state()); + } + + private static StatusMapping openStage(String key, LocalDate applicationDate) { + StatusMapping mapping = OPEN_STAGES.get(key); + if (mapping == null) { + return StatusMapping.needsReview("ambiguous-or-unknown-status"); + } + if (mapping.stage() == ApplicationStage.APPLIED && applicationDate == null) { + return StatusMapping.needsReview("rh-without-application-date"); + } + return mapping; + } + + private static StatusMapping mapRejected(String previousStatus, LocalDate applicationDate) { + String previous = key(previousStatus); + if (previous == null && applicationDate == null) { + // The API never accepts a status without a date, so this shape is the nightly job expiring a draft. + return StatusMapping.mapped(ApplicationStage.DRAFT, null, null, "scheduler-expired-draft"); + } + StatusMapping last = previous == null ? null : openStage(previous, applicationDate); + if (last != null && last.isOpenStage()) { + return StatusMapping.mapped(last.stage(), ApplicationOutcome.REJECTED, null, "rejected-after-" + last.stage()); + } + return StatusMapping.mapped(ApplicationStage.APPLIED, ApplicationOutcome.REJECTED, null, "rejected-last-known-applied"); + } + + private static StatusMapping mapGhosting(String previousStatus, LocalDate applicationDate) { + String previous = key(previousStatus); + if (previous == null) { + return StatusMapping.needsReview("ghosting-without-previous"); + } + if (REJECTED.contains(previous)) { + return applicationDate == null + ? StatusMapping.needsReview("ghosting-over-rejected-without-date") + : StatusMapping.mapped(ApplicationStage.APPLIED, ApplicationOutcome.REJECTED, null, "ghosting-over-rejected"); + } + StatusMapping last = openStage(previous, applicationDate); + return last.isOpenStage() + ? StatusMapping.mapped(last.stage(), null, WaitingOn.COMPANY, "ghosting-after-" + last.stage()) + : StatusMapping.needsReview("ghosting-over-unmappable-previous"); + } + + private static String key(String status) { + if (status == null || status.isBlank()) { + return null; + } + return status.trim().toLowerCase(Locale.ROOT); + } + + private static Set keys(String... values) { + return Set.of(java.util.Arrays.stream(values).map(LegacyStatusMapper::key).distinct().toArray(String[]::new)); + } + + private static Map.Entry stage(String legacy, ApplicationStage stage, WaitingOn waitingOn) { + return Map.entry(key(legacy), StatusMapping.mapped(stage, null, waitingOn, "stage-" + stage)); + } +} diff --git a/src/main/java/com/jobtracker/service/status/StatusMapping.java b/src/main/java/com/jobtracker/service/status/StatusMapping.java new file mode 100644 index 00000000..8e61a181 --- /dev/null +++ b/src/main/java/com/jobtracker/service/status/StatusMapping.java @@ -0,0 +1,27 @@ +package com.jobtracker.service.status; + +import com.jobtracker.entity.enums.ApplicationOutcome; +import com.jobtracker.entity.enums.ApplicationStage; +import com.jobtracker.entity.enums.StatusMigrationState; +import com.jobtracker.entity.enums.WaitingOn; + +/** Result of interpreting a legacy status value; {@code rule} names the rule that produced it for audit logs. */ +public record StatusMapping( + ApplicationStage stage, + ApplicationOutcome outcome, + WaitingOn waitingOn, + StatusMigrationState state, + String rule +) { + static StatusMapping mapped(ApplicationStage stage, ApplicationOutcome outcome, WaitingOn waitingOn, String rule) { + return new StatusMapping(stage, outcome, waitingOn, StatusMigrationState.MAPPED, rule); + } + + static StatusMapping needsReview(String rule) { + return new StatusMapping(null, null, null, StatusMigrationState.NEEDS_REVIEW, rule); + } + + boolean isOpenStage() { + return state == StatusMigrationState.MAPPED && outcome == null && stage != ApplicationStage.DRAFT; + } +} diff --git a/src/test/java/com/jobtracker/unit/status/LegacyStatusMapperTest.java b/src/test/java/com/jobtracker/unit/status/LegacyStatusMapperTest.java new file mode 100644 index 00000000..4cdf705c --- /dev/null +++ b/src/test/java/com/jobtracker/unit/status/LegacyStatusMapperTest.java @@ -0,0 +1,166 @@ +package com.jobtracker.unit.status; + +import com.jobtracker.entity.JobApplication; +import com.jobtracker.entity.enums.ApplicationOutcome; +import com.jobtracker.entity.enums.ApplicationStage; +import com.jobtracker.entity.enums.StatusMigrationState; +import com.jobtracker.entity.enums.WaitingOn; +import com.jobtracker.service.status.LegacyStatusMapper; +import com.jobtracker.service.status.StatusMapping; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.time.LocalDate; + +import static com.jobtracker.entity.enums.StatusMigrationState.MAPPED; +import static com.jobtracker.entity.enums.StatusMigrationState.NEEDS_REVIEW; +import static org.assertj.core.api.Assertions.assertThat; + +class LegacyStatusMapperTest { + + private static final LocalDate DATE = LocalDate.of(2026, 11, 9); + + private static StatusMapping map(String status, String previous) { + return LegacyStatusMapper.map(status, previous, false, DATE); + } + + private static void assertMapped(StatusMapping m, ApplicationStage stage, ApplicationOutcome outcome, WaitingOn waitingOn) { + assertThat(m.state()).isEqualTo(MAPPED); + assertThat(m.stage()).isEqualTo(stage); + assertThat(m.outcome()).isEqualTo(outcome); + assertThat(m.waitingOn()).isEqualTo(waitingOn); + assertThat(m.rule()).isNotBlank(); + } + + private static void assertNeedsReview(StatusMapping m) { + assertThat(m.state()).isEqualTo(NEEDS_REVIEW); + assertThat(m.stage()).isNull(); + assertThat(m.outcome()).isNull(); + assertThat(m.waitingOn()).isNull(); + assertThat(m.rule()).isNotBlank(); + } + + @Test + void draftWithoutDateMapsToDraft() { + assertMapped(LegacyStatusMapper.map(null, null, true, null), ApplicationStage.DRAFT, null, null); + } + + @Test + void nullStatusThatIsNotAConsistentDraftNeedsReview() { + assertNeedsReview(LegacyStatusMapper.map(null, null, true, DATE)); + assertNeedsReview(LegacyStatusMapper.map(null, null, false, null)); + } + + @Test + void rhWithDateIsApplied() { + assertMapped(map("RH", null), ApplicationStage.APPLIED, null, null); + } + + @Test + void rhWithoutDateNeedsReview() { + assertNeedsReview(LegacyStatusMapper.map("RH", null, false, null)); + } + + @ParameterizedTest + @ValueSource(strings = {"Pending HR Response", "RH (Negociação)", "RH_NEGOCIACAO", "Tarde demais", + "TARDE_DEMAIS", "Approved", "Something Else"}) + void ambiguousValuesNeedReview(String status) { + assertNeedsReview(map(status, null)); + } + + @ParameterizedTest + @CsvSource(delimiter = '|', value = { + "Pending Hiring Manager Response|HIRING_MANAGER|COMPANY", + "FIZ_A_HIRING_MANAGER_AGUARDANDO_ATUALIZACAO|HIRING_MANAGER|COMPANY", + "Fiz a Hiring Manager - Aguardando Atualização|HIRING_MANAGER|COMPANY", + "FIZ_A_RH_AGUARDANDO_ATUALIZACAO|RECRUITER_SCREEN|COMPANY", + "Fiz a RH - Aguardando Atualização|RECRUITER_SCREEN|COMPANY", + "Technical Test|ASSESSMENT|", + "TESTE_TECNICO|ASSESSMENT|", + "Teste Técnico|ASSESSMENT|", + "Pending Technical Test Response|ASSESSMENT|COMPANY", + "FIZ_TESTE_TECNICO_AGUARDANDO_ATUALIZACAO|ASSESSMENT|COMPANY", + "Fiz teste Técnico - aguardando atualização|ASSESSMENT|COMPANY", + "ENTREVISTA_MARCADA|INTERVIEW|", + "Entrevista marcada|INTERVIEW|", + "Offer Negotiation|OFFER|" + }) + void deterministicStages(String status, ApplicationStage stage, WaitingOn waitingOn) { + assertMapped(map(status, null), stage, null, waitingOn); + } + + @ParameterizedTest + @ValueSource(strings = {" rejected ", "REJECTED", "rh", " RH"}) + void lookupIgnoresCaseAndSurroundingWhitespace(String status) { + assertThat(map(status, null).state()).isEqualTo(MAPPED); + } + + @Test + void rejectedWithoutDateOrPreviousIsAnExpiredDraft() { + assertMapped(LegacyStatusMapper.map("Rejected", null, false, null), ApplicationStage.DRAFT, null, null); + } + + @ParameterizedTest + @ValueSource(strings = {"Rejected", "REJEITADO", "Rejeitado"}) + void rejectedKeepsLastKnownStage(String status) { + assertMapped(map(status, "Technical Test"), ApplicationStage.ASSESSMENT, ApplicationOutcome.REJECTED, null); + } + + @Test + void rejectedWithUnknownPreviousFallsBackToApplied() { + assertMapped(map("Rejected", null), ApplicationStage.APPLIED, ApplicationOutcome.REJECTED, null); + assertMapped(map("Rejected", "Pending HR Response"), ApplicationStage.APPLIED, ApplicationOutcome.REJECTED, null); + } + + @Test + void ghostingOverARejectionRestoresTheRejection() { + assertMapped(map("Ghosting", "Rejected"), ApplicationStage.APPLIED, ApplicationOutcome.REJECTED, null); + assertMapped(map("GHOSTING", "REJEITADO"), ApplicationStage.APPLIED, ApplicationOutcome.REJECTED, null); + } + + @Test + void ghostingOverAnOpenStageKeepsTheStageAndWaitsOnTheCompany() { + assertMapped(map("Ghosting", "Technical Test"), ApplicationStage.ASSESSMENT, null, WaitingOn.COMPANY); + assertMapped(map("Ghosting", "RH"), ApplicationStage.APPLIED, null, WaitingOn.COMPANY); + } + + @ParameterizedTest + @CsvSource(nullValues = "NULL", value = {"NULL", "Ghosting", "Approved", "Pending HR Response", "garbage"}) + void ghostingWithoutAMappablePreviousNeedsReview(String previous) { + assertNeedsReview(map("Ghosting", previous)); + } + + @Test + void applyCopiesTheMappingAndTheExactLegacyValue() { + JobApplication app = new JobApplication(); + app.setStatus("Pending Technical Test Response"); + app.setApplicationDate(DATE); + + LegacyStatusMapper.apply(app); + + assertThat(app.getStage()).isEqualTo(ApplicationStage.ASSESSMENT); + assertThat(app.getWaitingOn()).isEqualTo(WaitingOn.COMPANY); + assertThat(app.getOutcome()).isNull(); + assertThat(app.getLegacyStatus()).isEqualTo("Pending Technical Test Response"); + assertThat(app.getStatusMigration()).isEqualTo(StatusMigrationState.MAPPED); + } + + @Test + void applyClearsStaleFieldsWhenTheNewValueNeedsReview() { + JobApplication app = new JobApplication(); + app.setStage(ApplicationStage.OFFER); + app.setOutcome(ApplicationOutcome.REJECTED); + app.setWaitingOn(WaitingOn.COMPANY); + app.setStatus("Approved"); + app.setApplicationDate(DATE); + + LegacyStatusMapper.apply(app); + + assertThat(app.getStage()).isNull(); + assertThat(app.getOutcome()).isNull(); + assertThat(app.getWaitingOn()).isNull(); + assertThat(app.getStatusMigration()).isEqualTo(NEEDS_REVIEW); + } +} From dfa9717a2d354ad02fee32d199ba2b89581d0630 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 18:36:30 +0000 Subject: [PATCH 04/24] fix(scheduler): stop overwriting closed, archived and draft applications The nightly job turned week-old drafts into Rejected and any record untouched for a month (Rejected, Approved and archived included) into Ghosting. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GfjfbQseka7Y3pN4sK32Pe --- .../repository/ApplicationRepository.java | 8 +- .../tasks/StaleApplicationsScheduler.java | 39 +++++----- .../unit/StaleApplicationsSchedulerTest.java | 74 +++++++++++++++++++ 3 files changed, 98 insertions(+), 23 deletions(-) create mode 100644 src/test/java/com/jobtracker/unit/StaleApplicationsSchedulerTest.java diff --git a/src/main/java/com/jobtracker/repository/ApplicationRepository.java b/src/main/java/com/jobtracker/repository/ApplicationRepository.java index 2c65f1bb..66069a78 100644 --- a/src/main/java/com/jobtracker/repository/ApplicationRepository.java +++ b/src/main/java/com/jobtracker/repository/ApplicationRepository.java @@ -11,6 +11,7 @@ import org.springframework.stereotype.Repository; import java.time.LocalDateTime; +import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.UUID; @@ -52,9 +53,10 @@ public interface ApplicationRepository extends JpaRepository :expireThreshold AND a.archived = false ORDER BY a.createdAt ASC") List findOverdueByUserId(@Param("userId") UUID userId, @Param("reminderThreshold") LocalDateTime reminderThreshold, @Param("expireThreshold") LocalDateTime expireThreshold); - List findByStatusIsNullAndUpdatedAtBefore(LocalDateTime updatedAt); - - List findByStatusIsNotNullAndStatusNotAndUpdatedAtBefore(String status, LocalDateTime updatedAt); + @Query("SELECT a FROM JobApplication a WHERE a.status IS NOT NULL AND a.status NOT IN :excludedStatuses " + + "AND a.outcome IS NULL AND a.archived = false AND a.updatedAt < :updatedBefore") + List findStaleActiveApplications(@Param("excludedStatuses") Collection excludedStatuses, + @Param("updatedBefore") LocalDateTime updatedBefore); /** * Atomically sets {@code driveVacancyFolderId} on an application only when the column is diff --git a/src/main/java/com/jobtracker/tasks/StaleApplicationsScheduler.java b/src/main/java/com/jobtracker/tasks/StaleApplicationsScheduler.java index 4bfe771f..e4615299 100644 --- a/src/main/java/com/jobtracker/tasks/StaleApplicationsScheduler.java +++ b/src/main/java/com/jobtracker/tasks/StaleApplicationsScheduler.java @@ -2,16 +2,31 @@ import com.jobtracker.entity.JobApplication; import com.jobtracker.repository.ApplicationRepository; +import com.jobtracker.service.status.LegacyStatusMapper; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import java.time.LocalDateTime; import java.util.List; +import java.util.Set; +/** + * Marks open, active applications without any update for a month as Ghosting. Closed outcomes, archived records and + * drafts are never touched: overwriting them used to turn rejections into ghosting and unsent drafts into rejections. + */ @Component public class StaleApplicationsScheduler { + private static final String GHOSTING = "Ghosting"; + + private static final Set TERMINAL_STATUSES = Set.of( + GHOSTING, "GHOSTING", + "Rejected", "REJEITADO", "Rejeitado", + "Approved", + "Tarde demais", "TARDE_DEMAIS" + ); + private final ApplicationRepository applicationRepository; public StaleApplicationsScheduler(ApplicationRepository applicationRepository) { @@ -21,28 +36,12 @@ public StaleApplicationsScheduler(ApplicationRepository applicationRepository) { @Scheduled(cron = "0 0 0 * * ?") @Transactional public void updateStaleApplications() { - LocalDateTime now = LocalDateTime.now(); - LocalDateTime oneWeekAgo = now.minusWeeks(1); - LocalDateTime oneMonthAgo = now.minusMonths(1); - - List toSendLaterExpired = applicationRepository.findByStatusIsNullAndUpdatedAtBefore(oneWeekAgo); - for (JobApplication application : toSendLaterExpired) { - application.setPreviousStatus(null); - application.setStatus("Rejected"); - application.setToSendLater(false); - } - if (!toSendLaterExpired.isEmpty()) { - applicationRepository.saveAll(toSendLaterExpired); - } - List staleApplications = applicationRepository - .findByStatusIsNotNullAndStatusNotAndUpdatedAtBefore("Ghosting", oneMonthAgo); + .findStaleActiveApplications(TERMINAL_STATUSES, LocalDateTime.now().minusMonths(1)); for (JobApplication application : staleApplications) { - String currentStatus = application.getStatus(); - if (!"Ghosting".equals(currentStatus)) { - application.setPreviousStatus(currentStatus); - application.setStatus("Ghosting"); - } + application.setPreviousStatus(application.getStatus()); + application.setStatus(GHOSTING); + LegacyStatusMapper.apply(application); } if (!staleApplications.isEmpty()) { applicationRepository.saveAll(staleApplications); diff --git a/src/test/java/com/jobtracker/unit/StaleApplicationsSchedulerTest.java b/src/test/java/com/jobtracker/unit/StaleApplicationsSchedulerTest.java new file mode 100644 index 00000000..8ff1370b --- /dev/null +++ b/src/test/java/com/jobtracker/unit/StaleApplicationsSchedulerTest.java @@ -0,0 +1,74 @@ +package com.jobtracker.unit; + +import com.jobtracker.entity.JobApplication; +import com.jobtracker.entity.enums.ApplicationStage; +import com.jobtracker.entity.enums.WaitingOn; +import com.jobtracker.repository.ApplicationRepository; +import com.jobtracker.tasks.StaleApplicationsScheduler; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.Collection; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyCollection; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class StaleApplicationsSchedulerTest { + + @Mock + private ApplicationRepository applicationRepository; + + @Test + @SuppressWarnings("unchecked") + void excludesEveryTerminalAliasFromTheGhostingSweep() { + when(applicationRepository.findStaleActiveApplications(anyCollection(), any())).thenReturn(List.of()); + + new StaleApplicationsScheduler(applicationRepository).updateStaleApplications(); + + ArgumentCaptor> excluded = ArgumentCaptor.forClass(Collection.class); + ArgumentCaptor before = ArgumentCaptor.forClass(LocalDateTime.class); + verify(applicationRepository).findStaleActiveApplications(excluded.capture(), before.capture()); + assertThat(excluded.getValue()).contains("Ghosting", "GHOSTING", "Rejected", "REJEITADO", "Rejeitado", + "Approved", "Tarde demais", "TARDE_DEMAIS"); + assertThat(before.getValue()).isBefore(LocalDateTime.now().minusDays(27)); + verify(applicationRepository, never()).saveAll(any()); + } + + @Test + void staleOpenApplicationBecomesGhostingAndKeepsItsStage() { + JobApplication app = new JobApplication(); + app.setStatus("Technical Test"); + app.setApplicationDate(LocalDate.of(2026, 9, 1)); + when(applicationRepository.findStaleActiveApplications(anyCollection(), any())).thenReturn(List.of(app)); + + new StaleApplicationsScheduler(applicationRepository).updateStaleApplications(); + + assertThat(app.getStatus()).isEqualTo("Ghosting"); + assertThat(app.getPreviousStatus()).isEqualTo("Technical Test"); + assertThat(app.getStage()).isEqualTo(ApplicationStage.ASSESSMENT); + assertThat(app.getWaitingOn()).isEqualTo(WaitingOn.COMPANY); + assertThat(app.getOutcome()).isNull(); + verify(applicationRepository).saveAll(List.of(app)); + } + + @Test + void neverRejectsDrafts() { + when(applicationRepository.findStaleActiveApplications(anyCollection(), any())).thenReturn(List.of()); + + new StaleApplicationsScheduler(applicationRepository).updateStaleApplications(); + + verify(applicationRepository, never()).save(any()); + verify(applicationRepository, never()).saveAll(any()); + } +} From ffa7c058aa2a64c39b8d286ce4cb2aca5e4abf72 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 18:37:13 +0000 Subject: [PATCH 05/24] feat(applications): backfill stage/outcome from legacy status on startup Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GfjfbQseka7Y3pN4sK32Pe --- .../repository/ApplicationRepository.java | 17 ++++ .../service/status/LegacyStatusBackfill.java | 63 ++++++++++++++ .../unit/status/LegacyStatusBackfillTest.java | 86 +++++++++++++++++++ 3 files changed, 166 insertions(+) create mode 100644 src/main/java/com/jobtracker/service/status/LegacyStatusBackfill.java create mode 100644 src/test/java/com/jobtracker/unit/status/LegacyStatusBackfillTest.java diff --git a/src/main/java/com/jobtracker/repository/ApplicationRepository.java b/src/main/java/com/jobtracker/repository/ApplicationRepository.java index 66069a78..c724355f 100644 --- a/src/main/java/com/jobtracker/repository/ApplicationRepository.java +++ b/src/main/java/com/jobtracker/repository/ApplicationRepository.java @@ -1,6 +1,10 @@ package com.jobtracker.repository; import com.jobtracker.entity.JobApplication; +import com.jobtracker.entity.enums.ApplicationOutcome; +import com.jobtracker.entity.enums.ApplicationStage; +import com.jobtracker.entity.enums.StatusMigrationState; +import com.jobtracker.entity.enums.WaitingOn; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; @@ -58,6 +62,19 @@ public interface ApplicationRepository extends JpaRepository findStaleActiveApplications(@Param("excludedStatuses") Collection excludedStatuses, @Param("updatedBefore") LocalDateTime updatedBefore); + List findTop500ByStatusMigrationIsNullOrderByIdAsc(); + + /** Bulk update so the backfill does not bump {@code updatedAt}, which the stale-application sweep relies on. */ + @Modifying + @Query("UPDATE JobApplication a SET a.stage = :stage, a.outcome = :outcome, a.waitingOn = :waitingOn, " + + "a.legacyStatus = :legacyStatus, a.statusMigration = :migration WHERE a.id = :id AND a.statusMigration IS NULL") + int applyStatusMapping(@Param("id") UUID id, + @Param("stage") ApplicationStage stage, + @Param("outcome") ApplicationOutcome outcome, + @Param("waitingOn") WaitingOn waitingOn, + @Param("legacyStatus") String legacyStatus, + @Param("migration") StatusMigrationState migration); + /** * Atomically sets {@code driveVacancyFolderId} on an application only when the column is * currently {@code NULL}. Returns the number of rows updated (1 on success, 0 if another diff --git a/src/main/java/com/jobtracker/service/status/LegacyStatusBackfill.java b/src/main/java/com/jobtracker/service/status/LegacyStatusBackfill.java new file mode 100644 index 00000000..97595adf --- /dev/null +++ b/src/main/java/com/jobtracker/service/status/LegacyStatusBackfill.java @@ -0,0 +1,63 @@ +package com.jobtracker.service.status; + +import com.jobtracker.entity.JobApplication; +import com.jobtracker.entity.enums.StatusMigrationState; +import com.jobtracker.repository.ApplicationRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +import java.util.EnumMap; +import java.util.List; +import java.util.Map; + +/** + * One-off, idempotent migration of legacy statuses into stage/outcome/waitingOn. Only rows that were never mapped are + * read, so restarts after the first run do nothing; new writes are mapped by ApplicationService (dual-write). + */ +@Component +public class LegacyStatusBackfill { + + private static final Logger log = LoggerFactory.getLogger(LegacyStatusBackfill.class); + + private final ApplicationRepository applicationRepository; + + public LegacyStatusBackfill(ApplicationRepository applicationRepository) { + this.applicationRepository = applicationRepository; + } + + @EventListener(ApplicationReadyEvent.class) + @Transactional + public int run() { + Map totals = new EnumMap<>(StatusMigrationState.class); + int migrated = 0; + List batch; + while (!(batch = applicationRepository.findTop500ByStatusMigrationIsNullOrderByIdAsc()).isEmpty()) { + int batchMigrated = 0; + for (JobApplication app : batch) { + StatusMapping mapping = LegacyStatusMapper.map( + app.getStatus(), app.getPreviousStatus(), app.isToSendLater(), app.getApplicationDate()); + int updated = applicationRepository.applyStatusMapping(app.getId(), mapping.stage(), mapping.outcome(), + mapping.waitingOn(), app.getStatus(), mapping.state()); + if (updated > 0) { + batchMigrated += updated; + totals.merge(mapping.state(), updated, Integer::sum); + log.debug("Legacy status mapped: id={} status={} previous={} -> {}", + app.getId(), app.getStatus(), app.getPreviousStatus(), mapping); + } + } + migrated += batchMigrated; + if (batchMigrated == 0) { + log.warn("Legacy status backfill stopped: a batch of {} rows made no progress", batch.size()); + break; + } + } + if (migrated > 0) { + log.info("Legacy status backfill migrated {} applications: {}", migrated, totals); + } + return migrated; + } +} diff --git a/src/test/java/com/jobtracker/unit/status/LegacyStatusBackfillTest.java b/src/test/java/com/jobtracker/unit/status/LegacyStatusBackfillTest.java new file mode 100644 index 00000000..ffcdd6f2 --- /dev/null +++ b/src/test/java/com/jobtracker/unit/status/LegacyStatusBackfillTest.java @@ -0,0 +1,86 @@ +package com.jobtracker.unit.status; + +import com.jobtracker.entity.JobApplication; +import com.jobtracker.entity.enums.ApplicationOutcome; +import com.jobtracker.entity.enums.ApplicationStage; +import com.jobtracker.entity.enums.StatusMigrationState; +import com.jobtracker.repository.ApplicationRepository; +import com.jobtracker.service.status.LegacyStatusBackfill; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.time.LocalDate; +import java.util.List; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class LegacyStatusBackfillTest { + + @Mock + private ApplicationRepository applicationRepository; + + private static JobApplication app(String status, String previous) { + JobApplication app = new JobApplication(); + app.setId(UUID.randomUUID()); + app.setStatus(status); + app.setPreviousStatus(previous); + app.setApplicationDate(LocalDate.of(2026, 10, 1)); + return app; + } + + @Test + void migratesEveryUnmappedRowInBatchesWithoutTouchingLegacyFields() { + JobApplication rejected = app("Ghosting", "Rejected"); + JobApplication ambiguous = app("Pending HR Response", null); + JobApplication assessment = app("Technical Test", null); + when(applicationRepository.findTop500ByStatusMigrationIsNullOrderByIdAsc()) + .thenReturn(List.of(rejected, ambiguous), List.of(assessment), List.of()); + when(applicationRepository.applyStatusMapping(any(), any(), any(), any(), any(), any())).thenReturn(1); + + int migrated = new LegacyStatusBackfill(applicationRepository).run(); + + assertThat(migrated).isEqualTo(3); + verify(applicationRepository).applyStatusMapping(rejected.getId(), ApplicationStage.APPLIED, + ApplicationOutcome.REJECTED, null, "Ghosting", StatusMigrationState.MAPPED); + verify(applicationRepository).applyStatusMapping(ambiguous.getId(), null, null, null, + "Pending HR Response", StatusMigrationState.NEEDS_REVIEW); + verify(applicationRepository).applyStatusMapping(assessment.getId(), ApplicationStage.ASSESSMENT, null, null, + "Technical Test", StatusMigrationState.MAPPED); + verify(applicationRepository, never()).save(any()); + verify(applicationRepository, never()).saveAll(any()); + assertThat(rejected.getStatus()).isEqualTo("Ghosting"); + assertThat(rejected.getPreviousStatus()).isEqualTo("Rejected"); + } + + @Test + void secondRunWritesNothing() { + when(applicationRepository.findTop500ByStatusMigrationIsNullOrderByIdAsc()).thenReturn(List.of()); + + int migrated = new LegacyStatusBackfill(applicationRepository).run(); + + assertThat(migrated).isZero(); + verify(applicationRepository, times(1)).findTop500ByStatusMigrationIsNullOrderByIdAsc(); + verify(applicationRepository, never()).applyStatusMapping(any(), any(), any(), any(), any(), any()); + } + + @Test + void stopsWhenABatchMakesNoProgress() { + JobApplication stuck = app("RH", null); + when(applicationRepository.findTop500ByStatusMigrationIsNullOrderByIdAsc()).thenReturn(List.of(stuck)); + when(applicationRepository.applyStatusMapping(any(), any(), any(), any(), any(), any())).thenReturn(0); + + int migrated = new LegacyStatusBackfill(applicationRepository).run(); + + assertThat(migrated).isZero(); + verify(applicationRepository, times(1)).findTop500ByStatusMigrationIsNullOrderByIdAsc(); + } +} From f74901ddc76931ae8d25d3dca57a8d67f23ffaea Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 18:38:29 +0000 Subject: [PATCH 06/24] feat(applications): dual-write stage/outcome on status changes and expose them in responses Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GfjfbQseka7Y3pN4sK32Pe --- .../dto/application/ApplicationResponse.java | 14 +++++- .../jobtracker/mapper/ApplicationMapper.java | 10 +++- .../service/ApplicationService.java | 2 + .../unit/ApplicationServiceTest.java | 49 ++++++++++++++++++- .../unit/mcp/McpAnalyticsToolsTest.java | 2 +- .../unit/mcp/McpApplicationToolsTest.java | 2 +- 6 files changed, 74 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/jobtracker/dto/application/ApplicationResponse.java b/src/main/java/com/jobtracker/dto/application/ApplicationResponse.java index 08ec82fe..fa8b2893 100644 --- a/src/main/java/com/jobtracker/dto/application/ApplicationResponse.java +++ b/src/main/java/com/jobtracker/dto/application/ApplicationResponse.java @@ -69,5 +69,17 @@ public record ApplicationResponse( LocalDateTime createdAt, @Schema(description = "Last update timestamp", example = "2024-06-05T12:30:00") @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") - LocalDateTime updatedAt + LocalDateTime updatedAt, + @Schema(description = "Funnel stage derived from the legacy status; null while the mapping needs review", + example = "ASSESSMENT", + allowableValues = {"DRAFT", "APPLIED", "RECRUITER_SCREEN", "HIRING_MANAGER", "ASSESSMENT", "INTERVIEW", "OFFER"}) + String stage, + @Schema(description = "Closing outcome, independent of stage and archival", example = "REJECTED", + allowableValues = {"HIRED", "REJECTED", "ROLE_CANCELLED", "WITHDREW"}) + String outcome, + @Schema(description = "Who the next move is waiting on", example = "COMPANY", allowableValues = {"COMPANY", "CANDIDATE"}) + String waitingOn, + @Schema(description = "MAPPED when stage/outcome were derived deterministically, NEEDS_REVIEW when the legacy status is ambiguous", + example = "MAPPED", allowableValues = {"MAPPED", "NEEDS_REVIEW"}) + String statusMigration ) {} diff --git a/src/main/java/com/jobtracker/mapper/ApplicationMapper.java b/src/main/java/com/jobtracker/mapper/ApplicationMapper.java index 10b97b65..e2d4f1f2 100644 --- a/src/main/java/com/jobtracker/mapper/ApplicationMapper.java +++ b/src/main/java/com/jobtracker/mapper/ApplicationMapper.java @@ -34,7 +34,15 @@ public ApplicationResponse toResponse(JobApplication app) { app.isToSendLater(), app.getInterviewCount(), app.getCreatedAt(), - app.getUpdatedAt() + app.getUpdatedAt(), + name(app.getStage()), + name(app.getOutcome()), + name(app.getWaitingOn()), + name(app.getStatusMigration()) ); } + + private static String name(Enum value) { + return value == null ? null : value.name(); + } } diff --git a/src/main/java/com/jobtracker/service/ApplicationService.java b/src/main/java/com/jobtracker/service/ApplicationService.java index 34072c3d..f95d128d 100644 --- a/src/main/java/com/jobtracker/service/ApplicationService.java +++ b/src/main/java/com/jobtracker/service/ApplicationService.java @@ -9,6 +9,7 @@ import com.jobtracker.repository.ApplicationRepository; import com.jobtracker.repository.ApplicationSpecifications; import com.jobtracker.repository.ApplicationStatusRepository; +import com.jobtracker.service.status.LegacyStatusMapper; import com.jobtracker.repository.InterviewEventRepository; import com.jobtracker.util.SecurityUtils; import io.micrometer.tracing.Span; @@ -354,6 +355,7 @@ private void applyStatusChange(JobApplication app, String newStatus) { app.setApplicationDate(null); app.setToSendLater(true); } + LegacyStatusMapper.apply(app); } private static boolean isRejectedOrGhosting(String status) { diff --git a/src/test/java/com/jobtracker/unit/ApplicationServiceTest.java b/src/test/java/com/jobtracker/unit/ApplicationServiceTest.java index 95ed68a8..a5391fa8 100644 --- a/src/test/java/com/jobtracker/unit/ApplicationServiceTest.java +++ b/src/test/java/com/jobtracker/unit/ApplicationServiceTest.java @@ -3,6 +3,10 @@ import com.jobtracker.dto.application.*; import com.jobtracker.entity.JobApplication; import com.jobtracker.entity.User; +import com.jobtracker.entity.enums.ApplicationOutcome; +import com.jobtracker.entity.enums.ApplicationStage; +import com.jobtracker.entity.enums.StatusMigrationState; +import org.mockito.ArgumentCaptor; import com.jobtracker.exception.BadRequestException; import com.jobtracker.exception.ResourceNotFoundException; import com.jobtracker.mapper.ApplicationMapper; @@ -343,6 +347,49 @@ void patch_shouldValidateStatusAgainstRepository() { verify(interviewMetricsService).recordStatusTransition(app, "RH", "Technical Test"); } + @Test + void create_dualWritesTheDerivedStage() { + when(securityUtils.getCurrentUser()).thenReturn(user); + when(applicationStatusRepository.existsByName("RH")).thenReturn(true); + when(applicationRepository.save(any(JobApplication.class))).thenAnswer(invocation -> invocation.getArgument(0)); + + applicationService.create(buildRequest()); + + ArgumentCaptor saved = ArgumentCaptor.forClass(JobApplication.class); + verify(applicationRepository).save(saved.capture()); + assertThat(saved.getValue().getStage()).isEqualTo(ApplicationStage.APPLIED); + assertThat(saved.getValue().getLegacyStatus()).isEqualTo("RH"); + assertThat(saved.getValue().getStatusMigration()).isEqualTo(StatusMigrationState.MAPPED); + } + + @Test + void updateStatus_rejectionKeepsTheLastStageAsOutcome() { + app.setStatus("Technical Test"); + when(securityUtils.getCurrentUserId()).thenReturn(USER_UUID); + when(applicationRepository.findByIdAndUserId(APP_UUID, USER_UUID)).thenReturn(Optional.of(app)); + when(applicationStatusRepository.existsByName("Rejected")).thenReturn(true); + when(applicationRepository.save(app)).thenReturn(app); + + applicationService.updateStatus(APP_UUID, new UpdateStatusRequest("Rejected")); + + assertThat(app.getStage()).isEqualTo(ApplicationStage.ASSESSMENT); + assertThat(app.getOutcome()).isEqualTo(ApplicationOutcome.REJECTED); + assertThat(app.getLegacyStatus()).isEqualTo("Rejected"); + } + + @Test + void patch_clearingStatus_dualWritesDraft() { + stubPatchLookup(); + ApplicationPatchRequest request = new ApplicationPatchRequest(); + request.setStatus(null); + + applicationService.patch(APP_UUID, request); + + assertThat(app.getStage()).isEqualTo(ApplicationStage.DRAFT); + assertThat(app.getOutcome()).isNull(); + assertThat(app.getStatusMigration()).isEqualTo(StatusMigrationState.MAPPED); + } + @Test void patch_applicationDateOnly_keepsStatusWithoutRevalidatingIt() { LocalDate newDate = LocalDate.now().minusDays(5); @@ -605,6 +652,6 @@ private ApplicationResponse buildApplicationResponse(UUID id) { return new ApplicationResponse(id, "Software Engineer", "Recruiter", "HR", "https://example.com/job", LocalDate.now(), false, false, null, "RH", null, false, LocalDateTime.now(), "Follow up this week", null, false, null, null, null, null, null, null, - false, 0, LocalDateTime.now(), LocalDateTime.now()); + false, 0, LocalDateTime.now(), LocalDateTime.now(), null, null, null, null); } } diff --git a/src/test/java/com/jobtracker/unit/mcp/McpAnalyticsToolsTest.java b/src/test/java/com/jobtracker/unit/mcp/McpAnalyticsToolsTest.java index 094ecd2e..6d907340 100644 --- a/src/test/java/com/jobtracker/unit/mcp/McpAnalyticsToolsTest.java +++ b/src/test/java/com/jobtracker/unit/mcp/McpAnalyticsToolsTest.java @@ -259,6 +259,6 @@ private static ApplicationResponse applicationResponseWithId(UUID id) { null, false, null, null, null, null, null, null, - false, 0, null, null); + false, 0, null, null, null, null, null, null); } } diff --git a/src/test/java/com/jobtracker/unit/mcp/McpApplicationToolsTest.java b/src/test/java/com/jobtracker/unit/mcp/McpApplicationToolsTest.java index c5526174..8db6b97d 100644 --- a/src/test/java/com/jobtracker/unit/mcp/McpApplicationToolsTest.java +++ b/src/test/java/com/jobtracker/unit/mcp/McpApplicationToolsTest.java @@ -425,6 +425,6 @@ private static ApplicationResponse applicationResponseWithId(UUID id) { null, false, null, null, null, null, null, null, - false, 0, null, null); + false, 0, null, null, null, null, null, null); } } From 5669561b77e698a439925ff110ecc97a4b92e8cc Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 18:39:06 +0000 Subject: [PATCH 07/24] docs(mcp): give each status a meaning and one rule for RH; fix Swagger status values Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GfjfbQseka7Y3pN4sK32Pe --- .../dto/application/ApplicationRequest.java | 4 ++-- .../dto/application/ApplicationResponse.java | 4 ++-- .../dto/application/UpdateStatusRequest.java | 4 ++-- .../com/jobtracker/mcp/McpPromptsConfig.java | 4 ++-- .../McpApplicationCreationRulesResource.java | 6 +++-- .../McpApplicationStatusesResource.java | 22 +++++++++++++++++-- 6 files changed, 32 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/jobtracker/dto/application/ApplicationRequest.java b/src/main/java/com/jobtracker/dto/application/ApplicationRequest.java index 27f1a5ed..d6c06091 100644 --- a/src/main/java/com/jobtracker/dto/application/ApplicationRequest.java +++ b/src/main/java/com/jobtracker/dto/application/ApplicationRequest.java @@ -42,8 +42,8 @@ public record ApplicationRequest( @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") LocalDateTime nextStepDateTime, - @Schema(description = "Application status", example = "APPLIED", - allowableValues = {"RH", "Fiz a RH - Aguardando Atualização", "Fiz a Hiring Manager - Aguardando Atualização", "Teste Técnico", "Fiz teste Técnico - aguardando atualização", "RH (Negociação)", "Rejeitado", "Tarde demais", "Ghosting"}) + @Schema(description = "Application status", example = "RH", + allowableValues = {"RH", "Pending HR Response", "Pending Hiring Manager Response", "Technical Test", "Pending Technical Test Response", "Offer Negotiation", "Ghosting", "Rejected", "Approved", "TO_SEND_LATER"}) String status, @Schema(description = "Whether a DM reminder to the recruiter is enabled", example = "true") diff --git a/src/main/java/com/jobtracker/dto/application/ApplicationResponse.java b/src/main/java/com/jobtracker/dto/application/ApplicationResponse.java index fa8b2893..682c2daa 100644 --- a/src/main/java/com/jobtracker/dto/application/ApplicationResponse.java +++ b/src/main/java/com/jobtracker/dto/application/ApplicationResponse.java @@ -31,9 +31,9 @@ public record ApplicationResponse( @Schema(description = "Next step date/time", example = "2024-06-10T14:00:00") @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") LocalDateTime nextStepDateTime, - @Schema(description = "Application status", example = "APPLIED") + @Schema(description = "Legacy application status display name", example = "RH") String status, - @Schema(description = "Previous application status before Rejeitado or Ghosting", example = "Teste Técnico") + @Schema(description = "Previous application status before Rejected or Ghosting", example = "Technical Test") String previousStatus, @Schema(description = "Whether a recruiter DM reminder is enabled", example = "true") boolean recruiterDmReminderEnabled, diff --git a/src/main/java/com/jobtracker/dto/application/UpdateStatusRequest.java b/src/main/java/com/jobtracker/dto/application/UpdateStatusRequest.java index 06badfac..0de9ca99 100644 --- a/src/main/java/com/jobtracker/dto/application/UpdateStatusRequest.java +++ b/src/main/java/com/jobtracker/dto/application/UpdateStatusRequest.java @@ -4,7 +4,7 @@ @Schema(description = "Request to update the status of a job application") public record UpdateStatusRequest( - @Schema(description = "New application status", example = "Teste Técnico", - allowableValues = {"RH", "Fiz a RH - Aguardando Atualização", "Fiz a Hiring Manager - Aguardando Atualização", "Teste Técnico", "Fiz teste Técnico - aguardando atualização", "RH (Negociação)", "Rejeitado", "Tarde demais", "Ghosting"}) + @Schema(description = "New application status", example = "Technical Test", + allowableValues = {"RH", "Pending HR Response", "Pending Hiring Manager Response", "Technical Test", "Pending Technical Test Response", "Offer Negotiation", "Ghosting", "Rejected", "Approved", "TO_SEND_LATER"}) String status ) {} diff --git a/src/main/java/com/jobtracker/mcp/McpPromptsConfig.java b/src/main/java/com/jobtracker/mcp/McpPromptsConfig.java index 94b283a5..cd60aa4e 100644 --- a/src/main/java/com/jobtracker/mcp/McpPromptsConfig.java +++ b/src/main/java/com/jobtracker/mcp/McpPromptsConfig.java @@ -153,8 +153,8 @@ public GetPromptResult prepareNewApplicationPrompt( Read %s for field defaults before calling Create-Application. Ask me for any missing required fields (rhAcceptedConnection, interviewScheduled, recruiterDmReminderEnabled), - then call Create-Application with the complete data. Use status "RH" for a standard - LinkedIn/HR cold outreach. + then call Create-Application with the complete data. Use status "RH" once the application + was sent; omit status only if it is still a draft. """.formatted( valueOrDefault(vacancyName), valueOrDefault(recruiterName), diff --git a/src/main/java/com/jobtracker/mcp/resources/McpApplicationCreationRulesResource.java b/src/main/java/com/jobtracker/mcp/resources/McpApplicationCreationRulesResource.java index cecc2d59..6dc1643b 100644 --- a/src/main/java/com/jobtracker/mcp/resources/McpApplicationCreationRulesResource.java +++ b/src/main/java/com/jobtracker/mcp/resources/McpApplicationCreationRulesResource.java @@ -11,7 +11,7 @@ @Service public class McpApplicationCreationRulesResource { - private static final String LAST_MODIFIED = "2026-07-29"; + private static final String LAST_MODIFIED = "2026-11-30"; @McpResource( uri = McpResourcesConfig.URI_APPLICATION_CREATION_RULES, @@ -65,7 +65,9 @@ Always confirm to the user, explicitly, that the vacancy was registered (or that - applicationDate: always today's date in yyyy-MM-dd format. Never the vacancy posting date. - nextStepDateTime: do not auto-fill. Set only when the user explicitly provides it. - - status: omit (null) for a fresh cold outreach. Use "RH" only when already in process. + - status: "RH" once the application was actually sent (manually, by email or automatically, e.g. + DevScout); it does not imply any recruiter contact. Omit (null) only for a draft not sent yet. + Never use "Pending HR Response" for a fresh application or an automatic acknowledgement. - recruiterDmReminderEnabled: true only when a recruiter email or contact exists. - rhAcceptedConnection: false unless the LinkedIn connection is confirmed accepted. - interviewScheduled: false unless an interview is confirmed. diff --git a/src/main/java/com/jobtracker/mcp/resources/McpApplicationStatusesResource.java b/src/main/java/com/jobtracker/mcp/resources/McpApplicationStatusesResource.java index 159429fb..bc71db34 100644 --- a/src/main/java/com/jobtracker/mcp/resources/McpApplicationStatusesResource.java +++ b/src/main/java/com/jobtracker/mcp/resources/McpApplicationStatusesResource.java @@ -10,10 +10,23 @@ import org.springframework.ai.mcp.annotation.McpResource.McpAnnotations; import org.springframework.stereotype.Service; +import java.util.Map; + @Service public class McpApplicationStatusesResource { - private static final String LAST_MODIFIED = "2026-06-08"; + private static final String LAST_MODIFIED = "2026-11-30"; + + private static final Map MEANINGS = Map.of( + "RH", "application sent (manual or automatic); no recruiter contact implied", + "Pending HR Response", "a human recruiter contacted or screened the candidate and a reply is pending; never for automatic acknowledgements", + "Pending Hiring Manager Response", "the candidate talked to the hiring manager and a reply is pending", + "Technical Test", "assessment received or in progress", + "Pending Technical Test Response", "assessment submitted, waiting for feedback", + "Offer Negotiation", "offer received or being negotiated; not an acceptance", + "Ghosting", "no reply after follow-ups", + "Rejected", "the company explicitly rejected the candidate; if the role was cancelled, say so in the note", + "Approved", "hired: offer accepted and confirmed"); private final ApplicationStatusRepository applicationStatusRepository; @@ -42,7 +55,12 @@ Use the exact names below (case-sensitive). Call List-Statuses or \ """); for (ApplicationStatusEntity status : applicationStatusRepository.findAllByOrderByDisplayOrderAsc()) { - text.append("- ").append(status.getName()).append('\n'); + text.append("- ").append(status.getName()); + String meaning = MEANINGS.get(status.getName()); + if (meaning != null) { + text.append(" — ").append(meaning); + } + text.append('\n'); } text.append("\nOmit status (pass null) when logging a draft/to-send-later application.\n"); From f335e0203c6b0ae137e3a43d0f76953239ad4f39 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 18:59:40 +0000 Subject: [PATCH 08/24] docs: phase 1 implementation plan for the status model (#108) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GfjfbQseka7Y3pN4sK32Pe --- ...6-11-30-application-status-model-phase1.md | 120 ++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 docs/superpowers/plans/2026-11-30-application-status-model-phase1.md diff --git a/docs/superpowers/plans/2026-11-30-application-status-model-phase1.md b/docs/superpowers/plans/2026-11-30-application-status-model-phase1.md new file mode 100644 index 00000000..f0a98386 --- /dev/null +++ b/docs/superpowers/plans/2026-11-30-application-status-model-phase1.md @@ -0,0 +1,120 @@ +# Application Status Model — Phase 1 Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Stop the nightly scheduler from corrupting outcomes, add the approved stage/outcome/waitingOn model alongside the legacy `status` (expand + dual-write), and migrate every record whose mapping is deterministic, flagging the rest `NEEDS_REVIEW`. + +**Architecture:** Legacy `status` stays the write contract (API, MCP, frontend unchanged). A pure `LegacyStatusMapper` derives `stage`/`outcome`/`waitingOn`/`statusMigration` from the legacy fields; `ApplicationService` and the scheduler call it on every status change (dual-write), and a startup backfill runs it once over rows not yet mapped. One rule set, unit-tested, no SQL duplicate. + +**Tech Stack:** Spring Boot 4, JPA/Hibernate, Flyway (PostgreSQL only — `db/migration/postgresql`), JUnit 5 + Mockito. + +**Spec:** `docs/superpowers/specs/2026-11-30-application-status-model-rfc.md` + +## Global Constraints + +- Never overwrite or delete `status`, `previous_status`, interview fields or `archived` during migration; `legacy_status` is an exact copy of `status`. +- Never invent dates, activities, `waiting_since` or an outcome that the legacy data does not state. +- Ambiguous legacy values map to `statusMigration = NEEDS_REVIEW` with `stage`/`outcome`/`waitingOn` null. +- Stable keys: stages `DRAFT, APPLIED, RECRUITER_SCREEN, HIRING_MANAGER, ASSESSMENT, INTERVIEW, OFFER`; outcomes `HIRED, REJECTED, ROLE_CANCELLED, WITHDREW`; waitingOn `COMPANY, CANDIDATE`; migration `MAPPED, NEEDS_REVIEW`. +- Flyway migrations go only in `src/main/resources/db/migration/postgresql/` (prod/dev locations); next version is `V40`. + +## Review Focus + +- Case/whitespace variants of legacy values (`rejected`, ` RH `) — expected to map like the canonical value. Test in Task 2. +- `Ghosting` whose `previous_status` is itself `Ghosting` or unknown text — expected `NEEDS_REVIEW`, no loop. Test in Task 2. +- Archived rows older than a month — expected untouched by the scheduler. Test in Task 3. +- Backfill rerun on restart — expected zero writes the second time. Test in Task 4. +- API clients that ignore the new response fields — expected no breaking change (fields are additive, `NON_NULL`). Covered by Task 5 mapper test. + +--- + +### Task 1: Model enums + schema expand + +**Files:** +- Create: `src/main/java/com/jobtracker/entity/enums/ApplicationStage.java`, `ApplicationOutcome.java`, `WaitingOn.java`, `StatusMigrationState.java` +- Create: `src/main/resources/db/migration/postgresql/V40__add_application_stage_outcome.sql` +- Modify: `src/main/java/com/jobtracker/entity/JobApplication.java` (fields + getters/setters) +- Delete: `src/main/java/com/jobtracker/entity/enums/ApplicationStatus.java` (unused) + +**Interfaces — Produces:** `JobApplication#get/setStage(ApplicationStage)`, `get/setOutcome(ApplicationOutcome)`, `get/setWaitingOn(WaitingOn)`, `get/setLegacyStatus(String)`, `get/setStatusMigration(StatusMigrationState)`; all `@Enumerated(STRING)`, nullable. + +- [ ] Migration adds nullable `stage VARCHAR(32)`, `outcome VARCHAR(32)`, `waiting_on VARCHAR(16)`, `legacy_status VARCHAR(100)`, `status_migration VARCHAR(16)` plus `CREATE INDEX idx_app_status_migration ON job_applications (status_migration)`. No data changes in SQL. +- [ ] `mvn -q -DskipTests compile` passes. Commit. + +### Task 2: `LegacyStatusMapper` + +**Files:** Create `src/main/java/com/jobtracker/service/status/LegacyStatusMapper.java`, `StatusMapping.java`; Test `src/test/java/com/jobtracker/unit/status/LegacyStatusMapperTest.java` + +**Interfaces — Produces:** +- `record StatusMapping(ApplicationStage stage, ApplicationOutcome outcome, WaitingOn waitingOn, StatusMigrationState state, String rule)` +- `static StatusMapping LegacyStatusMapper.map(String status, String previousStatus, boolean toSendLater, LocalDate applicationDate)` +- `static void LegacyStatusMapper.apply(JobApplication app)` — sets the five new fields (`legacyStatus = status`). + +Rules (lookup by trimmed, case-insensitive value; aliases = V29 label, enum display name, enum constant name): + +| Legacy | Result | +|---|---| +| null + `toSendLater` + no date | `DRAFT` MAPPED | +| null otherwise | NEEDS_REVIEW | +| `RH` with date | `APPLIED` | +| `RH` without date | NEEDS_REVIEW | +| `Pending HR Response`, `RH (Negociação)`/`RH_NEGOCIACAO`, `Tarde demais`/`TARDE_DEMAIS`, `Approved`, unknown | NEEDS_REVIEW | +| `Pending Hiring Manager Response`, `FIZ_A_HIRING_MANAGER_AGUARDANDO_ATUALIZACAO` + label | `HIRING_MANAGER` + `COMPANY` | +| `FIZ_A_RH_AGUARDANDO_ATUALIZACAO` + label | `RECRUITER_SCREEN` + `COMPANY` | +| `Technical Test`, `TESTE_TECNICO`, `Teste Técnico` | `ASSESSMENT` | +| `Pending Technical Test Response`, `FIZ_TESTE_TECNICO_AGUARDANDO_ATUALIZACAO` + label | `ASSESSMENT` + `COMPANY` | +| `ENTREVISTA_MARCADA`, `Entrevista marcada` | `INTERVIEW` | +| `Offer Negotiation` | `OFFER` | +| Rejected family (`Rejected`, `REJEITADO`, `Rejeitado`), no date, no previous | `DRAFT` (scheduler-expired draft signature; API forbids status without date) | +| Rejected family, previous maps to a non-terminal stage | that stage + `REJECTED` | +| Rejected family otherwise (has date) | `APPLIED` + `REJECTED` (last stage proven by the date) | +| Ghosting family, previous in Rejected family, has date | `APPLIED` + `REJECTED` | +| Ghosting family, previous maps to a non-terminal MAPPED stage | that stage + `COMPANY`, no outcome | +| Ghosting family otherwise | NEEDS_REVIEW | + +- [ ] Write parameterized tests covering every row above plus the Review Focus cases (`" rejected "`, Ghosting→Ghosting). Run `mvn -q test -Dtest=LegacyStatusMapperTest` → FAIL (class missing). +- [ ] Implement; rerun → PASS. Commit. + +### Task 3: Scheduler hotfix + dual-write there + +**Files:** Modify `tasks/StaleApplicationsScheduler.java`, `repository/ApplicationRepository.java`; Test `unit/StaleApplicationsSchedulerTest.java` + +**Interfaces — Consumes:** `LegacyStatusMapper.apply`. +**Produces:** `ApplicationRepository#findStaleActiveApplications(Collection excludedStatuses, LocalDateTime updatedBefore)` — JPQL: `status IS NOT NULL AND status NOT IN :excluded AND archived = false AND updatedAt < :before`. + +- [ ] Tests: drafts older than a week are not touched (`findByStatusIsNullAndUpdatedAtBefore` never called); terminal set passed to the query contains every Rejected/Ghosting/Approved/Tarde demais alias; a stale `Technical Test` becomes `Ghosting` with `previousStatus=Technical Test`, `stage=ASSESSMENT`, `waitingOn=COMPANY`. +- [ ] Remove the draft→Rejected branch; replace the ghosting query; call `LegacyStatusMapper.apply` after setting `Ghosting`. Drop the now-unused repository methods. Tests PASS. Commit. + +### Task 4: Startup backfill + +**Files:** Create `service/status/LegacyStatusBackfill.java`; Modify `ApplicationRepository` (`findTop500ByStatusMigrationIsNull()` + `countByStatusMigrationIsNull()`); Test `unit/status/LegacyStatusBackfillTest.java` + +- [ ] `@EventListener(ApplicationReadyEvent.class) @Transactional public int run()` loops batches of 500 from `findTop500ByStatusMigrationIsNull`, applies the mapper, `saveAll`, logs counts per state; returns rows migrated. Rows are selected by `status_migration IS NULL`, so a second run writes nothing. Must not change `updatedAt` semantics for ghosting: set `updatedAt` back to its previous value before save is not possible with `@PreUpdate`, so use a bulk JPQL `UPDATE` per row instead of entity save (`ApplicationRepository#applyStatusMapping(UUID id, stage, outcome, waitingOn, legacyStatus, migration)` with `@Modifying`), leaving `updated_at` untouched. +- [ ] Tests: two batches then empty → returns total and calls `applyStatusMapping` once per row; second invocation with empty page writes nothing. PASS. Commit. + +### Task 5: Dual-write in `ApplicationService` + API exposure + +**Files:** Modify `service/ApplicationService.java` (`applyStatusChange` end → `LegacyStatusMapper.apply(app)`; also after `mapRequestToEntity`/patch date changes since `RH` depends on the date), `dto/application/ApplicationResponse.java` (append `String stage, String outcome, String waitingOn, String statusMigration`), `mapper/ApplicationMapper.java`, positional constructors in `ApplicationServiceTest`, `McpAnalyticsToolsTest`, `McpApplicationToolsTest`. + +- [ ] Tests in `ApplicationServiceTest`: create with `RH` + date → entity `stage=APPLIED`, `statusMigration=MAPPED`, `legacyStatus=RH`; updateStatus to `Rejected` from `Technical Test` → `stage=ASSESSMENT`, `outcome=REJECTED`; patch status null → `DRAFT`. +- [ ] Implement; `mvn -q test -Dtest='ApplicationServiceTest,Mcp*Test'` PASS. Commit. + +### Task 6: Contract hygiene (MCP + Swagger) + +**Files:** `dto/application/ApplicationRequest.java`, `UpdateStatusRequest.java` (allowableValues = the nine V29 names + `TO_SEND_LATER`), `mcp/McpPromptsConfig.java`, `mcp/resources/McpApplicationCreationRulesResource.java`, `mcp/resources/McpApplicationStatusesResource.java` (bump `LAST_MODIFIED`, add one-line meaning per status). + +Single rule everywhere: *`RH` = application sent (manual or automatic), no human recruiter contact implied. Omit status only for drafts not yet sent. Never use `Pending HR Response` unless a human recruiter actually replied.* + +- [ ] Update tests asserting these strings (`McpApplicationCreationRulesResourceTest`, `McpPromptsConfigTest`); PASS. Commit. + +### Task 7: n8n workflow `Candidaturas enviadas → Applywell` + +- [ ] Replace "call List-Statuses once and use a valid status from its result" with: `status` must be exactly `"RH"`; remove `List-Statuses` from the tool list. Validate, publish, re-read to confirm. + +### Task 8: Verification + +- [ ] `mvn -B -ntp verify` locally for unit tests (integration tests need Docker → CI). Push, watch CI. + +## Out of scope (needs brainstorm) + +Frontend consumption of `stage`/`outcome`, a `NEEDS_REVIEW` review UI, new MCP tools (`Set-Application-Stage`, `Close-Application`), metrics/dashboard/gamification on the new model, activities table, computed ghosting indicator, contract phase. From 878795af7c32eec5a63ffc104eb0244419406322 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 19:01:02 +0000 Subject: [PATCH 09/24] fix: keep ApplicationStatus enum, now used by assistant status aliases from main Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GfjfbQseka7Y3pN4sK32Pe --- ...6-11-30-application-status-model-phase1.md | 2 +- .../entity/enums/ApplicationStatus.java | 39 +++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/jobtracker/entity/enums/ApplicationStatus.java diff --git a/docs/superpowers/plans/2026-11-30-application-status-model-phase1.md b/docs/superpowers/plans/2026-11-30-application-status-model-phase1.md index f0a98386..4db61b86 100644 --- a/docs/superpowers/plans/2026-11-30-application-status-model-phase1.md +++ b/docs/superpowers/plans/2026-11-30-application-status-model-phase1.md @@ -34,7 +34,7 @@ - Create: `src/main/java/com/jobtracker/entity/enums/ApplicationStage.java`, `ApplicationOutcome.java`, `WaitingOn.java`, `StatusMigrationState.java` - Create: `src/main/resources/db/migration/postgresql/V40__add_application_stage_outcome.sql` - Modify: `src/main/java/com/jobtracker/entity/JobApplication.java` (fields + getters/setters) -- Delete: `src/main/java/com/jobtracker/entity/enums/ApplicationStatus.java` (unused) +- Keep: `entity/enums/ApplicationStatus.java` — since #119 the assistant query repository uses it for status aliases. **Interfaces — Produces:** `JobApplication#get/setStage(ApplicationStage)`, `get/setOutcome(ApplicationOutcome)`, `get/setWaitingOn(WaitingOn)`, `get/setLegacyStatus(String)`, `get/setStatusMigration(StatusMigrationState)`; all `@Enumerated(STRING)`, nullable. diff --git a/src/main/java/com/jobtracker/entity/enums/ApplicationStatus.java b/src/main/java/com/jobtracker/entity/enums/ApplicationStatus.java new file mode 100644 index 00000000..c0728d13 --- /dev/null +++ b/src/main/java/com/jobtracker/entity/enums/ApplicationStatus.java @@ -0,0 +1,39 @@ +package com.jobtracker.entity.enums; + +public enum ApplicationStatus { + RH("RH", "Initial HR outreach stage."), + ENTREVISTA_MARCADA("Entrevista marcada", "An interview has been scheduled."), + FIZ_A_RH_AGUARDANDO_ATUALIZACAO("Fiz a RH - Aguardando Atualização", "HR contact has happened and a reply is pending."), + FIZ_A_HIRING_MANAGER_AGUARDANDO_ATUALIZACAO("Fiz a Hiring Manager - Aguardando Atualização", "Hiring manager contact has happened and a reply is pending."), + TESTE_TECNICO("Teste Técnico", "Technical test phase."), + FIZ_TESTE_TECNICO_AGUARDANDO_ATUALIZACAO("Fiz teste Técnico - aguardando atualização", "Technical test has been sent and feedback is pending."), + RH_NEGOCIACAO("RH (Negociação)", "Recruiter negotiation or offer discussion."), + REJEITADO("Rejeitado", "Application was rejected."), + TARDE_DEMAIS("Tarde demais", "The opportunity was missed or closed too late."), + GHOSTING("Ghosting", "No response after follow-up attempts."); + + private final String displayName; + private final String description; + + ApplicationStatus(String displayName, String description) { + this.displayName = displayName; + this.description = description; + } + + public String getDisplayName() { + return displayName; + } + + public String getDescription() { + return description; + } + + public static ApplicationStatus fromDisplayName(String displayName) { + for (ApplicationStatus status : values()) { + if (status.displayName.equalsIgnoreCase(displayName)) { + return status; + } + } + throw new IllegalArgumentException("Unknown status: " + displayName); + } +} From 8d1d2547599acc642692bade82636da59936371a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 19:31:37 +0000 Subject: [PATCH 10/24] docs: design for the stage/outcome cutover (#108) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GfjfbQseka7Y3pN4sK32Pe --- ...12-01-application-status-cutover-design.md | 174 ++++++++++++++++++ 1 file changed, 174 insertions(+) create mode 100644 docs/superpowers/specs/2026-12-01-application-status-cutover-design.md diff --git a/docs/superpowers/specs/2026-12-01-application-status-cutover-design.md b/docs/superpowers/specs/2026-12-01-application-status-cutover-design.md new file mode 100644 index 00000000..aae01fec --- /dev/null +++ b/docs/superpowers/specs/2026-12-01-application-status-cutover-design.md @@ -0,0 +1,174 @@ +# Virada para o modelo de etapa/resultado — design + +- **Issue:** #108 · **Base:** RFC `2026-11-30-application-status-model-rfc.md` e fase 1 (PR #117, não mergeado) +- **Data:** 2026-12-01 +- **Repos:** backend (`SpringBoot-JobApplyTracker`) e frontend (`React-JobApplyTracker`) + +## 1. Intenção + +O mantenedor não quer fila nem tela de revisão. A migração converte o que der, em melhor esforço. O que não converter fica exatamente como está e só é cobrado quando alguém editar o registro. A partir da virada, **todo mundo grava e lê o modelo novo** (etapa + resultado + aguardando): formulário web, API REST, MCP (ChatGPT), assistente e n8n. Assim os números param de mentir: vaga cancelada deixa de contar como rejeição, e ghosting passa a significar "a empresa sumiu", não "faz 30 dias que ninguém editou". + +### Objetivos +- Modelo novo vira a fonte da verdade de leitura e escrita em todos os consumidores. +- Conversão de melhor esforço com as regras da §3. Sem estado `NEEDS_REVIEW`. +- Registro não convertido aparece com o rótulo antigo. Ao salvar uma edição de conteúdo, exige etapa. +- Ghosting calculado, nunca gravado. + +### Não-objetivos +- Tela ou fila de revisão. +- Tabela de atividades (contatos, entrevistas individuais), datas de entrada em etapa, follow-ups. +- Mudar o que a gamificação recompensa (só troca a fonte do sinal). +- Remover a coluna `status` do banco (fica para a fase de limpeza). + +### Anti-objetivos (falha mesmo que "funcione") +- A conversão inventar um resultado que o dado não sustenta: `Approved` é exceção explícita do mantenedor. +- Uma automação (n8n/ChatGPT) gravar um registro sem etapa. +- Números do dashboard mudarem sem explicação: o PR precisa listar o que muda. +- Ghosting aparecer em candidatura encerrada, arquivada ou em rascunho. + +## 2. Abordagens consideradas + +| | Descrição | Troca | Decisão | +|---|---|---|---| +| A | Modelo novo + sincronizar status antigo de volta | Menor, mas a tradução reversa mente (cancelada→Rejected) | Descartada | +| **B** | **Virada completa: todos os consumidores leem e gravam os campos novos; `status` vira só leitura** | Maior entrega, números corretos de uma vez | **Escolhida pelo mantenedor** | +| C | Híbrido: migra o visível, sincroniza o resto | Dois mundos por mais tempo | Descartada | + +Entrega em dois PRs: backend primeiro (aceita status antigo exato durante a transição, então o frontend atual não quebra) e depois o frontend. + +## 3. Regras de conversão (decididas com o mantenedor) + +Chave = valor trimado, sem diferenciar maiúsculas; aliases = rótulo V29, `displayName` do enum, nome da constante. + +| Legado | Etapa | Resultado | Aguardando | +|---|---|---|---| +| `NULL` + `to_send_later` + sem data | DRAFT | — | — | +| `RH` com data | APPLIED | — | — | +| `Pending HR Response` | RECRUITER_SCREEN | — | COMPANY | +| `Pending Hiring Manager Response`, `FIZ_A_HIRING_MANAGER_*` | HIRING_MANAGER | — | COMPANY | +| `FIZ_A_RH_*` | RECRUITER_SCREEN | — | COMPANY | +| `Technical Test`, `TESTE_TECNICO` | ASSESSMENT | — | — | +| `Pending Technical Test Response`, `FIZ_TESTE_TECNICO_*` | ASSESSMENT | — | COMPANY | +| `ENTREVISTA_MARCADA` | INTERVIEW | — | — | +| `Offer Negotiation`, `RH (Negociação)`, `RH_NEGOCIACAO` | OFFER | — | — | +| `Approved` | OFFER | HIRED | — | +| `Tarde demais`, `TARDE_DEMAIS` | APPLIED se tem data, senão DRAFT | WITHDREW | — | +| `Rejected`, `REJEITADO`, `Rejeitado` sem data e sem anterior | DRAFT (rascunho expirado pelo scheduler antigo) | — | — | +| Rejected-família, anterior com etapa aberta | etapa do anterior | REJECTED | — | +| Rejected-família, demais | APPLIED | REJECTED | — | +| `Ghosting`, anterior = encerramento (Rejected/Approved/Tarde demais) | aplica a regra do anterior | idem | — | +| `Ghosting`, anterior = etapa aberta | etapa do anterior | — | COMPANY | +| `Ghosting`, sem anterior ou anterior não mapeável, com data | APPLIED | — | COMPANY | +| Qualquer outro caso (desconhecido, `RH` sem data, rascunho inconsistente, Ghosting sem data) | **não convertido** | | | + +Vaga cancelada (`ROLE_CANCELLED`) nunca vem da conversão: o legado `Rejected` misturava as duas coisas, e quem separa é a edição manual. + +## 4. Modelo e persistência + +- Colunas novas (já no V40 do PR #117, que ainda não foi para produção, então **o V40 é reescrito, não somado**): `stage`, `outcome`, `waiting_on`, `legacy_status`. **`status_migration` sai.** +- **Não convertido** ⇔ `stage IS NULL AND legacy_status IS NOT NULL`. **Nunca tentado** ⇔ `legacy_status IS NULL` (o backfill usa isso para ser idempotente). +- `status` (coluna antiga) fica congelado: não é mais escrito nem lido por regra de negócio. Serve só para exibir o rótulo de registro não convertido, via `legacy_status`. +- Registros criados depois da virada têm `status` e `legacy_status` nulos e `stage` preenchido. Nenhum código pode voltar a interpretar `status IS NULL` como rascunho. *(Decisão minha.)* +- `to_send_later` passa a ser derivado: `stage == DRAFT`. Continua gravado enquanto existir, para não quebrar índices e consultas nativas. +- `applicationDate`: obrigatória para qualquer etapa ≠ DRAFT (mesma regra de hoje, trocando "status" por "etapa"). Mudar para DRAFT limpa a data. +- Restrições de consistência (validadas no serviço, sem CHECK no banco): + - `outcome` só existe com `stage` não nulo. DRAFT aceita `outcome` apenas `WITHDREW`. + - `HIRED` exige `stage = OFFER`. + - `waitingOn` é ignorado (gravado nulo) quando há `outcome` ou `stage = DRAFT`. + +## 5. Ghosting calculado + +`isGhosting = stage != null && stage != DRAFT && outcome == null && waitingOn != CANDIDATE && !archived && updatedAt < now - 30 dias` + +- `waitingOn` nulo conta como aguardando a empresa. Só `CANDIDATE` tira a candidatura do ghosting. +- Exposto no `ApplicationResponse` como `ghosting: boolean`. Contado no dashboard e nas métricas com a mesma regra, numa query só (JPQL) para não divergir. +- **O scheduler noturno é removido.** Nada é gravado. +- Limite de 30 dias numa constante de configuração (`app.applications.ghosting-after-days`, default 30). + +## 6. Contrato de escrita (API REST e MCP) + +Campos novos nos requests `ApplicationRequest` (PUT/POST), `ApplicationPatchRequest` e no novo `UpdateStageRequest`: `stage`, `outcome`, `waitingOn`. + +Resolução da etapa em cada escrita de conteúdo: +1. Veio `stage` (com ou sem `outcome`/`waitingOn`) → usa. +2. Senão, veio `status` legado → passa pelo conversor da §3. Se converter, usa. Se não converter, **400** com mensagem dizendo para enviar `stage`. +3. Senão (não mexeu em status/etapa) → mantém a etapa atual. **Se o registro está não convertido, 400** ("este registro usa um status antigo; informe a etapa"). Essa é a regra "editar e salvar obriga escolher". + +Operações que **não** exigem etapa mesmo em registro não convertido, porque não são "editar e salvar": arquivar/restaurar, marcar DM enviada, ligar/desligar lembrete, excluir, gerar currículo/rascunho de e-mail. *(Decisão minha: bloquear essas ações prenderia o usuário sem motivo.)* + +Endpoints: +- `PATCH /applications/{id}/status` continua existindo (aceita legado convertível) e ganha o irmão `PATCH /applications/{id}/stage` com `{stage, outcome?, waitingOn?}`. +- `GET /applications/statuses` continua (compat). Novo `GET /applications/stages` devolve o catálogo `{stages:[{key,label}], outcomes:[...], waitingOn:[...]}` com rótulos PT-BR, para o front e o MCP não hardcodarem. +- Filtros (`ApplicationFilter`, `ExportFilters`, busca do assistente): ganham `stage`, `outcome`, `ghosting`. O filtro `status` antigo continua aceito: converte para etapa/resultado pelo conversor e filtra nos campos novos. `TO_SEND_LATER` vira `stage=DRAFT`. + +MCP: +- `Create-Application`, `Update-Application`, `Patch-Application`: novos parâmetros `stage`, `outcome`, `waitingOn`. Descrição deixa claro que `status` é legado. +- Novo `Update-Application-Stage` (substitui o uso de `Update-Application-Status`, que segue funcionando para legado convertível). Mesma regra de rejeição do atual: mudar resultado não arquiva. +- `List-Statuses` passa a devolver o catálogo novo com o significado de cada valor (texto da RFC §3.1). Os recursos `Application Statuses` e `Application Creation Rules` são reescritos para o modelo novo (APPLIED = enviado, sem contato implícito). +- `Get-Analytics`: rates por `outcome` (rejeição só `REJECTED`), ghosting pela regra da §5, breakdown por etapa e resultado. +- n8n `Candidaturas enviadas → Applywell`: trocar `status:"RH"` por `stage:"APPLIED"`. Pode ser feito depois do deploy do backend, porque `RH` continua aceito. + +## 7. Consumidores de leitura no backend + +| Consumidor | Hoje | Depois | +|---|---|---| +| `DashboardService` | listas de strings | `toSendLater` = DRAFT; `waitingResponses` = aberta e aguardando empresa; `rejectedCount` = REJECTED; `ghostingCount` = §5. Novo `cancelledCount`? **Não**, fora de escopo | +| `InterviewMetricsService` | grava `interview_events` ao entrar em 11 status | grava ao **entrar** numa etapa ∈ {RECRUITER_SCREEN, HIRING_MANAGER, ASSESSMENT, INTERVIEW, OFFER} vinda de etapa fora desse conjunto (mesma semântica de hoje). `old/new_status` recebem a chave da etapa | +| `GamificationService` | status strings | interview progress = entrar no mesmo conjunto acima; OFFER_WON = entrar em OFFER; GHOSTBUSTER = existe candidatura com `isGhosting` | +| `McpAnalyticsTools` | strings + `updatedAt` | ver §6 | +| `ApplicationSpecifications` / assistente | `status` | `stage`/`outcome`/ghosting; aliases do assistente traduzem nome antigo → etapa/resultado pelo conversor | +| `ExportColumn` | `status` | colunas `stage`, `outcome`, `waiting_on`, `ghosting`, e `legacy_status` só quando não convertido | +| `ApplicationRepository` | queries por `status` | equivalentes por `stage`/`outcome` | + +## 8. Frontend + +- **Formulário (`ApplicationForm`):** + - O select de status sai. Entram **Etapa** (obrigatório; "Rascunho" equivale a "To Send Later"), **Resultado** (opcional: em andamento / Contratado / Rejeitada / Vaga cancelada / Desisti) e **Aguardando** (Empresa / Eu; só aparece com resultado "em andamento" e etapa ≠ Rascunho; padrão Empresa). + - Registro não convertido abre com Etapa vazia, um aviso "Status antigo: *Approved* — escolha a etapa para salvar" e o botão salvar bloqueado até escolher. + - A confirmação de entrevista passa a disparar ao entrar numa etapa do conjunto da §7. +- **Lista / tabela / cards:** a coluna e o badge de status mostram a etapa (ou o resultado, se encerrada) e um selo "ghosting" quando calculado. Não convertido mostra o rótulo antigo em itálico. +- **Board:** colunas por etapa (DRAFT…OFFER). Encerradas ficam numa coluna "Encerradas" com o resultado no card. Não convertidas, numa coluna "Status antigo". +- **Filtros:** status → etapa, resultado, "só ghosting". +- **Métricas:** funil por etapa alcançada (Applications → Applied → Recruiter/HM → Assessment → Interview → Offer → Hired). Breakdown por etapa e por resultado. Filtro de família vira filtro de etapa. +- **Dashboard:** mesmos cards, lendo os campos novos do backend (o contrato `DashboardSummaryResponse` não muda de forma). +- Rótulos PT-BR vêm de `GET /applications/stages`, com fallback estático em `src/lib/stages.ts` (substitui `statuses.ts`). + +### Esboço do formulário + +``` +Etapa * [ Candidatura enviada ▾ ] +Resultado [ Em andamento ▾ ] (Contratado | Rejeitada | Vaga cancelada | Desisti) +Aguardando (•) Empresa ( ) Eu +-------------------------------------------------- +⚠ Status antigo: "Approved". Escolha a etapa para salvar. (só em não convertido) +``` + +## 9. Migração e deploy + +1. Reescrever V40 (sem `status_migration`); ajustar mapper/backfill às regras da §3; o backfill roda no startup só em `legacy_status IS NULL`, por bulk update, sem tocar `updated_at`. +2. Deploy do backend: o front antigo continua funcionando (status legado convertível aceito; resposta ganha campos). +3. Deploy do frontend. +4. Atualizar o workflow n8n para `stage: "APPLIED"`. +5. Os números do dashboard mudam no passo 2. O PR lista o quê: ghosting deixa de contar Rejected/Approved/arquivados e passa a ser calculado; rejeição deixa de contar Tarde demais (já não contava) e conta Ghosting-sobre-Rejected como rejeição. + +## 10. Testes + +- Conversor: uma linha de teste por linha da §3, mais casos de caixa/espaço. +- Resolução de escrita: as três regras da §6, incluindo 400 em registro não convertido e as operações isentas. +- Consistência: HIRED sem OFFER → 400; outcome em DRAFT ≠ WITHDREW → 400; waitingOn zerado com outcome. +- Ghosting: cada termo da fórmula isoladamente (encerrada, arquivada, rascunho, aguardando eu, 29 vs 31 dias). +- Dashboard/analytics: contagens com fixture mista (inclui não convertido, que não entra em nenhuma contagem de etapa mas entra no total). +- Gamificação/entrevistas: entrar em RECRUITER_SCREEN concede uma vez; ir de ASSESSMENT para INTERVIEW não concede de novo. +- Frontend: formulário bloqueia salvar em não convertido; board agrupa; funil. + +## 11. Decisões deixadas ao builder + +Nomes de classes/componentes, organização de arquivos, texto exato de mensagens de erro (em inglês na API, como hoje), layout fino do board e do formulário dentro do design system existente. + +## 12. Decisões que tomei (para conferir) + +- Operações isentas da exigência de etapa (§6). +- `waitingOn` nulo conta como aguardando a empresa no cálculo de ghosting. +- `Tarde demais` sem data vira DRAFT + WITHDREW. +- Sem contador novo de "vagas canceladas" no dashboard nesta entrega. +- Limite de ghosting configurável, default 30 dias. From fddbb2063bb2f24bdc7c8f0dc046e2c39e5075ff Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 19:43:09 +0000 Subject: [PATCH 11/24] docs: backend and frontend plans for the stage/outcome cutover (#108) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GfjfbQseka7Y3pN4sK32Pe --- ...026-12-01-stage-outcome-cutover-backend.md | 115 ++++++++++++++++++ ...26-12-01-stage-outcome-cutover-frontend.md | 67 ++++++++++ 2 files changed, 182 insertions(+) create mode 100644 docs/superpowers/plans/2026-12-01-stage-outcome-cutover-backend.md create mode 100644 docs/superpowers/plans/2026-12-01-stage-outcome-cutover-frontend.md diff --git a/docs/superpowers/plans/2026-12-01-stage-outcome-cutover-backend.md b/docs/superpowers/plans/2026-12-01-stage-outcome-cutover-backend.md new file mode 100644 index 00000000..fc721074 --- /dev/null +++ b/docs/superpowers/plans/2026-12-01-stage-outcome-cutover-backend.md @@ -0,0 +1,115 @@ +# Stage/Outcome Cutover — Backend Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Make stage/outcome/waitingOn the read and write model for every backend consumer (REST, MCP, assistant, dashboard, metrics, gamification, export), with best-effort conversion of legacy statuses and calculated ghosting. + +**Architecture:** A pure `LegacyStatusMapper` converts legacy values; a `StageResolver` decides the stage of every content write (explicit stage → convertible legacy status → keep current, failing on unconverted records); `GhostingPolicy` is the single ghosting rule used by responses, dashboard, analytics and gamification. Legacy `status` stays accepted on input during the transition so the current frontend keeps working. + +**Tech Stack:** Spring Boot 4, JPA/Hibernate, Flyway (PostgreSQL), Spring AI MCP annotations, JUnit 5 + Mockito. + +**Spec:** `docs/superpowers/specs/2026-12-01-application-status-cutover-design.md` (conversion table §3, write rules §6, ghosting §5) + +## Global Constraints + +- Keys: stages `DRAFT, APPLIED, RECRUITER_SCREEN, HIRING_MANAGER, ASSESSMENT, INTERVIEW, OFFER`; outcomes `HIRED, REJECTED, ROLE_CANCELLED, WITHDREW`; waitingOn `COMPANY, CANDIDATE`. +- "Progress" stages (interview metrics, gamification): `RECRUITER_SCREEN, HIRING_MANAGER, ASSESSMENT, INTERVIEW, OFFER`. +- Unconverted ⇔ `stage IS NULL AND legacy_status IS NOT NULL`; never attempted ⇔ `legacy_status IS NULL AND stage IS NULL`. +- Consistency: outcome requires stage; DRAFT allows only `WITHDREW`; `HIRED` requires `OFFER`; waitingOn is stored null when outcome is set or stage is DRAFT; stage ≠ DRAFT requires `applicationDate`; DRAFT clears `applicationDate` and sets `to_send_later=true`. +- Ghosting: `stage != null && stage != DRAFT && outcome == null && waitingOn != CANDIDATE && !archived && updatedAt < now - app.applications.ghosting-after-days (default 30)`. Never persisted. +- `status` column: **transition rule (deviation from spec §4, for the old frontend)** — a write that arrives as a legacy status stores that value in `status`; a write that arrives as `stage` stores `status = null`. No business logic reads `status`. +- API error messages in English, as today. MCP copy in English. +- Migrations only in `src/main/resources/db/migration/postgresql/`. V40 is unreleased: rewrite it in place. +- Local checks: `mvn -B -ntp -q test -Dtest='com.jobtracker.unit.**.*Test' -Dsurefire.failIfNoSpecifiedTests=false` (ITs need Docker → CI). + +## Review Focus + +- Archive/restore/mark-DM/reminder/delete on an **unconverted** record — must succeed without a stage. Test in Task 2. +- PATCH that only changes `applicationDate` to null on an open (non-DRAFT) record — must 400, not silently turn it into a draft. Test in Task 2. +- Legacy `status: "TO_SEND_LATER"` or blank from the current frontend — must map to DRAFT. Test in Task 2. +- Dashboard totals with unconverted records — they count in `totalApplications` and in no stage/outcome bucket. Test in Task 4. +- Ghosting boundary at exactly 30 days and on archived records. Test in Task 3. + +--- + +### Task 1: Converter rules + schema/backfill rework + +**Files:** Modify `entity/enums/ApplicationStage.java` (add `boolean isProgress()`), `service/status/LegacyStatusMapper.java`, `service/status/StatusMapping.java` → replace with `service/status/StageState.java`, `service/status/LegacyStatusBackfill.java`, `entity/JobApplication.java` (drop `statusMigration`; add `void applyStage(StageState s)`), `repository/ApplicationRepository.java`, `postgresql/V40__add_application_stage_outcome.sql` (drop `status_migration` + its index); Delete `entity/enums/StatusMigrationState.java`; Tests `unit/status/LegacyStatusMapperTest.java`, `unit/status/LegacyStatusBackfillTest.java`. + +**Interfaces — Produces:** +- `record StageState(ApplicationStage stage, ApplicationOutcome outcome, WaitingOn waitingOn)` with `StageState normalized()` (applies waitingOn-null rule) and `void validate()` (throws `BadRequestException` per Global Constraints). +- `static Optional LegacyStatusMapper.map(String status, String previousStatus, boolean toSendLater, LocalDate applicationDate)` — empty = not converted. Blank or `TO_SEND_LATER` status is treated like null. +- `JobApplication#applyStage(StageState)` sets stage/outcome/waitingOn, `toSendLater = stage == DRAFT`, clears `applicationDate` on DRAFT. +- `ApplicationRepository#findTop500ByLegacyStatusIsNullAndStageIsNullOrderByIdAsc()`; `applyStatusMapping(UUID id, ApplicationStage, ApplicationOutcome, WaitingOn, String legacyStatus)` (bulk, `WHERE legacy_status IS NULL AND stage IS NULL`). For rows that do not convert, it still writes `legacyStatus` so they are not retried. + +- [ ] Rewrite mapper tests to the spec §3 table, one case per row, including: `Pending HR Response`→RECRUITER_SCREEN+COMPANY; `RH (Negociação)`→OFFER; `Approved`→OFFER+HIRED; `Tarde demais` with date→APPLIED+WITHDREW, without→DRAFT+WITHDREW; Ghosting over `Approved`→OFFER+HIRED; Ghosting over `Tarde demais`→APPLIED+WITHDREW; Ghosting without previous + date→APPLIED+COMPANY; Ghosting without date→empty; `RH` without date→empty; `"garbage"`→empty; `" rejected "`→APPLIED+REJECTED. Backfill test: unconverted row is written with null stage and its legacy value; second run reads nothing. +- [ ] Run → FAIL. Implement. Run → PASS. Commit `refactor(status): best-effort conversion, drop NEEDS_REVIEW`. + +### Task 2: Stage resolution on writes + +**Files:** Create `service/status/StageResolver.java`, `service/status/StageInput.java`; Modify `dto/application/ApplicationRequest.java`, `ApplicationPatchRequest.java` (+ `hasStage()`, etc.), `service/ApplicationService.java`, `controller/ApplicationController.java`; Create `dto/application/UpdateStageRequest.java`; Test `unit/status/StageResolverTest.java`, `unit/ApplicationServiceTest.java`. + +**Interfaces:** +- Consumes: `StageState`, `LegacyStatusMapper.map`, `JobApplication#applyStage`. +- Produces: `record StageInput(boolean stageProvided, ApplicationStage stage, ApplicationOutcome outcome, WaitingOn waitingOn, boolean legacyProvided, String legacyStatus)`; `static StageState StageResolver.resolve(JobApplication current, StageInput input, LocalDate effectiveApplicationDate)` — rules spec §6 1-3; unconverted + nothing provided → `BadRequestException("This application still uses a legacy status; provide a stage")`; unconvertible legacy → `BadRequestException("Status '' cannot be converted; provide a stage")`. +- `ApplicationService#updateStage(UUID id, UpdateStageRequest)`; `PATCH /api/v1/applications/{id}/stage`. `updateStatus` keeps working through the resolver. +- Request fields `stage`, `outcome`, `waitingOn` (enum-typed, Jackson rejects unknown keys with 400). `status` stays, documented as legacy. +- `status` column per the transition rule in Global Constraints. + +- [ ] Tests (`StageResolverTest`): explicit stage wins over legacy; convertible legacy used; unconvertible legacy → 400; nothing provided keeps current; nothing provided on unconverted → 400; `TO_SEND_LATER` → DRAFT; HIRED with ASSESSMENT → 400; outcome on DRAFT other than WITHDREW → 400. +- [ ] Tests (`ApplicationServiceTest`): create with `stage=APPLIED` + date → `status` null, `toSendLater` false; create with legacy `RH` → stage APPLIED and `status` "RH"; patch note-only on unconverted → 400; `archive`, `markDmSent`, `updateReminder` on unconverted succeed; patch `applicationDate=null` on APPLIED → 400; `updateStage(DRAFT)` clears the date. +- [ ] Run → FAIL. Implement; delete the old `applyStatusChange`/`previous_status` bookkeeping (resolver replaces it; `previous_status` is no longer written). Run → PASS. Commit. + +### Task 3: Ghosting policy, scheduler removal, response shape + +**Files:** Create `service/status/GhostingPolicy.java`; Delete `tasks/StaleApplicationsScheduler.java` + its test; Modify `application.yml` (`app.applications.ghosting-after-days: 30`), `dto/application/ApplicationResponse.java`, `mapper/ApplicationMapper.java` (now a bean that gets `GhostingPolicy`), `repository/ApplicationRepository.java`; Test `unit/status/GhostingPolicyTest.java`. + +**Interfaces — Produces:** +- `GhostingPolicy#isGhosting(JobApplication app)`, `GhostingPolicy#cutoff(): LocalDateTime` (uses an injected `Clock`). +- `ApplicationRepository#countGhosting(UUID userId, LocalDateTime cutoff)` and a reusable `ApplicationSpecifications.ghosting(LocalDateTime cutoff)` — the same predicate as `isGhosting`, archived excluded. +- `ApplicationResponse`: replace `statusMigration` with `String legacyStatus` (non-null only when unconverted) and `boolean ghosting`; keep `stage`, `outcome`, `waitingOn`, `status`. + +- [ ] Tests: each false term flips the result (DRAFT, outcome set, CANDIDATE, archived, null stage); `updatedAt` 29 days → false, 31 → true; waitingOn null → counts. +- [ ] Implement; PASS; commit. + +### Task 4: Dashboard, interview metrics, gamification + +**Files:** Modify `service/DashboardService.java`, `service/InterviewMetricsService.java`, `service/GamificationService.java`, `repository/ApplicationRepository.java`; Tests `unit/DashboardServiceTest.java` (create if absent), `InterviewMetricsServiceTest`, `GamificationServiceTest`. + +**Interfaces:** +- `InterviewMetricsService#recordStageTransition(JobApplication app, ApplicationStage from, ApplicationStage to)` — records when `to.isProgress() && (from == null || !from.isProgress())`; `old_status/new_status` get the stage names. +- `GamificationService#onApplicationUpdated(JobApplication, ApplicationStage previousStage, boolean previousInterviewScheduled, String previousNote)` and `onApplicationStageUpdated(JobApplication, ApplicationStage previousStage)`; interview progress = entering a progress stage; OFFER_WON = entering OFFER; GHOSTBUSTER = any `GhostingPolicy#isGhosting`. +- Dashboard: `toSendLater` = stage DRAFT; `waitingResponses` = open, stage ∉ {null, DRAFT}, waitingOn ≠ CANDIDATE, not archived; `rejectedCount` = outcome REJECTED; `ghostingCount` = `countGhosting`. + +- [ ] Tests: fixture with one of each (DRAFT, APPLIED waiting, ASSESSMENT waiting CANDIDATE, REJECTED, ROLE_CANCELLED, stale APPLIED, unconverted) → expected counts (`rejectedCount` 1, ghosting 1, toSendLater 1, total 7). Entering RECRUITER_SCREEN from APPLIED records one event; ASSESSMENT→INTERVIEW records none. +- [ ] Implement; remove the legacy string sets; PASS; commit. + +### Task 5: Filters, specifications, export + +**Files:** `dto/application/ApplicationFilter.java`, `dto/export/ExportFilters.java`, `repository/ApplicationSpecifications.java`, `controller/ApplicationController.java` (query params `stage`, `outcome`, `ghosting`), `service/export/ExportColumn.java`; Tests `unit/export/*`, `ApplicationSpecifications` coverage via `ApplicationRepositoryIT` (CI). + +- [ ] Filters accept `stage`, `outcome` (lists for export), `ghosting` (Boolean); legacy `status` is converted with `LegacyStatusMapper.map(status, null, false, LocalDate.MIN)` to stage/outcome predicates; `TO_SEND_LATER` → DRAFT; unconvertible legacy filters on `legacy_status` equality. Global search also matches stage/outcome keys. +- [ ] Export columns: `STATUS` becomes the display of `outcome ?: stage ?: legacy_status`; add `STAGE`, `OUTCOME`, `WAITING_ON`, `GHOSTING`. +- [ ] Tests for legacy-filter translation and export column values; PASS; commit. + +### Task 6: Assistant queries + +**Files:** `repository/assistant/AssistantApplicationQueryRepository.java`, `service/assistant/AssistantTools.java`, `service/assistant/AssistantApplicationQueryService.java`; Tests `unit/AssistantApplicationQueryRepositoryTest.java`, `AssistantToolsTest.java`. + +- [ ] Replace `CANONICAL_STATUS` with `COALESCE(outcome, stage, legacy_status)` exposed as `phase`; filters accept stage/outcome keys or legacy names (translated by the mapper); the `GroupBy.STATUS` aggregate groups by `phase`. Tool descriptions list the new keys. `"Ghosting"` in a filter means the ghosting predicate. +- [ ] Update tests' expected SQL fragments and alias cases; PASS; commit. + +### Task 7: Catalog endpoint + MCP + +**Files:** Create `dto/application/StageCatalogResponse.java`, `service/status/StageCatalog.java`; Modify `ApplicationController` (`GET /applications/stages`), `mcp/tools/McpApplicationTools.java`, `mcp/tools/McpAnalyticsTools.java`, `mcp/resources/McpApplicationStatusesResource.java`, `McpApplicationCreationRulesResource.java`, `McpApplicationLifecycleRulesResource.java`, `mcp/McpPromptsConfig.java`; Tests `unit/mcp/*`. + +**Interfaces:** `record StageCatalogResponse(List