Use Case Documentation
Overview
This document describes the business use cases and application layer logic for the Customer Management module. Each use case encapsulates business rules, permissions, and orchestrates the interaction between domain entities, repositories, and external integrations within the order and payment ecosystem.
Architecture Pattern
The module follows the CQRS (Command Query Responsibility Segregation) pattern with the following structure:
Use Cases: Application layer orchestrating business logic
Commands: Write operations (Create, Update, Delete Customer)
Queries: Read operations (Get Customer, Search Customers)
Domain Entities: Business logic and validation
Value Objects: Customer data and relationship objects
Integration Services: Order and payment system integration
Core Use Cases
1. CreateCustomerUseCase
Purpose: Creates a new customer record with comprehensive validation and business rule enforcement.
Input: CreateCustomerUseCaseParams
Output: string (Customer ID)
Business Rules:
User must have
CREATE_CUSTOMERpermissionAt least one of firstName, lastName, email, or phone must be provided
Email must be valid format if provided
Phone must be valid format if provided (automatically normalized)
Customer type defaults to 'regular' if not specified
No duplicate customers based on email/phone combination
Customer is created with 'active' state
Process Flow:
Validate user permissions using
PermissionValidatorUseCaseValidate customer data using
CustomerValidatorExecute
AddRegularCustomerCommandvia command busCommand handler validates domain rules and creates entity
Persist customer to database with tenant isolation
Clear relevant cache entries
Publish
CustomerAddedMessageeventReturn generated customer ID
Validation Rules:
Cache Invalidation: Clears CustomerCacheKeys.GET_PAGED_CUSTOMERS
2. GetCustomerUseCase
Purpose: Retrieves detailed customer information by ID with permission validation.
Input: GetCustomerUseCaseParams
Output: CustomerDto
Business Rules:
User must have
READ_CUSTOMERpermissionCustomer must exist and belong to the authenticated tenant
Returns complete customer information including state history
Respects tenant data isolation
Process Flow:
Validate user permissions
Execute
GetCustomerByIdQueryvia query busQuery handler retrieves customer from repository
Transform persistence model to DTO
Return customer data or throw exception if not found
Error Scenarios:
Insufficient permissions โ
ForbiddenExceptionCustomer not found โ
CustomerNotFoundExceptionDatabase errors โ Logged and re-thrown
Caching: Results are cached using CustomerCacheKeys.GET_CUSTOMER
3. UpdateCustomerUseCase
Purpose: Updates existing customer information with partial update support and validation.
Input: UpdateCustomerUseCaseParams
Output: void
Business Rules:
User must have
EDIT_CUSTOMERpermissionCustomer must exist and belong to the authenticated tenant
Supports partial updates (only provided fields are updated)
Email and phone validation applied if provided
Customer type can be changed with proper validation
Updates increment version number for optimistic locking
Process Flow:
Validate user permissions
Verify customer exists using
GetCustomerByIdQueryValidate update data using
CustomerValidatorExecute
UpdateCustomerCommandvia command busCommand handler applies domain validation and updates entity
Persist changes with optimistic locking
Clear relevant cache entries
Publish
CustomerUpdatedMessageevent
Domain Validation:
Cache Invalidation: Clears CustomerCacheKeys.GET_CUSTOMER and CustomerCacheKeys.GET_PAGED_CUSTOMERS
4. DeleteCustomerUseCase
Purpose: Soft deletes a customer record with business rule validation.
Input: DeleteCustomerUseCaseParams
Output: void
Business Rules:
User must have
DELETE_CUSTOMERpermissionCustomer must exist and belong to the authenticated tenant
Performs soft delete (sets state to 'deleted')
Validates no active orders exist for the customer
Preserves historical data for reporting and compliance
Process Flow:
Validate user permissions
Verify customer exists
Check for active orders or dependencies
Execute
DeleteCustomerCommandvia command busCommand handler performs soft delete
Update state history with deletion reason
Clear relevant cache entries
Publish
CustomerDeletedMessageevent
Dependency Validation:
5. GetPagedCustomersUseCase
Purpose: Retrieves paginated customer list with search and filtering capabilities.
Input: GetPagedCustomersUseCaseParams
Output: PaginationResponseDto<CustomerDto>
Business Rules:
User must have
READ_CUSTOMERpermissionResults are filtered by tenant for data isolation
Supports text search across name and email fields
Supports filtering by customer type and state
Implements efficient pagination with cursor support
Maximum page size limit enforced
Process Flow:
Validate user permissions
Validate pagination parameters
Execute
GetPagedCustomersQueryvia query busQuery handler applies filters and pagination
Transform results to DTOs
Return paginated response with metadata
Search Implementation:
Caching: Results cached using CustomerCacheKeys.GET_PAGED_CUSTOMERS with pagination context
Order Integration Use Cases
6. AddAttendeesUseCase
Purpose: Processes customer attendees for order services, creating or updating customer records as needed.
Input: AddAttendeesCommand
Output: AttendantDto[] (Processed attendees with customer IDs)
Business Rules:
Creates regular customers for attendees with email/phone
Reuses existing customers when found by email/phone match
Marks first-time visitors based on order history
Validates attendee information against business settings
Maintains customer snapshots in order data
Process Flow:
Iterate through provided attendees
For each attendee with contact information:
Search for existing customer by email/phone
If found, use existing customer and mark
firstTime: falseIf not found, create new regular customer
Validate customer data meets business requirements
Create customer snapshots for order persistence
Return processed attendee list with customer references
Customer Matching Logic:
7. AddPublicAttendeesUseCase
Purpose: Processes customer information from public order creation with flexible customer handling.
Input: AddPublicAttendeesCommand
Output: AttendantDto[]
Business Rules:
Handles anonymous and unregistered customers
Creates minimal customer records for public orders
Validates mandatory attendee properties per business settings
Supports guest checkout scenarios
Maintains privacy for public customers
Process Flow:
Validate attendee information against business booking settings
For each public attendee:
Check if customer exists by contact information
Create unregistered customer if sufficient information provided
Create anonymous customer for minimal information
Apply business mandatory property requirements
Return processed attendee list for order creation
Mandatory Property Validation:
Payment Integration Use Cases
8. ProcessPaymentCustomerUseCase
Purpose: Handles customer information during payment processing with customer creation as needed.
Input: ProcessPaymentCustomerParams
Output: CustomerDto (Processed payer information)
Business Rules:
Creates customer record for payment if not exists
Validates payer information for payment processing
Maintains customer snapshots in payment records
Supports guest payment scenarios
Links payment history to customer records
Process Flow:
Validate payer information format
Search for existing customer by email/phone
If customer exists, update payment-relevant information
If customer doesn't exist, create new customer record
Return customer information for payment processing
Payment Customer Creation:
Query Handlers
GetCustomerByIdHandler
Responsibilities:
Customer retrieval with tenant filtering
State validation and access control
Data transformation to DTO format
Cache management and optimization
Implementation:
GetPagedCustomersHandler
Responsibilities:
Advanced filtering and search implementation
Efficient pagination with cursor support
Sort optimization and index utilization
Result transformation and metadata
Search Strategy:
IsCustomerExistHandler
Responsibilities:
Duplicate customer detection
Email and phone uniqueness validation
Performance-optimized existence checks
Multi-field search support
Existence Check:
Command Handlers
AddRegularCustomerHandler
Responsibilities:
Domain entity creation and validation
Business rule enforcement
Database persistence with tenant ID
Event publishing and cache invalidation
Customer Creation Process:
UpdateCustomerHandler
Responsibilities:
Customer existence validation
Partial update processing
Domain validation enforcement
Optimistic locking support
DeleteCustomerHandler
Responsibilities:
Soft delete implementation
Dependency validation
State history maintenance
Cleanup operations
Domain Validation Rules
Customer Entity Validation
Validation Helper Methods
Cache Management
Cache Keys and Strategy
Cache Invalidation Strategy
Permission Integration
Permission Validation
All customer use cases integrate with the PermissionValidatorUseCase:
Required Permissions
READ_CUSTOMER: View customer information and lists
CREATE_CUSTOMER: Create new customer records
EDIT_CUSTOMER: Modify existing customer information
DELETE_CUSTOMER: Delete customer records
Permission Matrix
Get Customer
READ_CUSTOMER
Tenant
Read access to customer data
Get Paged Customers
READ_CUSTOMER
Tenant
List and search customers
Create Customer
CREATE_CUSTOMER
Tenant
Create new customer records
Update Customer
EDIT_CUSTOMER
Tenant
Modify customer information
Delete Customer
DELETE_CUSTOMER
Tenant
Soft delete customer records
Add Attendees
EDIT_CUSTOMER
Tenant
Process order attendees
Error Handling
Exception Types
Error Logging
All use cases implement comprehensive error logging:
Testing Considerations
Unit Testing
Integration Testing
Business Workflow Integration
Customer Lifecycle Workflow
Customer Creation: Initial customer registration or first order
Profile Completion: Adding additional information and preferences
Order Association: Linking customers to orders as payers and attendees
Payment Processing: Customer information in payment records
Relationship Management: Ongoing customer interaction and updates
Order Integration Workflow
Attendee Processing: Convert order attendees to customer records
Customer Matching: Find existing customers or create new ones
Snapshot Creation: Preserve customer data in order records
First-Time Detection: Mark new customers for special handling
History Tracking: Maintain customer order history
Payment Integration Workflow
Payer Identification: Link payment to customer record
Customer Creation: Create customer if not exists for payment
Payment History: Track customer payment patterns
Billing Information: Manage customer billing preferences
Performance Considerations
Database Optimization
Indexing Strategy: Optimize for common query patterns
Query Optimization: Efficient filtering and sorting
Batch Processing: Handle bulk customer operations
Connection Pooling: Manage database connections efficiently
Query Patterns
Memory Management
Selective Field Projection: Load only required fields
Streaming Results: Handle large result sets efficiently
Cache Optimization: Balance memory usage and performance
Connection Management: Proper resource cleanup
Security Considerations
Data Protection
PII Handling: Secure processing of personal information
Encryption: Protect sensitive customer data
Access Logging: Track customer data access
Data Retention: Comply with retention policies
Privacy Compliance
GDPR Support: Data portability and deletion rights
Consent Management: Track customer consent preferences
Data Minimization: Store only necessary information
Audit Trail: Complete change history for compliance
Access Control
Permission Validation: Enforce role-based access
Tenant Isolation: Strict multi-tenant data separation
Rate Limiting: Prevent abuse and DoS attacks
Input Validation: Sanitize all customer inputs
Business Rules Summary
Customer Data Rules
Mandatory Information: At least one identifying field required
Data Validation: Email and phone format validation
Normalization: Phone numbers stored in normalized format
Uniqueness: Prevent duplicate customers per tenant
State Management: Soft deletion preserves historical data
Order Integration Rules
Attendee Matching: Smart customer matching by email/phone
Customer Creation: Automatic customer creation for orders
Snapshot Preservation: Historical customer data in orders
First-Time Tracking: Identify new customer visits
Multi-Attendee Support: Multiple customers per order service
Business Logic Rules
Tenant Isolation: Complete data separation per business
Permission Enforcement: Role-based operation access
Cache Consistency: Proper cache invalidation on updates
Event Publishing: Async notification of customer changes
Error Recovery: Graceful handling of validation and system errors
Future Enhancements
Planned Features
Customer Segmentation: Advanced customer categorization
Preference Management: Detailed customer preferences
Communication History: Track all customer interactions
Analytics Integration: Customer behavior analysis
Loyalty Programs: Customer loyalty and rewards
Marketing Automation: Automated customer communication
Scalability Improvements
Read Replicas: Optimize read performance
Sharding Strategy: Handle large customer datasets
Event Sourcing: Complete audit trail with events
CQRS Optimization: Separate read/write models
Microservice Decomposition: Split by business domains
Summary
The Customer Management use cases provide a comprehensive foundation for handling customer operations within the Bee O'clock ecosystem. Key capabilities include:
Complete Customer Lifecycle: From creation to deletion with validation
Order Integration: Seamless customer handling in order processing
Payment Integration: Customer information in payment workflows
Advanced Search: Efficient customer discovery and management
Multi-Tenant Security: Proper data isolation and access control
Performance Optimization: Caching and efficient query patterns
Business Rule Enforcement: Comprehensive validation and business logic
Event-Driven Architecture: Async communication for scalability
The use cases support complex business scenarios while maintaining high performance, data integrity, and security standards across the customer management domain.
Last updated
Was this helpful?