Auto Review Request Controller
Source: internal/api/v1/reviews/controllers/auto-review-request.controller.js
Service: autoReviewRequest service
Module: Reviews
Overview
The Auto Review Request controller manages the automated review request configuration. It enables businesses to automatically send review requests to customers after certain triggers (e.g., order completion, service delivery). This controller handles the configuration settings that determine when and how automatic review requests are sent.
Key Capabilities
- Get Auto-Request Configuration with sorting and pagination
- Update Configuration Settings for automated review requests
- Multi-Platform Support for different review platforms
- Trigger Conditions based on business events
- Template Management for request messages
MongoDB Collections
| Collection | Operations | Purpose |
|---|---|---|
review-auto-request-config | READ, UPDATE | Auto-request configuration per account |
Service Methods
1. getAutoReviewRequest()
Retrieve the auto review request configuration for an account.
Endpoint: GET /reviews/auto-review-request
Controller Logic:
const getAutoReviewRequest = catchAsync(async (req, res) => {
let { limit, page, sort_by, order } = req.query;
const accountId = req.auth.account_id;
limit = parseInt(limit);
page = page ? parseInt(page) : 0;
let skip = page ? (page - 1) * limit : 0;
const autoReviewRequestData = await autoReviewRequest.getAutoReviewRequest({
limit,
skip,
sortBy: sort_by,
order,
accountId,
});
res.json({
success: true,
data: autoReviewRequestData,
});
});
Request:
GET /api/v1/v1/reviews/auto-review-request?page=1&limit=20&sort_by=created_at&order=desc
Query Parameters:
limit(number, optional) - Items per pagepage(number, optional) - Page number (default: 0)sort_by(string, optional) - Field to sort by (created_at, updated_at, name)order(string, optional) - Sort order ('asc' or 'desc')
Response:
{
"success": true,
"data": {
"configs": [
{
"_id": "config_abc123",
"account_id": "acc_123",
"enabled": true,
"trigger": "order_completed",
"delay_hours": 24,
"platforms": ["google", "facebook"],
"template_id": "template_xyz",
"conditions": {
"min_order_value": 50,
"customer_segment": "all"
},
"created_at": "2024-12-01T10:00:00Z",
"updated_at": "2024-12-08T10:00:00Z"
}
],
"pagination": {
"page": 1,
"limit": 20,
"total": 1
}
}
}
Business Logic:
graph TD
A[Receive Request] --> B[Parse Query Parameters]
B --> C[Convert to Integers]
C --> D{page > 0?}
D -->|Yes| E[Calculate skip = page - 1 * limit]
D -->|No| F[Set skip = 0]
E --> G[Extract account_id]
F --> G
G --> H[Call autoReviewRequest.getAutoReviewRequest]
H --> I[Query MongoDB with Filters]
I --> J[Apply Sorting]
J --> K[Apply Pagination]
K --> L[Return Configs + Pagination]
L --> M[Send Response]
Key Features:
- Flexible Sorting: Sort by any field
- Pagination Support: Handle large config lists
- Account Scoped: Only return configs for authenticated account
- Default Values: Handles missing query params gracefully
Use Cases:
- View all configured auto-request triggers
- Audit enabled/disabled configurations
- Sort by creation date to see newest first
- Paginate through multiple configurations
2. updateAutoReviewRequest()
Update the auto review request configuration settings.
Endpoint: PUT /reviews/auto-review-request
Controller Logic:
const updateAutoReviewRequest = catchAsync(async (req, res) => {
const autoReviewRequestDetails = req.body;
const accountId = req.auth.account_id;
const parentAccount = req.auth.parent_account || req.auth.account_id;
const autoReviewRequestData = await autoReviewRequest.updateAutoReviewRequest({
autoReviewRequestDetails,
accountId,
parentAccount,
});
res.json({
success: true,
data: autoReviewRequestData,
});
});
Request:
PUT /api/v1/v1/reviews/auto-review-request
Content-Type: application/json
{
"enabled": true,
"trigger": "order_completed",
"delay_hours": 24,
"platforms": ["google", "facebook", "yelp"],
"template_id": "template_xyz",
"conditions": {
"min_order_value": 50,
"exclude_refunded": true,
"customer_segment": "all"
},
"send_method": "email",
"from_email": "reviews@company.com"
}
Request Body:
{
enabled: boolean; // Enable/disable auto-requests
trigger: string; // Event that triggers request
// Options: 'order_completed', 'service_delivered',
// 'appointment_finished', 'custom_event'
delay_hours: number; // Hours to wait after trigger
platforms: string[]; // Target platforms (google, facebook, yelp)
template_id?: string; // Optional template reference
conditions?: { // Optional filtering conditions
min_order_value?: number; // Minimum order value
exclude_refunded?: boolean; // Skip refunded orders
customer_segment?: string; // Target segment (all, vip, new)
exclude_repeated?: boolean; // Skip customers already requested
};
send_method: 'email' | 'sms' | 'both'; // Delivery method
from_email?: string; // Sender email (for email method)
from_phone?: string; // Sender phone (for SMS method)
}
Response:
{
"success": true,
"data": {
"_id": "config_abc123",
"account_id": "acc_123",
"enabled": true,
"trigger": "order_completed",
"delay_hours": 24,
"platforms": ["google", "facebook", "yelp"],
"template_id": "template_xyz",
"conditions": {
"min_order_value": 50,
"exclude_refunded": true,
"customer_segment": "all"
},
"send_method": "email",
"from_email": "reviews@company.com",
"updated_at": "2024-12-08T15:00:00Z"
}
}
Business Logic:
graph TD
A[Receive Update Request] --> B[Extract Request Body]
B --> C[Extract Auth Context]
C --> D{Has parent_account?}
D -->|Yes| E[Use parent_account]
D -->|No| F[Use account_id as parent]
E --> G[Call updateAutoReviewRequest]
F --> G
G --> H{Config Exists?}
H -->|No| I[Create New Config]
H -->|Yes| J[Update Existing Config]
I --> K[Validate Settings]
J --> K
K --> L{Valid Configuration?}
L -->|No| M[Throw Validation Error]
L -->|Yes| N[Save to MongoDB]
N --> O[Return Updated Config]
O --> P[Send Response]
Key Features:
- Upsert Logic: Creates config if doesn't exist
- Parent Account Support: Sub-accounts can inherit parent config
- Full Configuration: All settings in one update
- Validation: Service layer validates trigger types and platforms
Configuration Examples:
1. Basic Order Completion Trigger:
{
"enabled": true,
"trigger": "order_completed",
"delay_hours": 24,
"platforms": ["google"],
"send_method": "email"
}
2. High-Value Customer Only:
{
"enabled": true,
"trigger": "order_completed",
"delay_hours": 48,
"platforms": ["google", "facebook"],
"conditions": {
"min_order_value": 100,
"exclude_refunded": true
},
"send_method": "both"
}
3. Service Delivery Trigger:
{
"enabled": true,
"trigger": "service_delivered",
"delay_hours": 2,
"platforms": ["google", "yelp"],
"conditions": {
"customer_segment": "vip",
"exclude_repeated": true
},
"send_method": "sms"
}
4. Disabled Configuration (Pause):
{
"enabled": false,
"trigger": "order_completed",
"delay_hours": 24
}
Request/Response Flow
Complete Auto-Review Request Flow
sequenceDiagram
participant Client
participant Controller
participant Service
participant MongoDB
participant QueueManager
Note over Client,QueueManager: Get Configuration
Client->>Controller: GET /auto-review-request
Controller->>Service: getAutoReviewRequest(account_id)
Service->>MongoDB: Find config by account_id
MongoDB-->>Service: Config document
Service-->>Controller: Config data
Controller-->>Client: JSON response
Note over Client,QueueManager: Update Configuration
Client->>Controller: PUT /auto-review-request
Controller->>Service: updateAutoReviewRequest(details)
Service->>MongoDB: findOneAndUpdate or insert
MongoDB-->>Service: Updated config
Service-->>Controller: Config data
Controller-->>Client: Success response
Note over Client,QueueManager: Trigger Event (Background)
QueueManager->>Service: order_completed event
Service->>MongoDB: Find active configs for account
MongoDB-->>Service: Enabled configs
Service->>Service: Check conditions match
Service->>Service: Calculate delay time
Service->>QueueManager: Schedule review request job
QueueManager->>QueueManager: Wait delay_hours
QueueManager->>Service: Send review request
Service->>Service: Generate review link
Service->>Service: Apply template
Service->>Service: Send via email/SMS
Edge Cases & Error Handling
Common Scenarios
1. No Configuration Exists:
// First time GET returns empty or default config
{
"success": true,
"data": {
"configs": [],
"pagination": { "total": 0 }
}
}
2. Invalid Trigger Type:
// Service layer validates trigger
const validTriggers = [
'order_completed',
'service_delivered',
'appointment_finished',
'custom_event',
];
if (!validTriggers.includes(trigger)) {
throw new ApiError(400, 'Invalid trigger type');
}
3. Invalid Platform:
// Platform must be supported
const validPlatforms = ['google', 'facebook', 'yelp', 'trustpilot'];
platforms.forEach(platform => {
if (!validPlatforms.includes(platform)) {
throw new ApiError(400, `Invalid platform: ${platform}`);
}
});
4. Negative Delay Hours:
// Delay must be positive
if (delay_hours < 0) {
throw new ApiError(400, 'Delay hours must be positive');
}
5. Missing Template ID:
// Template optional, but if provided must exist
if (template_id) {
const template = await Template.findById(template_id);
if (!template) {
throw new ApiError(404, 'Template not found');
}
}
6. Parent Account Inheritance:
// Sub-accounts can use parent's config
const parentAccount = req.auth.parent_account || req.auth.account_id;
// If sub-account has no config, fallback to parent
let config = await Config.findOne({ account_id: accountId });
if (!config && parentAccount !== accountId) {
config = await Config.findOne({ account_id: parentAccount });
}
Authorization
Authentication: Required (JWT Bearer token)
Authorization Rules:
- ✅ Account-scoped: Config tied to
account_id - ✅ Parent-account support: Sub-accounts can inherit
- ❌ No cross-account access
- ❌ Cannot modify other accounts' configs
Multi-Tenant Pattern:
// Primary account from auth
const accountId = req.auth.account_id;
// Parent account for inheritance
const parentAccount = req.auth.parent_account || req.auth.account_id;
// Service enforces ownership
await Config.findOne({ account_id: accountId });
Integration Points
Related Controllers
Dependencies:
- Request Review Controller: Uses auto-request config for sending
- Config Controller: Requires platform connections
- Response Templates Controller: References template_id
Triggered By:
- Store Webhooks: Order completion events
- Projects Controller: Service delivery events
- Queue Manager: Scheduled job execution
Triggers:
- Queue Manager: Schedules review request jobs
- Notification Service: Sends email/SMS
- Activity Log: Records auto-request events
Important Notes
Trigger Event Types
-
order_completed: E-commerce order fulfillment
- Triggered when order status → 'completed'
- Typical delay: 24-48 hours
- Use case: Product reviews
-
service_delivered: Service completion
- Triggered when service marked delivered
- Typical delay: 2-24 hours
- Use case: Service-based businesses
-
appointment_finished: Appointment completion
- Triggered after appointment end time
- Typical delay: 1-12 hours
- Use case: Healthcare, salons, consultations
-
custom_event: Custom trigger
- Triggered by custom integration
- Delay varies
- Use case: Unique business workflows
Configuration Strategies
Timing Best Practices:
- Immediate Products: 2-4 hours (food, entertainment)
- Standard Products: 24-48 hours (retail, services)
- Complex Services: 3-7 days (home improvement, consulting)
- High-Value Items: 7-14 days (allow time to experience)
Platform Selection:
- Google: Priority for local businesses
- Facebook: Social proof emphasis
- Yelp: Service industry standard
- Multiple Platforms: Increase review volume
Condition Strategies:
- min_order_value: Focus on satisfied customers (higher value = higher satisfaction)
- exclude_refunded: Avoid negative reviews from unhappy customers
- exclude_repeated: Prevent review fatigue
- customer_segment: Target VIP/loyal customers for better response rate
Performance Considerations
- Job Scheduling: Queue manager handles delayed execution
- Batch Processing: Multiple configs evaluated per event
- Rate Limiting: Prevent spam (1 request per customer per platform per 30 days)
- Condition Evaluation: O(n) complexity based on number of conditions
Related Documentation
- Request Review Controller - Manual review requests
- Response Templates Controller - Message templates
- Config Controller - Platform connections
- Webhooks Controller - Trigger events
Version: 1.0
Last Updated: December 2024
Status: ✅ Production Ready