Fix RFV all-period scaling
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 50s

This commit is contained in:
Cauê Faleiros
2026-06-17 16:12:36 -03:00
parent 2445272f3a
commit ca90a6e94b
2 changed files with 110 additions and 45 deletions

View File

@@ -325,58 +325,54 @@ test('getRfmAnalytics classifies period buyers by history through the selected r
}
});
test('getRfmAnalytics reuses period rows as RFV history for all-period ranges', async () => {
test('getRfmAnalytics reuses client aggregate rows as RFV history for all-period ranges', async () => {
const originalQuery = pool.query;
const originalConnect = pool.connect;
const calls = [];
const mockClient = {
query: async (sql, params = []) => {
calls.push({ sql, params });
if (!sql.includes('FROM orders')) {
return { rows: [] };
}
pool.query = async (sql, params = []) => {
calls.push({ sql, params });
return {
rows: [
{
customer_key: '1',
name: 'Cliente Frequente',
phone: '1',
monetary: 5000,
frequency: 20,
quantity_purchased: 20,
last_purchase_date: '2026-06-14',
recency_days: 1
},
{
customer_key: 'name:Cliente Sem Fone',
name: 'Cliente Sem Fone',
phone: null,
monetary: 50,
frequency: 1,
quantity_purchased: 1,
last_purchase_date: '2026-01-01',
recency_days: 165
}
]
};
},
release: () => {}
return {
rows: [
{
customer_key: '1',
name: 'Cliente Frequente',
phone: '1',
total_spent: 5000,
order_count: 20,
quantity_purchased: 20,
last_purchase_date: '2026-06-14'
},
{
customer_key: 'name:Cliente Sem Fone',
name: 'Cliente Sem Fone',
phone: null,
total_spent: 50,
order_count: 1,
quantity_purchased: 1,
last_purchase_date: '2026-01-01'
}
]
};
};
pool.connect = async () => {
throw new Error('all-period RFV should not use a checked-out client');
};
pool.connect = async () => mockClient;
try {
const result = await getRfmAnalytics({ start: '2000-01-01', end: '2026-06-15' });
const selectCalls = calls.filter(call => call.sql.includes('FROM orders'));
assert.equal(selectCalls.length, 1);
assert.match(selectCalls[0].sql, /\(\$2::date - MAX\(data_pedido_date\)\)::int/);
assert.doesNotMatch(selectCalls[0].sql, /= ANY/);
assert.deepEqual(selectCalls[0].params, ['2000-01-01', '2026-06-15']);
assert.equal(calls.length, 1);
assert.match(calls[0].sql, /GROUP BY customer_key/);
assert.doesNotMatch(calls[0].sql, /recency_days/);
assert.doesNotMatch(calls[0].sql, /data_pedido_date >=/);
assert.deepEqual(calls[0].params, ['2026-06-15']);
assert.equal(result.clients.length, 2);
assert.equal(result.segments.reduce((total, segment) => total + segment.count, 0), 2);
assert.ok(result.clients.some(client => client.customerKey === 'name:Cliente Sem Fone' && client.phone === ''));
} finally {
pool.query = originalQuery;
pool.connect = originalConnect;
}
});