Fix RFM date range consistency
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 1m5s

This commit is contained in:
Cauê Faleiros
2026-06-15 10:48:00 -03:00
parent ac692b8e10
commit fc7a50fddf
8 changed files with 262 additions and 84 deletions

View File

@@ -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<DateRangePickerProps> = ({ dateRange, onChange, refreshInterval, setRefreshInterval, onManualRefresh }) => {
const [isPresetOpen, setIsPresetOpen] = useState(false);
const startRef = useRef<HTMLInputElement>(null);
@@ -65,32 +42,23 @@ const DateRangePicker: React.FC<DateRangePickerProps> = ({ 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<HTMLInputElement>) => {
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<HTMLInputElement>) => {
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 });
}
};

View File

@@ -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<OrderData[]>([]);

View File

@@ -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<Respo
return response;
};
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}`;
};
export const fetchDashboardAnalytics = async (dateRange: DateRange): Promise<DashboardAnalytics | null> => {
try {
const params = new URLSearchParams({

54
src/dateRanges.test.ts Normal file
View File

@@ -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);
});

58
src/dateRanges.ts Normal file
View File

@@ -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}`;
};