Optimize RFV all-period analytics
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 58s
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 58s
This commit is contained in:
@@ -262,12 +262,14 @@ 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 recencyReferenceDate = normalizedEnd ? '$1::date' : 'CURRENT_DATE';
|
const recencyReferenceDate = normalizedEnd ? '$1::date' : 'CURRENT_DATE';
|
||||||
const historyParams = normalizedEnd ? [normalizedEnd] : [];
|
const historyParams = normalizedEnd ? [normalizedEnd] : [];
|
||||||
|
const usePeriodAsHistory = !normalizedStart || normalizedStart <= '2000-01-01';
|
||||||
|
|
||||||
const [periodResult, historyResult] = await Promise.all([
|
const periodQuery = pool.query(`
|
||||||
pool.query(`
|
|
||||||
SELECT
|
SELECT
|
||||||
${CUSTOMER_KEY_SQL} as customer_key,
|
${CUSTOMER_KEY_SQL} as customer_key,
|
||||||
MAX(cliente_nome) as name,
|
MAX(cliente_nome) as name,
|
||||||
@@ -275,13 +277,15 @@ 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
|
||||||
ORDER BY monetary DESC;
|
ORDER BY monetary DESC;
|
||||||
`, params),
|
`, params);
|
||||||
pool.query(`
|
|
||||||
|
const historyQuery = usePeriodAsHistory ? null : pool.query(`
|
||||||
SELECT
|
SELECT
|
||||||
${CUSTOMER_KEY_SQL} as customer_key,
|
${CUSTOMER_KEY_SQL} as customer_key,
|
||||||
MAX(cliente_nome) as name,
|
MAX(cliente_nome) as name,
|
||||||
@@ -295,10 +299,15 @@ const getRfmAnalytics = async (range = {}) => {
|
|||||||
WHERE data_pedido_date IS NOT NULL
|
WHERE data_pedido_date IS NOT NULL
|
||||||
AND data_pedido_date <= ${recencyReferenceDate}
|
AND data_pedido_date <= ${recencyReferenceDate}
|
||||||
GROUP BY customer_key;
|
GROUP BY customer_key;
|
||||||
`, historyParams)
|
`, historyParams);
|
||||||
]);
|
|
||||||
|
|
||||||
const historyClients = buildRfmClients(historyResult.rows.map(row => ({
|
const [periodResult, historyResult] = historyQuery
|
||||||
|
? await Promise.all([periodQuery, historyQuery])
|
||||||
|
: [await periodQuery, null];
|
||||||
|
|
||||||
|
const historyRows = historyResult ? historyResult.rows : periodResult.rows;
|
||||||
|
|
||||||
|
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 || '',
|
||||||
|
|||||||
@@ -197,7 +197,7 @@ test('getRfmAnalytics classifies period buyers by history through the selected r
|
|||||||
|
|
||||||
pool.query = async (sql, params) => {
|
pool.query = async (sql, params) => {
|
||||||
calls.push({ sql, params });
|
calls.push({ sql, params });
|
||||||
const isHistoryQuery = sql.includes('recency_days');
|
const isHistoryQuery = sql.includes('AND data_pedido_date <= $1::date');
|
||||||
const referenceDate = params[0];
|
const referenceDate = params[0];
|
||||||
|
|
||||||
if (isHistoryQuery) {
|
if (isHistoryQuery) {
|
||||||
@@ -282,3 +282,48 @@ test('getRfmAnalytics classifies period buyers by history through the selected r
|
|||||||
pool.query = originalQuery;
|
pool.query = originalQuery;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('getRfmAnalytics reuses period rows as RFV history for all-period ranges', async () => {
|
||||||
|
const originalQuery = pool.query;
|
||||||
|
const calls = [];
|
||||||
|
|
||||||
|
pool.query = async (sql, params) => {
|
||||||
|
calls.push({ sql, params });
|
||||||
|
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: '2',
|
||||||
|
name: 'Cliente Antigo',
|
||||||
|
phone: '2',
|
||||||
|
monetary: 50,
|
||||||
|
frequency: 1,
|
||||||
|
quantity_purchased: 1,
|
||||||
|
last_purchase_date: '2026-01-01',
|
||||||
|
recency_days: 165
|
||||||
|
}
|
||||||
|
]
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await getRfmAnalytics({ start: '2000-01-01', end: '2026-06-15' });
|
||||||
|
|
||||||
|
assert.equal(calls.length, 1);
|
||||||
|
assert.match(calls[0].sql, /\(\$2::date - MAX\(data_pedido_date\)\)::int/);
|
||||||
|
assert.deepEqual(calls[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);
|
||||||
|
} finally {
|
||||||
|
pool.query = originalQuery;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user