Skip to content

Conversation

@Omri-Levy
Copy link
Contributor

@Omri-Levy Omri-Levy commented Jun 25, 2025

Summary by CodeRabbit

  • Bug Fixes
    • Improved phone number parsing to handle input more accurately by disabling automatic extraction.
  • Tests
    • Added unit tests to verify phone number formatting across various input scenarios.

@changeset-bot
Copy link

changeset-bot bot commented Jun 25, 2025

⚠️ No Changeset found

Latest commit: f975549

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 25, 2025

Walkthrough

The getPhoneNumberFormatter function was updated to call parsePhoneNumber with an options object { extract: false } to disable automatic extraction during parsing. A new unit test file was added to verify the function’s behavior with various input types, including invalid strings and formatted phone numbers. A data-migrations commit reference was also updated.

Changes

File(s) Change Summary
apps/backoffice-v2/src/common/utils/get-phone-number-formatter/get-phone-number-formatter.ts Modified parsePhoneNumber call to include { extract: false } option, disabling automatic extraction.
apps/backoffice-v2/src/common/utils/get-phone-number-formatter/get-phone-number-formatter.unit.test.ts Added unit tests covering invalid input (email), valid phone numbers with country code, and hyphenated input.
services/workflows-service/prisma/data-migrations Updated commit reference for data-migrations subproject.

Poem

A number parsed with careful art,
Extraction paused, a brand new start!
Tests now check each string with care,
No sneaky emails hiding there.
🐇🔢 Precision hops through the air!


📜 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 02129dd and f975549.

📒 Files selected for processing (2)
  • apps/backoffice-v2/src/common/utils/get-phone-number-formatter/get-phone-number-formatter.ts (1 hunks)
  • services/workflows-service/prisma/data-migrations (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • services/workflows-service/prisma/data-migrations
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/backoffice-v2/src/common/utils/get-phone-number-formatter/get-phone-number-formatter.ts
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: test_linux
  • GitHub Check: spell_check
  • GitHub Check: lint
  • GitHub Check: build (ubuntu-latest)
  • GitHub Check: format
  • GitHub Check: Analyze (javascript)
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @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
Contributor

@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)
apps/backoffice-v2/src/common/utils/get-phone-number-formatter/get-phone-number-formatter.unit.test.ts (1)

1-44: Expand test coverage to include more edge cases and validation scenarios.

The current tests cover basic scenarios but lack comprehensive edge case testing for the new validation logic. Consider expanding the test suite to ensure robustness.

Add these additional test cases to improve coverage:

+  describe('when invalid phone formats are passed', () => {
+    it.each([
+      ['empty string', ''],
+      ['just plus sign', '+'],
+      ['just hyphens', '---'],
+      ['email with numbers', '[email protected]'],
+      ['starts with hyphen', '-1234567890'],
+      ['ends with hyphen', '1234567890-'],
+      ['double hyphens', '123--456-7890'],
+      ['hyphen before plus', '123-+456'],
+    ])('should return undefined for %s', (_, value) => {
+      const result = getPhoneNumberFormatter(value);
+      expect(result).toBeUndefined();
+    });
+  });
+
+  describe('when valid phone formats are passed', () => {
+    it.each([
+      ['US format without country code', '1234567890'],
+      ['international with spaces', '+1 234 567 8900'],
+      ['with parentheses', '+1 (234) 567-8900'],
+      ['UK format', '+44 20 7946 0958'],
+    ])('should return a formatter for %s', (_, value) => {
+      const result = getPhoneNumberFormatter(value);
+      expect(result).toBeDefined();
+    });
+  });
+
+  describe('when testing actual formatting', () => {
+    it('should format phone numbers correctly', () => {
+      const result = getPhoneNumberFormatter('+972-052-625-3312');
+      expect(result?.formatInternational()).toBe('+972 52-625-3312');
+    });
+  });

The current tests also don't verify that the formatted output is correct - only that something is returned. Consider testing the actual formatting behavior to ensure the function works end-to-end.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4b8d1a2 and 02129dd.

