solorpower/app/utils/statsChart.js
haneulai f2bb131884
Some checks are pending
CI / Crawler (Python ${{ matrix.python-version }}) (3.10) (push) Waiting to run
CI / Crawler (Python ${{ matrix.python-version }}) (3.11) (push) Waiting to run
CI / API (Python 3.11) (push) Waiting to run
CI / Database migration (push) Waiting to run
CI / App web build (Node 20) (push) Waiting to run
refactor: complete repository structure cleanup
2026-08-07 15:30:44 +09:00

88 lines
2.7 KiB
JavaScript

const EMPTY_BAR_COLOR = '#E5E7EB';
const DATA_BAR_COLOR = '#3B82F6';
const CURRENT_BAR_COLOR = '#10B981';
export const toLocalIsoDate = (value) => {
const year = value.getFullYear();
const month = String(value.getMonth() + 1).padStart(2, '0');
const day = String(value.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
};
const labelTextStyle = (shiftX) => ({
fontSize: 10,
color: '#6B7280',
width: 40,
textAlign: 'center',
shiftX,
});
const formatYearLabel = (label) => (
label?.length === 4 ? `${label.slice(2)}` : (label || '')
);
export const formatHourlyChartData = (hourlyData, selectedDate, now = new Date()) => {
const byHour = new Map(hourlyData.map((item) => [item.hour, item]));
const isToday = toLocalIsoDate(now) === toLocalIsoDate(selectedDate);
return Array.from({ length: 25 }, (_, hour) => {
if (hour === 24) {
return { value: 0, label: '24시', frontColor: 'transparent' };
}
const item = byHour.get(hour) || {};
const hasData = item.has_data || item.current_kw > 0;
const isCurrentHour = isToday && hour === now.getHours();
return {
value: item.current_kw || 0,
label: hour % 2 === 0 ? `${hour}` : '',
frontColor: isCurrentHour
? CURRENT_BAR_COLOR
: (hasData ? DATA_BAR_COLOR : EMPTY_BAR_COLOR),
};
});
};
export const formatPeriodChartData = (period, rawData, selectedDate) => {
const year = selectedDate.getFullYear();
const month = selectedDate.getMonth() + 1;
const dataMap = new Map(rawData.map((item) => [item.label, item.value || 0]));
if (period === 'day') {
const lastDay = new Date(year, month, 0).getDate();
return Array.from({ length: lastDay }, (_, index) => {
const day = index + 1;
const key = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
const value = dataMap.get(key) || 0;
return {
value,
label: day === 1 || day % 5 === 0 ? `${day}` : '',
labelTextStyle: labelTextStyle(-10),
frontColor: value > 0 ? DATA_BAR_COLOR : EMPTY_BAR_COLOR,
};
});
}
if (period === 'month') {
return Array.from({ length: 12 }, (_, index) => {
const itemMonth = index + 1;
const key = `${year}-${String(itemMonth).padStart(2, '0')}`;
const value = dataMap.get(key) || 0;
return {
value,
label: `${itemMonth}`,
labelTextStyle: labelTextStyle(-5),
frontColor: value > 0 ? DATA_BAR_COLOR : EMPTY_BAR_COLOR,
};
});
}
return rawData.map((item) => ({
value: item.value || 0,
label: formatYearLabel(item.label),
labelTextStyle: labelTextStyle(-10),
frontColor: item.value > 0 ? DATA_BAR_COLOR : EMPTY_BAR_COLOR,
}));
};