All files / src/sections/PayBuilder/components/InvoicePreview utils.ts

7.63% Statements 10/131
0% Branches 0/83
0% Functions 0/15
8.69% Lines 10/115

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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273                                    14x                                                               14x                                   14x                                                                         14x                                                                             14x                                 14x               14x             14x                                             14x             14x                                                                                                                                    
import { isUrl } from "@sections/PayBuilder/helpers";
import { ICartItem } from "@sections/PayBuilder/provider/CartContext";
import { MediaItem } from "@sections/PayBuilder/provider/provider.type";
import { safeParse } from "@utils/index";
import {
  addMonths,
  addYears,
  compareAsc,
  format,
  isValid,
  parse,
} from "date-fns";
import draftToHtml from "draftjs-to-html";
 
type RecurrenceInterval = "once" | "monthly" | "quarterly" | "yearly";
 
type IDateInput = string | number | Date;
 
const normalizeDate = (dateInput?: IDateInput) => {
  if (!dateInput) {
    return new Date();
  }
 
  // if it is a date obj
  if (dateInput instanceof Date) {
    return isValid(dateInput) ? dateInput : new Date();
  }
 
  // if it is a  timestamp
  if (typeof dateInput === "number") {
    const date = new Date(dateInput);
    return isValid(date) ? date : new Date();
  }
 
  // if it is a string
  if (typeof dateInput === "string") {
    if (dateInput.includes("/")) {
      const parsedDate = parse(dateInput, "MM/dd/yyyy", new Date());
      if (isValid(parsedDate)) {
        return parsedDate;
      }
    }
 
    const date = new Date(dateInput);
    return isValid(date) ? date : new Date();
  }
 
  return new Date();
};
 
const calculateNextRenewalDate = (
  startDate: Date,
  recurrenceInterval: RecurrenceInterval,
) => {
  switch (recurrenceInterval) {
    case "once":
      return null;
    case "monthly":
      return addMonths(startDate, 1);
    case "quarterly":
      return addMonths(startDate, 3);
    case "yearly":
      return addYears(startDate, 1);
    default:
      return null;
  }
};
 
const getClosestRenewalDate = (
  items: ICartItem[],
  formCreationDate?: IDateInput,
) => {
  const baseDate = normalizeDate(formCreationDate);
 
  let closestDate: Date | null = null;
 
  items.forEach((item) => {
    if (item.recurringIntervalName === "once") {
      return;
    }
 
    const nextRenewal = calculateNextRenewalDate(
      baseDate,
      item.recurringIntervalName,
    );
 
    if (
      nextRenewal &&
      (!closestDate || compareAsc(nextRenewal, closestDate) < 0)
    ) {
      closestDate = nextRenewal;
    }
  });
 
  if (closestDate) {
    return format(closestDate, "MM/dd/yyyy");
  }
  return undefined;
};
 
export interface StyledText {
  content: string;
  style?: Record<string, string>;
}
 
const extractParagraphs = (html: string): Array<StyledText> => {
  const parser = new DOMParser();
  const doc = parser.parseFromString(html, "text/html");
 
  // Find all paragraph elements
  const paragraphs: Array<StyledText> = [];
  const pElements = doc.getElementsByTagName("p");
 
  for (let i = 0; i < pElements.length; i++) {
    const p = pElements[i];
 
    // Process each child node in the paragraph
    for (let j = 0; j < p.childNodes.length; j++) {
      const node = p.childNodes[j];
 
      if (node.nodeType === 3) {
        // TEXT_NODE
        // Plain text
        paragraphs.push({ content: node.textContent || "" });
      } else if (node.nodeType === 1) {
        // ELEMENT_NODE
        const element = node as Element;
        if (element.nodeName.toLowerCase() === "span") {
          const styleAttr = element.getAttribute("style");
          const styleObj = parseStyle(styleAttr || "");
 
          paragraphs.push({
            content: element.textContent || "",
            style: styleObj,
          });
        }
      }
    }
  }
 
  return paragraphs;
};
 
