All files / src/pages/flowsheet-page/economics/schedule-selector scheduleErrors.ts

82.35% Statements 14/17
53.84% Branches 7/13
100% Functions 3/3
87.5% Lines 14/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55  1x 1x         1x         2x   1x         1x 1x   1x 1x 1x         103x                   1x                 1x       1x    
export function scheduleMutationErrorMessage(error: unknown, fallback: string) {
  const messages = flattenScheduleError(error);
  return messages.length > 0 ? messages.join(" ") : fallback;
}
 
function flattenScheduleError(error: unknown): string[] {
  if (typeof error === "string") {
    return looksLikeHtml(error) ? [] : [error];
  }
  if (Array.isArray(error)) {
    return error.flatMap(flattenScheduleError);
  }
  Iif (!error || typeof error !== "object") return [];
  if ("data" in error) {
    return flattenScheduleError(error.data);
  }
  if ("message" in error && typeof error.message === "string") {
    return flattenScheduleError(error.message);
  }
  return Object.entries(error)
    .filter(([key]) => !SCHEDULE_ERROR_INTERNAL_KEYS.has(key))
    .flatMap(([key, value]) => {
      const label = scheduleFieldLabel(key);
      return flattenScheduleError(value).map((message) =>
        label ? `${label}: ${message}` : message,
      );
    });
}
 
const SCHEDULE_ERROR_INTERNAL_KEYS = new Set([
  "ctx",
  "input",
  "loc",
  "status",
  "type",
  "url",
]);
 
function scheduleFieldLabel(field: string) {
  const labels: Record<string, string> = {
    rules: "Schedule rules",
    source_scenario: "Source scenario",
    days_mask: "Days",
    start_time: "Start time",
    label: "Label",
    detail: "",
    non_field_errors: "",
  };
  return labels[field] ?? "Schedule field";
}
 
function looksLikeHtml(value: string) {
  return /^\s*(?:<!doctype\s+html|<html[\s>])/i.test(value);
}