From f924d466cbb075fb4315d6e2d12ee27def8cd430 Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Mon, 24 Jul 2023 13:44:45 +0200 Subject: [PATCH] feat: support all recurrency types in charging profiles MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Jérôme Benoit --- src/charging-station/ChargingStationUtils.ts | 55 +++++++++++++++----- 1 file changed, 41 insertions(+), 14 deletions(-) diff --git a/src/charging-station/ChargingStationUtils.ts b/src/charging-station/ChargingStationUtils.ts index 749b876b..f6119f3d 100644 --- a/src/charging-station/ChargingStationUtils.ts +++ b/src/charging-station/ChargingStationUtils.ts @@ -4,7 +4,23 @@ import { basename, dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import chalk from 'chalk'; -import { addSeconds, isAfter, isTomorrow, isYesterday } from 'date-fns'; +import { + addDays, + addMonths, + addSeconds, + addWeeks, + endOfMonth, + endOfWeek, + isAfter, + isBefore, + isTomorrow, + isYesterday, + startOfMonth, + startOfWeek, + subDays, + subMonths, + subWeeks, +} from 'date-fns'; import type { ChargingStation } from './ChargingStation'; import { BaseError } from '../exception'; @@ -679,19 +695,30 @@ const getLimitFromChargingProfiles = ( ); chargingSchedule.startSchedule = convertToDate(chargingSchedule.startSchedule)!; } - // Adjust the daily recurring schedule to today - if ( - chargingProfile.chargingProfileKind === ChargingProfileKindType.RECURRING && - chargingProfile.recurrencyKind === RecurrencyKindType.DAILY - ) { - if (isYesterday(chargingSchedule.startSchedule)) { - chargingSchedule.startSchedule.setFullYear( - currentDate.getFullYear(), - currentDate.getMonth(), - currentDate.getDate(), - ); - } else if (isTomorrow(chargingSchedule.startSchedule)) { - chargingSchedule.startSchedule.setDate(currentDate.getDate() - 1); + // Adjust recurring schedule + if (chargingProfile.chargingProfileKind === ChargingProfileKindType.RECURRING) { + switch (chargingProfile.recurrencyKind) { + case RecurrencyKindType.DAILY: + if (isYesterday(chargingSchedule.startSchedule)) { + addDays(chargingSchedule.startSchedule, 1); + } else if (isTomorrow(chargingSchedule.startSchedule)) { + subDays(chargingSchedule.startSchedule, 1); + } + break; + case RecurrencyKindType.WEEKLY: + if (isBefore(chargingSchedule.startSchedule, startOfWeek(currentDate))) { + addWeeks(chargingSchedule.startSchedule, 1); + } else if (isAfter(chargingSchedule.startSchedule, endOfWeek(currentDate))) { + subWeeks(chargingSchedule.startSchedule, 1); + } + break; + case RecurrencyKindType.MONTHLY: + if (isBefore(chargingSchedule.startSchedule, startOfMonth(currentDate))) { + addMonths(chargingSchedule.startSchedule, 1); + } else if (isAfter(chargingSchedule.startSchedule, endOfMonth(currentDate))) { + subMonths(chargingSchedule.startSchedule, 1); + } + break; } } // Check if the charging profile is active -- 2.34.1