All files / src/features/TransactionPanel/helpers normalizeCustomFieldsSnapshot.ts

100% Statements 10/10
100% Branches 10/10
100% Functions 3/3
100% Lines 9/9

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                      54x         54x 15x   25x                               54x     94x   15x 1x     14x            
import {
  CustomFieldSnapshotItem,
  TCustomFieldsSnapshot,
} from "@components/ManageMoney/TransactionTable/transactions.types";
 
export interface NormalizedCustomFieldsSnapshot {
  /** Empty when the snapshot carries no title — callers apply their own default. */
  sectionTitle: string;
  answers: CustomFieldSnapshotItem[];
}
 
const EMPTY_SNAPSHOT: NormalizedCustomFieldsSnapshot = {
  sectionTitle: "",
  answers: [],
};
 
const toAnswerList = (answers: unknown): CustomFieldSnapshotItem[] =>
  Array.isArray(answers)
    ? (answers.filter(
        (answer) => Boolean(answer) && typeof answer === "object",
      ) as CustomFieldSnapshotItem[])
    : [];
 
/**
 * `transactions.customFieldsSnapshot` is a JSONB column whose shape changed:
 * it used to be a bare answers array and now is an object that freezes the
 * merchant's Section Title together with the answers (GB-21559).
 *
 * The panel spread the raw value to sort it, so once the BE started serving the
 * object shape every transaction that captured custom fields threw
 * "snapshot is not iterable" and took the whole side panel down with the
 * "Technical Difficulties" fallback (GB-21600).
 *
 * @returns The answers and the frozen section title, whichever shape came in.
 */
export const normalizeCustomFieldsSnapshot = (
  snapshot?: TCustomFieldsSnapshot | null,
): NormalizedCustomFieldsSnapshot => {
  if (!snapshot) return EMPTY_SNAPSHOT;
 
  if (Array.isArray(snapshot)) {
    return { sectionTitle: "", answers: toAnswerList(snapshot) };
  }
 
  return {
    sectionTitle:
      typeof snapshot.sectionTitle === "string" ? snapshot.sectionTitle : "",
    answers: toAnswerList(snapshot.answers),
  };
};