import { Utils as QbUtils, type ImmutableTree, } from "@react-awesome-query-builder/ui"; import type { AlertQueryField, AlertQueryOperator } from "./types"; import { ALERT_QUERY_FIELDS, ALL_NUMERIC_OPERATORS, BOOLEAN_OPERATORS, OPERATOR_LABELS, } from "./config"; export function longestOf(labels: string[]): string { return labels.reduce((a, b) => (a.length >= b.length ? a : b), ""); } export function allOperatorLabels(fields: AlertQueryField[]): string[] { const ops = new Set(); for (const f of fields) { const fieldOps = f.type === "boolean" ? BOOLEAN_OPERATORS : (f.operators ?? ALL_NUMERIC_OPERATORS); fieldOps.forEach((op) => ops.add(op)); } return Array.from(ops).map((op) => OPERATOR_LABELS[op]); } export function formatWithCommas(raw: string): string { if (!raw) return ""; const [int, dec] = raw.split("."); const formatted = int.replace(/\B(?=(\d{3})+(?!\d))/g, ","); return dec !== undefined ? `${formatted}.${dec}` : formatted; } export function parseCommas(display: string): string { return display.replace(/[^\d.]/g, "").replace(/(\..*)\./g, "$1"); } export function ruleSummary( // eslint-disable-next-line @typescript-eslint/no-explicit-any ruleProps: any, fields: AlertQueryField[], ): string { const field: string = ruleProps?.field ?? ""; const operator: string = ruleProps?.operator ?? "equal"; const value0 = ruleProps?.value?.[0]; const fieldDef = fields.find((f) => f.key === field); const fieldLabel = fieldDef?.label ?? field; const opLabel = OPERATOR_LABELS[operator as AlertQueryOperator] ?? operator; const formatVal = (v: unknown): string => { if (v === null || v === undefined) return "…"; if (fieldDef?.type === "boolean") return v ? "Yes" : "No"; const n = typeof v === "number" ? v : parseFloat(String(v)); if (!isFinite(n)) return "…"; if (fieldDef?.unit === "dollar") return `$${formatWithCommas(n.toString())}`; if (fieldDef?.unit === "percent") return `${n}%`; return String(v); }; return `${fieldLabel} ${opLabel} ${formatVal(value0)}`; } // eslint-disable-next-line @typescript-eslint/no-explicit-any function checkGroupValid(children: any[]): boolean { return children.some((child) => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const c = child as any; if (c.type === "rule") { const field: string | undefined = c.properties?.field; if (!field) return false; const fieldDef = ALERT_QUERY_FIELDS.find((f) => f.key === field); if (fieldDef?.type === "boolean") return true; const v = c.properties?.value?.[0]; return v !== null && v !== undefined; } if (c.type === "group") return checkGroupValid(c.children1 ?? []); return false; }); } export function isTreeValid(tree: ImmutableTree): boolean { // eslint-disable-next-line @typescript-eslint/no-explicit-any const json = QbUtils.getTree(tree) as any; return checkGroupValid(json?.children1 ?? []); }