Skip to content

[feature/28] :: create mock for id registration pt br#44

Merged
wellfernandes merged 13 commits intodevelopfrom
feature/28-create-mock-for-id-registration-pt-br
Apr 4, 2025
Merged

[feature/28] :: create mock for id registration pt br#44
wellfernandes merged 13 commits intodevelopfrom
feature/28-create-mock-for-id-registration-pt-br

Conversation

@wellfernandes
Copy link
Copy Markdown
Member

@wellfernandes wellfernandes commented Apr 3, 2025

  • added rg document generation (national id)

#28

Summary by CodeRabbit

  • New Features

    • Enhanced mock output examples to include a generated national identification number with details such as the issuing state and authority.
    • Updated the formatting of identity-related information for improved clarity and consistency.
    • Introduced functionality for generating valid Brazilian national IDs (RG) specifically for São Paulo.
  • Documentation

    • Updated mascot image source in the README files to improve visual representation.

@wellfernandes wellfernandes requested a review from DODOSUBI April 3, 2025 16:27
@wellfernandes wellfernandes self-assigned this Apr 3, 2025
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 3, 2025

Walkthrough

This pull request introduces national ID generation functionality into the mock example. The GenerateMockExample function now calls national_id.GenerateNationalID to produce and print a Brazilian national ID (RG) along with its state and issuing body. In support of this, new modules in the national_id package have been added, including generation, formatting, check digit calculation, and detailed error handling. The changes affect both the mock example and the national ID generation infrastructure.

Changes

File(s) Change Summary
examples/mock_example.go Modified GenerateMockExample to call national_id.GenerateNationalID(false), printing the national ID details and handling errors.
pkg/mocai/entities/national_id/generator.go, pkg/mocai/entities/national_id/countries/brazilian_national_id.go, pkg/mocai/entities/national_id/countries/errors.go Introduced national ID generation modules: a new NationalID struct with generator function; implementation of Brazilian RG generation with check digit and formatting functions; and custom error definitions for handling generation issues.
README.md, docs/localization/pt/README-PT.md Updated image source for the project mascot from mocai-mascot.png to mocai.svg.

Possibly related issues

Possibly related PRs

Suggested labels

enhancement

Suggested reviewers

  • BertBR
  • DODOSUBI

Poem

I'm but a little rabbit, coding through the night,
Hopping among the functions with pure delight.
National IDs now spring from lines neat and true,
Each RG number crafted, formatted just for you.
With every check digit computed, I cheer in my code glen,
Skipping along, a joyful rabbit among the den.
Coding carrots and bytes, I celebrate these changes again!


📜 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 57edec8 and 35555a2.

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

🪧 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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: 3

🧹 Nitpick comments (8)
pkg/mocai/entities/national_id/generator.go (2)

5-7: Struct design looks good but consider future extensibility.

The NationalID struct is well-designed for the current implementation with Brazilian RG support. However, as new national IDs from other countries are added in the future, you might need to refactor this structure.

Consider whether you'll want to structure this more generically in the future, perhaps with a country-agnostic interface or a type field to identify which country's ID is being used.


9-11: Documentation is clear but could mention Brazil-specific scope.

The documentation clearly explains the formatting options, but it could be more explicit that this currently only supports Brazilian IDs.

-// GenerateNationalID generates a Brazilian national ID [RG].
+// GenerateNationalID generates a national ID, currently supporting only Brazilian RG.
pkg/mocai/entities/national_id/countries/errors.go (1)

8-8: Error message could be more specific.

The error message for ErrToConvertDigit is a bit vague.

-	ErrToConvertDigit                = errors.New("error converting digit")
+	ErrToConvertDigit                = errors.New("error converting RG digit from string to integer")
examples/mock_example.go (1)

55-59: Error handling inconsistency.

The error handling for the national ID generation doesn't follow the same pattern as the other error handling blocks in this file which include a return statement.

	nationalID_mock, err := national_id.GenerateNationalID(false)
	if err != nil {
		fmt.Print(err)
+		return
	}
pkg/mocai/entities/national_id/countries/brazilian_national_id.go (4)

18-32: Function implementation is correct but state-specific.

