Aggregate RFM period buyers by prior tag
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 55s
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 55s
This commit is contained in:
@@ -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 RFM_SEGMENTS = {
|
||||
@@ -253,9 +262,11 @@ const getClientAnalytics = async (range = {}) => {
|
||||
|
||||
const getRfmAnalytics = async (range = {}) => {
|
||||
const { params, whereClause } = buildDateFilter(range);
|
||||
const normalizedStart = normalizeDateParam(range.start);
|
||||
const normalizedEnd = normalizeDateParam(range.end);
|
||||
const recencyReferenceDate = normalizedEnd ? '$1::date' : 'CURRENT_DATE';
|
||||
const historyParams = normalizedEnd ? [normalizedEnd] : [];
|
||||
const tagReference = getPreviousDate(normalizedStart) || normalizedEnd;
|
||||
const recencyReferenceDate = tagReference ? '$1::date' : 'CURRENT_DATE';
|
||||
const historyParams = tagReference ? [tagReference] : [];
|
||||
|
||||
const [periodResult, historyResult] = await Promise.all([
|
||||
pool.query(`
|
||||
@@ -292,13 +303,7 @@ const getRfmAnalytics = async (range = {}) => {
|
||||
`, historyParams)
|
||||
]);
|
||||
|
||||
const periodByPhone = new Map(periodResult.rows.map(row => [row.phone, {
|
||||
monetary: toNumber(row.monetary),
|
||||
frequency: toNumber(row.frequency),
|
||||
quantityPurchased: toNumber(row.quantity_purchased)
|
||||
}]));
|
||||
|
||||
const clients = buildRfmClients(historyResult.rows.map(row => ({
|
||||
const historyClients = buildRfmClients(historyResult.rows.map(row => ({
|
||||
name: row.name,
|
||||
phone: row.phone,
|
||||
monetary: toNumber(row.monetary),
|
||||
@@ -306,14 +311,39 @@ const getRfmAnalytics = async (range = {}) => {
|
||||
quantityPurchased: toNumber(row.quantity_purchased),
|
||||
lastPurchaseDate: row.last_purchase_date,
|
||||
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 {
|
||||
...client,
|
||||
monetary: periodClient?.monetary || 0,
|
||||
frequency: periodClient?.frequency || 0,
|
||||
quantityPurchased: periodClient?.quantityPurchased || 0
|
||||
...taggedClient,
|
||||
name: row.name,
|
||||
phone: row.phone,
|
||||
monetary: toNumber(row.monetary),
|
||||
frequency: toNumber(row.frequency),
|
||||
quantityPurchased: toNumber(row.quantity_purchased),
|
||||
lastPurchaseDate: row.last_purchase_date
|
||||
};
|
||||
}).sort((a, b) => {
|
||||
if (b.recencyScore !== a.recencyScore) return b.recencyScore - a.recencyScore;
|
||||
@@ -339,6 +369,7 @@ module.exports = {
|
||||
buildDateFilter,
|
||||
buildRfmClients,
|
||||
buildRfmSegments,
|
||||
getPreviousDate,
|
||||
getRfmAnalytics,
|
||||
getRfmSegment,
|
||||
getClientAnalytics,
|
||||
|
||||
@@ -5,6 +5,7 @@ const {
|
||||
buildRfmClients,
|
||||
buildRfmSegments,
|
||||
buildDateFilter,
|
||||
getPreviousDate,
|
||||
getRfmAnalytics,
|
||||
getRfmSegment,
|
||||
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', () => {
|
||||
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);
|
||||
});
|
||||
|
||||
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 calls = [];
|
||||
|
||||
@@ -203,7 +210,7 @@ test('getRfmAnalytics calculates recency against selected range end date', async
|
||||
frequency: 20,
|
||||
quantity_purchased: 20,
|
||||
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',
|
||||
@@ -236,6 +243,14 @@ test('getRfmAnalytics calculates recency against selected range end date', async
|
||||
frequency: 1,
|
||||
quantity_purchased: 1,
|
||||
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.match(calls[1].sql, /\(\$1::date - MAX\(data_pedido_date\)\)::int/);
|
||||
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[3].params, ['2026-06-14']);
|
||||
assert.deepEqual(calls[3].params, ['2026-06-13']);
|
||||
assert.equal(sevenDays.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].monetary, 100);
|
||||
assert.equal(yesterday.clients.length, 3);
|
||||
assert.ok(yesterday.clients.some(client => client.recencyScore === 1));
|
||||
assert.ok(yesterday.clients.some(client => client.phone === '2' && client.monetary === 0 && client.frequency === 0));
|
||||
assert.equal(yesterday.clients.length, 2);
|
||||
assert.ok(!yesterday.clients.some(client => client.phone === '2'));
|
||||
assert.ok(yesterday.clients.some(client => client.phone === '4' && client.segmentKey === 'new_customers'));
|
||||
} finally {
|
||||
pool.query = originalQuery;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user