📒 Files selected for processing (2)
  • apps/backoffice-v2/src/common/utils/get-phone-number-formatter/get-phone-number-formatter.ts (1 hunks)
  • apps/backoffice-v2/src/common/utils/get-phone-number-formatter/get-phone-number-formatter.unit.test.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`apps/backoffice-v2/**/*.{ts,tsx}`: Use functional components with TypeScript. Implement smart/dumb component pattern. Place components in feature-based directories. Use compound c...

apps/backoffice-v2/**/*.{ts,tsx}: Use functional components with TypeScript.
Implement smart/dumb component pattern.
Place components in feature-based directories.
Use compound components for complex UIs.
Follow atomic design principles.
Use React Query for server state and API calls.
Use Context for shared state.
Implement state machines for complex flows.
Use local state for UI-only state.
Follow unidirectional data flow.
Use strict TypeScript configuration.
Define interfaces for all props.
Use discriminated unions for state.
Leverage type inference.
Use Radix UI for accessible components.
Implement proper ARIA attributes.
Follow consistent styling patterns.
Use composition over inheritance.
Keep components small and focused.
Use React Hook Form for forms.
Implement Zod for validation.
Handle form submission states.
Show validation feedback.
Use controlled inputs when needed.
Implement proper loading states for data fetching.
Handle error states gracefully.
Cache responses appropriately.
Type API responses.
Use error boundaries.
Implement fallback UI.
Handle async errors.
Show user-friendly error messages.
Log errors appropriately.
Use React.memo wisely.
Implement proper code splitting.
Use lazy loading for routes.
Optimize re-renders.
Profile performance regularly.
Write unit tests for components.
Use React Testing Library.
Mock external dependencies in tests.
Maintain good test coverage.
Follow feature-based organization.
Use index files for exports.
Keep related files together.
Use consistent naming.
Implement barrel exports.
Use Tailwind CSS for styling.
Follow utility-first approach for styling.
Use CSS variables for theming.
Keep styles maintainable.
Use CSS modules when needed.
Document complex logic.
Write clear component documentation.
Keep documentation up to date.
Use JSDoc when helpful.
Follow ESLint rules.
Use consistent formatting.
Write clear variable names.
Keep functions pure.
Use meaningful types.
Validate user input.
Implement proper authentication.
Handle sensitive data carefully.
Follow security best practices.
Use HTTPS for API calls.
Follow WCAG guidelines for accessibility.
Use semantic HTML.
Test with screen readers.
Ensure keyboard navigation.
Provide proper focus management.

  • apps/backoffice-v2/src/common/utils/get-phone-number-formatter/get-phone-number-formatter.unit.test.ts
  • apps/backoffice-v2/src/common/utils/get-phone-number-formatter/get-phone-number-formatter.ts
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Analyze (javascript)
  • GitHub Check: test_linux
  • GitHub Check: build (ubuntu-latest)
  • GitHub Check: lint
  • GitHub Check: format

