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

@@ -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
};