Skip to content

refactor: Introduce factory pattern for barcode invoice handlers#91

Merged
jldsilva merged 2 commits into
developmentfrom
Refactor-InvoiceBarcodeHandlers
May 14, 2026
Merged

refactor: Introduce factory pattern for barcode invoice handlers#91
jldsilva merged 2 commits into
developmentfrom
Refactor-InvoiceBarcodeHandlers

Conversation

@jldsilva
Copy link
Copy Markdown
Owner

@jldsilva jldsilva commented May 13, 2026

Refactors BarcodeReaderService to use a BarcodeHandlerFactory for resolving IInvoiceBarcodeHandler implementations based on InvoiceType.

This change:

  • Replaces the manual switch statement for handler selection within BarcodeReaderService with a dedicated factory.
  • Leverages dependency injection to register and provide all IInvoiceBarcodeHandler implementations to the factory.
  • Enhances extensibility, allowing new invoice types and their corresponding handlers to be added without modifying the BarcodeReaderService directly.
  • Updates the DI configuration to Append registrations for barcode handlers, ensuring all implementations are available to the factory.

Summary by CodeRabbit

Notas de Lançamento

  • Refactor

    • Refatorada a arquitetura interna de processamento de códigos de barras para melhor manutenibilidade e extensibilidade. O novo design facilita o suporte futuro a diferentes tipos de faturas através de um padrão factory.
  • Tests

    • Adicionados testes unitários abrangentes para validar o comportamento correto da nova arquitetura de processamento de códigos de barras.

Review Change Stack

Refactors `BarcodeReaderService` to use a `BarcodeHandlerFactory` for resolving `IInvoiceBarcodeHandler` implementations based on `InvoiceType`.

This change:
*   Replaces the manual `switch` statement for handler selection within `BarcodeReaderService` with a dedicated factory.
*   Leverages dependency injection to register and provide all `IInvoiceBarcodeHandler` implementations to the factory.
*   Enhances extensibility, allowing new invoice types and their corresponding handlers to be added without modifying the `BarcodeReaderService` directly.
*   Updates the DI configuration to `Append` registrations for barcode handlers, ensuring all implementations are available to the factory.
@jldsilva jldsilva self-assigned this May 13, 2026
@jldsilva jldsilva added the enhancement New feature or request label May 13, 2026
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 13, 2026

Warning

Rate limit exceeded

@jldsilva has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 28 minutes and 52 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 91c4ea5c-9aca-48f6-a264-7cc2f8c7aeb6

📥 Commits

Reviewing files that changed from the base of the PR and between 74f0689 and 9dbaf83.

📒 Files selected for processing (2)
  • InvoiceReminder.ExternalServices/BarcodeReader/BarcodeHandlerFactory.cs
  • InvoiceReminder.UnitTests.ExternalServices/BarcodeReader/BarcodeHandlerFactoryTests.cs

Walkthrough

O PR introduz um padrão factory para gerenciar handlers especializados de leitura de código de barras. Cada handler agora expõe seu tipo de nota fiscal correspondente, permitindo que a factory centralize a seleção correta. O BarcodeReaderService é refatorado para solicitar handlers via factory ao invés de gerenciar estado interno, e a estratégia de registro DI muda para permitir múltiplas implementações.

Changes

Factory Pattern para Seleção de Barcode Handler

Layer / File(s) Summary
Contratos de Factory e Handler
InvoiceReminder.ExternalServices/BarcodeReader/IBarcodeHandlerFactory.cs, InvoiceReminder.ExternalServices/BarcodeReader/IInvoiceBarcodeHandler.cs
Interface IBarcodeHandlerFactory define contrato factory com método GetHandler(InvoiceType). Interface IInvoiceBarcodeHandler adiciona propriedade InvoiceType { get; } para que handlers se identifiquem por tipo.
Implementações de Handler com InvoiceType
InvoiceReminder.ExternalServices/BarcodeReader/AccountInvoiceBarcodeHandler.cs, InvoiceReminder.ExternalServices/BarcodeReader/BankInvoiceBarcodeHandler.cs
Ambos handlers importam InvoiceReminder.Domain.Enums e implementam propriedade InvoiceType retornando o tipo específico (InvoiceType.AccountInvoice ou InvoiceType.BankInvoice).
Factory e Refatoração de Serviço
InvoiceReminder.ExternalServices/BarcodeReader/BarcodeHandlerFactory.cs, InvoiceReminder.ExternalServices/BarcodeReader/BarcodeReaderService.cs
BarcodeHandlerFactory constrói dicionário interno mapeando tipos de nota fiscal a handlers e retorna o apropriado via GetHandler() ou lança NotSupportedException. BarcodeReaderService recebe factory via DI e a chama em ReadTextContentFromPdf() ao invés de gerenciar _barcodeHandler interno.
Atualização de Configuração de DI
InvoiceReminder.CrossCutting.IoC/DependencyInjectionConfig.cs
Estratégia Scrutor em AddExternalServices muda de RegistrationStrategy.Skip para RegistrationStrategy.Append para permitir múltiplas implementações de IInvoiceBarcodeHandler no container.
Testes Completos
InvoiceReminder.UnitTests.ExternalServices/BarcodeReader/BarcodeHandlerFactoryTests.cs, InvoiceReminder.UnitTests.ExternalServices/BarcodeReader/BarcodeReaderServiceTests.cs
BarcodeHandlerFactoryTests valida construção, lookup correto por tipo, e lançamento de exceção para tipos não suportados. BarcodeReaderServiceTests mocka factory e configura respostas de GetHandler() para cada tipo de teste.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

