Repository navigation
feat(variáveis): adiciona suporte para processamento automático de variáveis suspensas - #511
Conversation
…riáveis suspensas Implementa a capacidade de processar variáveis globais suspensas, copiando valores automaticamente para variáveis não acumulativas e definindo zero para acumulativas. Isso melhora a eficiência ao evitar a necessidade de intervenção manual para variáveis suspensas, garantindo que os ciclos possam ser fechados automaticamente quando todas as filhas estão suspensas. Além disso, adiciona novos campos e validações para gerenciar variáveis filhas e suspensas, aprimorando a integridade dos dados e a experiência do usuário.
|
Caution Review failedThe pull request is closed. 📝 WalkthroughWalkthroughSchema and service were updated to support suspended global variables: added Changes
Sequence DiagramsequenceDiagram
participant Client
participant Controller as VariavelGlobalController
participant Service as VariavelService
participant DB as PrismaDatabase
participant Recalc as RecalculationEngine
Client->>Controller: POST /processa-variaveis-globais-suspensas
Controller->>Service: processVariaveisGlobaisSuspensasController()
Service->>Service: begin transaction
Service->>DB: query suspended global variables (variavel, suspendida_em, ciclo_referencia)
DB-->>Service: suspended variable rows
loop per suspended variable
Service->>DB: upsert serie_variavel (copy previous or set 0)
DB-->>Service: upsert result
Service->>DB: insert/update variavel_suspensa_controle (ciclo_referencia, processado_em)
end
Service->>Recalc: trigger dependent series recalculation
Recalc->>DB: update dependent series
Recalc-->>Service: recalculation complete
Service->>DB: query parent cycles affected
DB-->>Service: parent cycle info
alt parent with all children suspended
Service->>DB: close parent cycle, insert automatic analysis entry
Service->>Recalc: enqueue recalculation/meta tasks
end
Service->>Service: commit transaction
Service-->>Controller: return processed variable IDs
Controller-->>Client: 200 OK with results
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 6
🤖 Fix all issues with AI agents
In
`@backend/prisma/migrations/20260117025443_add_ciclo_referencia_to_suspensa_controle/migration.sql`:
- Around line 13-14: The index on variavel_suspensa_controle
(variavel_suspensa_controle_variavel_id_serie_ciclo_referenc_idx) currently
allows duplicates; if (variavel_id, serie, ciclo_referencia) must be unique,
change the migration to create a UNIQUE index (replace CREATE INDEX with CREATE
UNIQUE INDEX for that index name) so the DB enforces singleton rows, otherwise
update the schema/migration comments to clarify that uniqueness is not required
to avoid implying uniqueness.
In `@backend/prisma/schema.prisma`:
- Around line 2026-2029: The schema comment incorrectly calls the constraint an
"índice único" while the actual declaration is @@index([variavel_id, serie,
ciclo_referencia]); either change that declaration to @@unique([variavel_id,
serie, ciclo_referencia]) so the DB enforces uniqueness for the global
suspension control, and regenerate/create a migration that creates a UNIQUE
index, or if uniqueness is not intended, update the comment text to remove
"índice único" and clarify it is a non-unique index; locate the @@index line and
the surrounding comment in the Prisma model to make the appropriate change.
In `@backend/src/variavel/variavel.ciclo.service.ts`:
- Around line 1056-1061: The current logic in formatarValores (where
filhasNaoSuspensas and todasVariaveis are built) allows pushing the parent into
the editable list when all children are suspended, but validaValoresVariaveis
rejects parent submissions if the variable has any children; fix by keeping the
parent out whenever the variable has children regardless of their suspended
state: replace the fallback that pushes variavel into todasVariaveis with a
check against variavel.variaveis_filhas.length (i.e., only push the parent when
variavel.variaveis_filhas.length === 0), and ensure formatarValores and
validaValoresVariaveis share the same rule; alternatively, if you prefer showing
the parent row, set a flag on the parent (e.g., isEditableParent = false) in
formatarValores so the UI can disable/hide inputs and validation will accept no
editable parent values.
In `@backend/src/variavel/variavel.service.ts`:
- Around line 2431-2460: The auto-close loop over ownersToClose creates
variavelGlobalCicloAnalise and updates variavelCicloCorrente but fails to call
the database function f_atualiza_variavel_ciclo_corrente or the same
enqueue/recalc logic used by marcaLiberacaoEnviada, leaving cycle state stale;
update the loop (after prismaTx.variavelCicloCorrente.update) to invoke
f_atualiza_variavel_ciclo_corrente for the given variavel_id and to enqueue the
same recalculation/job dispatch used by marcaLiberacaoEnviada so the ciclo state
and downstream recalcs are refreshed immediately.
- Around line 2277-2353: The temp table _suspend_values_global currently uses
COALESCE(last_val.valor_nominal, 0) for valor_novo which creates a 0 Realizado
when there was no prior value; change the SELECT that defines valor_novo to:
WHEN j.acumulativa = true THEN 0 ELSE last_val.valor_nominal END (i.e., remove
COALESCE) so non-acumulativa rows produce NULL when no prior value exists, and
then in the INSERT (ins_real / INSERT INTO serie_variavel ... FROM
_suspend_values_global) add a filter to skip rows where valor_novo IS NULL for
non-acumulativa variables (e.g., add WHERE (acumulativa = true) OR (valor_novo
IS NOT NULL)) so you only insert copied values when a previous value exists and
only default 0 for RealizadoAcumulado.
- Around line 1395-1408: The current check in variavel.service.ts (using
selfBefUpdate, allowedFieldsForChildren and UpdateVariavelDto) rejects any
child-variable PATCH except 'suspendida' but the error message is generic;
update the HttpException text to clearly instruct clients to use the dedicated
child endpoint (PATCH variavel/:id/filha/:id2) for changes that require
valor_base and indicate which fields are allowed via the generic endpoint (e.g.,
only 'suspendida' here) so callers know to migrate to the child-specific route.
…o de variáveis filhas Implementa um método dedicado para atualizar o status de suspensão de variáveis filhas, garantindo que apenas o campo 'suspendida' possa ser alterado diretamente. Isso melhora a segurança e a integridade dos dados, assegurando que outras alterações sejam feitas através da variável mãe. Além disso, a lógica de formatação de valores foi ajustada para permitir a inclusão da variável mãe quando todas as filhas estão suspensas, se configurado.
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
backend/src/variavel/variavel.service.ts (1)
1395-1417: Add Calculada suspension guard toupdateSuspensaoFilha.The early return for child variables bypasses the Calculada suspension check. Since Calculada variables can be created as children (confirmed in
variavel.calculada.service.ts:219), a Calculada child could be suspended throughupdateSuspensaoFilha, which lacks the guard present in the parent update path. Add the same check from line 1416 before processing the suspension.
🤖 Fix all issues with AI agents
In
`@backend/prisma/migrations/20260117162549_add_ciclo_referencia_to_suspensa_controle/migration.sql`:
- Around line 14-20: The unique index
"variavel_suspensa_controle_variavel_id_serie_ciclo_referenc_key" on table
"variavel_suspensa_controle" will not enforce uniqueness for rows where
"ciclo_referencia" is NULL; either backfill "ciclo_referencia" and ALTER COLUMN
"ciclo_referencia" SET NOT NULL then create the UNIQUE INDEX, or replace the
index with a partial unique index that only enforces uniqueness for non-NULL
values (e.g., UNIQUE ON ("variavel_id","serie","ciclo_referencia") WHERE
"ciclo_referencia" IS NOT NULL); choose one approach, apply the corresponding
migration steps (backfill, change nullability, recreate index OR create partial
index) and ensure the migration drops the previous index before creating the
corrected one.
In `@backend/src/variavel/variavel.service.ts`:
- Around line 2378-2391: When no rows are inserted by ins_real (filledVarIds is
empty) the current logic skips autoCloseParentCyclesIfAllChildrenSuspended, so
parent cycles never close; change the flow to always compute cycleOwnerIds from
the suspend-job source (use affectedVars or derive from
_suspend_jobs_global/ins_ctrl when affectedVars has no filled entries) and call
autoCloseParentCyclesIfAllChildrenSuspended(cycleOwnerIds, prismaTx)
unconditionally, while keeping calls to recalc_series_dependentes(filledVarIds,
prismaTx) and recalc_indicador_usando_variaveis(filledVarIds, prismaTx) gated
behind filledVarIds.length > 0 so recalculations only run when actual inserts
occurred.
…ora validação de campos A atualização de variáveis filhas foi simplificada ao consolidar a lógica de suspensão e valor_base em um único método, reduzindo duplicação de código. A validação de campos agora assegura que apenas 'suspendida' e 'valor_base' podem ser alterados, melhorando a segurança e clareza do código. Além disso, a lógica de suspensão foi extraída para uma função dedicada, tornando o código mais modular e fácil de manter.
…is mãe sem valores inseridos Ajusta a consulta para buscar todos os cycle owners, garantindo que ciclos de variáveis mãe sejam fechados automaticamente mesmo quando não há valores inseridos. Isso é necessário para lidar com casos em que todas as variáveis filhas estão suspensas, mas não há valores novos, assegurando a consistência do estado do ciclo.
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In `@backend/src/variavel/variavel.service.ts`:
- Around line 2421-2435: The created variavelGlobalCicloAnalise record uses an
array for the valores field (valores: []) while other flows use an object
(valores: {}); update the variavelGlobalCicloAnalise.create call in
variavel.service.ts (the block that builds the auto-close record for owner.id /
fase 'Liberacao') to set valores to the consistent JSON shape used elsewhere
(e.g., valores: {}) so downstream consumers receive the expected object
structure.
- Around line 2400-2415: The query populating ownersToClose (prismaTx.$queryRaw
in variavel.service.ts) can match childless variables because NOT EXISTS(...) is
true for standalones; modify the SQL to also require that the parent has at
least one child by adding an EXISTS(...) clause that checks for any child rows
(e.g., SELECT 1 FROM variavel child WHERE child.variavel_mae_id =
vcc.variavel_id AND child.removido_em IS NULL AND child.tipo = 'Global') so only
parents with children are considered for auto-close; update the query that
selects from variavel_ciclo_corrente (alias vcc) accordingly.
| // Cria registro de análise para cada fase pendente | ||
| await prismaTx.variavelGlobalCicloAnalise.create({ | ||
| data: { | ||
| variavel_id: owner.id, | ||
| fase: 'Liberacao', | ||
| referencia_data: owner.ultimo_periodo_valido, | ||
| informacoes_complementares: | ||
| 'Ciclo encerrado automaticamente: Todas as variáveis filhas estão suspensas.', | ||
| eh_liberacao_auto: true, | ||
| aprovada: true, | ||
| ultima_revisao: true, | ||
| valores: [], | ||
| criado_por: CONST_BOT_USER_ID, | ||
| sincronizar_serie_variavel: false, | ||
| }, |
There was a problem hiding this comment.
Use a consistent JSON shape for valores.
Other flows set valores: {}, but this auto-close path writes []. If consumers expect an object, this mismatch can break parsing.
🛠️ Suggested fix
- valores: [],
+ valores: {},📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| // Cria registro de análise para cada fase pendente | |
| await prismaTx.variavelGlobalCicloAnalise.create({ | |
| data: { | |
| variavel_id: owner.id, | |
| fase: 'Liberacao', | |
| referencia_data: owner.ultimo_periodo_valido, | |
| informacoes_complementares: | |
| 'Ciclo encerrado automaticamente: Todas as variáveis filhas estão suspensas.', | |
| eh_liberacao_auto: true, | |
| aprovada: true, | |
| ultima_revisao: true, | |
| valores: [], | |
| criado_por: CONST_BOT_USER_ID, | |
| sincronizar_serie_variavel: false, | |
| }, | |
| // Cria registro de análise para cada fase pendente | |
| await prismaTx.variavelGlobalCicloAnalise.create({ | |
| data: { | |
| variavel_id: owner.id, | |
| fase: 'Liberacao', | |
| referencia_data: owner.ultimo_periodo_valido, | |
| informacoes_complementares: | |
| 'Ciclo encerrado automaticamente: Todas as variáveis filhas estão suspensas.', | |
| eh_liberacao_auto: true, | |
| aprovada: true, | |
| ultima_revisao: true, | |
| valores: {}, | |
| criado_por: CONST_BOT_USER_ID, | |
| sincronizar_serie_variavel: false, | |
| }, |
🤖 Prompt for AI Agents
In `@backend/src/variavel/variavel.service.ts` around lines 2421 - 2435, The
created variavelGlobalCicloAnalise record uses an array for the valores field
(valores: []) while other flows use an object (valores: {}); update the
variavelGlobalCicloAnalise.create call in variavel.service.ts (the block that
builds the auto-close record for owner.id / fase 'Liberacao') to set valores to
the consistent JSON shape used elsewhere (e.g., valores: {}) so downstream
consumers receive the expected object structure.
…iáveis independentes Adiciona uma verificação para garantir que variáveis independentes, que podem estar em cycleOwnerIds, não passem incorretamente na verificação NOT EXISTS. Isso corrige um problema onde variáveis sem filhos eram tratadas de forma inadequada, assegurando que apenas variáveis com filhos ativos e não removidos sejam consideradas.
|



…
Implementa a capacidade de processar variáveis globais suspensas, copiando valores automaticamente para variáveis não acumulativas e definindo zero para acumulativas. Isso melhora a eficiência ao evitar a necessidade de intervenção manual para variáveis suspensas, garantindo que os ciclos possam ser fechados automaticamente quando todas as filhas estão suspensas. Além disso, adiciona novos campos e validações para gerenciar variáveis filhas e suspensas, aprimorando a integridade dos dados e a experiência do usuário.
Summary by CodeRabbit
New Features
Improvements
✏️ Tip: You can customize this high-level summary in your review settings.