Aggregate RFM period buyers by prior tag
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 55s

This commit is contained in:
Cauê Faleiros
2026-06-15 13:39:04 -03:00
parent b416154868
commit 73033cac3d
2 changed files with 68 additions and 23 deletions

View File

@@ -53,6 +53,15 @@ const buildDateFilter = ({ start, end } = {}) => {
}; };
}; };
const getPreviousDate = (value) => {
const normalizedDate = normalizeDateParam(value);
if (!normalizedDate) return null;
const date = new Date(`${normalizedDate}T00:00:00.000Z`);
date.setUTCDate(date.getUTCDate() - 1);
return date.toISOString().slice(0, 10);
};
const toNumber = (value) => Number(value || 0); const toNumber = (value) => Number(value || 0);
const RFM_SEGMENTS = { const RFM_SEGMENTS = {
@@ -253,9 +262,11 @@ 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 recencyReferenceDate = normalizedEnd ? '$1::date' : 'CURRENT_DATE'; const tagReference = getPreviousDate(normalizedStart) || normalizedEnd;
const historyParams = normalizedEnd ? [normalizedEnd] : []; const recencyReferenceDate = tagReference ? '$1::date' : 'CURRENT_DATE';
const historyParams = tagReference ? [tagReference] : [];
const [periodResult, historyResult] = await Promise.all([ const [periodResult, historyResult] = await Promise.all([
pool.query(` pool.query(`
@@ -292,13 +303,7 @@ const getRfmAnalytics = async (range = {}) => {
`, historyParams) `, historyParams)
]); ]);
const periodByPhone = new Map(periodResult.rows.map(row => [row.phone, { const historyClients = buildRfmClients(historyResult.rows.map(row => ({
monetary: toNumber(row.monetary),
frequency: toNumber(row.frequency),
quantityPurchased: toNumber(row.quantity_purchased)
}]));
const clients = buildRfmClients(historyResult.rows.map(row => ({
name: row.name, name: row.name,
phone: row.phone, phone: row.phone,
monetary: toNumber(row.monetary), monetary: toNumber(row.monetary),
@@ -306,14 +311,39 @@ const getRfmAnalytics = async (range = {}) => {
quantityPurchased: toNumber(row.quantity_purchased), quantityPurchased: toNumber(row.quantity_purchased),
lastPurchaseDate: row.last_purchase_date, lastPurchaseDate: row.last_purchase_date,
recencyDays: toNumber(row.recency_days) recencyDays: toNumber(row.recency_days)
}))).map(client => { })));
const periodClient = periodByPhone.get(client.phone); const tagsByPhone = new Map(historyClients.map(client => [client.phone, client]));
const clients = periodResult.rows.map(row => {
const taggedClient = tagsByPhone.get(row.phone);
if (!taggedClient) {
const newCustomerSegment = getRfmSegment(3, 1);
return {
name: row.name,
phone: row.phone,
monetary: toNumber(row.monetary),
frequency: toNumber(row.frequency),
quantityPurchased: toNumber(row.quantity_purchased),
lastPurchaseDate: row.last_purchase_date,
recencyDays: 0,
recencyScore: 3,
frequencyScore: 1,
monetaryScore: 1,
valueScore: 1,
rfmScore: '311',
segmentKey: newCustomerSegment.key,
segmentLabel: newCustomerSegment.label
};
}
return { return {
...client, ...taggedClient,
monetary: periodClient?.monetary || 0, name: row.name,
frequency: periodClient?.frequency || 0, phone: row.phone,
quantityPurchased: periodClient?.quantityPurchased || 0 monetary: toNumber(row.monetary),
frequency: toNumber(row.frequency),
quantityPurchased: toNumber(row.quantity_purchased),
lastPurchaseDate: row.last_purchase_date
}; };
}).sort((a, b) => { }).sort((a, b) => {
if (b.recencyScore !== a.recencyScore) return b.recencyScore - a.recencyScore; if (b.recencyScore !== a.recencyScore) return b.recencyScore - a.recencyScore;
@@ -339,6 +369,7 @@ module.exports = {
buildDateFilter, buildDateFilter,
buildRfmClients, buildRfmClients,
buildRfmSegments, buildRfmSegments,
getPreviousDate,
getRfmAnalytics, getRfmAnalytics,
getRfmSegment, getRfmSegment,
getClientAnalytics, getClientAnalytics,

View File

@@ -5,6 +5,7 @@ const {
buildRfmClients, buildRfmClients,
buildRfmSegments, buildRfmSegments,
buildDateFilter, buildDateFilter,
getPreviousDate,
getRfmAnalytics, getRfmAnalytics,
getRfmSegment, getRfmSegment,
normalizeDateParam, normalizeDateParam,
@@ -82,6 +83,12 @@ test('buildDateFilter ignores invalid bounds', () => {
); );
}); });
test('getPreviousDate returns the calendar day before an ISO date', () => {
assert.equal(getPreviousDate('2026-06-15'), '2026-06-14');
assert.equal(getPreviousDate('2026-03-01'), '2026-02-28');
assert.equal(getPreviousDate('invalid'), null);
});
test('scoreTertile scores higher values higher by default', () => { test('scoreTertile scores higher values higher by default', () => {
const values = [10, 20, 30, 40, 50]; const values = [10, 20, 30, 40, 50];
@@ -184,7 +191,7 @@ test('buildRfmClients scores segments from RFM history when period totals are sm
assert.equal(yesterdayBuyer.monetaryScore, 3); assert.equal(yesterdayBuyer.monetaryScore, 3);
}); });
test('getRfmAnalytics calculates recency against selected range end date', async () => { test('getRfmAnalytics groups period buyers by their RFM tag before the selected period', async () => {
const originalQuery = pool.query; const originalQuery = pool.query;
const calls = []; const calls = [];
@@ -203,7 +210,7 @@ test('getRfmAnalytics calculates recency against selected range end date', async
frequency: 20, frequency: 20,
quantity_purchased: 20, quantity_purchased: 20,
last_purchase_date: '2026-06-14', last_purchase_date: '2026-06-14',
recency_days: endDate === '2026-06-14' ? 0 : 1 recency_days: endDate === '2026-06-13' ? 0 : 1
}, },
{ {
name: 'Cliente Antigo', name: 'Cliente Antigo',
@@ -236,6 +243,14 @@ test('getRfmAnalytics calculates recency against selected range end date', async
frequency: 1, frequency: 1,
quantity_purchased: 1, quantity_purchased: 1,
last_purchase_date: '2026-06-14' last_purchase_date: '2026-06-14'
},
{
name: 'Cliente Novo no Periodo',
phone: '4',
monetary: 25,
frequency: 1,
quantity_purchased: 1,
last_purchase_date: '2026-06-14'
} }
] ]
}; };
@@ -248,17 +263,16 @@ test('getRfmAnalytics calculates recency against selected range end date', async
assert.deepEqual(calls[0].params, ['2026-06-09', '2026-06-15']); assert.deepEqual(calls[0].params, ['2026-06-09', '2026-06-15']);
assert.match(calls[1].sql, /\(\$1::date - MAX\(data_pedido_date\)\)::int/); assert.match(calls[1].sql, /\(\$1::date - MAX\(data_pedido_date\)\)::int/);
assert.match(calls[1].sql, /data_pedido_date <= \$1::date/); assert.match(calls[1].sql, /data_pedido_date <= \$1::date/);
assert.deepEqual(calls[1].params, ['2026-06-15']); assert.deepEqual(calls[1].params, ['2026-06-08']);
assert.deepEqual(calls[2].params, ['2026-06-14', '2026-06-14']); assert.deepEqual(calls[2].params, ['2026-06-14', '2026-06-14']);
assert.deepEqual(calls[3].params, ['2026-06-14']); assert.deepEqual(calls[3].params, ['2026-06-13']);
assert.equal(sevenDays.clients[0].segmentKey, 'champions'); assert.equal(sevenDays.clients[0].segmentKey, 'champions');
assert.equal(yesterday.clients[0].segmentKey, 'champions'); assert.equal(yesterday.clients[0].segmentKey, 'champions');
assert.equal(yesterday.clients[0].recencyDays, 0);
assert.equal(yesterday.clients[0].frequency, 1); assert.equal(yesterday.clients[0].frequency, 1);
assert.equal(yesterday.clients[0].monetary, 100); assert.equal(yesterday.clients[0].monetary, 100);
assert.equal(yesterday.clients.length, 3); assert.equal(yesterday.clients.length, 2);
assert.ok(yesterday.clients.some(client => client.recencyScore === 1)); assert.ok(!yesterday.clients.some(client => client.phone === '2'));
assert.ok(yesterday.clients.some(client => client.phone === '2' && client.monetary === 0 && client.frequency === 0)); assert.ok(yesterday.clients.some(client => client.phone === '4' && client.segmentKey === 'new_customers'));
} finally { } finally {
pool.query = originalQuery; pool.query = originalQuery;
} }