refactor: add more sanity checks to charging profiles handling code
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStationUtils.ts
index 1af1266110bd62d2e49f42e5ec801cc34fac8546..628b7eb9c03510511c6d48736726186daf028534 100644 (file)
@@ -672,8 +672,10 @@ interface ChargingProfilesLimit {
 }
 
 /**
- * Charging profiles should already be sorted by connector id and stack level (highest stack level has priority)
+ * Charging profiles shall already be sorted by connector id and stack level (highest stack level has priority)
  *
+ * @param chargingStation -
+ * @param connectorId -
  * @param chargingProfiles -
  * @param logPrefix -
  * @returns ChargingProfilesLimit
@@ -703,16 +705,16 @@ const getLimitFromChargingProfiles = (
     const chargingSchedule = chargingProfile.chargingSchedule;
     if (connectorStatus?.transactionStarted && !chargingSchedule?.startSchedule) {
       logger.debug(
-        `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: startSchedule is not defined in charging profile id ${chargingProfile.chargingProfileId}. Trying to set it to the connector transaction start date`,
+        `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Charging profile id ${chargingProfile.chargingProfileId} has no startSchedule defined. Trying to set it to the connector current transaction start date`,
       );
       // OCPP specifies that if startSchedule is not defined, it should be relative to start of the connector transaction
       chargingSchedule.startSchedule = connectorStatus?.transactionStart;
     }
     if (!(chargingSchedule?.startSchedule instanceof Date)) {
       logger.warn(
-        `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: startSchedule is not a Date object in charging profile id ${chargingProfile.chargingProfileId}. Trying to convert it to a Date object`,
+        `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Charging profile id ${chargingProfile.chargingProfileId} startSchedule property is not a Date object. Trying to convert it to a Date object`,
       );
-      chargingSchedule.startSchedule = convertToDate(chargingSchedule.startSchedule)!;
+      chargingSchedule.startSchedule = convertToDate(chargingSchedule?.startSchedule)!;
     }
     if (
       chargingProfile.chargingProfileKind === ChargingProfileKindType.RECURRING &&
@@ -731,9 +733,21 @@ const getLimitFromChargingProfiles = (
     ) {
       chargingSchedule.startSchedule = connectorStatus?.transactionStart;
     }
+    if (isNullOrUndefined(chargingSchedule?.startSchedule)) {
+      logger.error(
+        `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Charging profile id ${chargingProfile.chargingProfileId} has (still) no startSchedule defined`,
+      );
+      continue;
+    }
+    if (isNullOrUndefined(chargingSchedule?.duration)) {
+      logger.error(
+        `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Charging profile id ${chargingProfile.chargingProfileId} has no duration defined, not yet supported`,
+      );
+      continue;
+    }
     // Check if the charging profile is active
     if (
-      isValidDate(chargingSchedule.startSchedule) &&
+      isValidDate(chargingSchedule?.startSchedule) &&
       isWithinInterval(currentDate, {
         start: chargingSchedule.startSchedule!,
         end: addSeconds(chargingSchedule.startSchedule!, chargingSchedule.duration!),
@@ -762,7 +776,7 @@ const getLimitFromChargingProfiles = (
           );
           continue;
         }
-        // Handling of only one schedule period
+        // Handle only one schedule period
         if (chargingSchedule.chargingSchedulePeriod.length === 1) {
           const result: ChargingProfilesLimit = {
             limit: chargingSchedule.chargingSchedulePeriod[0].limit,
@@ -818,7 +832,7 @@ const getLimitFromChargingProfiles = (
 };
 
 /**
- *  Adjust recurring charging profile startSchedule to the current recurrency time interval if needed
+ * Adjust recurring charging profile startSchedule to the current recurrency time interval if needed
  *
  * @param chargingProfile -
  * @param currentDate -
@@ -828,8 +842,9 @@ const prepareRecurringChargingProfile = (
   chargingProfile: ChargingProfile,
   currentDate: Date,
   logPrefix: string,
-) => {
+): boolean => {
   const chargingSchedule = chargingProfile.chargingSchedule;
+  let recurringIntervalTranslated = false;
   let recurringInterval: Interval;
   switch (chargingProfile.recurrencyKind) {
     case RecurrencyKindType.DAILY:
@@ -840,16 +855,17 @@ const prepareRecurringChargingProfile = (
       checkRecurringChargingProfileDuration(chargingProfile, recurringInterval, logPrefix);
       if (
         !isWithinInterval(currentDate, recurringInterval) &&
-        isBefore(chargingSchedule.startSchedule!, currentDate)
+        isBefore(recurringInterval.end, currentDate)
       ) {
         chargingSchedule.startSchedule = addDays(
-          chargingSchedule.startSchedule!,
+          recurringInterval.start,
           differenceInDays(currentDate, recurringInterval.start),
         );
         recurringInterval = {
           start: chargingSchedule.startSchedule,
           end: addDays(chargingSchedule.startSchedule, 1),
         };
+        recurringIntervalTranslated = true;
       }
       break;
     case RecurrencyKindType.WEEKLY:
@@ -860,38 +876,56 @@ const prepareRecurringChargingProfile = (
       checkRecurringChargingProfileDuration(chargingProfile, recurringInterval, logPrefix);
       if (
         !isWithinInterval(currentDate, recurringInterval) &&
-        isBefore(chargingSchedule.startSchedule!, currentDate)
+        isBefore(recurringInterval.end, currentDate)
       ) {
         chargingSchedule.startSchedule = addWeeks(
-          chargingSchedule.startSchedule!,
+          recurringInterval.start,
           differenceInWeeks(currentDate, recurringInterval.start),
         );
         recurringInterval = {
           start: chargingSchedule.startSchedule,
           end: addWeeks(chargingSchedule.startSchedule, 1),
         };
+        recurringIntervalTranslated = true;
       }
       break;
+    default:
+      logger.error(
+        `${logPrefix} ${moduleName}.prepareRecurringChargingProfile: Recurring charging profile id ${chargingProfile.chargingProfileId} recurrency kind ${chargingProfile.recurrencyKind} is not supported`,
+      );
   }
-  if (!isWithinInterval(currentDate, recurringInterval!)) {
+  if (recurringIntervalTranslated && !isWithinInterval(currentDate, recurringInterval!)) {
     logger.error(
       `${logPrefix} ${moduleName}.prepareRecurringChargingProfile: Recurring ${
         chargingProfile.recurrencyKind
-      } charging profile id ${
-        chargingProfile.chargingProfileId
-      } startSchedule ${chargingSchedule.startSchedule!.toISOString()} is not properly translated to current recurrency time interval [${toDate(
+      } charging profile id ${chargingProfile.chargingProfileId} recurrency time interval [${toDate(
         recurringInterval!.start,
-      ).toISOString()}, ${toDate(recurringInterval!.end).toISOString()}]`,
+      ).toISOString()}, ${toDate(
+        recurringInterval!.end,
+      ).toISOString()}] has not been properly translated to current date ${currentDate.toISOString()} `,
     );
   }
+  return recurringIntervalTranslated;
 };
 
 const checkRecurringChargingProfileDuration = (
   chargingProfile: ChargingProfile,
   interval: Interval,
   logPrefix: string,
-) => {
-  if (
+): void => {
+  if (isNullOrUndefined(chargingProfile.chargingSchedule.duration)) {
+    logger.warn(
+      `${logPrefix} ${moduleName}.checkRecurringChargingProfileDuration: Recurring ${
+        chargingProfile.chargingProfileKind
+      } charging profile id ${
+        chargingProfile.chargingProfileId
+      } duration is not defined, set it to the recurrency time interval duration ${differenceInSeconds(
+        interval.end,
+        interval.start,
+      )}`,
+    );
+    chargingProfile.chargingSchedule.duration = differenceInSeconds(interval.end, interval.start);
+  } else if (
     chargingProfile.chargingSchedule.duration! > differenceInSeconds(interval.end, interval.start)
   ) {
     logger.warn(