Skip to content

Conversation

@robertatakenaka
Copy link
Member

@robertatakenaka robertatakenaka commented Feb 2, 2026

O que esse PR faz?

Este PR realiza uma refatoração no modelo Journal para encapsular a lógica de criação e associação de instituições vinculadas ao histórico do periódico (Publishers, Owners, Sponsors e Copyright Holders).

As principais mudanças incluem:

  • Implementação dos métodos add_publisher, add_owner, add_sponsor e add_copyright_holder diretamente na classe Journal.
  • Limpeza do script am_to_core.py, substituindo blocos repetitivos de código por chamadas simplificadas aos novos métodos do modelo.
  • Centralização da responsabilidade de criação de registros de histórico, garantindo que a integridade dos dados (como a associação com o usuário e as datas) seja mantida em um único local.

Onde a revisão poderia começar?

A revisão deve começar pelo arquivo journal/models.py, onde os novos métodos foram implementados para entender a lógica de abstração. Em seguida, verifique journal/sources/am_to_core.py para validar como o código ficou mais enxuto após a substituição das chamadas diretas aos modelos de instituição.

Como este poderia ser testado manualmente?

  1. Execute o processo de importação/migração de um periódico via script de origem (Airflow ou comando de gerenciamento que utilize am_to_core.py).
  2. Verifique no banco de dados ou no painel administrativo se as instituições (Publishers, Sponsors, etc.) foram criadas corretamente.
  3. Certifique-se de que os registros de histórico (PublisherHistory, SponsorHistory, etc.) foram gerados e vinculados ao Journal e ao User corretos.
  4. Tente adicionar uma instituição via shell utilizando os novos métodos: journal_instance.add_publisher(user=user, original_data="Nome da Editora").

Algum cenário de contexto que queira dar?

Anteriormente, a lógica de instanciar uma instituição e logo em seguida criar seu registro de histórico estava espalhada por diversos pontos dos scripts de conversão. Isso gerava código duplicado e dificultava a manutenção caso o esquema do histórico mudasse. Ao mover essa lógica para o Journal, tornamos o código mais "Django-like" e facilitamos a reutilização em outras partes do sistema.

Screenshots

N/A (Alteração de backend/lógica de modelos)

Quais são tickets relevantes?

  • Ref: #ID_DO_TICKET_AQUI

Referências

…elo Journal

- Adiciona métodos helper (add_publisher, add_owner, add_sponsor, add_copyright_holder) ao model Journal
- Refatora am_to_core.py para utilizar os novos métodos, reduzindo a duplicação de código
- Centraliza a criação de registros de histórico de instituições
Copilot AI review requested due to automatic review settings February 2, 2026 17:36
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR refactors the institution addition logic in the journal module by encapsulating repetitive code into helper methods on the Journal model. The refactoring aims to reduce code duplication and centralize the creation of institution history records.

Changes:

  • Added four helper methods (add_publisher, add_owner, add_sponsor, add_copyright_holder) to the Journal model
  • Refactored am_to_core.py to use these new methods instead of directly calling institution models
  • Removed unused import of institution models from am_to_core.py

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 7 comments.