The function correctly implements the Brazilian national ID generation, but it's specifically for São Paulo (SP). This could be made clearer in the documentation.

-// GenerateBrazilianNationalID generates a valid Brazilian national ID [RG] for São Paulo.
+// GenerateBrazilianNationalID generates a valid Brazilian national ID [RG].
+// Currently, only São Paulo (SP) state IDs are supported.

34-38: Missing validation for base number length.

The function generates a random base number but doesn't validate that it doesn't exceed 8 digits, despite having an error defined for this case (ErrBaseNumberExceedsLimit).

// calculateSPRGDigit generates a valid Brazilian national ID [RG] for São Paulo.
func calculateSPRGDigit() (string, error) {
	// generate a random base until 8 digits
	base := globalRand.Intn(100000000)
	baseStr := fmt.Sprintf("%08d", base)
+	
+	if len(baseStr) > 8 {
+		return "", ErrBaseNumberExceedsLimit
+	}

41-48: Inefficient array initialization.

Creating a fixed-size array and populating it in a loop is less efficient and clear than using a slice literal or more direct conversion.

-	// slice contains the digits
-	d := make([]int, 8)
-	for i := range 8 {
-		val, err := strconv.Atoi(string(baseStr[i]))
-		if err != nil {
-			return "", ErrToConvertDigit
-		}
-		d[i] = val
-	}
+	// slice contains the digits
+	d := make([]int, 8)
+	for i, r := range baseStr {
+		val, err := strconv.Atoi(string(r))
+		if err != nil {
+			return "", ErrToConvertDigit
+		}
+		d[i] = val
+	}

51-51: Typo in variable name.

The variable is named "wheights" when it should be "weights".

-	// wheights from right to left: 9, 8, 7, 6, 5, 4, 3, 2
-	wheights := []int{2, 3, 4, 5, 6, 7, 8, 9}
+	// weights from right to left: 9, 8, 7, 6, 5, 4, 3, 2
+	weights := []int{2, 3, 4, 5, 6, 7, 8, 9}

And then update the reference in the calculation:

	for i := 0; i < 8; i++ {
-		sum += d[7-i] * wheights[i]
+		sum += d[7-i] * weights[i]
	}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9b06814 and 55ca91d.

📒 Files selected for processing (4)
  • examples/mock_example.go (2 hunks)
  • pkg/mocai/entities/national_id/countries/brazilian_national_id.go (1 hunks)
  • pkg/mocai/entities/national_id/countries/errors.go (1 hunks)
  • pkg/mocai/entities/national_id/generator.go (1 hunks)
🧰 Additional context used
🧬 Code Definitions (3)
pkg/mocai/entities/national_id/generator.go (1)
pkg/mocai/entities/national_id/countries/brazilian_national_id.go (2)
  • RG (12-16)
  • GenerateBrazilianNationalID (19-32)
examples/mock_example.go (1)
pkg/mocai/entities/company/countries/brazilian_company.go (1)
  • BrazilianCompany (15-18)
pkg/mocai/entities/national_id/countries/brazilian_national_id.go (1)
pkg/mocai/entities/national_id/countries/errors.go (1)
  • ErrToConvertDigit (8-8)
🔇 Additional comments (5)
pkg/mocai/entities/national_id/generator.go (1)

12-19: Function implementation is correct and handles errors properly.

The implementation correctly calls the country-specific function and properly handles error cases.

examples/mock_example.go (3)

10-10: Import addition is correct.

The national_id package import is properly added to support the new functionality.


67-69: Output formatting for national ID is well-structured.

The output formatting for the national ID is consistent with the other data being displayed.


70-91: Formatting improvements enhance readability.

The consistent formatting throughout the output section improves the overall readability of the output.

pkg/mocai/entities/national_id/countries/brazilian_national_id.go (1)

12-16: RG struct design is appropriate.

The RG struct contains all necessary fields for a Brazilian national ID.

"time"
)

var globalRand = rand.New(rand.NewSource(time.Now().UnixNano()))
Copy link
Copy Markdown

@coderabbitai coderabbitai bot Apr 3, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

Security risk with math/rand for ID generation.

