From db1a2f35314209be58d501887855d6cc45c369e1 Mon Sep 17 00:00:00 2001 From: mortezaei Date: Sat, 31 Oct 2026 12:55:06 +0330 Subject: [PATCH] fix(questions): remove title heuristics for dataset injection and ignore stale unmatched option IDs --- .../[slug]/question-detail-client.tsx | 27 ++ .../Componentes/question-dropdown.tsx | 36 +- .../Componentes/question-sheet.test.tsx | 85 +++++ src/components/Componentes/question-sheet.tsx | 308 +++++++++--------- 4 files changed, 292 insertions(+), 164 deletions(-) diff --git a/src/app/questions-list/[slug]/question-detail-client.tsx b/src/app/questions-list/[slug]/question-detail-client.tsx index 053bcf3..4f35d50 100644 --- a/src/app/questions-list/[slug]/question-detail-client.tsx +++ b/src/app/questions-list/[slug]/question-detail-client.tsx @@ -231,6 +231,33 @@ function QuestionFlowWrapper({ isAnswered = Boolean(parsed.country?.trim() && parsed.city?.trim()); } else if (question.type === "checkbox") { isAnswered = Array.isArray(answer) ? answer.length > 0 : hasAnswer; + } else if ( + (question.type === "dropdown" || + question.type === "select" || + question.type === "choice") && + question.options && + question.options.length > 0 && + !question.ui_config?.dataset && + question.id !== "personal_identity.mother_tongue" && + question.id !== "personal_info.mother_tongue" && + question.id !== "personal_identity.current_nationality_citizenship" && + question.id !== "personal_info.country_of_birth" + ) { + const matchesValidOption = (val: string) => { + const norm = String(val || "").toLowerCase().trim(); + if (!norm) return false; + return question.options.some( + (o) => + o.id === val || + o.id.toLowerCase() === norm || + String(o.value).toLowerCase() === norm || + o.label.toLowerCase().trim() === norm || + o.id.toLowerCase().endsWith(`.${norm}`), + ); + }; + isAnswered = Array.isArray(answer) + ? answer.some((item) => matchesValidOption(String(item))) + : matchesValidOption(String(answer)); } } diff --git a/src/components/Componentes/question-dropdown.tsx b/src/components/Componentes/question-dropdown.tsx index d239368..01b88c3 100644 --- a/src/components/Componentes/question-dropdown.tsx +++ b/src/components/Componentes/question-dropdown.tsx @@ -36,12 +36,34 @@ export function QuestionDropdown({ question.ui_config?.max_select || (question.validation?.max ? Number(question.validation.max) : undefined); - const selectedList = Array.isArray(rawValue) - ? rawValue - : typeof rawValue === "string" && rawValue - ? [rawValue] - : []; - const singleValue = typeof rawValue === "string" ? rawValue : ""; + const options = question.options || []; + + const isOptionValid = useCallback( + (optId: string) => { + if (!optId || typeof optId !== "string" || !optId.trim()) return false; + if (options.length === 0) return true; + const normalized = optId.toLowerCase().trim(); + return options.some( + (o) => + o.id === optId || + o.id.toLowerCase() === normalized || + String(o.value ?? "").toLowerCase() === normalized || + o.label.toLowerCase().trim() === normalized || + o.id.toLowerCase().endsWith(`.${normalized}`), + ); + }, + [options], + ); + + const selectedList = ( + Array.isArray(rawValue) + ? rawValue + : typeof rawValue === "string" && rawValue + ? [rawValue] + : [] + ).filter((item) => isOptionValid(String(item))); + const singleValue = + typeof rawValue === "string" && isOptionValid(rawValue) ? rawValue : ""; const [isOpen, setIsOpen] = useState(false); const [searchQuery, setSearchQuery] = useState(""); @@ -107,8 +129,6 @@ export function QuestionDropdown({ } }, [isOpen]); - const options = question.options || []; - const showSearch = (() => { if (question.extras?.noSearch) return false; return options.length > 10; diff --git a/src/components/Componentes/question-sheet.test.tsx b/src/components/Componentes/question-sheet.test.tsx index 39645fa..1fe89aa 100644 --- a/src/components/Componentes/question-sheet.test.tsx +++ b/src/components/Componentes/question-sheet.test.tsx @@ -1278,8 +1278,93 @@ describe("QuestionSheet component", () => { expect(screen.queryByRole("button", { name: "Afghanistan" })).toBeNull(); expect(screen.queryByPlaceholderText("جستجو...")).toBeNull(); }); + + it("ignores stale/invalid option slugs (e.g. .chile from previous bug) and renders placeholder instead of raw slug", async () => { + const { useI18n } = await import("@/translations/provider"); + (useI18n as any).mockReturnValue({ + locale: "fa", + dictionary: { Confirm: "تایید" }, + }); + + const { useMarriageSectionDataQuery } = await import("@/hooks/marriage/use-section-data"); + (useMarriageSectionDataQuery as any).mockReturnValue({ + data: { + data: [ + { + key: "beliefs_lifestyle.political_stance_towards_governance", + label: "موضع کلی شما نسبت به حکومت مستقر در کشور محل زندگی‌تان چیست؟", + type: "dropdown", + value: "beliefs_lifestyle.political_stance_towards_governance.chile", + option_id: "beliefs_lifestyle.political_stance_towards_governance.chile", + }, + ], + version: 1, + }, + isLoading: false, + }); + + const politicalQuestionFa: QuestionField = { + id: "beliefs_lifestyle.political_stance_towards_governance", + title: "موضع کلی شما نسبت به حکومت مستقر در کشور محل زندگی‌تان چیست؟", + type: "dropdown", + order: 10, + required: false, + baseRequired: false, + isVisible: true, + private: true, + description: "", + tooltip: "", + ui_config: { + private: true, + noSearch: false, + placeholder_en: "Select one option", + placeholder_fa: "یک گزینه را انتخاب کنید", + }, + extras: { + placeHolder: "یک گزینه را انتخاب کنید", + range: [0, 0], + options: [], + noSearch: false, + }, + options: [ + { + id: "beliefs_lifestyle.political_stance_towards_governance.strongly_supportive", + value: "strongly_supportive", + label: "قویاً موافق و حامی هستم", + order: 1, + }, + { + id: "beliefs_lifestyle.political_stance_towards_governance.generally_supportive_with_critiques", + value: "generally_supportive_with_critiques", + label: "در مجموع موافقم، اما نقدهای مشخصی دارم", + order: 2, + }, + ], + }; + + render( + + + + + , + ); + + // Must show placeholder, NOT "...cal_stance_towards_governance.chile" + expect(screen.getByRole("button", { name: "یک گزینه را انتخاب کنید" })).toBeDefined(); + expect( + screen.queryByText(/political_stance_towards_governance\.chile/i), + ).toBeNull(); + + // Reset mock for any subsequent tests + (useMarriageSectionDataQuery as any).mockReturnValue({ + data: undefined, + isLoading: false, + }); + }); }); + diff --git a/src/components/Componentes/question-sheet.tsx b/src/components/Componentes/question-sheet.tsx index 933f839..57d0452 100644 --- a/src/components/Componentes/question-sheet.tsx +++ b/src/components/Componentes/question-sheet.tsx @@ -108,158 +108,17 @@ export function QuestionSheet({ question, disabled }: QuestionSheetProps) { question.ui_config?.max_select || (question.validation?.max ? Number(question.validation.max) : undefined); - const selectedList = useMemo(() => { - if (Array.isArray(rawValue)) return rawValue; - if (typeof rawValue === "string" && rawValue) return [rawValue]; - return EMPTY_ARRAY; - }, [rawValue]); - const singleValue = typeof rawValue === "string" ? rawValue : ""; - - const [isOpen, setIsOpen] = useState(false); - const [isClosing, setIsClosing] = useState(false); - const [searchQuery, setSearchQuery] = useState(""); - const listRef = useRef(null); - const headerRef = useRef(null); - const sheetRef = useRef(null); - const sheetSizeRef = useRef(SHEET_INITIAL_SIZE); - const restingStateRef = useRef(SHEET_INITIAL_SIZE); - const [localSelectedList, setLocalSelectedList] = useState(selectedList); - const localSelectedListRef = useRef(selectedList); - - useEffect(() => { - localSelectedListRef.current = localSelectedList; - }, [localSelectedList]); - - useEffect(() => { - if (!isOpen) { - setLocalSelectedList(selectedList); - localSelectedListRef.current = selectedList; - } - }, [isOpen, selectedList]); - - const closeSheet = useCallback(() => { - setIsClosing(true); - if (isMulti) { - const currentList = localSelectedListRef.current; - const trimmedList = - maxSelect && currentList.length > maxSelect - ? currentList.slice(0, maxSelect) - : currentList; - setAnswerValue( - question, - trimmedList.length > 0 ? trimmedList : null, - ); - } - window.setTimeout(() => { - setIsOpen(false); - setIsClosing(false); - setSearchQuery(""); - }, EXIT_ANIMATION_MS); - }, [isMulti, maxSelect, question, setAnswerValue]); - - const openSheet = useCallback(() => { - if (disabled) return; - sheetSizeRef.current = SHEET_INITIAL_SIZE; - restingStateRef.current = SHEET_INITIAL_SIZE; - if (sheetRef.current) { - sheetRef.current.style.transition = ""; - sheetRef.current.style.setProperty( - "--sheet-size", - SHEET_INITIAL_SIZE.toFixed(4), - ); - } - setLocalSelectedList(selectedList); - localSelectedListRef.current = selectedList; - setIsOpen(true); - setIsClosing(false); - }, [disabled, selectedList]); - - useEffect(() => { - if (isOpen) { - sheetSizeRef.current = SHEET_INITIAL_SIZE; - restingStateRef.current = SHEET_INITIAL_SIZE; - if (sheetRef.current) { - sheetRef.current.style.transition = ""; - sheetRef.current.style.setProperty( - "--sheet-size", - SHEET_INITIAL_SIZE.toFixed(4), - ); - } - } - }, [isOpen]); - - useSheetScrollLock(isOpen, { onBack: closeSheet }); - - // Handle escape key - useEffect(() => { - if (!isOpen) return; - - const handleKeyDown = (e: KeyboardEvent) => { - if (e.key === "Escape") { - closeSheet(); - } - }; - - window.addEventListener("keydown", handleKeyDown); - return () => window.removeEventListener("keydown", handleKeyDown); - }, [isOpen, closeSheet]); - - const isExcludedFromAutoDatasets = - question.id?.toLowerCase().includes("representative") || - question.id?.toLowerCase().includes("relationship") || - question.id?.toLowerCase().includes("residence_status") || - question.id?.toLowerCase().includes("status") || - question.id?.toLowerCase().includes("responsibility") || - question.id?.toLowerCase().includes("difference") || - question.id?.toLowerCase().includes("impact") || - question.id?.toLowerCase().includes("political") || - question.id?.toLowerCase().includes("governance") || - question.id?.toLowerCase().includes("stance") || - question.id?.toLowerCase().includes("government"); - - const hasStructuredBackendId = Boolean(question.id?.includes(".")); - const isLanguageQuestion = Boolean( question.ui_config?.dataset === "languages" || - question.id?.endsWith(".mother_tongue") || - question.id?.endsWith(".native_language") || - question.id?.endsWith(".other_languages") || - question.id?.endsWith(".languages") || - question.id?.endsWith(".language") || - (!hasStructuredBackendId && - !isExcludedFromAutoDatasets && - Boolean( - question.title?.toLowerCase().includes("mother tongue") || - question.title?.toLowerCase().includes("native language") || - question.title?.toLowerCase() === "language" || - question.title?.toLowerCase() === "languages" || - question.title?.includes("زبان مادری") || - question.title?.includes("زبان‌های مسلط") || - question.title?.includes("زبان های مسلط") - )) + question.id === "personal_identity.mother_tongue" || + question.id === "personal_info.mother_tongue", ); const isCountryQuestion = Boolean( - !isExcludedFromAutoDatasets && - (question.ui_config?.dataset === "countries" || - question.ui_config?.dataset === "nationalities" || - question.id?.includes("nationality") || - question.id?.includes("citizenship") || - question.id?.includes("country_of_") || - question.id?.endsWith(".birthplace") || - question.id?.endsWith(".current_residence") || - question.id?.endsWith(".country") || - (!hasStructuredBackendId && - !question.title?.includes("؟") && - !question.title?.includes("?") && - Boolean( - question.title?.toLowerCase().includes("nationality") || - question.title?.toLowerCase().includes("citizenship") || - question.title?.toLowerCase().includes("country") || - question.title?.includes("تابعیت") || - question.title?.includes("ملیت") || - question.title?.includes("کشور") - ))) + question.ui_config?.dataset === "countries" || + question.ui_config?.dataset === "nationalities" || + question.id === "personal_identity.current_nationality_citizenship" || + question.id === "personal_info.country_of_birth", ); const options = useMemo(() => { @@ -389,6 +248,147 @@ export function QuestionSheet({ question, disabled }: QuestionSheetProps) { })); }, [question, isLanguageQuestion, isCountryQuestion, locale, t]); + const findMatchingOption = useCallback( + (optId: string) => { + const normalized = String(optId || "").toLowerCase().trim(); + if (!normalized) return undefined; + return options.find( + (o) => + o.id === optId || + o.id.toLowerCase() === normalized || + String(o.value).toLowerCase() === normalized || + o.label.toLowerCase().trim() === normalized || + o.id.toLowerCase().endsWith(`.${normalized}`), + ); + }, + [options], + ); + + const isOptionSelectionValid = useCallback( + (optId: string) => { + if (!optId || typeof optId !== "string" || !optId.trim()) return false; + if (options.length === 0) return true; + if (findMatchingOption(optId)) return true; + if (isLanguageQuestion) { + const resolved = resolveLanguageName(optId, locale); + return Boolean(resolved && resolved !== optId); + } + if (isCountryQuestion) { + const resolved = resolveCountryName(optId, locale); + return Boolean(resolved && resolved !== optId); + } + return false; + }, + [options.length, findMatchingOption, isLanguageQuestion, isCountryQuestion, locale], + ); + + const selectedList = useMemo(() => { + const rawList = Array.isArray(rawValue) + ? rawValue + : typeof rawValue === "string" && rawValue + ? [rawValue] + : EMPTY_ARRAY; + if (rawList.length === 0) return EMPTY_ARRAY; + const validList = rawList.filter((item) => + isOptionSelectionValid(String(item)), + ); + return validList.length > 0 ? validList : EMPTY_ARRAY; + }, [rawValue, isOptionSelectionValid]); + + const singleValue = + typeof rawValue === "string" && isOptionSelectionValid(rawValue) + ? rawValue + : ""; + + const [isOpen, setIsOpen] = useState(false); + const [isClosing, setIsClosing] = useState(false); + const [searchQuery, setSearchQuery] = useState(""); + const listRef = useRef(null); + const headerRef = useRef(null); + const sheetRef = useRef(null); + const sheetSizeRef = useRef(SHEET_INITIAL_SIZE); + const restingStateRef = useRef(SHEET_INITIAL_SIZE); + const [localSelectedList, setLocalSelectedList] = useState(selectedList); + const localSelectedListRef = useRef(selectedList); + + useEffect(() => { + localSelectedListRef.current = localSelectedList; + }, [localSelectedList]); + + useEffect(() => { + if (!isOpen) { + setLocalSelectedList(selectedList); + localSelectedListRef.current = selectedList; + } + }, [isOpen, selectedList]); + + const closeSheet = useCallback(() => { + setIsClosing(true); + if (isMulti) { + const currentList = localSelectedListRef.current; + const trimmedList = + maxSelect && currentList.length > maxSelect + ? currentList.slice(0, maxSelect) + : currentList; + setAnswerValue( + question, + trimmedList.length > 0 ? trimmedList : null, + ); + } + window.setTimeout(() => { + setIsOpen(false); + setIsClosing(false); + setSearchQuery(""); + }, EXIT_ANIMATION_MS); + }, [isMulti, maxSelect, question, setAnswerValue]); + + const openSheet = useCallback(() => { + if (disabled) return; + sheetSizeRef.current = SHEET_INITIAL_SIZE; + restingStateRef.current = SHEET_INITIAL_SIZE; + if (sheetRef.current) { + sheetRef.current.style.transition = ""; + sheetRef.current.style.setProperty( + "--sheet-size", + SHEET_INITIAL_SIZE.toFixed(4), + ); + } + setLocalSelectedList(selectedList); + localSelectedListRef.current = selectedList; + setIsOpen(true); + setIsClosing(false); + }, [disabled, selectedList]); + + useEffect(() => { + if (isOpen) { + sheetSizeRef.current = SHEET_INITIAL_SIZE; + restingStateRef.current = SHEET_INITIAL_SIZE; + if (sheetRef.current) { + sheetRef.current.style.transition = ""; + sheetRef.current.style.setProperty( + "--sheet-size", + SHEET_INITIAL_SIZE.toFixed(4), + ); + } + } + }, [isOpen]); + + useSheetScrollLock(isOpen, { onBack: closeSheet }); + + // Handle escape key + useEffect(() => { + if (!isOpen) return; + + const handleKeyDown = (e: KeyboardEvent) => { + if (e.key === "Escape") { + closeSheet(); + } + }; + + window.addEventListener("keydown", handleKeyDown); + return () => window.removeEventListener("keydown", handleKeyDown); + }, [isOpen, closeSheet]); + const noSearch = Boolean( !isLanguageQuestion && !isCountryQuestion && @@ -687,20 +687,16 @@ export function QuestionSheet({ question, disabled }: QuestionSheetProps) { }, [options, searchQuery, isLanguageQuestion, isCountryQuestion, locale]); const getCleanLabel = (optId: string) => { - const normalized = String(optId || "").toLowerCase().trim(); - const opt = options.find( - (o) => - o.id === optId || - o.id.toLowerCase() === normalized || - String(o.value).toLowerCase() === normalized || - o.label.toLowerCase().trim() === normalized || - o.id.endsWith(`.${normalized}`), - ); + const opt = findMatchingOption(optId); if (!opt) { if (isLanguageQuestion) { const resolved = resolveLanguageName(optId, locale); if (resolved && resolved !== optId) return resolved; } + if (isCountryQuestion) { + const resolved = resolveCountryName(optId, locale); + if (resolved && resolved !== optId) return resolved; + } return optId; } return opt.label.split(" - ")[0];