Skip to content

[feature/22] :: generate a valid cpf#21

Merged
wellfernandes merged 6 commits intodevelopfrom
feature/22-generate-a-valid-cpf
Mar 8, 2025
Merged

[feature/22] :: generate a valid cpf#21
wellfernandes merged 6 commits intodevelopfrom
feature/22-generate-a-valid-cpf

Conversation

@wellfernandes
Copy link
Copy Markdown
Member

@wellfernandes wellfernandes commented Feb 23, 2025

  • added valid cpf generator
  • added cpf composition in person

obs: cpf added as an entity

Summary by CodeRabbit

  • New Features
    • Person information is now enhanced to display CPF details.
    • Introduced functionality to generate valid CPF numbers with an option for formatted output.
    • Added validation checks for CPF numbers, ensuring correct formatting and digit accuracy.
    • Improved error messaging for cases of invalid CPF entries.

@wellfernandes wellfernandes self-assigned this Feb 23, 2025
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Feb 23, 2025

Walkthrough

This pull request updates multiple components to enhance CPF (Cadastro de Pessoas Físicas) support. The mock example now prints the CPF field in addition to the usual person details. In the CPF package, a new error variable is added, and two new files introduce functions for generating and validating CPF numbers. Additionally, the Person entity is updated to include a CPF field, with corresponding changes in the person generator to call the CPF generation functionality and handle any errors.

Changes

File(s) Change Summary
examples/mock_example.go Updated the output format in the GenerateMockExample function to include the CPF field (person_mock.CPF) in the printed string.
pkg/mocai/entities/cpf/{errors.go, generator.go, validator.go} Introduced CPF-specific functionality in the CPF package: added ErrInvalidCPF in errors.go; implemented GenerateCPF (with helper calculateCheckDigit) in generator.go; added ValidateCPF in validator.go to validate CPF values.
pkg/mocai/entities/person/generator.go Added a new CPF string field to the Person struct and integrated CPF generation via a call to cpf.GenerateCPF(false) in the GeneratePerson function, including error handling for CPF generation failures.

Sequence Diagram(s)

sequenceDiagram
  participant Client as Client
  participant PersonGen as GeneratePerson
  participant CPFGen as GenerateCPF
  Client->>PersonGen: Call GeneratePerson()
  PersonGen->>CPFGen: Request CPF generation (formatted=false)
  CPFGen-->>PersonGen: Return generated CPF or error
  PersonGen-->>Client: Return Person struct with CPF field
Loading
sequenceDiagram
  participant CPFGen as GenerateCPF
  participant Calc as calculateCheckDigit
  CPFGen->>Calc: Compute first check digit (from first 9 digits)
  Calc-->>CPFGen: Return first check digit
  CPFGen->>Calc: Compute second check digit (from first 10 digits)
  Calc-->>CPFGen: Return second check digit
  CPFGen-->>CPFGen: Format CPF string if required
  CPFGen-->>Caller: Return complete CPF number
Loading

Possibly related PRs

  • [feature-34] :: docs: updated readme #19: Addresses modifications in the GeneratePerson function and handling of person-related data, which aligns with the CPF integration changes introduced in this PR.

Suggested reviewers

  • DODOSUBI
  • nikunjxforia
  • nikultaka

Poem

I'm a little rabbit, hopping through code today,
Discovering CPFs in functions, in a bright new display.
Check digits calculated with a swift little spree,
New fields and errors, as neat as can be.
With bytes and bounds all set, I'm full of delight—
Celebrating this change with a joyful hop into the night! 🐇


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f826d41 and 8a494c2.

📒 Files selected for processing (1)
  • pkg/mocai/entities/cpf/validator.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/mocai/entities/cpf/validator.go

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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.

Actionable comments posted: 1

🔭 Outside diff range comments (1)
pkg/mocai/entities/person/generator.go (1)

60-64: 💡 Verification agent

🧩 Analysis chain

Consider adding CPF validation in Person validation.

While the CPF generation likely includes validation, consider adding CPF validation to the Person struct's validation logic to ensure data integrity at the entity level. This could help catch any potential issues if the CPF field is modified directly.

Let's check if there's CPF validation in the generator:


🏁 Script executed:

#!/bin/bash
# Search for CPF validation in the codebase
rg -A 5 "ValidateCPF|validateCPF" .

Length of output: 656


Action Required: Incorporate CPF Validation in Person Entity

While CPF generation appears to use the dedicated validator (see pkg/mocai/entities/cpf/validator.go and its ValidateCPF function), the Person struct’s validation (in pkg/mocai/entities/person/generator.go around lines 60–64) currently only checks for non-empty names. To ensure full data integrity—especially if the CPF field could be altered directly—please integrate CPF validation into the Person validation logic using the existing CPF validator.

  • Action: Update the Person validation to include a call to ValidateCPF(cpf) if a CPF field exists.
  • Rationale: This will help catch potential issues with CPF values at the entity level, complementing the CPF generation process.