Using math/rand for generating identity documents is not secure enough as it's predictable. For security-sensitive data like national IDs, crypto/rand should be used instead.

-import (
-	"fmt"
-	"math/rand"
-	"strconv"
-	"time"
-)
+import (
+	"crypto/rand"
+	"fmt"
+	"math/big"
+	"strconv"
+	"time"
+)

-var globalRand = rand.New(rand.NewSource(time.Now().UnixNano()))
+// No need for a global variable with crypto/rand

Then update the calculateSPRGDigit function:

func calculateSPRGDigit() (string, error) {
	// generate a random base until 8 digits
-	base := globalRand.Intn(100000000)
-	baseStr := fmt.Sprintf("%08d", base)
+	max := big.NewInt(100000000)
+	n, err := rand.Int(rand.Reader, max)
+	if err != nil {
+		return "", ErrGeneratingBrazilianNationalID
+	}
+	baseStr := fmt.Sprintf("%08d", n.Int64())
📝 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
var globalRand = rand.New(rand.NewSource(time.Now().UnixNano()))
package brazilian_national_id
import (
"crypto/rand"
"fmt"
"math/big"
"strconv"
"time"
)
// No need for a global variable with crypto/rand
func calculateSPRGDigit() (string, error) {
// generate a random base until 8 digits
max := big.NewInt(100000000)
n, err := rand.Int(rand.Reader, max)
if err != nil {
return "", ErrGeneratingBrazilianNationalID
}
baseStr := fmt.Sprintf("%08d", n.Int64())
return baseStr, nil
}

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.

there’s no need since the data is made up

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 You're right. Since this is just for generating mock data and not real IDs, using math/rand is perfectly fine. No need for the cryptographically secure alternative in this case.

✏️ Learnings added
Learnt from: wellfernandes
PR: brazzcore/mocai#44
File: pkg/mocai/entities/national_id/countries/brazilian_national_id.go:10-10
Timestamp: 2025-04-03T19:13:54.519Z
Learning: For the mocai project, using math/rand is acceptable for generating mock data (like national IDs) since the data is fictitious and not intended for security-sensitive purposes.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

Comment on lines +72 to +75
func formatRG(input string) string {
if len(input) != 9 {
return input
}
Copy link
Copy Markdown

@coderabbitai coderabbitai bot Apr 3, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improve validation in formatRG function.

The function only checks if the length is not equal to 9, but doesn't handle cases where it's less than 9, which could cause a panic with the slicing operations.

func formatRG(input string) string {
-	if len(input) != 9 {
+	if len(input) < 9 {
		return input
	}
📝 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
func formatRG(input string) string {
if len(input) != 9 {
return input
}
func formatRG(input string) string {
if len(input) < 9 {
return input
}
// ... (rest of the function logic)
}

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.

its not the best option as it doesn’t cover all cases

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Get the complete implementation of the formatRG function
cat pkg/mocai/entities/national_id/countries/brazilian_national_id.go

Length of output: 1697


@wellfernandes You're absolutely right. Looking at the full function:

func formatRG(input string) string {
	if len(input) != 9 {
		return input
	}
	return fmt.Sprintf("%s.%s.%s-%s", input[0:3], input[3:6], input[6:8], input[8:])
}

The original check len(input) != 9 is better as it handles both cases:

  • Inputs shorter than 9 characters (preventing slice panics)
  • Inputs longer than 9 characters (preventing incorrect formatting)

My suggested change would incorrectly attempt to format inputs that are too long. The current implementation is already optimal for handling all edge cases.

✏️ Learnings added
Learnt from: wellfernandes
PR: brazzcore/mocai#44
File: pkg/mocai/entities/national_id/countries/brazilian_national_id.go:72-75
Timestamp: 2025-04-03T19:39:07.868Z
Learning: In the Brazilian RG (national ID) formatter, the check for `len(input) != 9` is intentional as it handles both cases where input is too short (preventing panics) and too long (preventing incorrect formatting).

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

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: 0

🧹 Nitpick comments (3)
pkg/mocai/entities/national_id/countries/brazilian_national_id.go (3)

34-35: Incorrect function comment for calculateSPRGDigit.

The function comment appears to be copied from GenerateBrazilianNationalID and doesn't accurately describe this function's specific purpose.

-// calculateSPRGDigit generates a valid Brazilian national ID [RG] for São Paulo.
+// calculateSPRGDigit generates a random base number and calculates the check digit
+// for a São Paulo RG (Registro Geral) document.

41-48: Digit extraction loop could be simplified.

The current implementation creates a slice and loops through the string to convert each character to an integer. This could be more concise.

-	// slice contains the digits
-	d := make([]int, 8)
-	for i := range 8 {
-		val, err := strconv.Atoi(string(baseStr[i]))
-		if err != nil {
-			return "", ErrToConvertDigit
-		}
-		d[i] = val
-	}
+	// slice contains the digits
+	d := make([]int, 8)
+	for i, char := range baseStr {
+		val, err := strconv.Atoi(string(char))
+		if err != nil {
+			return "", ErrToConvertDigit
+		}
+		d[i] = val
+	}

50-51: Typo in variable name.

There's a spelling error in the variable name "wheights".

-	// wheights from right to left: 9, 8, 7, 6, 5, 4, 3, 2
-	wheights := []int{2, 3, 4, 5, 6, 7, 8, 9}
+	// weights from right to left: 9, 8, 7, 6, 5, 4, 3, 2
+	weights := []int{2, 3, 4, 5, 6, 7, 8, 9}

Don't forget to update the reference in the calculation part as well:

-		sum += d[7-i] * wheights[i]
+		sum += d[7-i] * weights[i]
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 12e83f0 and 57edec8.

📒 Files selected for processing (2)
  • pkg/mocai/entities/national_id/countries/brazilian_national_id.go (1 hunks)
  • pkg/mocai/entities/national_id/countries/errors.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/mocai/entities/national_id/countries/errors.go
🧰 Additional context used
🧠 Learnings (1)
pkg/mocai/entities/national_id/countries/brazilian_national_id.go (2)
Learnt from: wellfernandes
PR: brazzcore/mocai#44
File: pkg/mocai/entities/national_id/countries/brazilian_national_id.go:10-10
Timestamp: 2025-04-03T19:13:54.833Z
Learning: For the mocai project, using math/rand is acceptable for generating mock data (like national IDs) since the data is fictitious and not intended for security-sensitive purposes.
Learnt from: wellfernandes
PR: brazzcore/mocai#44
File: pkg/mocai/entities/national_id/countries/brazilian_national_id.go:72-75
Timestamp: 2025-04-03T19:39:08.168Z
Learning: In the Brazilian RG (national ID) formatter, the check for `len(input) != 9` is intentional as it handles both cases where input is too short (preventing panics) and too long (preventing incorrect formatting).
🧬 Code Definitions (1)
pkg/mocai/entities/national_id/countries/brazilian_national_id.go (1)
pkg/mocai/entities/national_id/countries/errors.go (1)
  • ErrToConvertDigit (7-7)
🔇 Additional comments (4)
pkg/mocai/entities/national_id/countries/brazilian_national_id.go (4)

4-10: Import and global rand setup looks good.

The use of math/rand is appropriate for generating mock data as confirmed in previous discussions. The global random number generator is properly initialized with the current time as seed.


12-16: RG struct design is clean and appropriate.

The struct contains all necessary fields for a Brazilian national ID: Number, State, and IssuingBody.


18-32: GenerateBrazilianNationalID function implementation is well-structured.

The function properly handles error cases and conditionally formats the RG number. The returned struct contains all required information.


72-77: The formatRG function validation is appropriate.

The check for len(rgNumber) != 9 correctly handles both cases where input is too short (preventing panics) and too long (preventing incorrect formatting).

Copy link
Copy Markdown
Collaborator

@DODOSUBI DODOSUBI left a comment

Choose a reason for hiding this comment

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

LGTM

@wellfernandes wellfernandes merged commit fd80969 into develop Apr 4, 2025
2 checks passed
@wellfernandes wellfernandes deleted the feature/28-create-mock-for-id-registration-pt-br branch April 4, 2025 19:34
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.

3 participants