Optimize RFV all-period scoring
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 51s

This commit is contained in:
Cauê Faleiros
2026-06-17 15:50:27 -03:00
parent 7764933fd9
commit 2445272f3a
2 changed files with 107 additions and 39 deletions

View File

@@ -263,7 +263,10 @@ const getClientAnalytics = async (range = {}) => {
const getRfmAnalytics = async (range = {}) => { const getRfmAnalytics = async (range = {}) => {
const { params, whereClause } = buildDateFilter(range); const { params, whereClause } = buildDateFilter(range);
const normalizedStart = normalizeDateParam(range.start);
const normalizedEnd = normalizeDateParam(range.end); const normalizedEnd = normalizeDateParam(range.end);
const periodRecencyReferenceDate = normalizedEnd ? `$${params.length}::date` : 'CURRENT_DATE';
const usePeriodAsHistory = !normalizedStart || normalizedStart <= '2000-01-01';
const client = await pool.connect(); const client = await pool.connect();
try { try {
@@ -278,7 +281,8 @@ const getRfmAnalytics = async (range = {}) => {
COALESCE(SUM(quantidade * valor_unitario), 0) as monetary, COALESCE(SUM(quantidade * valor_unitario), 0) as monetary,
COUNT(DISTINCT COALESCE(NULLIF(pedido_id, ''), data_pedido || '_' || valor_pedido::text))::int as frequency, COUNT(DISTINCT COALESCE(NULLIF(pedido_id, ''), data_pedido || '_' || valor_pedido::text))::int as frequency,
COALESCE(SUM(quantidade), 0) as quantity_purchased, COALESCE(SUM(quantidade), 0) as quantity_purchased,
MAX(data_pedido_date) as last_purchase_date MAX(data_pedido_date) as last_purchase_date,
GREATEST((${periodRecencyReferenceDate} - MAX(data_pedido_date))::int, 0) as recency_days
FROM orders FROM orders
${whereClause} ${whereClause}
GROUP BY customer_key GROUP BY customer_key
@@ -301,6 +305,9 @@ const getRfmAnalytics = async (range = {}) => {
}; };
} }
let historyRows = periodResult.rows;
if (!usePeriodAsHistory) {
const periodPhones = [...new Set(periodResult.rows.map(row => row.phone).filter(Boolean))]; const periodPhones = [...new Set(periodResult.rows.map(row => row.phone).filter(Boolean))];
const periodNamesWithoutPhone = [...new Set(periodResult.rows const periodNamesWithoutPhone = [...new Set(periodResult.rows
.filter(row => !row.phone && String(row.customer_key || '').startsWith('name:')) .filter(row => !row.phone && String(row.customer_key || '').startsWith('name:'))
@@ -335,8 +342,10 @@ const getRfmAnalytics = async (range = {}) => {
) )
GROUP BY customer_key; GROUP BY customer_key;
`, historyParams); `, historyParams);
historyRows = historyResult.rows;
}
const historyClients = buildRfmClients(historyResult.rows.map(row => ({ const historyClients = buildRfmClients(historyRows.map(row => ({
customerKey: row.customer_key, customerKey: row.customer_key,
name: row.name, name: row.name,
phone: row.phone || '', phone: row.phone || '',

View File

@@ -197,7 +197,7 @@ test('getRfmAnalytics classifies period buyers by history through the selected r
const mockClient = { const mockClient = {
query: async (sql, params = []) => { query: async (sql, params = []) => {
calls.push({ sql, params }); calls.push({ sql, params });
const isHistoryQuery = sql.includes('recency_days'); const isHistoryQuery = sql.includes('= ANY');
const isPeriodQuery = sql.includes('FROM orders'); const isPeriodQuery = sql.includes('FROM orders');
const referenceDate = params[0]; const referenceDate = params[0];
@@ -261,7 +261,8 @@ test('getRfmAnalytics classifies period buyers by history through the selected r
monetary: 100, monetary: 100,
frequency: 1, frequency: 1,
quantity_purchased: 1, quantity_purchased: 1,
last_purchase_date: '2026-06-14' last_purchase_date: '2026-06-14',
recency_days: 1
}, },
{ {
customer_key: '4', customer_key: '4',
@@ -270,7 +271,8 @@ test('getRfmAnalytics classifies period buyers by history through the selected r
monetary: 25, monetary: 25,
frequency: 1, frequency: 1,
quantity_purchased: 1, quantity_purchased: 1,
last_purchase_date: '2026-06-14' last_purchase_date: '2026-06-14',
recency_days: 1
}, },
{ {
customer_key: 'name:Cliente Sem Fone', customer_key: 'name:Cliente Sem Fone',
@@ -279,7 +281,8 @@ test('getRfmAnalytics classifies period buyers by history through the selected r
monetary: 30, monetary: 30,
frequency: 1, frequency: 1,
quantity_purchased: 1, quantity_purchased: 1,
last_purchase_date: '2026-06-14' last_purchase_date: '2026-06-14',
recency_days: 1
} }
] ]
}; };
@@ -321,3 +324,59 @@ test('getRfmAnalytics classifies period buyers by history through the selected r
pool.connect = originalConnect; pool.connect = originalConnect;
} }
}); });
test('getRfmAnalytics reuses period rows as RFV history for all-period ranges', async () => {
const originalConnect = pool.connect;
const calls = [];
const mockClient = {
query: async (sql, params = []) => {
calls.push({ sql, params });
if (!sql.includes('FROM orders')) {
return { rows: [] };
}
return {
rows: [
{
customer_key: '1',
name: 'Cliente Frequente',
phone: '1',
monetary: 5000,
frequency: 20,
quantity_purchased: 20,
last_purchase_date: '2026-06-14',
recency_days: 1
},
{
customer_key: 'name:Cliente Sem Fone',
name: 'Cliente Sem Fone',
phone: null,
monetary: 50,
frequency: 1,
quantity_purchased: 1,
last_purchase_date: '2026-01-01',
recency_days: 165
}
]
};
},
release: () => {}
};
pool.connect = async () => mockClient;
try {
const result = await getRfmAnalytics({ start: '2000-01-01', end: '2026-06-15' });
const selectCalls = calls.filter(call => call.sql.includes('FROM orders'));
assert.equal(selectCalls.length, 1);
assert.match(selectCalls[0].sql, /\(\$2::date - MAX\(data_pedido_date\)\)::int/);
assert.doesNotMatch(selectCalls[0].sql, /= ANY/);
assert.deepEqual(selectCalls[0].params, ['2000-01-01', '2026-06-15']);
assert.equal(result.clients.length, 2);
assert.equal(result.segments.reduce((total, segment) => total + segment.count, 0), 2);
assert.ok(result.clients.some(client => client.customerKey === 'name:Cliente Sem Fone' && client.phone === ''));
} finally {
pool.connect = originalConnect;
}
});