Score RFM segments against customer history
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 1m35s

This commit is contained in:
Cauê Faleiros
2026-06-15 12:05:54 -03:00
parent de6a263ec9
commit 76b1c545f1
2 changed files with 91 additions and 45 deletions

View File

@@ -74,7 +74,7 @@ const scoreTertile = (value, values, higherIsBetter = true) => {
const min = Math.min(...numericValues);
const max = Math.max(...numericValues);
if (min === max) return 2;
if (min === max) return higherIsBetter ? 2 : 3;
const sorted = [...numericValues].sort((a, b) => higherIsBetter ? a - b : b - a);
const index = sorted.findIndex(candidate => candidate === toNumber(value));
@@ -253,16 +253,12 @@ 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';
const recencyReferenceDate = normalizedEnd ? '$1::date' : 'CURRENT_DATE';
const historyParams = normalizedEnd ? [normalizedEnd] : [];
if (normalizedEnd) {
queryParams.push(normalizedEnd);
}
const result = await pool.query(`
WITH period_clients AS (
const [periodResult, historyResult] = await Promise.all([
pool.query(`
SELECT
MAX(cliente_nome) as name,
cliente_fone as phone,
@@ -275,49 +271,55 @@ const getRfmAnalytics = async (range = {}) => {
AND cliente_fone IS NOT NULL
AND cliente_fone != ''
GROUP BY cliente_fone
),
rfm_clients AS (
ORDER BY monetary DESC
LIMIT 1000;
`, params),
pool.query(`
SELECT
MAX(cliente_nome) as name,
cliente_fone as phone,
COALESCE(SUM(quantidade * valor_unitario), 0) as rfm_monetary,
COUNT(DISTINCT COALESCE(NULLIF(pedido_id, ''), data_pedido || '_' || valor_pedido::text))::int as rfm_frequency,
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((${recencyReferenceDate} - MAX(data_pedido_date))::int, 0) as recency_days
FROM orders
WHERE data_pedido_date IS NOT NULL
AND data_pedido_date <= ${recencyReferenceDate}
AND cliente_fone IS NOT NULL
AND cliente_fone != ''
GROUP BY cliente_fone
)
SELECT
period_clients.name,
period_clients.phone,
period_clients.monetary,
period_clients.frequency,
period_clients.quantity_purchased,
period_clients.last_purchase_date,
rfm_clients.rfm_monetary,
rfm_clients.rfm_frequency,
rfm_clients.recency_days
FROM period_clients
INNER JOIN rfm_clients ON rfm_clients.phone = period_clients.phone
ORDER BY monetary DESC
LIMIT 1000;
`, queryParams);
GROUP BY cliente_fone;
`, historyParams)
]);
const baseClients = result.rows.map(row => ({
const historyClients = buildRfmClients(historyResult.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),
rfmFrequency: toNumber(row.rfm_frequency),
rfmMonetary: toNumber(row.rfm_monetary)
}));
recencyDays: toNumber(row.recency_days)
})));
const rfmByPhone = new Map(historyClients.map(client => [client.phone, client]));
const clients = buildRfmClients(baseClients);
const clients = periodResult.rows.map(row => {
const rfmClient = rfmByPhone.get(row.phone);
return {
...rfmClient,
name: row.name,
phone: row.phone,
monetary: toNumber(row.monetary),
frequency: toNumber(row.frequency),
quantityPurchased: toNumber(row.quantity_purchased),
lastPurchaseDate: row.last_purchase_date
};
}).filter(client => client.segmentKey).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: {