Add RFM segmentation analytics
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 3m12s

This commit is contained in:
Cauê Faleiros
2026-06-12 11:22:57 -03:00
parent 25ab6cd448
commit fe8d0ff105
10 changed files with 1231 additions and 14 deletions

View File

@@ -3,7 +3,8 @@ const { verifyToken } = require('../auth');
const {
getClientAnalytics,
getDashboardAnalytics,
getProductAnalytics
getProductAnalytics,
getRfmAnalytics
} = require('../services/analyticsService');
const router = express.Router();
@@ -40,4 +41,13 @@ router.get('/analytics/clients', verifyToken, async (req, res) => {
}
});
router.get('/analytics/rfm', verifyToken, async (req, res) => {
try {
res.json(await getRfmAnalytics(getRange(req.query)));
} catch (error) {
console.error('Error fetching RFM analytics:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
module.exports = router;

View File

@@ -55,6 +55,52 @@ const buildDateFilter = ({ start, end } = {}) => {
const toNumber = (value) => Number(value || 0);
const RFM_SEGMENTS = {
'3-3': { key: 'champions', label: 'Champions' },
'3-2': { key: 'potential_loyalists', label: 'Potenciais Leais' },
'3-1': { key: 'new_customers', label: 'Novos Clientes' },
'2-3': { key: 'loyal_customers', label: 'Clientes Leais' },
'2-2': { key: 'need_attention', label: 'Precisam de Atenção' },
'2-1': { key: 'about_to_sleep', label: 'Quase Dormindo' },
'1-3': { key: 'at_risk', label: 'Em Risco' },
'1-2': { key: 'hibernating', label: 'Hibernando' },
'1-1': { key: 'lost', label: 'Perdidos' }
};
const scoreTertile = (value, values, higherIsBetter = true) => {
const numericValues = values.map(toNumber).filter(Number.isFinite);
if (!numericValues.length) return 1;
if (numericValues.length === 1) return 3;
const min = Math.min(...numericValues);
const max = Math.max(...numericValues);
if (min === max) return 2;
const sorted = [...numericValues].sort((a, b) => higherIsBetter ? a - b : b - a);
const index = sorted.findIndex(candidate => candidate === toNumber(value));
const percentile = index / (sorted.length - 1);
return Math.min(3, Math.max(1, Math.floor(percentile * 3) + 1));
};
const getRfmSegment = (recencyScore, valueScore) => {
return RFM_SEGMENTS[`${recencyScore}-${valueScore}`] || RFM_SEGMENTS['1-1'];
};
const buildRfmSegments = (clients) => {
return Object.values(RFM_SEGMENTS).map(segment => {
const segmentClients = clients.filter(client => client.segmentKey === segment.key);
const totalRevenue = segmentClients.reduce((sum, client) => sum + client.monetary, 0);
return {
...segment,
count: segmentClients.length,
totalRevenue,
averageRevenue: segmentClients.length ? totalRevenue / segmentClients.length : 0
};
});
};
const getDashboardAnalytics = async (range = {}) => {
const { params, whereClause } = buildDateFilter(range);
const [totalsResult, salesResult, revenueResult] = await Promise.all([
@@ -174,10 +220,85 @@ const getClientAnalytics = async (range = {}) => {
}));
};
const getRfmAnalytics = async (range = {}) => {
const { params, whereClause } = buildDateFilter(range);
const result = await pool.query(`
SELECT
MAX(cliente_nome) as name,
cliente_fone as phone,
COALESCE(SUM(quantidade * valor_unitario), 0) as monetary,
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
FROM orders
${whereClause}
AND cliente_fone IS NOT NULL
AND cliente_fone != ''
GROUP BY cliente_fone
ORDER BY monetary DESC
LIMIT 1000;
`, params);
const baseClients = result.rows.map(row => ({
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: 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;
});
return {
range: {
start: normalizeDateParam(range.start),
end: normalizeDateParam(range.end)
},
clients,
segments: buildRfmSegments(clients),
matrix: {
recencyScores: [3, 2, 1],
valueScores: [1, 2, 3]
}
};
};
module.exports = {
buildDateFilter,
buildRfmSegments,
getRfmAnalytics,
getRfmSegment,
getClientAnalytics,
getDashboardAnalytics,
getProductAnalytics,
normalizeDateParam
normalizeDateParam,
scoreTertile
};

View File

@@ -1,7 +1,13 @@
const assert = require('node:assert/strict');
const test = require('node:test');
const { buildDateFilter, normalizeDateParam } = require('../services/analyticsService');
const {
buildRfmSegments,
buildDateFilter,
getRfmSegment,
normalizeDateParam,
scoreTertile
} = require('../services/analyticsService');
test('normalizeDateParam accepts strict ISO dates', () => {
assert.equal(normalizeDateParam('2026-05-28'), '2026-05-28');
@@ -32,3 +38,42 @@ test('buildDateFilter ignores invalid bounds', () => {
'WHERE data_pedido_date IS NOT NULL AND data_pedido_date <= $1::date'
);
});
test('scoreTertile scores higher values higher by default', () => {
const values = [10, 20, 30, 40, 50];
assert.equal(scoreTertile(10, values), 1);
assert.equal(scoreTertile(30, values), 2);
assert.equal(scoreTertile(50, values), 3);
});
test('scoreTertile can score lower values higher for recency', () => {
const recencyDays = [2, 10, 20, 40, 80];
assert.equal(scoreTertile(2, recencyDays, false), 3);
assert.equal(scoreTertile(20, recencyDays, false), 2);
assert.equal(scoreTertile(80, recencyDays, false), 1);
});
test('getRfmSegment maps the 3x3 RFM matrix', () => {
assert.deepEqual(getRfmSegment(3, 3), { key: 'champions', label: 'Champions' });
assert.deepEqual(getRfmSegment(2, 2), { key: 'need_attention', label: 'Precisam de Atenção' });
assert.deepEqual(getRfmSegment(1, 1), { key: 'lost', label: 'Perdidos' });
});
test('buildRfmSegments summarizes segment count and revenue', () => {
const segments = buildRfmSegments([
{ segmentKey: 'champions', monetary: 100 },
{ segmentKey: 'champions', monetary: 50 },
{ segmentKey: 'lost', monetary: 25 }
]);
const champions = segments.find(segment => segment.key === 'champions');
const lost = segments.find(segment => segment.key === 'lost');
assert.equal(champions.count, 2);
assert.equal(champions.totalRevenue, 150);
assert.equal(champions.averageRevenue, 75);
assert.equal(lost.count, 1);
assert.equal(lost.totalRevenue, 25);
});