import type { CreateFlowState } from "../../app/(app)/create/types"; import { KINDS, type Kind } from "./deckTypes"; import { groupAnswersFromCreateFlowState } from "./groupAnswers"; const LOCATION_MAX = 200; function isKind(value: string): value is Kind { return (KINDS as readonly string[]).includes(value); } function trimmedLocation(raw: unknown): string | undefined { if (typeof raw !== "string") return undefined; const trimmed = raw.trim().replace(/\s+/g, " "); if (trimmed.length === 0) return undefined; return trimmed.slice(0, LOCATION_MAX); } /** Place and main group type stored on a finished Rule for launch counts. */ export function publishedRuleAnalyticsFromState(state: CreateFlowState): { communityLocation?: string; orgType?: Kind; } { const communityLocation = trimmedLocation(state.communityLocation); const orgType = groupAnswersFromCreateFlowState(state).mainKind ?? undefined; return { ...(communityLocation ? { communityLocation } : {}), ...(orgType ? { orgType } : {}), }; } export function publishedRuleAnalyticsFromDocument(document: unknown): { communityLocation: string | null; orgType: string | null; } { if (!document || typeof document !== "object" || Array.isArray(document)) { return { communityLocation: null, orgType: null }; } const row = document as Record; const communityLocation = trimmedLocation(row.communityLocation) ?? null; const orgTypeRaw = typeof row.orgType === "string" ? row.orgType.trim() : ""; const orgType = isKind(orgTypeRaw) ? orgTypeRaw : null; return { communityLocation, orgType }; }