Fix RFM date range consistency
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 1m5s
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 1m5s
This commit is contained in:
@@ -101,6 +101,35 @@ const buildRfmSegments = (clients) => {
|
||||
});
|
||||
};
|
||||
|
||||
const buildRfmClients = (baseClients) => {
|
||||
const recencyValues = baseClients.map(client => client.recencyDays);
|
||||
const frequencyValues = baseClients.map(client => client.frequency);
|
||||
const monetaryValues = baseClients.map(client => client.monetary);
|
||||
|
||||
return baseClients.map(client => {
|
||||
const recencyScore = scoreTertile(client.recencyDays, recencyValues, false);
|
||||
const frequencyScore = scoreTertile(client.frequency, frequencyValues, true);
|
||||
const monetaryScore = scoreTertile(client.monetary, monetaryValues, true);
|
||||
const valueScore = Math.min(3, Math.max(1, Math.round((frequencyScore + monetaryScore) / 2)));
|
||||
const segment = getRfmSegment(recencyScore, valueScore);
|
||||
|
||||
return {
|
||||
...client,
|
||||
recencyScore,
|
||||
frequencyScore,
|
||||
monetaryScore,
|
||||
valueScore,
|
||||
rfmScore: `${recencyScore}${frequencyScore}${monetaryScore}`,
|
||||
segmentKey: segment.key,
|
||||
segmentLabel: segment.label
|
||||
};
|
||||
}).sort((a, b) => {
|
||||
if (b.recencyScore !== a.recencyScore) return b.recencyScore - a.recencyScore;
|
||||
if (b.valueScore !== a.valueScore) return b.valueScore - a.valueScore;
|
||||
return b.monetary - a.monetary;
|
||||
});
|
||||
};
|
||||
|
||||
const getDashboardAnalytics = async (range = {}) => {
|
||||
const { params, whereClause } = buildDateFilter(range);
|
||||
const [totalsResult, salesResult, revenueResult] = await Promise.all([
|
||||
@@ -222,6 +251,14 @@ const getClientAnalytics = async (range = {}) => {
|
||||
|
||||
const getRfmAnalytics = async (range = {}) => {
|
||||
const { params, whereClause } = buildDateFilter(range);
|
||||
const queryParams = [...params];
|
||||
const normalizedEnd = normalizeDateParam(range.end);
|
||||
const recencyReferenceDate = normalizedEnd ? `$${queryParams.length + 1}::date` : 'CURRENT_DATE';
|
||||
|
||||
if (normalizedEnd) {
|
||||
queryParams.push(normalizedEnd);
|
||||
}
|
||||
|
||||
const result = await pool.query(`
|
||||
SELECT
|
||||
MAX(cliente_nome) as name,
|
||||
@@ -230,7 +267,7 @@ const getRfmAnalytics = async (range = {}) => {
|
||||
COUNT(DISTINCT COALESCE(NULLIF(pedido_id, ''), data_pedido || '_' || valor_pedido::text))::int as frequency,
|
||||
COALESCE(SUM(quantidade), 0) as quantity_purchased,
|
||||
MAX(data_pedido_date) as last_purchase_date,
|
||||
GREATEST((CURRENT_DATE - MAX(data_pedido_date))::int, 0) as recency_days
|
||||
GREATEST((${recencyReferenceDate} - MAX(data_pedido_date))::int, 0) as recency_days
|
||||
FROM orders
|
||||
${whereClause}
|
||||
AND cliente_fone IS NOT NULL
|
||||
@@ -238,7 +275,7 @@ const getRfmAnalytics = async (range = {}) => {
|
||||
GROUP BY cliente_fone
|
||||
ORDER BY monetary DESC
|
||||
LIMIT 1000;
|
||||
`, params);
|
||||
`, queryParams);
|
||||
|
||||
const baseClients = result.rows.map(row => ({
|
||||
name: row.name,
|
||||
@@ -250,32 +287,7 @@ const getRfmAnalytics = async (range = {}) => {
|
||||
recencyDays: toNumber(row.recency_days)
|
||||
}));
|
||||
|
||||
const recencyValues = baseClients.map(client => client.recencyDays);
|
||||
const frequencyValues = baseClients.map(client => client.frequency);
|
||||
const monetaryValues = baseClients.map(client => client.monetary);
|
||||
|
||||
const clients = baseClients.map(client => {
|
||||
const recencyScore = scoreTertile(client.recencyDays, recencyValues, false);
|
||||
const frequencyScore = scoreTertile(client.frequency, frequencyValues, true);
|
||||
const monetaryScore = scoreTertile(client.monetary, monetaryValues, true);
|
||||
const valueScore = Math.min(3, Math.max(1, Math.round((frequencyScore + monetaryScore) / 2)));
|
||||
const segment = getRfmSegment(recencyScore, valueScore);
|
||||
|
||||
return {
|
||||
...client,
|
||||
recencyScore,
|
||||
frequencyScore,
|
||||
monetaryScore,
|
||||
valueScore,
|
||||
rfmScore: `${recencyScore}${frequencyScore}${monetaryScore}`,
|
||||
segmentKey: segment.key,
|
||||
segmentLabel: segment.label
|
||||
};
|
||||
}).sort((a, b) => {
|
||||
if (b.recencyScore !== a.recencyScore) return b.recencyScore - a.recencyScore;
|
||||
if (b.valueScore !== a.valueScore) return b.valueScore - a.valueScore;
|
||||
return b.monetary - a.monetary;
|
||||
});
|
||||
const clients = buildRfmClients(baseClients);
|
||||
|
||||
return {
|
||||
range: {
|
||||
@@ -293,6 +305,7 @@ const getRfmAnalytics = async (range = {}) => {
|
||||
|
||||
module.exports = {
|
||||
buildDateFilter,
|
||||
buildRfmClients,
|
||||
buildRfmSegments,
|
||||
getRfmAnalytics,
|
||||
getRfmSegment,
|
||||
|
||||
@@ -2,12 +2,15 @@ const assert = require('node:assert/strict');
|
||||
const test = require('node:test');
|
||||
|
||||
const {
|
||||
buildRfmClients,
|
||||
buildRfmSegments,
|
||||
buildDateFilter,
|
||||
getRfmAnalytics,
|
||||
getRfmSegment,
|
||||
normalizeDateParam,
|
||||
scoreTertile
|
||||
} = require('../services/analyticsService');
|
||||
const { pool } = require('../db');
|
||||
|
||||
test('normalizeDateParam accepts strict ISO dates', () => {
|
||||
assert.equal(normalizeDateParam('2026-05-28'), '2026-05-28');
|
||||
@@ -29,6 +32,46 @@ test('buildDateFilter builds bounded date predicates', () => {
|
||||
);
|
||||
});
|
||||
|
||||
test('buildDateFilter builds Hoje as an inclusive single-day date predicate', () => {
|
||||
const filter = buildDateFilter({ start: '2026-06-15', end: '2026-06-15' });
|
||||
|
||||
assert.deepEqual(filter.params, ['2026-06-15', '2026-06-15']);
|
||||
assert.equal(
|
||||
filter.whereClause,
|
||||
'WHERE data_pedido_date IS NOT NULL AND data_pedido_date >= $1::date AND data_pedido_date <= $2::date'
|
||||
);
|
||||
});
|
||||
|
||||
test('buildDateFilter builds Ontem as an inclusive single-day date predicate', () => {
|
||||
const filter = buildDateFilter({ start: '2026-06-14', end: '2026-06-14' });
|
||||
|
||||
assert.deepEqual(filter.params, ['2026-06-14', '2026-06-14']);
|
||||
assert.equal(
|
||||
filter.whereClause,
|
||||
'WHERE data_pedido_date IS NOT NULL AND data_pedido_date >= $1::date AND data_pedido_date <= $2::date'
|
||||
);
|
||||
});
|
||||
|
||||
test('buildDateFilter builds Ultimos 7 dias as an inclusive calendar range', () => {
|
||||
const filter = buildDateFilter({ start: '2026-06-09', end: '2026-06-15' });
|
||||
|
||||
assert.deepEqual(filter.params, ['2026-06-09', '2026-06-15']);
|
||||
assert.equal(
|
||||
filter.whereClause,
|
||||
'WHERE data_pedido_date IS NOT NULL AND data_pedido_date >= $1::date AND data_pedido_date <= $2::date'
|
||||
);
|
||||
});
|
||||
|
||||
test('buildDateFilter builds custom single-day ranges inclusively', () => {
|
||||
const filter = buildDateFilter({ start: '2026-06-10', end: '2026-06-10' });
|
||||
|
||||
assert.deepEqual(filter.params, ['2026-06-10', '2026-06-10']);
|
||||
assert.equal(
|
||||
filter.whereClause,
|
||||
'WHERE data_pedido_date IS NOT NULL AND data_pedido_date >= $1::date AND data_pedido_date <= $2::date'
|
||||
);
|
||||
});
|
||||
|
||||
test('buildDateFilter ignores invalid bounds', () => {
|
||||
const filter = buildDateFilter({ start: 'invalid', end: '2026-05-28' });
|
||||
|
||||
@@ -77,3 +120,52 @@ test('buildRfmSegments summarizes segment count and revenue', () => {
|
||||
assert.equal(lost.count, 1);
|
||||
assert.equal(lost.totalRevenue, 25);
|
||||
});
|
||||
|
||||
test('buildRfmClients keeps a yesterday buyer in the same high-recency segment when it is the only qualifying client', () => {
|
||||
const sevenDayClients = buildRfmClients([
|
||||
{ name: 'Cliente Ontem', phone: '1', monetary: 500, frequency: 2, quantityPurchased: 2, lastPurchaseDate: '2026-06-14', recencyDays: 1 }
|
||||
]);
|
||||
const yesterdayClients = buildRfmClients([
|
||||
{ name: 'Cliente Ontem', phone: '1', monetary: 500, frequency: 2, quantityPurchased: 2, lastPurchaseDate: '2026-06-14', recencyDays: 0 }
|
||||
]);
|
||||
|
||||
assert.equal(sevenDayClients[0].segmentKey, 'champions');
|
||||
assert.equal(yesterdayClients[0].segmentKey, 'champions');
|
||||
assert.equal(sevenDayClients[0].phone, yesterdayClients[0].phone);
|
||||
});
|
||||
|
||||
test('getRfmAnalytics calculates recency against selected range end date', async () => {
|
||||
const originalQuery = pool.query;
|
||||
const calls = [];
|
||||
|
||||
pool.query = async (sql, params) => {
|
||||
calls.push({ sql, params });
|
||||
return {
|
||||
rows: [
|
||||
{
|
||||
name: 'Cliente Ontem',
|
||||
phone: '1',
|
||||
monetary: 500,
|
||||
frequency: 2,
|
||||
quantity_purchased: 2,
|
||||
last_purchase_date: '2026-06-14',
|
||||
recency_days: params[2] === '2026-06-14' ? 0 : 1
|
||||
}
|
||||
]
|
||||
};
|
||||
};
|
||||
|
||||
try {
|
||||
const sevenDays = await getRfmAnalytics({ start: '2026-06-09', end: '2026-06-15' });
|
||||
const yesterday = await getRfmAnalytics({ start: '2026-06-14', end: '2026-06-14' });
|
||||
|
||||
assert.match(calls[0].sql, /\(\$3::date - MAX\(data_pedido_date\)\)::int/);
|
||||
assert.deepEqual(calls[0].params, ['2026-06-09', '2026-06-15', '2026-06-15']);
|
||||
assert.deepEqual(calls[1].params, ['2026-06-14', '2026-06-14', '2026-06-14']);
|
||||
assert.equal(sevenDays.clients[0].segmentKey, 'champions');
|
||||
assert.equal(yesterday.clients[0].segmentKey, 'champions');
|
||||
assert.equal(yesterday.clients[0].recencyDays, 0);
|
||||
} finally {
|
||||
pool.query = originalQuery;
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user