Centralized_Reporting_Backend/src/data/repositories/zohoBulkReadRepository.js
2025-09-25 17:40:59 +05:30

253 lines
7.1 KiB
JavaScript

const ZohoContactsBulk = require('../models/zohoContactsBulk');
const ZohoLeadsBulk = require('../models/zohoLeadsBulk');
const ZohoAccountsBulk = require('../models/zohoAccountsBulk');
const ZohoTasksBulk = require('../models/zohoTasksBulk');
const ZohoVendorsBulk = require('../models/zohoVendorsBulk');
const ZohoInvoicesBulk = require('../models/zohoInvoicesBulk');
const ZohoSalesOrdersBulk = require('../models/zohoSalesOrdersBulk');
const ZohoPurchaseOrdersBulk = require('../models/zohoPurchaseOrdersBulk');
const ZohoDealsBulk = require('../models/zohoDealsBulk');
const ZohoBulkReadJobs = require('../models/zohoBulkReadJobs');
class ZohoBulkReadRepository {
constructor() {
this.models = {
'contacts': ZohoContactsBulk,
'leads': ZohoLeadsBulk,
'accounts': ZohoAccountsBulk,
'tasks': ZohoTasksBulk,
'vendors': ZohoVendorsBulk,
'invoices': ZohoInvoicesBulk,
'sales_orders': ZohoSalesOrdersBulk,
'purchase_orders': ZohoPurchaseOrdersBulk,
'deals': ZohoDealsBulk
};
}
/**
* Get the appropriate model for a module
* @param {string} module - Module name
* @returns {Object} Sequelize model
*/
getModel(module) {
const model = this.models[module.toLowerCase()];
if (!model) {
throw new Error(`No model found for module: ${module}`);
}
return model;
}
/**
* Bulk insert data for a specific module
* @param {string} module - Module name
* @param {Array} data - Array of records to insert
* @returns {Promise<Array>} Inserted records
*/
async bulkInsert(module, data) {
try {
const model = this.getModel(module);
console.log(`💾 Bulk inserting ${data.length} records for ${module}`);
const result = await model.bulkCreate(data, {
ignoreDuplicates: true,
validate: true
});
console.log(`✅ Successfully inserted ${result.length} records for ${module}`);
return result;
} catch (error) {
console.error(`❌ Error bulk inserting ${module}:`, error.message);
throw error;
}
}
/**
* Clear existing data for a user and module
* @param {string} userId - User UUID
* @param {string} module - Module name
* @param {string} jobId - Bulk job ID
* @returns {Promise<number>} Number of deleted records
*/
async clearUserData(userId, module, jobId) {
try {
const model = this.getModel(module);
console.log(`🗑️ Clearing existing data for user ${userId}, module ${module}, job ${jobId}`);
const result = await model.destroy({
where: {
user_uuid: userId,
provider: 'zoho',
bulk_job_id: jobId
}
});
console.log(`✅ Cleared ${result} existing records for ${module}`);
return result;
} catch (error) {
console.error(`❌ Error clearing data for ${module}:`, error.message);
throw error;
}
}
/**
* Get data for a user and module
* @param {string} userId - User UUID
* @param {string} module - Module name
* @param {Object} options - Query options
* @returns {Promise<Array>} Records
*/
async getUserData(userId, module, options = {}) {
try {
const model = this.getModel(module);
const { limit = 100, offset = 0, orderBy = 'created_time', orderDirection = 'DESC' } = options;
const records = await model.findAll({
where: {
user_uuid: userId,
provider: 'zoho'
},
limit: parseInt(limit),
offset: parseInt(offset),
order: [[orderBy, orderDirection]]
});
return records;
} catch (error) {
console.error(`❌ Error getting user data for ${module}:`, error.message);
throw error;
}
}
/**
* Get count of records for a user and module
* @param {string} userId - User UUID
* @param {string} module - Module name
* @returns {Promise<number>} Record count
*/
async getUserDataCount(userId, module) {
try {
const model = this.getModel(module);
const count = await model.count({
where: {
user_uuid: userId,
provider: 'zoho'
}
});
return count;
} catch (error) {
console.error(`❌ Error getting count for ${module}:`, error.message);
throw error;
}
}
// Bulk Read Jobs methods
/**
* Create a new bulk read job record
* @param {Object} jobData - Job data
* @returns {Promise<Object>} Created job
*/
async createBulkReadJob(jobData) {
try {
console.log('📝 Creating bulk read job:', jobData.id);
const job = await ZohoBulkReadJobs.create({
id: jobData.id,
user_uuid: jobData.user_uuid,
provider: 'zoho',
module: jobData.module,
operation: jobData.operation,
state: jobData.state,
file_type: jobData.file_type,
download_url: jobData.download_url,
records_count: jobData.records_count || 0,
status: 'pending'
});
console.log('✅ Bulk read job created successfully');
return job;
} catch (error) {
console.error('❌ Error creating bulk read job:', error.message);
throw error;
}
}
/**
* Update bulk read job status
* @param {string} jobId - Job ID
* @param {Object} updateData - Update data
* @returns {Promise<Object>} Updated job
*/
async updateBulkReadJob(jobId, updateData) {
try {
console.log(`🔄 Updating bulk read job ${jobId}:`, updateData);
const [updatedRows] = await ZohoBulkReadJobs.update(updateData, {
where: { id: jobId }
});
if (updatedRows === 0) {
throw new Error(`Job ${jobId} not found`);
}
const updatedJob = await ZohoBulkReadJobs.findByPk(jobId);
console.log('✅ Bulk read job updated successfully');
return updatedJob;
} catch (error) {
console.error('❌ Error updating bulk read job:', error.message);
throw error;
}
}
/**
* Get bulk read job by ID
* @param {string} jobId - Job ID
* @returns {Promise<Object>} Job record
*/
async getBulkReadJob(jobId) {
try {
const job = await ZohoBulkReadJobs.findByPk(jobId);
return job;
} catch (error) {
console.error('❌ Error getting bulk read job:', error.message);
throw error;
}
}
/**
* Get bulk read jobs for a user
* @param {string} userId - User UUID
* @param {Object} options - Query options
* @returns {Promise<Array>} Job records
*/
async getUserBulkReadJobs(userId, options = {}) {
try {
const { limit = 50, offset = 0, status } = options;
const whereClause = {
user_uuid: userId,
provider: 'zoho'
};
if (status) {
whereClause.status = status;
}
const jobs = await ZohoBulkReadJobs.findAll({
where: whereClause,
limit: parseInt(limit),
offset: parseInt(offset),
order: [['created_at', 'DESC']]
});
return jobs;
} catch (error) {
console.error('❌ Error getting user bulk read jobs:', error.message);
throw error;
}
}
}
module.exports = new ZohoBulkReadRepository();