[feature/22] :: generate a valid cpf#21
Conversation
WalkthroughThis 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
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
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
Possibly related PRs
Suggested reviewers
Poem
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
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.goand itsValidateCPFfunction), the Person struct’s validation (inpkg/mocai/entities/person/generator.goaround 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
11appears 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 thefalseparameter 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
📒 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.
pkg/mocai/entities/cpf/validator.go
Outdated
|
|
||
| // Calculate the second check digit | ||
| secondCheckDigit := calculateCheckDigit(digits[:10], 11) | ||
| return secondCheckDigit != digits[10] |
There was a problem hiding this comment.
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.
| return secondCheckDigit != digits[10] | |
| return secondCheckDigit == digits[10] |
There was a problem hiding this comment.
@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!
obs: cpf added as an entity
Summary by CodeRabbit