User Commission History API Reference
Overview​
The User Commission History API provides endpoints for managing and monitoring the distributed commission calculation system. These APIs are designed for internal system communication and administrative operations, handling large-scale batch processing of referral commissions.
Authentication​
All User Commission History API endpoints require API key authentication for secure internal communication.
Authentication Headers​
X-API-Key: <api_key>
Access Roles​
- CLOUD_SCHEDULES: For job orchestration endpoints
- CLOUD_TASKS: For task processing endpoints
- Public: For report generation endpoints (no authentication required)
Base URLs​
Jobs Controller (Orchestration)​
https://hooks.blockbet.com/user-commission-history-jobs
Tasks Controller (Processing)​
https://hooks.blockbet.com/user-commission-history
API Endpoints​
Job Orchestration Endpoints​
Daily Commission Calculation Job​
Orchestrates the daily commission calculation process by creating distributed tasks.
Endpoint: GET /user-commission-history-jobs/daily-commission
Authentication: API Key + CLOUD_SCHEDULES role
Parameters:
targetDate
(query, optional): Date to process in YYYY-MM-DD format. Defaults to yesterday.
Example Request:
curl -X GET "https://hooks.blockbet.com/user-commission-history-jobs/daily-commission?targetDate=2024-01-15" \
-H "X-API-Key: your_api_key"
Example Response:
{
"status": "success",
"message": "Commission calculation job completed successfully"
}
Commission Report Generation​
Generates comprehensive commission reports for users or system-wide analysis.
Endpoint: GET /user-commission-history-jobs/report
Authentication: None (public endpoint)
Parameters:
userId
(query, optional): Specific user ID for user-specific reportsstartDate
(query, optional): Report start date in YYYY-MM-DD formatendDate
(query, optional): Report end date in YYYY-MM-DD format
Example Request:
curl -X GET "https://hooks.blockbet.com/user-commission-history-jobs/report?userId=507f1f77bcf86cd799439011&startDate=2024-01-01&endDate=2024-01-31"
Example Response (User-Specific):
{
"reportType": "USER_SPECIFIC",
"userId": "507f1f77bcf86cd799439011",
"user": {
"username": "player123",
"email": "player123@example.com",
"createdAt": "2024-01-01T00:00:00.000Z"
},
"dateRange": {
"start": "2024-01-01T00:00:00.000Z",
"end": "2024-01-31T23:59:59.999Z"
},
"referralsByTier": {
"tier1": [
{
"referredUserId": "507f1f77bcf86cd799439012",
"referredUser": {
"username": "referred_user1",
"email": "user1@example.com"
},
"referralDate": "2024-01-15T10:30:00.000Z",
"tier": 1
}
],
"tier2": [],
"tier3": [],
"tier4": []
},
"commissionHistory": [
{
"day": "2024-01-15T00:00:00.000Z",
"totalCommission": 125.5,
"totalReferralStakes": 2500.0,
"totalHouseEdge": 75.0,
"commissions": "{\"TIER_1\":{\"CAT_1\":100.50,\"CAT_2\":25.00}}",
"referralHouseEdgeValues": "{\"TIER_1\":{\"CAT_1\":60.00,\"CAT_2\":15.00}}",
"referralStakeValues": "{\"TIER_1\":{\"CAT_1\":2000.00,\"CAT_2\":500.00}}"
}
],
"commissionClaims": [
{
"claimedAt": "2024-01-20T14:30:00.000Z",
"amount": 100.0,
"amountUsdc": 100.0,
"bhTransactionId": "BH_TXN_123456789"
}
],
"totals": {
"totalCommissionEarned": 125.5,
"totalCommissionClaimed": 100.0,
"totalCommissionPending": 25.5,
"totalReferralStakes": 2500.0,
"totalHouseEdge": 75.0,
"commissionByTier": {
"tier1": 125.5,
"tier2": 0,
"tier3": 0,
"tier4": 0
},
"referralCounts": {
"tier1": 1,
"tier2": 0,
"tier3": 0,
"tier4": 0
}
},
"generatedAt": "2024-01-31T12:00:00.000Z"
}
Task Processing Endpoints​
Batch Commission Processing​
Processes commission calculations for a batch of users.
Endpoint: GET /user-commission-history/daily-commission-calculation/{targetDate}/{batchSize}
Authentication: API Key + CLOUD_TASKS role
Parameters:
targetDate
(path): Date to process in YYYY-MM-DD formatbatchSize
(path): Maximum number of users to process in this batch
Example Request:
curl -X GET "https://hooks.blockbet.com/user-commission-history/daily-commission-calculation/2024-01-15/1000" \
-H "X-API-Key: your_api_key"
Example Response:
{
"status": "success",
"message": "Batch processing completed"
}
Response Formats​
Success Response​
{
"status": "success",
"message": "Operation completed successfully"
}
Error Response​
{
"status": "error",
"message": "Error description",
"details": {
"errorCode": "SPECIFIC_ERROR_CODE",
"timestamp": "2024-01-15T10:30:00.000Z"
}
}
Commission Report Data Models​
User-Specific Report Structure​
Report Metadata​
interface UserSpecificReport {
reportType: 'USER_SPECIFIC';
userId: string;
user: {
username: string;
email: string;
createdAt: Date;
};
dateRange: {
start: Date;
end: Date;
};
generatedAt: Date;
}
Referrals by Tier​
interface ReferralsByTier {
tier1: ReferralInfo[];
tier2: ReferralInfo[];
tier3: ReferralInfo[];
tier4: ReferralInfo[];
}
interface ReferralInfo {
referredUserId: string;
referredUser: {
username: string;
email: string;
};
referralDate: Date;
tier: number;
}
Commission History​
interface CommissionHistoryEntry {
day: Date;
totalCommission: number;
totalReferralStakes: number;
totalHouseEdge: number;
commissions: string; // JSON string of tier/game breakdown
referralHouseEdgeValues: string; // JSON string of tier/game breakdown
referralStakeValues: string; // JSON string of tier/game breakdown
}
Commission Claims​
interface CommissionClaim {
claimedAt: Date;
amount: number; // System currency
amountUsdc: number; // USDC value
bhTransactionId: string; // External transaction ID
}
Report Totals​
interface ReportTotals {
totalCommissionEarned: number;
totalCommissionClaimed: number;
totalCommissionPending: number;
totalReferralStakes: number;
totalHouseEdge: number;
commissionByTier: {
tier1: number;
tier2: number;
tier3: number;
tier4: number;
};
referralCounts: {
tier1: number;
tier2: number;
tier3: number;
tier4: number;
};
}
System-Wide Report Structure​
interface SystemWideReport {
reportType: 'SYSTEM_WIDE';
dateRange: {
start: Date;
end: Date;
};
systemStats: {
commission: {
totalCommission: number;
totalReferralStakes: number;
totalHouseEdge: number;
uniqueUsersCount: number;
avgCommissionPerUser: number;
avgStakesPerUser: number;
avgHouseEdgePerUser: number;
};
referrals: {
tier1Count: number;
tier2Count: number;
tier3Count: number;
tier4Count: number;
totalReferrals: number;
};
};
topReferrers: TopReferrer[];
commissionDistribution: CommissionDistribution[];
recentActivity: RecentActivity[];
generatedAt: Date;
}
Error Handling​
Common Error Codes​
Authentication Errors​
UNAUTHORIZED
: Missing or invalid API keyFORBIDDEN
: Insufficient permissions for the requested operation
Validation Errors​
INVALID_DATE_FORMAT
: Date parameter not in YYYY-MM-DD formatINVALID_BATCH_SIZE
: Batch size parameter not a valid numberINVALID_USER_ID
: User ID parameter not a valid ObjectId
Processing Errors​
NO_USERS_FOUND
: No users found needing commission updatesPROCESSING_FAILED
: Commission calculation processing failedDATA_PREPARATION_FAILED
: Failed to prepare data for processing
System Errors​
TASK_CREATION_FAILED
: Failed to create Google Cloud TasksDATABASE_ERROR
: Database operation failedEXTERNAL_API_ERROR
: External service integration failed
Error Response Examples​
Authentication Error​
{
"status": "error",
"message": "Unauthorized access",
"details": {
"errorCode": "UNAUTHORIZED",
"timestamp": "2024-01-15T10:30:00.000Z"
}
}
Validation Error​
{
"status": "error",
"message": "Invalid date format. Expected YYYY-MM-DD",
"details": {
"errorCode": "INVALID_DATE_FORMAT",
"providedValue": "2024/01/15",
"expectedFormat": "YYYY-MM-DD",
"timestamp": "2024-01-15T10:30:00.000Z"
}
}
Processing Error​
{
"status": "error",
"message": "No users found needing commission updates",
"details": {
"errorCode": "NO_USERS_FOUND",
"targetDate": "2024-01-15",
"timestamp": "2024-01-15T10:30:00.000Z"
}
}
Rate Limiting​
Job Orchestration Endpoints​
- Daily Commission Job: 1 request per minute (designed for scheduled execution)
- Report Generation: 10 requests per minute per IP
Task Processing Endpoints​
- Batch Processing: No explicit rate limiting (controlled by Google Cloud Tasks)
Monitoring and Observability​
Request Logging​
All API requests are logged with:
- Request timestamp
- Endpoint accessed
- Parameters provided
- Processing duration
- Response status
Performance Metrics​
Key metrics tracked:
- Job Duration: Time to complete daily commission jobs
- Batch Processing Time: Time to process individual batches
- Success Rates: Percentage of successful operations
- Error Rates: Frequency and types of errors
Health Checks​
The API provides health check endpoints for monitoring:
- Service availability
- Database connectivity
- External service integration status
Best Practices​
API Usage Guidelines​
For Job Orchestration​
- Schedule Appropriately: Run daily jobs during low-traffic periods
- Monitor Completion: Check job status and handle failures
- Avoid Overlapping: Ensure previous jobs complete before starting new ones
- Use Appropriate Dates: Specify target dates for reprocessing when needed
For Report Generation​
- Cache Results: Cache report results for frequently accessed data
- Use Date Ranges: Limit report scope with appropriate date ranges
- Handle Large Reports: Implement pagination for large system-wide reports
- Optimize Queries: Use specific user IDs when possible
For Task Processing​
- Internal Use Only: These endpoints are for internal system communication
- Proper Authentication: Always use appropriate API keys and roles
- Error Handling: Implement proper error handling and retry logic
- Monitoring: Monitor task completion and processing metrics
Performance Optimization​
Report Generation​
# Optimize by specifying user ID for targeted reports
curl "https://hooks.blockbet.com/user-commission-history-jobs/report?userId=507f1f77bcf86cd799439011"
# Use date ranges to limit data scope
curl "https://hooks.blockbet.com/user-commission-history-jobs/report?startDate=2024-01-01&endDate=2024-01-07"
Batch Processing​
- Use appropriate batch sizes (recommended: 1000 users)
- Monitor processing times and adjust if needed
- Implement proper error handling for failed batches
Integration Examples​
Daily Job Scheduling​
#!/bin/bash
# Daily commission calculation script
API_KEY="your_api_key"
TARGET_DATE=$(date -d "yesterday" +%Y-%m-%d)
response=$(curl -s -X GET \
"https://hooks.blockbet.com/user-commission-history-jobs/daily-commission?targetDate=${TARGET_DATE}" \
-H "X-API-Key: ${API_KEY}")
if [[ $(echo $response | jq -r '.status') == "success" ]]; then
echo "Commission calculation job completed successfully for ${TARGET_DATE}"
else
echo "Commission calculation job failed for ${TARGET_DATE}: $(echo $response | jq -r '.message')"
exit 1
fi
Report Generation Integration​
const generateCommissionReport = async (userId, startDate, endDate) => {
const params = new URLSearchParams();
if (userId) params.append('userId', userId);
if (startDate) params.append('startDate', startDate);
if (endDate) params.append('endDate', endDate);
const response = await fetch(
`https://hooks.blockbet.com/user-commission-history-jobs/report?${params}`,
);
if (!response.ok) {
throw new Error(`Report generation failed: ${response.statusText}`);
}
return await response.json();
};
// Usage examples
const userReport = await generateCommissionReport(
'507f1f77bcf86cd799439011',
'2024-01-01',
'2024-01-31',
);
const systemReport = await generateCommissionReport(
null,
'2024-01-01',
'2024-01-31',
);