File Description
journal/models.py Added four new helper methods to the Journal model for adding publisher, owner, sponsor, and copyright holder with their respective history records
journal/sources/am_to_core.py Removed direct institution creation code and replaced with calls to the new Journal helper methods; removed unused imports

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

)
publisher_history = PublisherHistory.get_or_create(
institution=created_publisher,
# Usa novo método add_owner ao invés de OwnerHistory
Copy link

Copilot AI Feb 2, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The comment has trailing whitespace at the end of the line. Remove the trailing spaces for consistency with code style standards.

Suggested change
# Usa novo método add_owner ao invés de OwnerHistory
# Usa novo método add_owner ao invés de OwnerHistory

Copilot uses AI. Check for mistakes.
Comment on lines +1083 to +1088
if not created_publisher and not organization:
raise ValueError("Either original_data or organization must be provided")

# Cria/busca o PublisherHistory
publisher_history = PublisherHistory.get_or_create(
institution=created_publisher,
Copy link

Copilot AI Feb 2, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The organization parameter is never used in this method. When original_data is None but organization is provided, the validation will pass but created_publisher will remain None, causing institution=None to be passed to PublisherHistory.get_or_create(). Either remove the unused organization parameter or implement the logic to use it when provided.

Copilot uses AI. Check for mistakes.
Comment on lines +1116 to +1121
if not created_owner and not organization:
raise ValueError("Either original_data or organization must be provided")

# Cria/busca o OwnerHistory
owner_history = OwnerHistory.get_or_create(
institution=created_owner,
Copy link

Copilot AI Feb 2, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The organization parameter is never used in this method. When original_data is None but organization is provided, the validation will pass but created_owner will remain None, causing institution=None to be passed to OwnerHistory.get_or_create(). Either remove the unused organization parameter or implement the logic to use it when provided.

Copilot uses AI. Check for mistakes.
Comment on lines +1149 to +1154
if not created_sponsor and not organization:
raise ValueError("Either original_data or organization must be provided")

# Cria/busca o SponsorHistory
sponsor_history = SponsorHistory.get_or_create(
institution=created_sponsor,
Copy link

Copilot AI Feb 2, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The organization parameter is never used in this method. When original_data is None but organization is provided, the validation will pass but created_sponsor will remain None, causing institution=None to be passed to SponsorHistory.get_or_create(). Either remove the unused organization parameter or implement the logic to use it when provided.

Copilot uses AI. Check for mistakes.
Comment on lines +1182 to +1184
if not created_copyright_holder and not organization:
raise ValueError("Either original_data or organization must be provided")

Copy link

Copilot AI Feb 2, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The organization parameter is never used in this method. When original_data is None but organization is provided, the validation will pass but created_copyright_holder will remain None, causing institution=None to be passed to CopyrightHolderHistory.get_or_create(). Either remove the unused organization parameter or implement the logic to use it when provided.

Suggested change
if not created_copyright_holder and not organization:
raise ValueError("Either original_data or organization must be provided")
# Se nenhum CopyrightHolder foi criado/encontrado, não é seguro continuar.
if not created_copyright_holder:
if organization is not None:
# Ainda não há lógica para derivar um CopyrightHolder a partir de organization.
# Evita criar um histórico com institution=None.
raise ValueError(
"original_data must be provided to create a CopyrightHolder "
"when organization is used."
)
raise ValueError("Either original_data or organization must be provided")

Copilot uses AI. Check for mistakes.
level_2=None,
level_3=None,
user=user,
location=None, # Pode ser ajustado conforme necessário
Copy link

Copilot AI Feb 2, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The refactoring changed the behavior: the old code passed the location variable (created on line 199) to Publisher.get_or_create(), but the new add_publisher() method hardcodes location=None. This may result in data loss if location information was previously being stored. Consider adding a location parameter to add_publisher() and passing it through, or verify this change is intentional.

Copilot uses AI. Check for mistakes.
level_2=None,
level_3=None,
user=user,
location=None, # Pode ser ajustado conforme necessário
Copy link

Copilot AI Feb 2, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The refactoring changed the behavior: the old code passed the location variable to Owner.get_or_create(), but the new add_owner() method hardcodes location=None. This may result in data loss if location information was previously being stored. Consider adding a location parameter to add_owner() and passing it through, or verify this change is intentional.

Copilot uses AI. Check for mistakes.
- Atualiza métodos add_publisher, add_owner, add_sponsor e add_copyright_holder para aceitarem o parâmetro location.
- Atualiza funções auxiliares em am_to_core.py para propagar o objeto location.
- Adiciona a função centralizada create_location_and_add_institutions para facilitar a criação de registros vinculados.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant