new(whatsapp.gblib): FB Analytics.

This commit is contained in:
Rodrigo Rodriguez 2025-02-16 18:22:14 -03:00
parent 614539a0b4
commit a693265cb1

View file

@ -1539,110 +1539,74 @@ private async sendButtonList(to: string, buttons: string[]) {
let buf: any = Buffer.from(await res.arrayBuffer());
return buf;
}
public async getLatestTemplateReport() {
const businessAccountId = this.whatsappBusinessManagerId;
const userAccessToken = this.whatsappServiceKey;
if (!(businessAccountId && userAccessToken)) {
return 'No statistics available for WhatsApp templates.';
}
try {
// Step 1: Fetch all templates ordered by creation time
const statsResponse = await fetch(
`https://graph.facebook.com/v20.0/${businessAccountId}/message_templates?` +
`fields=id,name,status,language,quality_score,category,created_time,` +
`message_sends_24h,message_sends_7d,message_sends_30d,` +
`delivered_24h,delivered_7d,delivered_30d,` +
`read_24h,read_7d,read_30d&` +
`ordering=[{created_time: 'DESC'}]`, {
headers: {
Authorization: `Bearer ${userAccessToken}`
}
});
const data = await statsResponse.json();
if (!statsResponse.ok) {
throw new Error(data.error.message);
}
if (!data.data || data.data.length === 0) {
throw new Error('No template statistics found');
}
// Get the last template from the sorted data
const templateData = data.data[data.data.length - 1];
console.log('Latest template statistics retrieved:', templateData.name);
// Step 2: Calculate key metrics
const metrics = {
name: templateData.name,
status: templateData.status,
language: templateData.language,
category: templateData.category,
qualityScore: templateData.quality_score,
createdTime: new Date(templateData.created_time).toLocaleString(),
// 24-hour metrics
sends24h: templateData.message_sends_24h,
delivered24h: templateData.delivered_24h,
read24h: templateData.read_24h,
deliveryRate24h: ((templateData.delivered_24h / templateData.message_sends_24h) * 100).toFixed(2),
readRate24h: ((templateData.read_24h / templateData.delivered_24h) * 100).toFixed(2),
// 7-day metrics
sends7d: templateData.message_sends_7d,
delivered7d: templateData.delivered_7d,
read7d: templateData.read_7d,
deliveryRate7d: ((templateData.delivered_7d / templateData.message_sends_7d) * 100).toFixed(2),
readRate7d: ((templateData.read_7d / templateData.delivered_7d) * 100).toFixed(2),
// 30-day metrics
sends30d: templateData.message_sends_30d,
delivered30d: templateData.delivered_30d,
read30d: templateData.read_30d,
deliveryRate30d: ((templateData.delivered_30d / templateData.message_sends_30d) * 100).toFixed(2),
readRate30d: ((templateData.read_30d / templateData.delivered_30d) * 100).toFixed(2)
};
// Step 3: Format and return the report
return `
Latest WhatsApp Template Statistics
---------------------------------
Template Name: ${metrics.name}
Created: ${metrics.createdTime}
Status: ${metrics.status}
Language: ${metrics.language}
Category: ${metrics.category}
Quality Score: ${metrics.qualityScore}
Last 24 Hours
------------
Messages Sent: ${metrics.sends24h?.toLocaleString() ?? '0'}
Delivered: ${metrics.delivered24h?.toLocaleString() ?? '0'}
Read: ${metrics.read24h?.toLocaleString() ?? '0'}
Delivery Rate: ${metrics.deliveryRate24h}%
Read Rate: ${metrics.readRate24h}%
Last 7 Days
----------
Messages Sent: ${metrics.sends7d?.toLocaleString() ?? '0'}
Delivered: ${metrics.delivered7d?.toLocaleString() ?? '0'}
Read: ${metrics.read7d?.toLocaleString() ?? '0'}
Delivery Rate: ${metrics.deliveryRate7d}%
Read Rate: ${metrics.readRate7d}%
Last 30 Days
-----------
Messages Sent: ${metrics.sends30d?.toLocaleString() ?? '0'}
Delivered: ${metrics.delivered30d?.toLocaleString() ?? '0'}
Read: ${metrics.read30d?.toLocaleString() ?? '0'}
Delivery Rate: ${metrics.deliveryRate30d}%
Read Rate: ${metrics.readRate30d}%
`.trim();
} catch (error) {
console.error('Error fetching latest WhatsApp template statistics:', error.message);
throw error;
}
}}
public async getLatestCampaignReport() {
const businessAccountId = this.whatsappBusinessManagerId;
const userAccessToken = this.whatsappServiceKey;
if (!(businessAccountId && userAccessToken)) {
return 'No statistics available for General Bots WhatsApp templates.';
}
try {
// Step 1: Fetch templates with edit time ordering
const statsResponse = await fetch(
`https://graph.facebook.com/v20.0/${businessAccountId}/message_templates?` +
`fields=id,name,category,language,status,created_time,last_edited_time,` +
`message_sends_24h,message_sends_7d,message_sends_30d,` +
`delivered_24h,delivered_7d,delivered_30d,` +
`read_24h,read_7d,read_30d,content,components,` +
`quality_score,rejection_reason&` +
`ordering=[{last_edited_time: 'DESC'}]`, {
headers: {
Authorization: `Bearer ${userAccessToken}`
}
});
const data = await statsResponse.json();
if (!statsResponse.ok) {
throw new Error(data.error.message);
}
if (!data.data || data.data.length === 0) {
throw new Error('No template statistics found');
}
// Process all templates and format them
const templateReports = data.data.map(template => {
// Calculate delivery and read rates
const delivered = template.delivered_24h || 0;
const read = template.read_24h || 0;
const readRate = delivered > 0 ? ((read / delivered) * 100).toFixed(0) : 0;
const lastEditedDate = new Date(template.last_edited_time || template.created_time);
return `
Template Name: **${template.name}**
Category: **${template.category}**
Language: **${template.language}**
Status: **${template.status}**
Messages Delivered: **${delivered.toLocaleString()}**
Message Read Rate: **${readRate}% (${read.toLocaleString()})**
Top Block Reason: **${template.rejection_reason || ''}**
Last Edited: **${lastEditedDate.toLocaleDateString('en-US', {
month: 'short',
day: '2-digit',
year: 'numeric'
})}**
${template.content ? `Content: ${template.content}` : ''}
-------------------`;
});
// Join all template reports with double line breaks
return `General Bots WhatsApp Analytics Report
============================================
${templateReports.join('\n\n')}`.trim();
} catch (error) {
console.error('Error fetching WhatsApp template statistics:', error.message);
throw error;
}
}
}