Spaces:
Runtime error
Runtime error
Merchant Settings Feature Implementation
Overview
This implementation adds comprehensive merchant settings functionality to the SCM microservice, following the existing codebase patterns and architecture.
Files Created
1. Model (app/models/merchant_settings_model.py)
- Pydantic model for database storage
- Defines all merchant configuration fields
- Includes business, inventory, notification, operating hours, pricing, and tax settings
2. Schemas (app/schemas/merchant_settings_schema.py)
- Request/response validation schemas
MerchantSettingsCreate- for creating new settingsMerchantSettingsUpdate- for partial updatesMerchantSettingsResponse- for API responses- Nested schemas for operating hours and tax settings
- Comprehensive field validation (time formats, percentage ranges, etc.)
3. Service (app/services/merchant_settings_service.py)
- Business logic layer
- CRUD operations (Create, Read, Update, Delete)
- Merchant validation (ensures merchant exists before creating settings)
- Duplicate prevention (one settings record per merchant)
- Soft delete functionality
- Comprehensive error handling and logging
4. Router (app/routers/merchant_settings_router.py)
- FastAPI endpoints following existing patterns
- Authentication and authorization using existing dependencies
- Comprehensive API documentation
- Multiple convenience endpoints for specific operations
API Endpoints
Core Operations
POST /merchant-settings- Create merchant settingsGET /merchant-settings/{merchant_id}- Get settings by merchant IDPUT /merchant-settings/{merchant_id}- Update settings (partial updates supported)DELETE /merchant-settings/{merchant_id}- Soft delete settingsGET /merchant-settings- List all settings with filters
Convenience Endpoints
PATCH /merchant-settings/{merchant_id}/activate- Activate settingsPATCH /merchant-settings/{merchant_id}/deactivate- Deactivate settingsPATCH /merchant-settings/{merchant_id}/operating-hours- Update operating hours onlyPATCH /merchant-settings/{merchant_id}/notifications- Update notification preferences
Settings Categories
Business Settings
auto_allocate_stock- Automatically allocate stock on orderscredit_limit- Credit limit in base currencypayment_terms_days- Payment terms (0-365 days)
Inventory Settings
low_stock_threshold- Alert threshold for low stockenable_backorder- Allow backorders when out of stockauto_reorder- Automatically create reorder when stock is low
Notification Settings
email_notifications- Enable/disable email notificationssms_notifications- Enable/disable SMS notificationslow_stock_alerts- Enable/disable low stock alertsorder_status_updates- Enable/disable order status notifications
Operating Hours
- Day-wise configuration (Monday to Sunday)
is_open- Whether merchant is open on that dayopen_time/close_time- Hours in HH:MM format- Validates time format (24-hour)
Pricing Settings
default_markup_percentage- Default markup percentage (0-1000%)allow_discount- Whether discounts are allowedmax_discount_percentage- Maximum discount allowed (0-100%)
Tax Settings
gst_rate- GST rate percentage (0-100%)inclusive_pricing- Whether prices include taxtax_exemption- Whether merchant is tax exempt
Additional
custom_fields- Extensible custom configurationis_active- Settings status (for soft delete)- Audit fields (
created_by,created_at,updated_by,updated_at)
Authentication & Authorization
- Uses existing authentication system (
get_current_user,require_admin_role) - Create/Update: Any authenticated user
- Delete/Activate/Deactivate: Admin role required
- List/Get: Any authenticated user
Validation Features
- Merchant existence validation
- Duplicate settings prevention
- Field validation (ranges, formats, patterns)
- Time format validation for operating hours
- Percentage validation for rates and discounts
- Partial update support (only provided fields are updated)
Error Handling
- Comprehensive error messages
- Proper HTTP status codes
- Detailed logging for debugging
- Graceful handling of edge cases
Database Integration
- MongoDB integration using existing patterns
- Follows existing nosql connection patterns
- Proper datetime handling
- Document-based storage with embedded sub-documents
Code Quality
- Follows existing codebase patterns and style
- Comprehensive docstrings and comments
- Type hints throughout
- Pydantic validation
- Structured logging
Usage Examples
Create Settings
POST /merchant-settings
{
"merchant_id": "mch_123",
"auto_allocate_stock": true,
"credit_limit": 500000.0,
"payment_terms_days": 30,
"low_stock_threshold": 10,
"operating_hours": {
"monday": {"is_open": true, "open_time": "09:00", "close_time": "18:00"},
"sunday": {"is_open": false}
},
"tax_settings": {
"gst_rate": 18.0,
"inclusive_pricing": true
}
}
Update Specific Fields
PUT /merchant-settings/mch_123
{
"credit_limit": 750000.0,
"low_stock_threshold": 5
}
Update Operating Hours Only
PATCH /merchant-settings/mch_123/operating-hours
{
"monday": {"is_open": true, "open_time": "08:00", "close_time": "20:00"},
"saturday": {"is_open": true, "open_time": "10:00", "close_time": "16:00"}
}
Integration Notes
- Added to main
app.pyrouter registration - Compatible with existing merchant management
- Extensible for future requirements
- Follows microservice patterns
Database Setup
Collection Structure
- Collection Name:
scm_merchant_settings - Database: MongoDB with schema validation
- Indexes: 11 optimized indexes for performance
Initialize Database
Run the database initialization script to create the collection and indexes:
# Initialize database structure
python3 manage_db.py init-db
# Verify database setup
python3 manage_db.py verify-db
Collection Features
- Schema Validation: MongoDB validates all documents against the defined schema
- Unique Constraint: Only one settings record per merchant (
merchant_id_uniqueindex) - Performance Indexes: Optimized for common query patterns
- Audit Trail: Tracks creation and update history with user information
Key Indexes
merchant_id_unique- Ensures one settings per merchantis_active_index- Fast filtering by active statusactive_merchant_index- Combined queries for active merchantsnotifications_index- Notification preference queriesinventory_settings_index- Inventory configuration queriesaudit_created_index- Audit trail queries
Testing
- Use the FastAPI docs at
/docsto test endpoints - Ensure MongoDB is running and connected
- Initialize database:
python3 manage_db.py init-db - Create a merchant first before creating settings
- Test with valid JWT tokens for authentication
Database Commands
# Initialize database collections and indexes
python3 manage_db.py init-db
# Verify database structure
python3 manage_db.py verify-db
# View database schema documentation
python3 DATABASE_SCHEMA.py
Sample Data Management
# Insert sample merchant settings records (5 realistic examples)
python3 sample_records.py insert
# View sample records in terminal
python3 sample_records.py view
# Export sample data to JSON file
python3 export_sample_data.py
# Clear all sample data
python3 sample_records.py clear
Sample Records Include:
- Premium retail (Mumbai) - High-end retail with full features
- distributor (Delhi) - Wholesale distributor with large credit limit
- Standard retail (Bangalore) - Regular retail with standard settings
- cnf (Chennai) - Carrying & Forwarding agent with enterprise settings
- Budget retail (Pune) - Small retail with basic configuration (inactive for testing)