🧹 Nitpick comments (8)
pkg/mocai/entities/cpf/errors.go (1)

5-7: Consider enhancing the error message.

The error message could be more descriptive to help users understand what makes a CPF invalid.

-	ErrInvalidCPF = errors.New("invalid CPF")
+	ErrInvalidCPF = errors.New("invalid CPF: must be 11 digits in format xxx.xxx.xxx-xx")
pkg/mocai/entities/cpf/validator.go (1)

31-40: Consider extracting repeated digit check into a helper function.

The repeated digit check could be extracted into a helper function for better readability and reusability.

+// hasRepeatedDigits checks if all digits in the slice are the same.
+func hasRepeatedDigits(digits []int) bool {
+	firstDigit := digits[0]
+	for _, digit := range digits[1:] {
+		if digit != firstDigit {
+			return false
+		}
+	}
+	return true
+}

 func ValidateCPF(cpf string) bool {
	// ... previous code ...

-	// Check if all digits are the same (invalid CPF)
-	allSame := true
-	for i := 1; i < len(digits); i++ {
-		if digits[i] != digits[0] {
-			allSame = false
-			break
-		}
-	}
-	if allSame {
+	if hasRepeatedDigits(digits) {
		return false
	}

	// ... rest of the code ...
}
pkg/mocai/entities/cpf/generator.go (3)

32-32: Simplify string conversion.

The current string conversion is unnecessarily complex. A simpler approach would be to build the string directly.

-	cpf := strings.Trim(strings.Join(strings.Fields(fmt.Sprint(digits)), ""), "[]")
+	var sb strings.Builder
+	for _, digit := range digits {
+		sb.WriteString(fmt.Sprint(digit))
+	}
+	cpf := sb.String()

37-37: Improve error wrapping.

Instead of creating a new error with the same message, wrap the existing error.

-			return "", errors.New(ErrInvalidCPF.Error())
+			return "", fmt.Errorf("failed to format CPF: %w", ErrInvalidCPF)

11-43: Consider adding a constant for CPF length.

The magic number 11 appears multiple times. Consider extracting it into a constant.

+const (
+	// CPFLength is the expected length of a CPF number
+	CPFLength = 11
+)

 func GenerateCPF(formatted bool) (string, error) {
	// ... previous code ...

	if formatted {
-		if len(cpf) != 11 {
+		if len(cpf) != CPFLength {
			return "", fmt.Errorf("failed to format CPF: %w", ErrInvalidCPF)
		}
		return cpf[:3] + "." + cpf[3:6] + "." + cpf[6:9] + "-" + cpf[9:], nil
	}

	return cpf, nil
}
examples/mock_example.go (1)

36-37: Consider improving error handling.

The code continues to print person details even if there's an error during generation. Consider adding a return statement after error handling.

 	person_mock, err := person.GeneratePerson()
 	if err != nil {
 		fmt.Print(err)
+		return
 	}
pkg/mocai/entities/person/generator.go (2)

14-22: Update struct documentation to include CPF field.

The struct comment should be updated to mention the CPF field since it's now part of the Person struct.

-// Person represents a mock person with first names, last name, and age.
+// Person represents a mock person with first names, last name, age, and CPF (Brazilian individual taxpayer registry).

54-58: Document the false parameter meaning.

While the comment indicates "without a mask", it would be clearer to document the boolean parameter's meaning directly in the code.

-	// Generate a random CPF without a mask
+	// Generate a random CPF (mask=false to get numbers only, without formatting)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ee39394 and f826d41.

📒 Files selected for processing (5)
  • examples/mock_example.go (1 hunks)
  • pkg/mocai/entities/cpf/errors.go (1 hunks)
  • pkg/mocai/entities/cpf/generator.go (1 hunks)
  • pkg/mocai/entities/cpf/validator.go (1 hunks)
  • pkg/mocai/entities/person/generator.go (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Build and Test
🔇 Additional comments (2)
pkg/mocai/entities/person/generator.go (2)

9-9: LGTM! Import added correctly.

The CPF package import is properly placed with other internal imports.


72-72: LGTM! CPF field initialized correctly.

The CPF field is properly initialized in the Person struct with the generated value.


// Calculate the second check digit
secondCheckDigit := calculateCheckDigit(digits[:10], 11)
return secondCheckDigit != digits[10]
Copy link
Copy Markdown

@coderabbitai coderabbitai bot Feb 23, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix the incorrect return statement logic.

The return statement is inverted. It currently returns true when the second check digit doesn't match, which is incorrect.

-	return secondCheckDigit != digits[10]
+	return secondCheckDigit == digits[10]
📝 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.

Suggested change
return secondCheckDigit != digits[10]
return secondCheckDigit == digits[10]

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

fixed

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@wellfernandes Thanks for fixing the CPF validator's return statement! 🎉


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

@BertBR BertBR self-requested a review March 8, 2025 18:40
Copy link
Copy Markdown
Collaborator

@BertBR BertBR left a comment

Choose a reason for hiding this comment

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

LGTM

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.

2 participants