TSD - Contact Management
1. Document Control
| Version | Date | Author | Description |
|---|---|---|---|
| 1.0 | 2025-09-15 | BA Team | Initial Version |
Table of Contents
- Overview
- Technology Stack
- System Architecture Overview
- Functional Overview
- 4.1 Primary Mobile Number Management
- 4.2 Alternative Mobile Number Management
- 4.3 Email Management
- 4.3.1 Email Addition and Validation
- 4.3.2 OTP Verification via Email
- 4.3.3 Primary Email Assignment
- 4.3.4 Email Management Operations
- 4.4 Landline Number Management
- 4.5 Cross-User Contact Detection
- 4.5.1 Detection Algorithm
- 4.5.2 Contact Removal Process
- 4.5.3 Notification System
- User Interface
- 5.1 Primary Contact Display
- 5.1.1 Mobile Number Display
- 5.1.2 Email Display
- 5.1.3 Landline Display
- 5.2 Alternative Contact Management
- 5.2.1 Mobile Number Addition Modal
- 5.2.2 Email Addition Modal
- 5.2.3 Landline Addition Modal
- 5.3 Cross-User Contact Interface
- 5.3.1 Contact List Display
- 5.3.2 Removal Interface
- 5.1 Primary Contact Display
- Technical Specification
- 6.1 Frontend Implementation
- 6.1.1 Component Architecture
- 6.1.2 Form Handling
- 6.1.3 Routing
- 6.1.4 API Interactions
- 6.1.5 Error Handling and User Feedback
- 6.2 Backend Implementation
- 6.2.1 Database Schema
- 6.2.2 GraphQL Schema
- 6.2.3 Service Layer Logic
- 6.1 Frontend Implementation
- Integration Requirements
- Authentication
- Security Considerations
- 9.1 Input Validation
- 9.2 Verification Security
- 9.3 Data Protection
- 9.4 Access Control
- Error Handling
- 10.1 Validation Errors
- 10.2 Verification Errors
- 10.3 Business Logic Errors
- Performance Requirements
- 11.1 Response Times
- 11.2 Scalability
- Testing Strategy
- 12.1 Unit Tests
- 12.2 Integration Tests
- 12.3 End-to-End Tests
- 12.4 Performance Tests
- Monitoring and Analytics
- 13.1 Enhanced Metrics
- 13.2 Analytics
- Deployment Considerations
- 14.1 Environment Variables
- 14.2 Database Migrations
- 14.3 Feature Flags
- Future Enhancements
1. Overview
1.1 Purpose
This Technical Requirements Document defines the comprehensive specification for the Contacts Management module within the application ecosystem. The document outlines the architecture, functionality, and implementation details for managing user contact information including mobile numbers, email addresses and landline numbers with relationship mapping and cross-user contact detection capabilities.
The system is designed to provide secure, verified contact management with audit trails, ensuring all user communications are routed through verified primary contacts while maintaining flexibility for multiple contact methods.
1.2 Scope
The Contacts Management module encompasses the following core functionalities:
Primary Contact Management:
- Automatic population and management of primary mobile numbers from login credentials
- Primary contact assignment capability across all contact types (mobile, email, landline)
- Notification routing exclusively through primary contacts
Alternative Contact Management:
- Addition and verification of alternative mobile numbers with relationship labels and flexible OTP delivery options
- Comprehensive email management with OTP-based verification
- Landline number management with STD code support
Advanced Features:
- Cross-user contact detection and management
- Relationship-based contact categorization
- Audit trail maintenance for all contact operations
- Secure verification processes for all contact types
Out of Scope:
- Communication preference management (all notifications route to primary contacts)
- Social media contact integration
- Contact import from external sources
- Bulk contact management operations
2. Technology Stack
2.1 Frontend Technologies
- Framework: Tanstack with TypeScript
- Routing: Tanstack Router for navigation management
- Forms: Tanstack Form for form state management
- Data Fetching: Apollo Client for GraphQL operations
- State Management: React Context API with hooks
- UI Components: Custom component library with status-aware components
- Camera Integration: Browser Camera API for selfie capture
2.2 Backend Technologies
- Framework: NestJS with TypeScript
- API Layer: GraphQL with Apollo Server
- Database ORM: Prisma ORM
- Authentication: JWT tokens with refresh mechanism
- File Storage: Cloud storage integration
- Validation: Class-validator and class-transformer
- Face Matching: Third-party face matching API integration
2.3 External Services
- SMS Gateway: Twilio or equivalent for SMS OTP delivery
- Email Service: SendGrid or equivalent for email OTP delivery
- WhatsApp Business API: Twilio WhatsApp API or equivalent for WhatsApp OTP delivery
3. System Architecture Overview
3.1 Component Interaction Flow
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ React │────│ Apollo Client │────│ GraphQL API │
│ Frontend │ │ │ │ Gateway │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│
▼
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ External APIs │ │ Redis Cache │ │ NestJS │
│ • SMS Gateway │◄───┤ │◄───┤ Backend │
│ • Email Service│ │ │ │ │
│ • WhatsApp API │ └─────────────────┘ └─────────────────┘
└─────────────────┘ │
▼
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Audit Service │◄───┤ Prisma ORM │◄───┤ PostgreSQL │
│ │ │ │ │ Database │
└─────────────────┘
3.2 High-Level Process Flow
Contact Addition & Verification Process
Complete Flow (Contact only added after successful OTP verification):
- User Input: User fills contact form and selects OTP delivery method
- Validation: System validates format and uniqueness
- Generate OTP: System creates 6-digit OTP (30-min expiry)
- Send OTP: OTP sent via selected method (SMS/WhatsApp for mobiles)
- User Enters OTP: User inputs received OTP code
- Verify OTP: System validates OTP and expiry
- Create Contact: Contact added to database as verified
- Success: User sees confirmation message
Important: Contact is NOT saved until OTP verification succeeds.
Email Verification Process
- Add Email: User enters email address and submits
- Validate Format: System checks email format and domain
- Generate OTP: Create 6-digit OTP with 30-minute expiry
- Send Email: OTP sent to email address with professional template
- Enter OTP: User inputs OTP from email
- Verify: System validates OTP and timing
- Add Contact: Email added as verified contact
- Success: User sees verification success message
Landline Contact Process
- Add Details: User enters STD code, landline number and label
- Validate Format: System checks STD code and number format
- Add Contact: Landline added immediately (no verification needed)
- Success: Landline contact ready for use
Note: Landlines don't require OTP verification - they're added directly.
Primary Contact Assignment Process
- Select New Primary: User clicks "Set as Primary" on verified contact
- Cross-User Validation: System checks if number is primary for another user
- Confirm Change: User confirms primary contact change after OTP validation
- Update Database: System changes primary flags (old→false, new→true)
- Update Session: System updates user authentication with new primary
- Send Notifications: Confirmation sent to both old and new primary contacts
- Success: UI updates to show new primary contact
Cross-User Contact Detection Process
- View Section: User can see "Your Number is linked to other accounts"
- Remove Request: User clicks "Remove" on unwanted contact
- Confirm Action: User confirms removal in popup
- Delete Contact: System removes contact from other user's list
- Send Notifications: Both users get removal notification
Key Process Characteristics
Asynchronous Operations:
- OTP delivery happens asynchronously
- Notifications sent in background
- Database updates use transactions
Error Handling:
- Each step includes validation checkpoints
- Failed operations trigger rollback procedures
- User feedback provided at each stage
Security Measures:
- OTP expiry enforcement
- Rate limiting on verification attempts
- Audit trail creation for all operations
- Soft deletion maintains data integrity
- Cross-user primary validation
Performance Optimization:
- Database queries optimized with indexes
- Caching implemented for frequent lookups
- Batch operations for multiple contact updates
4. Functional Overview
4.1 Primary Mobile Number Management
4.1.1 Auto-Population and Display
Functionality: The system automatically identifies and populates the user's primary mobile number from their authentication session. This number serves as the foundation for all system notifications and primary communications.
Process Flow:
- Extract mobile number from user authentication token
- Query existing UserContact records for the user
- If no primary mobile exists, create UserContact entry with:
contactType: MOBILEisPrimary: trueisVerified: truecontactValue: [login mobile number]dialCode: [extracted from login]
- Display in UI with clear primary designation
Business Rules:
- Login mobile number is automatically verified
- Primary mobile cannot be deleted through standard UI operations
- Primary mobile serves as the default notification endpoint
4.1.2 Cross-User Contact Detection Interface
When setting as primary, if the system detects the number exists in other users' contact lists, display an accordion section with:
- Section Title: "This number appears in other users' contacts"
- Expandable List: Shows contacts where this number is stored
- Contact Details: Each entry displays:
- Contact name and relationship from other user's list
- Company or organization information (if available)
- Date when contact was originally added
- Remove Action: Button to remove from that user's contact list
Removal Process from Primary Assignment Flow:
- User clicks "Remove" next to a detected contact entry
- Display confirmation dialog showing:
- Which user's contact list will be affected
- Contact name and relationship being removed
- Warning that action cannot be undone
- On confirmation, perform soft deletion of the UserContact entry
- Send notifications to both users about the removal
- Update the detection list in real-time
Business Rules:
- Only verified mobile numbers can become primary
- OTP re-verification is mandatory for all primary assignments from alternatives
- Mobile number cannot be primary for multiple users simultaneously
- System maintains exactly one primary mobile per user
- Primary change triggers authentication system updates
- All future notifications route to new primary mobile
- Failed OTP verification prevents primary assignment and maintains current primary status
4.1.3 Modification Restrictions
Functionality: The system enforces restrictions on primary mobile modifications to maintain account security and notification integrity.
Restrictions:
- Primary mobile number cannot be directly edited
- Primary mobile cannot be deleted
- Changes require verification of alternative number first
- UI disables edit/delete controls for primary mobile
4.2 Alternative Mobile Number Management
4.2.1 Mobile Number Addition with Relationship
Functionality: Users can add alternative mobile numbers with contextual relationship information and contact names for better organization and identification.
Input Requirements:
- Mobile Number: 10-digit number with international dial code
- Contact Name: 2-50 character name for identification
- Relationship: Predefined relationship category
Relationship Options:
- Self: User's own alternative number
- Spouse: Spouse's mobile number
- Parent: Parent's mobile number
- Son/Daughter: Child's mobile number
- Manager: Agricultural business contact
- Business Partner: Professional partnership contact
- Other: Miscellaneous relationships
Validation Rules:
- Mobile number format validation per country code
- Uniqueness check across user's existing contacts
- Contact name: alphabetic characters with spaces only
- Relationship: must match predefined enum values
Process Flow:
- Validate input format and uniqueness
- Create UserContact entry with
isVerified: false - Store relationship and contact name metadata
- Present OTP delivery method selection
- Trigger selected OTP verification process
- Display in contact list with pending verification status
4.2.2 OTP Delivery Method Selection
Functionality: Enhanced OTP delivery system allowing users to choose between SMS and WhatsApp delivery methods based on number type and availability, similar to the registration process.
Delivery Method Logic:
For Indian Numbers (+91):
- SMS: Available for all Indian mobile numbers
- WhatsApp: Available for all Indian mobile numbers
- User Choice: Radio button selection between SMS and WhatsApp
For International Numbers (Non-+91):
- SMS: Not available (due to cost/reliability)
- WhatsApp: Default and only option available
- Auto-Selection: WhatsApp automatically selected, no user choice needed
Selection Interface:
- Indian Numbers: Display both SMS and WhatsApp options with radio buttons
- International Numbers: Display WhatsApp option only with informational text
- Default Selection: SMS pre-selected for Indian numbers, WhatsApp for international
Validation Rules:
- Must select delivery method for Indian numbers before proceeding
- International numbers automatically use WhatsApp
- Selected method must be technically available for the number type
4.2.3 OTP Verification Process
Functionality: Secure verification process for alternative mobile numbers using time-limited OTP delivery via user's preferred method.
OTP Specifications:
- Length: 6-digit numeric code
- Expiry: 15 minutes from generation
- Attempts: Maximum 5 verification attempts
- Rate Limiting: 1 OTP per minute per number
Process Flow:
- Generate cryptographically secure 6-digit OTP
- Store OTP with expiry timestamp in
verificationToken - Increment
verificationTokenAttemptscounter - Send OTP via selected delivery method
- SMS: Direct SMS to mobile number
- WhatsApp: WhatsApp message via Business API
- Update
verificationTokenLastSentAttimestamp - Present OTP input interface to user
- Validate submitted OTP against stored value and expiry
- On successful verification:
- Set
isVerified: true - Set
verifiedAt: current timestamp - Clear verification token data
- Create audit trail entry
- Set
4.2.4 Contact Deletion
Functionality: Users can remove alternative mobile numbers while maintaining data integrity and audit trails.
Deletion Rules:
- Cannot delete current primary mobile
- Requires confirmation dialog
- Soft deletion preserves audit trail
- Notifications sent for security
Process Flow:
- Validate contact is not primary
- Display confirmation dialog with contact details
- Perform soft deletion:
- Set
isDeleted: true - Set
deletedAt: current timestamp - Preserve all other data for audit
- Set
- Create audit trail entry
- Remove from active UI displays
- Send deletion notification to primary contact
4.2.5 Primary Assignment from Alternatives
Functionality: Users can designate any verified alternative mobile number as their new primary contact. This process updates authentication capabilities and notification routing with enhanced validation.
Process Flow:
- Validate target mobile number is verified (
isVerified: true) - Check cross-user primary conflict: Ensure number is not set as primary (
isPrimary: true) for any other user - If number is primary for another user, display error message and prevent assignment
- Cross-user contact detection: Check if the number exists in other users' contact lists and display accordion with removal options
- OTP Re-verification Required: Generate and send new OTP to the alternative mobile number to confirm current access
- OTP Delivery Method Selection: Present SMS/WhatsApp options based on number type (same logic as initial verification)
- OTP Validation: User enters received OTP for verification
- On successful OTP verification, proceed with primary assignment
- update current primary mobile:
isPrimary: false - Update target mobile:
isPrimary: true - Create audit trail entries for both changes
- Update user session with new primary mobile
- update current primary mobile:
- Send confirmation notifications to both old and new primary numbers
OTP Re-verification Process:
- Purpose: Ensure user has current access to the mobile number before making it primary
- Security Rationale: Prevents unauthorized primary changes if alternative number access is compromised
- OTP Specifications:
- 6-digit numeric code
- 15-minute expiry
- Maximum 3 verification attempts
- Same delivery method options as initial verification
- User Experience: Clear explanation that re-verification is required for security
4.3 Email Management
4.3.1 Email Addition and Validation
Functionality: Comprehensive email management system supporting multiple email addresses with independent verification and primary assignment capabilities.
Input Validation:
- Format: RFC 5322 compliant email validation
- Length: Maximum 254 characters
- Uniqueness: Per user account validation
- Domain: Valid domain resolution check
Validation Process:
- Client-side format validation using regex
- Server-side comprehensive validation:
- RFC compliance check
- Domain MX record validation
- Uniqueness verification against user's existing emails
- Create UserContact entry with
contactType: EMAIL - Set initial status:
isVerified: false
4.3.2 OTP Verification via Email
Functionality: Secure email verification using OTP delivery directly to the email address, replacing traditional verification links for consistency with mobile verification flows.
OTP Email Specifications:
- OTP Format: 6-digit numeric code
- Email Template: Professional HTML template with branding
- Expiry Time: 15 minutes from generation
- Subject Line: "Verify Your Email - [App Name]"
- Security: OTP visible in email content and not in URL
Verification Process:
- Generate secure 6-digit OTP
- Create professional email template with:
- Clear OTP display
- Expiry time information
- Security reminders
- Company branding
- Send email via configured email service
- Store OTP in
verificationTokenwith expiry - Present OTP input interface in application
- Validate submitted OTP:
- Check against stored token
- Verify within expiry window
- Limit verification attempts
- On successful verification:
- Update
isVerified: true - Set
verifiedAt: timestamp - Create audit entry
- Update
Email Template Structure:
Subject: Verify Your Email Address - [App Name]
Dear [User Name],
Your verification code is: [6-DIGIT OTP]
This code will expire in 15 minutes.
If you didn't request this verification, please ignore this email.
Best regards,
[App Name] Team
4.3.3 Primary Email Assignment
Functionality: Users can designate any verified email as their primary email contact for system communications and notifications.
Primary Email Rules:
- Only verified emails can be set as primary
- One primary email per user account
- Primary email receives account notifications
- Previous primary becomes secondary automatically
Assignment Process:
- Validate target email verification status
- Update current primary email:
isPrimary: false - Update target email:
isPrimary: true - Create audit trail for primary assignment
- Send confirmation to new primary email
- Update user preferences and notification routing
4.3.4 Email Management Operations
Functionality: Complete lifecycle management for email contacts including addition, verification, primary assignment, and removal.
Supported Operations:
- Add Email: Create new email contact with validation
- Verify Email: OTP-based verification process
- Resend OTP: Regenerate and resend verification OTP
- Set Primary: Assign verified email as primary
- Delete Email: Remove email with confirmation
- Update Label: Modify email description/label
Business Rules:
- Cannot delete current primary email
- Deletion requires explicit confirmation
- Soft deletion maintains audit trail
- All operations logged for security
4.4 Landline Number Management
4.4.1 Landline Addition with STD Code
Functionality: Comprehensive landline number management supporting regional STD codes and descriptive labeling for business and personal landline contacts.
Input Requirements:
- STD Code: 3-4 digit regional code (e.g., 080, 011, 022)
- Landline Number: 6-8 digit local number
- Label: Optional descriptive label (Home, Office, Factory, etc.)
Validation Rules:
- STD code format validation per country
- Landline number format validation
- Combined number uniqueness per user
- Label length: 0-30 characters if provided
Addition Process:
- Validate STD code format
- Validate landline number format
- Check uniqueness of combined STD + landline number
- Create UserContact entry:
contactType: LANDLINEstdCode: STD codecontactValue: landline numbercontactLabel: descriptive labelisVerified: false(landlines not verified)
4.4.2 Primary Landline Assignment
Functionality: Users can designate one landline as primary for business communications and contact preferences.
Primary Assignment:
- No verification required for landlines
- One primary landline per user
- Primary landline displayed prominently
- Business communication preference routing
4.4.3 Landline Management Operations
Functionality: Complete landline lifecycle management with editing and removal capabilities.
Operations:
- Add Landline: Create new landline entry
- Edit Details: Update STD code, number, or label
- Set Primary: Assign as primary landline
- Delete Landline: Remove with confirmation
- Update Label: Modify descriptive information
4.5 Cross-User Contact Detection
4.5.1 Detection Algorithm
Functionality: Advanced algorithm to detect when a user's primary mobile number appears as an alternative contact in other users' contact lists, enabling privacy control and contact management.
Detection Process:
- Query UserContact table for entries where:
contactValuematches user's primary mobile numberuserIddiffers from current usercontactType: MOBILEisDeleted: false
- Retrieve associated user information and contact metadata
- Format results with anonymized user identifiers
- Display with contact context and relationship information
Query Optimization:
- Indexed query on
contactValuefield - Filtered by contact type and deletion status
- Limited result set for performance
- Cached results for frequent queries
4.5.2 Contact Removal Process
Functionality: Secure process allowing users to remove their primary number from other users' contact lists while maintaining audit trails and notifications.
Removal Process:
- Validate user ownership of primary number
- Display confirmation dialog with implications
- Begin removal transaction:
- Soft delete target UserContact entry
- Create audit trail entry
- Generate notification for contact owner
- Send notification to both users:
- Original user: Removal confirmation
- Contact owner: Contact removed notification
- Update cross-user detection results
- Business Rules:
- User can only remove their own primary number from others' lists
- Removal triggers notification to contact owner
- Action is logged for audit purposes
- Output: Contact removed from other user's list with notifications sent
Notification Content:
To Contact Owner:
"[Contact Name] has removed their number from your contact list. This contact is no longer available."
To Original User:
"Your number has been removed from [User]'s contact list successfully."
4.5.3 Notification System
Functionality: Comprehensive notification system for cross-user contact operations ensuring transparency and security.
Notification Types:
- Removal Notifications: Sent to both parties during contact removal
- Addition Alerts: Optional notifications when number is added elsewhere
- Security Alerts: Suspicious cross-user contact activity
Delivery Mechanism:
- Primary notifications via SMS to primary mobile
- In-app notifications for immediate feedback
- Email notifications for audit trail
- Push notifications if mobile app exists
5. User Interface
5.1 Primary Contact Display
5.1.1 Mobile Number Display
Design Elements:
- Primary Badge: Clear visual indicator with "Primary" label
- Lock Icon: Indicates restricted edit/delete operations
- Verification Status: Green checkmark with "Verified" text
- Action Buttons: Disabled state for edit/delete of login number
Interactive Elements:
- Tooltip on hover explaining primary designation
- Click-to-copy functionality for number
- Clear visual hierarchy distinguishing from alternatives
5.1.2 Email Display
Design Elements:
- Primary Indicator: "Primary Email" badge
- Verification Badge: Status indicator with timestamp
- Quick Actions: Set primary, edit, delete buttons
5.1.3 Landline Display
Design Elements:
- STD Code Display: Formatted with parentheses: (080) 1234-5678
- Label Badge: Descriptive label in subtle styling
- Primary Indicator: Star or badge for primary landline
5.2 Alternative Contact Management
5.2.1 Mobile Number Addition Modal
Modal Form Fields:
- Dial Code Selector: Country code dropdown with search functionality
- Mobile Number Field: 10-digit number input with format validation
- Contact Name Field: Text input for contact identification (2-50 characters)
- Relationship Dropdown: Select from predefined relationship options
- OTP Delivery Method: Radio buttons for SMS or WhatsApp delivery
- Action Buttons: Cancel and Add Contact buttons
Form Validation:
- Real-time validation feedback
- Error messages below each field
- OTP delivery method selection required for Indian numbers
- Submit button disabled until valid
- Loading state during API calls
Relationship Dropdown Options:
- Self
- Spouse
- Parent
- Son/Daughter
- Manager
- Business Partner
- Other
5.2.2 Email Addition Modal
Modal Form Fields:
- Email Address Field: Email input with format validation
- Action Buttons: Cancel and Send Verification Email buttons
Validation Features:
- Email format validation with regex
- Domain validation check
- Uniqueness validation
- Character limit indicators
5.2.3 Landline Addition Modal
Modal Form Fields:
- STD Code Field: 3-4 digit regional code input
- Landline Number Field: 6-8 digit local number input
- Label Field: Optional descriptive label (Home, Office, Factory)
- Action Buttons: Cancel and Add Landline buttons
5.3 Cross-User Contact Interface
5.3.1 Contact List Display
Section Organization:
- Section Header: "Your Number in Other Contacts" with icon
- Contact Entries: List format showing contact details
- Action Buttons: Remove and Details options for each entry
- Empty State: Message when no cross-user contacts found
Contact Entry Information:
- Contact Name: Display name and relationship
- Company Info: Show associated company or organization
- Date Added: When contact was originally added
- Quick Actions: Remove and View Details buttons
5.3.2 Removal Interface
Confirmation Dialog Steps:
- Contact Information Display: Show contact name, relationship, company
- Your Number Display: Show the mobile number being removed
- Consequence Warning: List what will happen after removal
- Impact Notice: Explain action cannot be undone
- Confirmation Actions: Cancel or proceed with removal
6. Technical Specification
6.1 Frontend Implementation
6.1.1 Component Architecture
-
ContactsPage (Root Component):
- Main container for contacts management
- Fetches user's contacts and cross-user relationships
- Manages overall state
-
MobileNumberSection:
- PrimaryMobileDisplay: Shows primary mobile with "Primary" badge and cross-user contact detection accordion
- AlternativeMobileList: Shows alternatives with relationship labels and names
- AddMobileNumberModal: Form with contact name, relationship, mobile inputs and OTP delivery method selection
- SetPrimaryModal: Multi-step confirmation dialog for changing primary mobile with:
- Cross-user validation and contact detection accordion
- OTP re-verification with delivery method selection
- Final confirmation and assignment
- OTPDeliveryMethodSelector: Component for SMS/WhatsApp selection based on number type
-
EmailSection:
- EmailList: Shows emails with primary indicators
- AddEmailModal: Email input with OTP verification
- EmailOTPVerificationModal: OTP input for email verification
-
LandlineSection:
- LandlineList: Shows landlines with STD codes and labels
- AddLandlineModal: STD code, number, and label inputs
-
CrossUserContactsSection:
- CrossUserContactsList: Shows where user's number appears in other contacts
- RemoveContactModal: Confirmation for removal from other user's contacts
6.1.2 Form Handling (Tanstack Form)
- Enhanced validation for relationship labels and contact names
- STD code and landline number validation
- Cross-user contact management forms
- OTP verification forms for emails and mobile numbers
- OTP delivery method selection validation
- Cross-user primary assignment validation
6.1.3 Routing (Tanstack Router)
- Main contacts route: /profile/contacts
- Modals managed by component state
- Deep linking for contact verification flows
6.1.4 API Interactions (Apollo Client)
New Queries:
- GET_CROSS_USER_CONTACTS: Fetch where user's number appears in other contacts
- GET_USER_CONTACTS_EXTENDED: Include relationship and name data
- CHECK_PRIMARY_CONFLICT: Validate if number is primary for another user
New Mutations:
- ADD_MOBILE_WITH_RELATIONSHIP_AND_METHOD: Add mobile with name, relationship, and OTP delivery method
- ADD_EMAIL_WITH_OTP: Add email and trigger OTP
- VERIFY_EMAIL_OTP: Verify email OTP
- ADD_LANDLINE_WITH_STD: Add landline with STD code
- SET_PRIMARY_CONTACT_WITH_VALIDATION: Set any contact type as primary with cross-user validation
- REMOVE_FROM_OTHER_USER: Remove number from other user's contacts
- SEND_OTP_WITH_METHOD: Send OTP via specified method (SMS/WhatsApp)
6.1.5 Error Handling and User Feedback
- Validation messages for relationship and name fields
- Cross-user contact operation confirmations
- Enhanced success messages for primary contact changes
- Error handling for OTP verification failures
- Cross-user primary conflict error messages
- OTP delivery method selection validation errors
6.2 Backend Implementation
6.2.1 Database Schema
-- Updated UserContact table
ALTER TABLE UserContact
ADD COLUMN contactName VARCHAR(50),
ADD COLUMN relationship VARCHAR(20) CHECK (relationship IN ('SELF', 'SPOUSE', 'PARENT', 'SON_DAUGHTER', 'FARM_MANAGER', 'BUSINESS_PARTNER', 'OTHER')),
ADD COLUMN stdCode VARCHAR(4);
-- Index for cross-user contact detection
CREATE INDEX idx_usercontact_contactvalue ON UserContact(contactValue) WHERE isDeleted = false;
-- Index for primary contact queries
CREATE INDEX idx_usercontact_primary ON UserContact(userId, contactType, isPrimary) WHERE isDeleted = false;
6.2.2 GraphQL Schema (High-Level)
# Types
type UserContact {
id: ID!
userId: ID!
contactType: ContactType!
contactValue: String!
dialCode: String
stdCode: String # For landlines
contactName: String # For alternative contacts
relationship: RelationshipType # For alternative contacts
contactLabel: String
isPrimary: Boolean!
isVerified: Boolean!
verifiedAt: DateTime
createdAt: DateTime!
updatedAt: DateTime!
}
enum ContactType {
MOBILE
EMAIL
LANDLINE
}
enum RelationshipType {
SELF
SPOUSE
PARENT
SON_DAUGHTER
MANAGER
BUSINESS_PARTNER
OTHER
}
enum OTPDeliveryMethod {
SMS
WHATSAPP
}
type CrossUserContact {
contactId: ID!
contactName: String!
ownerName: String!
dateAdded: DateTime!
relationship: RelationshipType!
}
type PrimaryValidationResult {
isValid: Boolean!
conflictUserId: ID
errorMessage: String
crossUserContacts: [CrossUserContact!]! # Contacts where this number appears
}
# Queries
type Query {
getUserContacts: [UserContact!]!
getCrossUserContacts: [CrossUserContact!]!
validatePrimaryAssignment(contactValue: String!): PrimaryValidationResult!
}
# Mutations
type Mutation {
# Mobile Management with OTP Method Selection
addMobileWithRelationshipAndMethod(
dialCode: String!
mobileNumber: String!
contactName: String!
relationship: RelationshipType!
otpMethod: OTPDeliveryMethod!
): UserContact!
# Email Management
addEmailWithOTP(email: String!): UserContact!
verifyEmailOTP(contactId: ID!, otp: String!): UserContact!
# Landline Management
addLandlineWithSTD(
stdCode: String!
landlineNumber: String!
label: String
): UserContact!
# Primary Contact Management with Validation and OTP Re-verification
setPrimaryContactWithValidation(contactId: ID!): PrimaryValidationResult!
requestPrimaryAssignmentOTP(contactId: ID!, method: OTPDeliveryMethod!): Boolean!
verifyPrimaryAssignmentOTP(contactId: ID!, otp: String!): UserContact!
# Cross-User Contact Management
removeFromOtherUserContact(contactId: ID!): Boolean!
# General
deleteUserContact(contactId: ID!): Boolean!
requestContactOTPWithMethod(contactId: ID!, method: OTPDeliveryMethod!): Boolean!
verifyContactOTP(contactId: ID!, otp: String!): UserContact!
}
6.2.3 Service Layer Logic
ContactsService Updates:
- addMobileWithRelationshipAndMethod: Create UserContact with relationship, name data, and handle OTP delivery method selection
- addEmailWithOTP: Create email contact and trigger OTP generation and sending
- verifyEmailOTP: Validate email OTP and mark as verified
- addLandlineWithSTD: Create landline contact with STD code
- setPrimaryContactWithValidation: Update primary status with cross-user validation and integrated cross-user contact detection
- requestPrimaryAssignmentOTP: Generate and send OTP to alternative mobile number for primary assignment verification
- verifyPrimaryAssignmentOTP: Validate OTP and complete primary assignment process
- validatePrimaryAssignmentWithDetection: Check if number is already primary for another user AND return list of cross-user contacts where number appears
- removeFromOtherUserContact: Remove user's number from others' contact lists
- requestContactOTPWithMethod: Generate and send OTP via specified method
Enhanced Business Logic:
- Two-step primary assignment process: validation followed by OTP verification
- Integrated cross-user primary validation with contact detection
- OTP re-verification mandatory for all primary assignments
- OTP delivery method routing (SMS vs WhatsApp) for primary assignment
- Enhanced error handling for validation conflicts
- Real-time cross-user contact management during primary assignment
- Transaction rollback if OTP verification fails during primary assignment
- STD code validation for landlines
- Email OTP generation and verification
- Cross-user contact detection and management
7. Integration Requirements
7.1 SMS Gateway Integration
- Enhanced OTP delivery for mobile contacts with method selection
- Support for relationship-based messaging
7.2 WhatsApp Integration
- OTP delivery via WhatsApp
- Template compliance for verification messages
7.3 Email Service Integration
- OTP email delivery
- Professional email templates
- Bounce and delivery tracking for OTPs
8. Authentication
8.1 Session Management
-
Description: Manage user sessions to ensure secure access to the Contacts Management module.
-
Process:
- Utilize JSON Web Tokens (JWT) for session authentication.
- Store JWT in secure HTTP-only cookies to prevent client-side access.
- Implement session expiry with a configurable timeout (e.g., 30 minutes of inactivity).
- Provide refresh token mechanism to extend session without re-authentication.
- Validate session tokens on each API request to the Contacts Management endpoints.
-
Output: Secure user session with automatic logout on token expiry or invalidation.
-
Business Rules:
- Only authenticated users with valid sessions can access contact management features.
- Session tokens are validated against the user’s primary contact (mobile) stored in the database.
- Invalid or expired tokens trigger a re-authentication flow.
8.2 Primary Contact Authentication
-
Description: Authenticate users using their primary contact (mobile) during login and contact management operations.
-
Process:
- On login, users provide their primary mobile number, followed by OTP verification.
- OTP is sent to the primary contact (mobile via SMS/WhatsApp).
- Upon successful OTP verification, issue a JWT for session management.
- Update login credentials in the database to reflect the new primary contact.
-
Output: User authenticated securely with primary contact; login credentials updated on primary contact change.
-
Business Rules:
- Only verified primary contacts can be used for authentication.
- OTP for authentication follows the same 6-digit format and 15-minute expiry as contact verification.
- Changing the primary contact requires re-authentication to ensure security.
- Audit trail logs all authentication attempts and primary contact changes.
9. Security Considerations
9.1 Input Validation
- Server-side validation for relationship types
- STD code format validation
- Contact name sanitization
- Cross-user contact access controls
- OTP delivery method validation
9.2 Verification Security
- Email OTP with time limits and attempt restrictions
- Secure OTP generation for email verification
- Rate limiting for OTP requests
- Cross-user primary assignment validation
9.3 Data Protection
- Contact name encryption
- Cross-user data access restrictions
- Audit trail for sensitive operations
- Primary assignment conflict prevention
9.4 Access Control
- Users can only modify their own contacts
- Cross-user contact removal permissions
- Primary contact change authorization
- Cross-user primary validation enforcement
10. Error Handling
10.1 Validation Errors
- Invalid relationship type selection
- Invalid STD code format
- Invalid contact name format
- Cross-user operation restrictions
- OTP delivery method selection errors
10.2 Verification Errors
- Email OTP validation failures
- OTP expiry handling
- Invalid OTP format errors
- Cross-user primary conflict errors
10.3 Business Logic Errors
- Setting unverified contact as primary
- Deleting current primary contacts
- Unauthorized cross-user operations
- Primary assignment conflicts
11. Performance Requirements
11.1 Response Time
- Contact list with relationships: < 2 seconds
- Cross-user contact detection: < 3 seconds
- Email OTP generation and sending: < 5 seconds
- Cross-user primary validation: < 1 second
11.2 Scalability
- Efficient cross-user contact queries
- Optimized primary contact updates
- Scalable OTP generation for emails
- Indexed database queries for validation
12. Testing Strategy
12.1 Unit Tests
- Relationship validation testing
- STD code validation testing
- Email OTP generation and verification
- Cross-user contact detection logic
- Cross-user primary validation
- OTP delivery method selection logic
- Primary assignment OTP re-verification logic
- Primary assignment transaction rollback scenarios
12.2 Integration Tests
- Email OTP delivery testing
- Cross-user notification delivery
- Primary contact assignment across types
- SMS and WhatsApp OTP delivery
- Cross-user primary conflict prevention
- Primary assignment OTP re-verification flow
- Primary assignment failure recovery
12.3 End-to-End Tests
- Complete contact addition with relationships and OTP method selection
- Email verification flow
- Cross-user contact management
- Primary contact switching with OTP re-verification
12.4 Performance Tests
- Cross-user contact query performance
- Email OTP delivery performance
- Database query optimization for relationships
- Primary validation query performance
13. Monitoring and Analytics
13.1 Enhanced Metrics
- Email OTP success rates
- Cross-user contact detection frequency
- Primary contact change patterns
- Relationship type distribution
- STD code validation success rates
- OTP delivery method selection patterns
- Cross-user primary conflict incidents
13.2 Analytics:
- User engagement with relationship features
- Email verification completion rates
- Cross-user contact removal patterns
- SMS vs WhatsApp delivery success rates
14. Deployment Considerations
14.1 Environment Variables:
- Email service configuration for OTPs
- Cross-user notification settings
- Relationship validation rules
- OTP delivery method configuration
- SMS and WhatsApp API credentials
14.2 Database Migrations:
- Add relationship and name columns
- Add STD code column for landlines
- Create cross-user contact indexes
14.3 Feature Flags:
- Email OTP verification
- Cross-user contact detection
- Relationship-based contacts
- Cross-user primary validation
- OTP delivery method selection
15. Future Enhancements
- Advanced relationship types
- Bulk contact import with relationships
- Contact sharing between users
- Enhanced cross-user contact permissions
- Advanced OTP delivery analytics
- Multi-language OTP templates