\.NET``

Poem

🐰 Factory patterns hop with grace,
Handlers mapped to each invoice case,
No state to carry, just ask and get,
The right barcode reader, no regret!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed O título descreve precisamente o principal objetivo da mudança: introduzir um padrão factory para os manipuladores de código de barras de faturas.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch Refactor-InvoiceBarcodeHandlers

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
InvoiceReminder.ExternalServices/BarcodeReader/BarcodeHandlerFactory.cs (1)

9-12: ⚡ Quick win

Melhorar a mensagem de erro para InvoiceType duplicado

Na Line 11, se dois handlers tiverem o mesmo InvoiceType, a falha de inicialização fica pouco diagnóstica. Vale validar duplicidade antes e lançar uma exceção explícita com os tipos conflitantes.

💡 Sugestão de ajuste
 public BarcodeHandlerFactory(IEnumerable<IInvoiceBarcodeHandler> handlers)
 {
-    _handlers = handlers.ToDictionary(h => h.InvoiceType, h => h);
+    var duplicatedTypes = handlers
+        .GroupBy(h => h.InvoiceType)
+        .Where(g => g.Count() > 1)
+        .Select(g => g.Key)
+        .ToArray();
+
+    if (duplicatedTypes.Length > 0)
+    {
+        throw new InvalidOperationException(
+            $"Duplicate barcode handlers registered for: {string.Join(", ", duplicatedTypes)}");
+    }
+
+    _handlers = handlers.ToDictionary(h => h.InvoiceType, h => h);
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@InvoiceReminder.ExternalServices/BarcodeReader/BarcodeHandlerFactory.cs`
around lines 9 - 12, A construção de _handlers em BarcodeHandlerFactory está
usando ToDictionary diretamente, o que deixa a falha pouco clara se houver
InvoiceType duplicado; antes de chamar ToDictionary, valide a coleção
IEnumerable<IInvoiceBarcodeHandler> (por exemplo em BarcodeHandlerFactory
constructor) agrupando por InvoiceType, detecte chaves com Count>1 e lance uma
ArgumentException/InvalidOperationException explícita que liste os InvoiceType
conflitantes (e opcionalmente os tipos das implementações) para facilitar
diagnóstico, caso contrário prossiga para popular _handlers.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@InvoiceReminder.ExternalServices/BarcodeReader/BarcodeHandlerFactory.cs`:
- Around line 9-12: A construção de _handlers em BarcodeHandlerFactory está
usando ToDictionary diretamente, o que deixa a falha pouco clara se houver
InvoiceType duplicado; antes de chamar ToDictionary, valide a coleção
IEnumerable<IInvoiceBarcodeHandler> (por exemplo em BarcodeHandlerFactory
constructor) agrupando por InvoiceType, detecte chaves com Count>1 e lance uma
ArgumentException/InvalidOperationException explícita que liste os InvoiceType
conflitantes (e opcionalmente os tipos das implementações) para facilitar
diagnóstico, caso contrário prossiga para popular _handlers.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8bd01250-319a-4552-9cde-fb49a9f6bf19

📥 Commits

Reviewing files that changed from the base of the PR and between 89428c9 and 74f0689.

📒 Files selected for processing (9)
  • InvoiceReminder.CrossCutting.IoC/DependencyInjectionConfig.cs
  • InvoiceReminder.ExternalServices/BarcodeReader/AccountInvoiceBarcodeHandler.cs
  • InvoiceReminder.ExternalServices/BarcodeReader/BankInvoiceBarcodeHandler.cs
  • InvoiceReminder.ExternalServices/BarcodeReader/BarcodeHandlerFactory.cs
  • InvoiceReminder.ExternalServices/BarcodeReader/BarcodeReaderService.cs
  • InvoiceReminder.ExternalServices/BarcodeReader/IBarcodeHandlerFactory.cs
  • InvoiceReminder.ExternalServices/BarcodeReader/IInvoiceBarcodeHandler.cs
  • InvoiceReminder.UnitTests.ExternalServices/BarcodeReader/BarcodeHandlerFactoryTests.cs
  • InvoiceReminder.UnitTests.ExternalServices/BarcodeReader/BarcodeReaderServiceTests.cs

Adds a check during `BarcodeHandlerFactory` initialization to ensure that no two `IInvoiceBarcodeHandler` implementations are registered for the same `InvoiceType`. This prevents potential runtime errors caused by ambiguous handler resolution and guarantees a clear one-to-one mapping between invoice types and their dedicated handlers.
@jldsilva jldsilva merged commit 49839a0 into development May 14, 2026
5 checks passed
@jldsilva jldsilva deleted the Refactor-InvoiceBarcodeHandlers branch May 14, 2026 00:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant