From fc7a50fddf425eee70a5de95db5e5e674213cc26 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Mon, 15 Jun 2026 10:48:00 -0300 Subject: [PATCH] Fix RFM date range consistency --- backend/services/analyticsService.js | 69 ++++++++++++-------- backend/test/analyticsService.test.js | 92 +++++++++++++++++++++++++++ src/components/DateRangePicker.tsx | 56 ++++------------ src/components/Layout.tsx | 6 +- src/dataService.ts | 8 +-- src/dateRanges.test.ts | 54 ++++++++++++++++ src/dateRanges.ts | 58 +++++++++++++++++ tsconfig.app.json | 3 +- 8 files changed, 262 insertions(+), 84 deletions(-) create mode 100644 src/dateRanges.test.ts create mode 100644 src/dateRanges.ts diff --git a/backend/services/analyticsService.js b/backend/services/analyticsService.js index e559630..a96eefb 100644 --- a/backend/services/analyticsService.js +++ b/backend/services/analyticsService.js @@ -101,6 +101,35 @@ const buildRfmSegments = (clients) => { }); }; +const buildRfmClients = (baseClients) => { + const recencyValues = baseClients.map(client => client.recencyDays); + const frequencyValues = baseClients.map(client => client.frequency); + const monetaryValues = baseClients.map(client => client.monetary); + + return 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; + }); +}; + const getDashboardAnalytics = async (range = {}) => { const { params, whereClause } = buildDateFilter(range); const [totalsResult, salesResult, revenueResult] = await Promise.all([ @@ -222,6 +251,14 @@ 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'; + + if (normalizedEnd) { + queryParams.push(normalizedEnd); + } + const result = await pool.query(` SELECT MAX(cliente_nome) as name, @@ -230,7 +267,7 @@ const getRfmAnalytics = async (range = {}) => { 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 + GREATEST((${recencyReferenceDate} - MAX(data_pedido_date))::int, 0) as recency_days FROM orders ${whereClause} AND cliente_fone IS NOT NULL @@ -238,7 +275,7 @@ const getRfmAnalytics = async (range = {}) => { GROUP BY cliente_fone ORDER BY monetary DESC LIMIT 1000; - `, params); + `, queryParams); const baseClients = result.rows.map(row => ({ name: row.name, @@ -250,32 +287,7 @@ const getRfmAnalytics = async (range = {}) => { 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; - }); + const clients = buildRfmClients(baseClients); return { range: { @@ -293,6 +305,7 @@ const getRfmAnalytics = async (range = {}) => { module.exports = { buildDateFilter, + buildRfmClients, buildRfmSegments, getRfmAnalytics, getRfmSegment, diff --git a/backend/test/analyticsService.test.js b/backend/test/analyticsService.test.js index 7d757d3..4ff6b95 100644 --- a/backend/test/analyticsService.test.js +++ b/backend/test/analyticsService.test.js @@ -2,12 +2,15 @@ const assert = require('node:assert/strict'); const test = require('node:test'); const { + buildRfmClients, buildRfmSegments, buildDateFilter, + getRfmAnalytics, getRfmSegment, normalizeDateParam, scoreTertile } = require('../services/analyticsService'); +const { pool } = require('../db'); test('normalizeDateParam accepts strict ISO dates', () => { assert.equal(normalizeDateParam('2026-05-28'), '2026-05-28'); @@ -29,6 +32,46 @@ test('buildDateFilter builds bounded date predicates', () => { ); }); +test('buildDateFilter builds Hoje as an inclusive single-day date predicate', () => { + const filter = buildDateFilter({ start: '2026-06-15', end: '2026-06-15' }); + + assert.deepEqual(filter.params, ['2026-06-15', '2026-06-15']); + assert.equal( + filter.whereClause, + 'WHERE data_pedido_date IS NOT NULL AND data_pedido_date >= $1::date AND data_pedido_date <= $2::date' + ); +}); + +test('buildDateFilter builds Ontem as an inclusive single-day date predicate', () => { + const filter = buildDateFilter({ start: '2026-06-14', end: '2026-06-14' }); + + assert.deepEqual(filter.params, ['2026-06-14', '2026-06-14']); + assert.equal( + filter.whereClause, + 'WHERE data_pedido_date IS NOT NULL AND data_pedido_date >= $1::date AND data_pedido_date <= $2::date' + ); +}); + +test('buildDateFilter builds Ultimos 7 dias as an inclusive calendar range', () => { + const filter = buildDateFilter({ start: '2026-06-09', end: '2026-06-15' }); + + assert.deepEqual(filter.params, ['2026-06-09', '2026-06-15']); + assert.equal( + filter.whereClause, + 'WHERE data_pedido_date IS NOT NULL AND data_pedido_date >= $1::date AND data_pedido_date <= $2::date' + ); +}); + +test('buildDateFilter builds custom single-day ranges inclusively', () => { + const filter = buildDateFilter({ start: '2026-06-10', end: '2026-06-10' }); + + assert.deepEqual(filter.params, ['2026-06-10', '2026-06-10']); + assert.equal( + filter.whereClause, + 'WHERE data_pedido_date IS NOT NULL AND data_pedido_date >= $1::date AND data_pedido_date <= $2::date' + ); +}); + test('buildDateFilter ignores invalid bounds', () => { const filter = buildDateFilter({ start: 'invalid', end: '2026-05-28' }); @@ -77,3 +120,52 @@ test('buildRfmSegments summarizes segment count and revenue', () => { assert.equal(lost.count, 1); assert.equal(lost.totalRevenue, 25); }); + +test('buildRfmClients keeps a yesterday buyer in the same high-recency segment when it is the only qualifying client', () => { + const sevenDayClients = buildRfmClients([ + { name: 'Cliente Ontem', phone: '1', monetary: 500, frequency: 2, quantityPurchased: 2, lastPurchaseDate: '2026-06-14', recencyDays: 1 } + ]); + const yesterdayClients = buildRfmClients([ + { name: 'Cliente Ontem', phone: '1', monetary: 500, frequency: 2, quantityPurchased: 2, lastPurchaseDate: '2026-06-14', recencyDays: 0 } + ]); + + assert.equal(sevenDayClients[0].segmentKey, 'champions'); + assert.equal(yesterdayClients[0].segmentKey, 'champions'); + assert.equal(sevenDayClients[0].phone, yesterdayClients[0].phone); +}); + +test('getRfmAnalytics calculates recency against selected range end date', async () => { + const originalQuery = pool.query; + const calls = []; + + pool.query = async (sql, params) => { + calls.push({ sql, params }); + return { + rows: [ + { + name: 'Cliente Ontem', + phone: '1', + monetary: 500, + frequency: 2, + quantity_purchased: 2, + last_purchase_date: '2026-06-14', + recency_days: params[2] === '2026-06-14' ? 0 : 1 + } + ] + }; + }; + + try { + const sevenDays = await getRfmAnalytics({ start: '2026-06-09', end: '2026-06-15' }); + const yesterday = await getRfmAnalytics({ start: '2026-06-14', end: '2026-06-14' }); + + assert.match(calls[0].sql, /\(\$3::date - MAX\(data_pedido_date\)\)::int/); + assert.deepEqual(calls[0].params, ['2026-06-09', '2026-06-15', '2026-06-15']); + assert.deepEqual(calls[1].params, ['2026-06-14', '2026-06-14', '2026-06-14']); + assert.equal(sevenDays.clients[0].segmentKey, 'champions'); + assert.equal(yesterday.clients[0].segmentKey, 'champions'); + assert.equal(yesterday.clients[0].recencyDays, 0); + } finally { + pool.query = originalQuery; + } +}); diff --git a/src/components/DateRangePicker.tsx b/src/components/DateRangePicker.tsx index 6f55eeb..04c30e5 100644 --- a/src/components/DateRangePicker.tsx +++ b/src/components/DateRangePicker.tsx @@ -1,6 +1,7 @@ import React, { useState, useRef } from 'react'; import { Calendar, RefreshCw, ChevronDown } from 'lucide-react'; import type { DateRange } from '../types'; +import { endOfLocalDay, formatDateParam, parseLocalDateInput, rangeForDay, rangeForLastDays, rangeForPreviousDay, startOfLocalDay } from '../dateRanges'; interface DateRangePickerProps { dateRange: DateRange; @@ -12,14 +13,14 @@ interface DateRangePickerProps { const PRESETS = [ { label: 'Hoje', getRange: () => rangeForDay(new Date()) }, - { label: 'Ontem', getRange: () => { const d = new Date(); d.setDate(d.getDate() - 1); return rangeForDay(d); } }, + { label: 'Ontem', getRange: () => rangeForPreviousDay() }, { label: 'Últimos 7 dias', getRange: () => rangeForLastDays(7) }, { label: 'Últimos 30 dias', getRange: () => rangeForLastDays(30) }, - { label: 'Este Mês', getRange: () => { const end = endOfDay(new Date()); const start = startOfDay(new Date(end.getFullYear(), end.getMonth(), 1)); return { start, end }; } }, + { label: 'Este Mês', getRange: () => { const end = endOfLocalDay(new Date()); const start = startOfLocalDay(new Date(end.getFullYear(), end.getMonth(), 1)); return { start, end }; } }, { label: 'Mês Passado', getRange: () => { const d = new Date(); const start = new Date(d.getFullYear(), d.getMonth() - 1, 1); const end = new Date(d.getFullYear(), d.getMonth(), 0, 23, 59, 59, 999); return { start, end }; } }, { label: 'Últimos 90 dias', getRange: () => rangeForLastDays(90) }, - { label: 'Este Ano', getRange: () => { const end = endOfDay(new Date()); const start = startOfDay(new Date(end.getFullYear(), 0, 1)); return { start, end }; } }, - { label: 'Todo o Período', getRange: () => { const end = endOfDay(new Date()); const start = startOfDay(new Date(2000, 0, 1)); return { start, end }; } }, + { label: 'Este Ano', getRange: () => { const end = endOfLocalDay(new Date()); const start = startOfLocalDay(new Date(end.getFullYear(), 0, 1)); return { start, end }; } }, + { label: 'Todo o Período', getRange: () => { const end = endOfLocalDay(new Date()); const start = startOfLocalDay(new Date(2000, 0, 1)); return { start, end }; } }, ]; const REFRESH_OPTIONS = [ @@ -31,30 +32,6 @@ const REFRESH_OPTIONS = [ { label: '5m', value: 300000 }, ]; -const startOfDay = (date: Date) => { - const nextDate = new Date(date); - nextDate.setHours(0, 0, 0, 0); - return nextDate; -}; - -const endOfDay = (date: Date) => { - const nextDate = new Date(date); - nextDate.setHours(23, 59, 59, 999); - return nextDate; -}; - -const rangeForDay = (date: Date) => ({ - start: startOfDay(date), - end: endOfDay(date), -}); - -const rangeForLastDays = (days: number) => { - const end = endOfDay(new Date()); - const start = startOfDay(end); - start.setDate(start.getDate() - Math.max(days - 1, 0)); - return { start, end }; -}; - const DateRangePicker: React.FC = ({ dateRange, onChange, refreshInterval, setRefreshInterval, onManualRefresh }) => { const [isPresetOpen, setIsPresetOpen] = useState(false); const startRef = useRef(null); @@ -65,32 +42,23 @@ const DateRangePicker: React.FC = ({ dateRange, onChange, }; const formatDateForInput = (date: Date) => { - const year = date.getFullYear(); - const month = String(date.getMonth() + 1).padStart(2, '0'); - const day = String(date.getDate()).padStart(2, '0'); - return `${year}-${month}-${day}`; - }; - - const parseLocalDate = (value: string) => { - if (!value) return null; - const [year, month, day] = value.split('-'); - return new Date(parseInt(year), parseInt(month) - 1, parseInt(day)); + return formatDateParam(date); }; const handleStartChange = (e: React.ChangeEvent) => { - const newStart = parseLocalDate(e.target.value); + const newStart = parseLocalDateInput(e.target.value); if (newStart && !isNaN(newStart.getTime())) { - const start = startOfDay(newStart); - const end = dateRange.end < start ? endOfDay(start) : dateRange.end; + const start = startOfLocalDay(newStart); + const end = dateRange.end < start ? endOfLocalDay(start) : dateRange.end; onChange({ start, end }); } }; const handleEndChange = (e: React.ChangeEvent) => { - const newEnd = parseLocalDate(e.target.value); + const newEnd = parseLocalDateInput(e.target.value); if (newEnd && !isNaN(newEnd.getTime())) { - const end = endOfDay(newEnd); - const start = dateRange.start > end ? startOfDay(end) : dateRange.start; + const end = endOfLocalDay(newEnd); + const start = dateRange.start > end ? startOfLocalDay(end) : dateRange.start; onChange({ start, end }); } }; diff --git a/src/components/Layout.tsx b/src/components/Layout.tsx index 1650cda..e8a7946 100644 --- a/src/components/Layout.tsx +++ b/src/components/Layout.tsx @@ -3,6 +3,7 @@ import { Outlet, Link, useLocation } from 'react-router-dom'; import { LayoutDashboard, Users, BarChart3, ChevronLeft, ChevronRight, Package, Loader2, LogOut, Megaphone, Grid3X3 } from 'lucide-react'; import type { DateRange, OrderData, StockData } from '../types'; import { fetchData, fetchStock, logout } from '../dataService'; +import { rangeForLastDays } from '../dateRanges'; const Layout = () => { const location = useLocation(); @@ -20,10 +21,7 @@ const Layout = () => { return { start: new Date(parsed.start), end: new Date(parsed.end) }; } catch (e) { console.error(e); } } - const end = new Date(); - const start = new Date(); - start.setMonth(start.getMonth() - 1); - return { start, end }; + return rangeForLastDays(30); }); const [ordersData, setOrdersData] = useState([]); diff --git a/src/dataService.ts b/src/dataService.ts index 38b06ec..73f0b26 100644 --- a/src/dataService.ts +++ b/src/dataService.ts @@ -1,4 +1,5 @@ import type { CampaignPreview, CampaignProcessSummary, CampaignQueueSummary, DashboardAnalytics, DateRange, OrderData, RfmAnalytics, StockData } from './types'; +import { formatDateParam } from './dateRanges'; const API_URL = import.meta.env.VITE_API_URL || '/api'; @@ -89,13 +90,6 @@ const authFetch = async (path: string, options: RequestInit = {}): Promise { - const year = date.getFullYear(); - const month = String(date.getMonth() + 1).padStart(2, '0'); - const day = String(date.getDate()).padStart(2, '0'); - return `${year}-${month}-${day}`; -}; - export const fetchDashboardAnalytics = async (dateRange: DateRange): Promise => { try { const params = new URLSearchParams({ diff --git a/src/dateRanges.test.ts b/src/dateRanges.test.ts new file mode 100644 index 0000000..4ba614d --- /dev/null +++ b/src/dateRanges.test.ts @@ -0,0 +1,54 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { endOfLocalDay, formatDateParam, parseLocalDateInput, rangeForDay, rangeForLastDays, rangeForPreviousDay, startOfLocalDay } from './dateRanges.ts'; + +const assertRange = (range: { start: Date; end: Date }, start: string, end: string) => { + assert.equal(formatDateParam(range.start), start); + assert.equal(formatDateParam(range.end), end); + assert.equal(range.start.getHours(), 0); + assert.equal(range.start.getMinutes(), 0); + assert.equal(range.start.getSeconds(), 0); + assert.equal(range.start.getMilliseconds(), 0); + assert.equal(range.end.getHours(), 23); + assert.equal(range.end.getMinutes(), 59); + assert.equal(range.end.getSeconds(), 59); + assert.equal(range.end.getMilliseconds(), 999); +}; + +test('Hoje uses full local calendar-day boundaries', () => { + const today = new Date(2026, 5, 15, 14, 30, 10, 50); + + assertRange(rangeForDay(today), '2026-06-15', '2026-06-15'); +}); + +test('Ontem uses the full previous local calendar day', () => { + const today = new Date(2026, 5, 15, 0, 5, 0, 0); + + assertRange(rangeForPreviousDay(today), '2026-06-14', '2026-06-14'); +}); + +test('Ultimos 7 dias includes today plus the previous 6 calendar days', () => { + const today = new Date(2026, 5, 15, 22, 10, 0, 0); + + assertRange(rangeForLastDays(7, today), '2026-06-09', '2026-06-15'); +}); + +test('Ultimos 30 and 90 dias use inclusive calendar-day ranges', () => { + const today = new Date(2026, 5, 15, 22, 10, 0, 0); + + assertRange(rangeForLastDays(30, today), '2026-05-17', '2026-06-15'); + assertRange(rangeForLastDays(90, today), '2026-03-18', '2026-06-15'); +}); + +test('custom single-day input parses as local date and can build a full-day range', () => { + const customDate = parseLocalDateInput('2026-06-14'); + + assert.ok(customDate); + assertRange({ start: startOfLocalDay(customDate), end: endOfLocalDay(customDate) }, '2026-06-14', '2026-06-14'); +}); + +test('API date params are stable YYYY-MM-DD strings', () => { + assert.equal(formatDateParam(new Date(2026, 5, 14, 23, 59, 59, 999)), '2026-06-14'); + assert.equal(parseLocalDateInput('14/06/2026'), null); +}); diff --git a/src/dateRanges.ts b/src/dateRanges.ts new file mode 100644 index 0000000..d8172eb --- /dev/null +++ b/src/dateRanges.ts @@ -0,0 +1,58 @@ +import type { DateRange } from './types'; + +export const startOfLocalDay = (date: Date): Date => { + const nextDate = new Date(date); + nextDate.setHours(0, 0, 0, 0); + return nextDate; +}; + +export const endOfLocalDay = (date: Date): Date => { + const nextDate = new Date(date); + nextDate.setHours(23, 59, 59, 999); + return nextDate; +}; + +export const rangeForDay = (date: Date): DateRange => ({ + start: startOfLocalDay(date), + end: endOfLocalDay(date), +}); + +export const rangeForLastDays = (days: number, today = new Date()): DateRange => { + const end = endOfLocalDay(today); + const start = startOfLocalDay(today); + start.setDate(start.getDate() - Math.max(days - 1, 0)); + return { start, end }; +}; + +export const rangeForPreviousDay = (today = new Date()): DateRange => { + const date = startOfLocalDay(today); + date.setDate(date.getDate() - 1); + return rangeForDay(date); +}; + +export const parseLocalDateInput = (value: string): Date | null => { + if (!value) return null; + + const match = value.match(/^(\d{4})-(\d{2})-(\d{2})$/); + if (!match) return null; + + const [, yearValue, monthValue, dayValue] = match; + const date = new Date(Number(yearValue), Number(monthValue) - 1, Number(dayValue)); + + if ( + date.getFullYear() !== Number(yearValue) || + date.getMonth() !== Number(monthValue) - 1 || + date.getDate() !== Number(dayValue) + ) { + return null; + } + + return date; +}; + +export const formatDateParam = (date: Date): string => { + const year = date.getFullYear(); + const month = String(date.getMonth() + 1).padStart(2, '0'); + const day = String(date.getDate()).padStart(2, '0'); + return `${year}-${month}-${day}`; +}; diff --git a/tsconfig.app.json b/tsconfig.app.json index 7f42e5f..71cc1ad 100644 --- a/tsconfig.app.json +++ b/tsconfig.app.json @@ -21,5 +21,6 @@ "erasableSyntaxOnly": true, "noFallthroughCasesInSwitch": true }, - "include": ["src"] + "include": ["src"], + "exclude": ["src/**/*.test.ts", "src/**/*.test.tsx"] }