Sync Accounts Processor
Overview
The Sync Accounts processor fixes data inconsistencies by finding accounts with has_orders: false that actually have active managed subscription orders. It updates the flag to maintain data integrity across the system.
Source File: queue-manager/services/projects/syncAccounts.js
Execution: Part of projects cron (every 5 minutes)
Type: Data maintenance
Business Impact: MEDIUM - Data integrity
Processing Flow
sequenceDiagram
participant CRON as Projects Cron
participant SVC as Sync Service
participant ACC as Accounts
participant ORD as Orders
CRON->>SVC: syncAccounts()
SVC->>ACC: Find accounts with<br/>has_orders: false
ACC-->>SVC: Account list
SVC->>ORD: Lookup active orders<br/>for each account
ORD-->>SVC: Order data
SVC->>SVC: Filter accounts<br/>with active orders
SVC->>ACC: Update has_orders: true
ACC-->>SVC: Update count
Key Logic
Problem Detection
Finds accounts where:
account.active === true
account.has_orders === false
BUT account has active managed subscription orders
Order Matching
Checks both buyer and seller roles:
$or: [{ $eq: ['$seller_account', '$$acc_id'] }, { $eq: ['$buyer_account', '$$acc_id'] }];
Managed Subscriptions
Only counts orders with managed product types:
'metadata.product_type': {
$in: MANAGED_SUBSCRIPTIONS
}
MongoDB Aggregation Pipeline
Stage 1: Find Inconsistent Accounts
{
$match: {
active: true,
has_orders: false
}
}
Stage 2: Lookup Active Orders
{
$lookup: {
from: '_store.orders',
let: { acc_id: '$_id' },
pipeline: [
{
$match: {
status: 'active',
'metadata.product_type': { $in: MANAGED_SUBSCRIPTIONS },
$expr: {
$or: [
{ $eq: ['$seller_account', '$$acc_id'] },
{ $eq: ['$buyer_account', '$$acc_id'] }
]
}
}
},
{ $limit: 1 }
],
as: 'hasOrder'
}
}
Stage 3: Filter Accounts with Orders
{
$match: {
hasOrder: {
$size: 1;
}
}
}
Stage 4: Group Account IDs
{
$group: {
_id: null,
ids: { $addToSet: '$_id' }
}
}
Update Operation
await Account.updateMany({ _id: { $in: accIds } }, { $set: { has_orders: true } });
Collections Used
Input: account
- Queries accounts with
has_orders: false - Filters by
active: true
Lookup: _store.orders
- Checks for active managed subscription orders
Output: account
- Updates
has_ordersflag
Error Handling
try {
// Aggregation and update
} catch (error) {
logger.error({
initiator: 'QM/projects/syncAccounts',
error: error,
});
throw error;
}
Return Value
return accIds; // Array of updated account ObjectIds
Logging
// No accounts found
'No accounts out of sync' // Accounts updated
`Found ${accIds.length} accounts out of sync`;
Performance
Execution Time: 1-3 seconds
Frequency: Every 5 minutes
Typical Results: 0-5 accounts per run
Complexity: LOW
Lines of Code: 109
Type: Maintenance