Optimize RFV all-period scoring
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 51s

This commit is contained in:
Cauê Faleiros
2026-06-17 15:50:27 -03:00
parent 7764933fd9
commit 2445272f3a
2 changed files with 107 additions and 39 deletions

View File

@@ -263,7 +263,10 @@ const getClientAnalytics = async (range = {}) => {
const getRfmAnalytics = async (range = {}) => {
const { params, whereClause } = buildDateFilter(range);
const normalizedStart = normalizeDateParam(range.start);
const normalizedEnd = normalizeDateParam(range.end);
const periodRecencyReferenceDate = normalizedEnd ? `$${params.length}::date` : 'CURRENT_DATE';
const usePeriodAsHistory = !normalizedStart || normalizedStart <= '2000-01-01';
const client = await pool.connect();
try {
@@ -278,7 +281,8 @@ const getRfmAnalytics = async (range = {}) => {
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
MAX(data_pedido_date) as last_purchase_date,
GREATEST((${periodRecencyReferenceDate} - MAX(data_pedido_date))::int, 0) as recency_days
FROM orders
${whereClause}
GROUP BY customer_key
@@ -301,42 +305,47 @@ const getRfmAnalytics = async (range = {}) => {
};
}
const periodPhones = [...new Set(periodResult.rows.map(row => row.phone).filter(Boolean))];
const periodNamesWithoutPhone = [...new Set(periodResult.rows
.filter(row => !row.phone && String(row.customer_key || '').startsWith('name:'))
.map(row => String(row.customer_key).slice(5))
.filter(Boolean))];
const historyParams = [];
const recencyReferenceDate = normalizedEnd
? `$${historyParams.push(normalizedEnd)}::date`
: 'CURRENT_DATE';
const phoneListParam = `$${historyParams.push(periodPhones)}::text[]`;
const nameListParam = `$${historyParams.push(periodNamesWithoutPhone)}::text[]`;
let historyRows = periodResult.rows;
const historyResult = await client.query(`
SELECT
${CUSTOMER_KEY_SQL} as customer_key,
MAX(COALESCE(NULLIF(cliente_nome, ''), 'Cliente Desconhecido')) as name,
MAX(NULLIF(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((${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 (
NULLIF(cliente_fone, '') = ANY(${phoneListParam})
OR (
NULLIF(cliente_fone, '') IS NULL
AND COALESCE(NULLIF(cliente_nome, ''), 'Cliente Desconhecido') = ANY(${nameListParam})
)
)
GROUP BY customer_key;
`, historyParams);
if (!usePeriodAsHistory) {
const periodPhones = [...new Set(periodResult.rows.map(row => row.phone).filter(Boolean))];
const periodNamesWithoutPhone = [...new Set(periodResult.rows
.filter(row => !row.phone && String(row.customer_key || '').startsWith('name:'))
.map(row => String(row.customer_key).slice(5))
.filter(Boolean))];
const historyParams = [];
const recencyReferenceDate = normalizedEnd
? `$${historyParams.push(normalizedEnd)}::date`
: 'CURRENT_DATE';
const phoneListParam = `$${historyParams.push(periodPhones)}::text[]`;
const nameListParam = `$${historyParams.push(periodNamesWithoutPhone)}::text[]`;
const historyClients = buildRfmClients(historyResult.rows.map(row => ({
const historyResult = await client.query(`
SELECT
${CUSTOMER_KEY_SQL} as customer_key,
MAX(COALESCE(NULLIF(cliente_nome, ''), 'Cliente Desconhecido')) as name,
MAX(NULLIF(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((${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 (
NULLIF(cliente_fone, '') = ANY(${phoneListParam})
OR (
NULLIF(cliente_fone, '') IS NULL
AND COALESCE(NULLIF(cliente_nome, ''), 'Cliente Desconhecido') = ANY(${nameListParam})
)
)
GROUP BY customer_key;
`, historyParams);
historyRows = historyResult.rows;
}
const historyClients = buildRfmClients(historyRows.map(row => ({
customerKey: row.customer_key,
name: row.name,
phone: row.phone || '',