Revert "Optimize RFV all-period analytics"

This reverts commit 7fb2507f53.
This commit is contained in:
Cauê Faleiros
2026-06-17 11:08:59 -03:00
parent ab4d7a3bd7
commit 19a29956d2
2 changed files with 9 additions and 63 deletions

View File

@@ -262,14 +262,12 @@ 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 recencyReferenceDate = normalizedEnd ? '$1::date' : 'CURRENT_DATE';
const historyParams = normalizedEnd ? [normalizedEnd] : [];
const usePeriodAsHistory = !normalizedStart || normalizedStart <= '2000-01-01';
const periodQuery = pool.query(`
const [periodResult, historyResult] = await Promise.all([
pool.query(`
SELECT
${CUSTOMER_KEY_SQL} as customer_key,
MAX(cliente_nome) as name,
@@ -277,15 +275,13 @@ 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,
GREATEST((${periodRecencyReferenceDate} - MAX(data_pedido_date))::int, 0) as recency_days
MAX(data_pedido_date) as last_purchase_date
FROM orders
${whereClause}
GROUP BY customer_key
ORDER BY monetary DESC;
`, params);
const historyQuery = usePeriodAsHistory ? null : pool.query(`
`, params),
pool.query(`
SELECT
${CUSTOMER_KEY_SQL} as customer_key,
MAX(cliente_nome) as name,
@@ -299,15 +295,10 @@ const getRfmAnalytics = async (range = {}) => {
WHERE data_pedido_date IS NOT NULL
AND data_pedido_date <= ${recencyReferenceDate}
GROUP BY customer_key;
`, historyParams);
`, historyParams)
]);
const [periodResult, historyResult] = historyQuery
? await Promise.all([periodQuery, historyQuery])
: [await periodQuery, null];
const historyRows = historyResult ? historyResult.rows : periodResult.rows;
const historyClients = buildRfmClients(historyRows.map(row => ({
const historyClients = buildRfmClients(historyResult.rows.map(row => ({
customerKey: row.customer_key,
name: row.name,
phone: row.phone || '',