// Helper to parse style string into object
const parseStyle = (styleString: string): Record<string, string> => {
  const result: Record<string, string> = {};
 
  if (!styleString) return result;
 
  styleString.split(";").forEach((item) => {
    const [key, value] = item.split(":").map((s) => s.trim());
    if (key && value) {
      // Convert CSS property names to camelCase
      const camelKey = key.replace(/-([a-z])/g, (g) => g[1].toUpperCase());
      result[camelKey] = value;
    }
  });
 
  return result;
};
 
const getHTMLFromWysiwyg = ({ logo }: { logo: string }) => {
  const parsed = safeParse(logo as string);
  if (parsed?.blocks) {
    const markup = draftToHtml(parsed);
    return markup;
  }
};
 
const isLogoMediaItem = (logo: MediaItem | string): logo is MediaItem => {
  return (
    typeof logo !== "string" && Object.keys(logo).length > 0 && isUrl(logo.URL)
  );
};
 
// Character width approximation (relative to a standard character)
const getCharacterWidth = (char: string): number => {
  // Uppercase letters (some are wider)
  if (/[MWQG]/.test(char)) return 1.2;
  if (/[A-Z]/.test(char)) return 1.0;
 
  // Lowercase letters (some are wider, some narrower)
  if (/[mw]/.test(char)) return 1.1;
  if (/[aeiouvxyz]/.test(char)) return 0.7;
  if (/[a-z]/.test(char)) return 0.8;
 
  // Numbers have consistent width
  if (/[0-9]/.test(char)) return 0.9;
 
  // Special characters
  if (/[\s]/.test(char)) return 0.5; // Space
  if (/[!,.:;'"`()]/.test(char)) return 0.4; // Narrow punctuation
  if (/[@#$%^&*\-+=\\|/<>?~]/.test(char)) return 1.0; // Wider symbols
 
  // Default for any other character
  return 1.0;
};
 
// Calculate the approximate width of a string
const calculateStringWidth = (text: string): number => {
  return text
    .split("")
    .reduce((total, char) => total + getCharacterWidth(char), 0);
};
 
// Custom hyphenation callback that forces text onto two lines with ellipsis only on second line
const hyphenationCallback = (word: string) => {
  // For short words, don't hyphenate
  if (word.length < 15) {
    return [word];
  }
 
  // Maximum width for first and second lines (in relative character width units)
  const maxFirstLineWidth = 35; // Adjust based on your container width
  const maxSecondLineWidth = 25; // Slightly less for second line to account for ellipsis
 
  // Find the optimal split point based on character widths
  let firstLine = "";
  let currentWidth = 0;
  let splitIndex = 0;
 
  // Build the first line until we reach the max width
  for (let i = 0; i < word.length; i++) {
    const charWidth = getCharacterWidth(word[i]);
    if (currentWidth + charWidth > maxFirstLineWidth) {
      splitIndex = i;
      break;
    }
    currentWidth += charWidth;
    firstLine += word[i];
    splitIndex = i + 1;
  }
 
  // If we couldn't fit even one character, force at least one
  if (splitIndex === 0) {
    splitIndex = 1;
    firstLine = word[0];
  }
 
  // Get the second line (no ellipsis on first line as requested)
  let secondLine = word.substring(splitIndex);
 
  // Check if second line needs truncation
  if (calculateStringWidth(secondLine) > maxSecondLineWidth) {
    // Truncate the second line
    let truncatedSecondLine = "";
    currentWidth = 0;
 
    for (let i = 0; i < secondLine.length; i++) {
      const charWidth = getCharacterWidth(secondLine[i]);
      if (currentWidth + charWidth > maxSecondLineWidth - 3) {
        // Reserve space for ellipsis
        truncatedSecondLine += "...";
        break;
      }
      currentWidth += charWidth;
      truncatedSecondLine += secondLine[i];
    }
 
    secondLine = truncatedSecondLine;
  }
 
  return [firstLine, secondLine];
};
 
export {
  getClosestRenewalDate,
  extractParagraphs,
  getHTMLFromWysiwyg,
  isLogoMediaItem,
  hyphenationCallback,
};