Comment on lines 9 to 11
if (!/^(?!-)(?!\+?$)(?!-+$)(?!.*-\+)(?!.*--)\+?[\d-]+(?<!-)$/.test(value)) {
return;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

🧩 Verification correct

Simplify the complex regex validation and add documentation.

The regex pattern is extremely complex with multiple negative lookaheads and lookbehinds, making it difficult to understand, maintain, and verify for correctness. This could lead to maintenance issues and potential bugs.

Consider these improvements:

  1. Add JSDoc documentation explaining the validation rules:
/**
 * Wraps {@link parsePhoneNumber} with try catch.
+ * Validates input format before parsing to reject non-phone number strings.
 * @param value
+ * @returns PhoneNumber instance or undefined if invalid/unparseable
 */
  1. Simplify the regex or use a more readable approach:
-    if (!/^(?!-)(?!\+?$)(?!-+$)(?!.*-\+)(?!.*--)\+?[\d-]+(?<!-)$/.test(value)) {
+    // Basic validation: should contain only digits, hyphens, and optional leading plus
+    // Reject obvious non-phone formats like emails
+    if (!/^\+?[\d\s\-\(\)]+$/.test(value) || value.includes('@')) {
  1. Extract validation logic to a separate function for better testability:
+const isValidPhoneNumberFormat = (value: string): boolean => {
+  // Reject emails and other obvious non-phone formats
+  if (value.includes('@') || value.includes('.com')) return false;
+  
+  // Allow only phone-like characters
+  return /^\+?[\d\s\-\(\)]+$/.test(value);
+};

export const getPhoneNumberFormatter = (value: string) => {
  try {
-    if (!/^(?!-)(?!\+?$)(?!-+$)(?!.*-\+)(?!.*--)\+?[\d-]+(?<!-)$/.test(value)) {
+    if (!isValidPhoneNumberFormat(value)) {

Let me verify the current regex behavior with edge cases:


🏁 Script executed:

#!/bin/bash
# Test the regex against various phone number formats to ensure it works correctly

cat > test_regex.js << 'EOF'
const regex = /^(?!-)(?!\+?$)(?!-+$)(?!.*-\+)(?!.*--)\+?[\d-]+(?<!-)$/;

const testCases = [
  // Should pass
  '+1234567890',
  '1234567890', 
  '+1-234-567-890',
  '+972-052-625-3312',
  
  // Should fail  
  '[email protected]',
  '[email protected]',
  '+',
  '-',
  '--',
  '+-123',
  '123-+456',
  '123--456',
  '123-',
  '-123'
];

testCases.forEach(test => {
  const result = regex.test(test);
  console.log(`"${test}": ${result}`);
});
EOF

node test_regex.js

Length of output: 278


Simplify the complex regex validation and add documentation.

The regex pattern is extremely complex with multiple negative lookaheads and lookbehinds, making it difficult to understand, maintain, and verify for correctness. This could lead to maintenance issues and potential bugs.

Consider these improvements:

  1. Add JSDoc documentation explaining the validation rules:
/**
 * Wraps {@link parsePhoneNumber} with try catch.
+ * Validates input format before parsing to reject non-phone number strings.
 * @param value
+ * @returns PhoneNumber instance or undefined if invalid/unparseable
 */
  1. Simplify the regex or use a more readable approach:
-    if (!/^(?!-)(?!\+?$)(?!-+$)(?!.*-\+)(?!.*--)\+?[\d-]+(?<!-)$/.test(value)) {
+    // Basic validation: should contain only digits, hyphens, and optional leading plus
+    // Reject obvious non-phone formats like emails
+    if (!/^\+?[\d\s\-\(\)]+$/.test(value) || value.includes('@')) {
  1. Extract validation logic to a separate function for better testability:
+const isValidPhoneNumberFormat = (value: string): boolean => {
+  // Reject emails and other obvious non-phone formats
+  if (value.includes('@') || value.includes('.com')) return false;
+  
+  // Allow only phone-like characters
+  return /^\+?[\d\s\-\(\)]+$/.test(value);
+};

export const getPhoneNumberFormatter = (value: string) => {
  try {
-    if (!/^(?!-)(?!\+?$)(?!-+$)(?!.*-\+)(?!.*--)\+?[\d-]+(?<!-)$/.test(value)) {
+    if (!isValidPhoneNumberFormat(value)) {

Let me verify the current regex behavior with edge cases:

#!/bin/bash
# Test the regex against various phone number formats to ensure it works correctly

cat > test_regex.js << 'EOF'
const regex = /^(?!-)(?!\+?$)(?!-+$)(?!.*-\+)(?!.*--)\+?[\d-]+(?<!-)$/;

const testCases = [
  // Should pass
  '+1234567890',
  '1234567890', 
  '+1-234-567-890',
  '+972-052-625-3312',
  
  // Should fail  
  '[email protected]',
  '[email protected]',
  '+',
  '-',
  '--',
  '+-123',
  '123-+456',
  '123--456',
  '123-',
  '-123'
];

testCases.forEach(test => {
  const result = regex.test(test);
  console.log(`"${test}": ${result}`);
});
EOF

node test_regex.js
🤖 Prompt for AI Agents
In
apps/backoffice-v2/src/common/utils/get-phone-number-formatter/get-phone-number-formatter.ts
around lines 9 to 11, the current regex for phone number validation is overly
complex and hard to maintain. Refactor by extracting the validation logic into a
separate well-named function, simplify the regex to cover the necessary
validation rules more clearly, and add JSDoc comments explaining the validation
criteria and expected input formats for better readability and maintainability.

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