diff --git a/src/components/modules/ModuleBuilderTab.tsx b/src/components/modules/ModuleBuilderTab.tsx index 647f2e9..b6888b8 100644 --- a/src/components/modules/ModuleBuilderTab.tsx +++ b/src/components/modules/ModuleBuilderTab.tsx @@ -15,22 +15,22 @@ import { import { ErrorBoundary } from '../common/ErrorBoundary'; const COMMON_TONGUE_SUGGESTIONS = [ - 'Pale and Thin.', - 'Purple.', - 'Normal.', - 'Red with yellow coat.', - 'Pale with tooth marks.', - 'Slightly Red sides or normal.', + 'Pale and Thin', + 'Purple', + 'Normal', + 'Red with yellow coat', + 'Pale with tooth marks', + 'Slightly Red sides or normal', ]; const COMMON_PULSE_SUGGESTIONS = [ - 'Choppy.', - 'Wiry.', - 'Deep and Wiry.', - 'Deep and Weak.', - 'Choppy or Fine.', - 'Rapid and Slippery.', - 'Floating.', + 'Choppy', + 'Wiry', + 'Deep and Wiry', + 'Deep and Weak', + 'Choppy or Fine', + 'Rapid and Slippery', + 'Floating', ]; const COMMON_POINT_SUGGESTIONS = [ @@ -66,6 +66,22 @@ const formatApiError = (err: any, fallback: string): string => { return String(detail); }; +const normalizeTreatmentPrinciple = (val: string[] | string | undefined): string[] => { + if (Array.isArray(val)) { + const cleaned = val.map((v) => String(v || '').trim()).filter(Boolean); + return cleaned.length > 0 ? cleaned : ['']; + } + const s = String(val || '').trim(); + return s ? [s] : ['']; +}; + +const suggestHyphenatedPoint = (raw: string): string | null => { + const cleaned = raw.trim().toUpperCase(); + const match = cleaned.match(/^([A-Z]{1,4})\s+(\d+[A-Z]?)$/) || cleaned.match(/^([A-Z]{1,4})(\d+[A-Z]?)$/); + if (!match) return null; + return `${match[1]}-${match[2]}`; +}; + const createBlankPattern = (moduleCode: string, catCode: string, disCode: string): BuilderPattern => ({ module_code: moduleCode, category_code: catCode, @@ -77,7 +93,7 @@ const createBlankPattern = (moduleCode: string, catCode: string, disCode: string clinical_manifestations: [''], tongue: '', pulse: '', - treatment_principle: '', + treatment_principle: [''], acupuncture: { points: '', method: '' }, explanation: [''], }, @@ -132,8 +148,11 @@ export const ModuleBuilderTabContent: React.FC = () => { const [newDiseaseName, setNewDiseaseName] = useState(''); const [modalDisError, setModalDisError] = useState(null); - // Point input state + // Chip & Point input state const [customPointInput, setCustomPointInput] = useState(''); + const [customTongueInput, setCustomTongueInput] = useState(''); + const [customPulseInput, setCustomPulseInput] = useState(''); + const [pendingPointSuggestion, setPendingPointSuggestion] = useState<{ raw: string; suggested: string } | null>(null); // 0. Load Modules List const fetchModules = async (selectCode?: string) => { @@ -262,7 +281,7 @@ export const ModuleBuilderTabContent: React.FC = () => { : [''], tongue: p.clinical_data?.tongue || '', pulse: p.clinical_data?.pulse || '', - treatment_principle: p.clinical_data?.treatment_principle || '', + treatment_principle: normalizeTreatmentPrinciple(p.clinical_data?.treatment_principle), acupuncture: { points: p.clinical_data?.acupuncture?.points || '', method: p.clinical_data?.acupuncture?.method || '', @@ -488,7 +507,7 @@ export const ModuleBuilderTabContent: React.FC = () => { clinical_manifestations: [''], tongue: '', pulse: '', - treatment_principle: '', + treatment_principle: [''], acupuncture: { points: '', method: '' }, explanation: [''], }, @@ -546,24 +565,143 @@ export const ModuleBuilderTabContent: React.FC = () => { })); }; + // Treatment Principle Row Helpers + const activePrinciples = Array.isArray(activePattern?.clinical_data?.treatment_principle) + ? activePattern.clinical_data.treatment_principle + : normalizeTreatmentPrinciple(activePattern?.clinical_data?.treatment_principle); + + const handlePrincipleChange = (pIdx: number, val: string) => { + updateActivePattern(p => { + const list = Array.isArray(p.clinical_data?.treatment_principle) + ? [...p.clinical_data.treatment_principle] + : normalizeTreatmentPrinciple(p.clinical_data?.treatment_principle); + list[pIdx] = val; + return { + ...p, + clinical_data: { ...p.clinical_data, treatment_principle: list }, + }; + }); + }; + + const handleAddPrinciple = () => { + updateActivePattern(p => { + const list = Array.isArray(p.clinical_data?.treatment_principle) + ? p.clinical_data.treatment_principle + : normalizeTreatmentPrinciple(p.clinical_data?.treatment_principle); + return { + ...p, + clinical_data: { + ...p.clinical_data, + treatment_principle: [...list, ''], + }, + }; + }); + }; + + const handleRemovePrinciple = (pIdx: number) => { + updateActivePattern(p => { + const list = Array.isArray(p.clinical_data?.treatment_principle) + ? p.clinical_data.treatment_principle + : normalizeTreatmentPrinciple(p.clinical_data?.treatment_principle); + return { + ...p, + clinical_data: { + ...p.clinical_data, + treatment_principle: list.filter((_, i) => i !== pIdx), + }, + }; + }); + }; + + // Tongue & Pulse Chips Helpers + const parseCommaChips = (val?: string) => + (val || '') + .split(',') + .map(s => s.trim().replace(/\.+$/, '')) + .filter(Boolean); + + const currentTongueChips = parseCommaChips(activePattern?.clinical_data?.tongue); + const currentPulseChips = parseCommaChips(activePattern?.clinical_data?.pulse); + + const handleAddDiagnosisChip = (field: 'tongue' | 'pulse', raw: string) => { + const parts = raw + .split(',') + .map(s => s.trim().replace(/\.+$/, '')) + .filter(Boolean); + if (parts.length === 0) return; + + const existing = field === 'tongue' ? currentTongueChips : currentPulseChips; + const merged = [...existing]; + let addedAny = false; + for (const part of parts) { + if (!merged.some(item => item.toLowerCase() === part.toLowerCase())) { + merged.push(part); + addedAny = true; + } + } + if (!addedAny) { + setError(`${field === 'tongue' ? 'Tongue' : 'Pulse'} finding "${parts[0]}" is already selected.`); + return; + } + setError(null); + updateActivePattern(p => ({ + ...p, + clinical_data: { ...p.clinical_data, [field]: merged.join(', ') }, + })); + if (field === 'tongue') setCustomTongueInput(''); + else setCustomPulseInput(''); + }; + + const handleRemoveDiagnosisChip = (field: 'tongue' | 'pulse', chipToRemove: string) => { + const existing = field === 'tongue' ? currentTongueChips : currentPulseChips; + const updated = existing.filter(c => c !== chipToRemove).join(', '); + updateActivePattern(p => ({ + ...p, + clinical_data: { ...p.clinical_data, [field]: updated }, + })); + }; + // Point Chips Helpers (100% Safe Optional Chaining) const currentPoints = (activePattern?.clinical_data?.acupuncture?.points || '') .split(',') .map(s => s.trim()) .filter(Boolean); - const handleAddPointChip = (point: string) => { - const trimmed = point.trim().toUpperCase(); - if (!trimmed) { - setError('Please enter a valid acupuncture point code (e.g. ST-36, RN-6).'); + const handleAddPointChip = (point: string, forceRaw = false) => { + const parts = point + .split(',') + .map(s => s.trim().toUpperCase()) + .filter(Boolean); + if (parts.length === 0) { + setError('Please enter an acupuncture point code (e.g. ST-36, RN-6).'); return; } - if (currentPoints.includes(trimmed)) { - setError(`Point "${trimmed}" is already added to this prescription.`); + + if (!forceRaw && parts.length === 1) { + const suggested = suggestHyphenatedPoint(parts[0]); + if (suggested && suggested !== parts[0]) { + setPendingPointSuggestion({ raw: parts[0], suggested }); + setError(null); + return; + } + } + + const merged = [...currentPoints]; + let addedAny = false; + for (const pt of parts) { + if (!merged.includes(pt)) { + merged.push(pt); + addedAny = true; + } + } + if (!addedAny) { + setError(`Point "${parts[0]}" is already added to this prescription.`); return; } + setError(null); - const updated = [...currentPoints, trimmed].join(', '); + setPendingPointSuggestion(null); + const updated = merged.join(', '); updateActivePattern(p => ({ ...p, clinical_data: { @@ -625,56 +763,104 @@ export const ModuleBuilderTabContent: React.FC = () => { // Save Full Disease & Patterns with Granular Validation const handleSaveFullDisease = async () => { + const showValidationError = (msg: string) => { + setError(msg); + window.scrollTo({ top: 0, behavior: 'smooth' }); + }; + if (!selectedCategoryCode) { - setError('Please select or create a Category before saving.'); + showValidationError('Please select or create a Category before saving.'); return; } const effectiveDiseaseName = diseaseName.trim(); if (!effectiveDiseaseName) { - setError('Please enter a Disease Name before saving.'); + showValidationError('Please enter a Disease Name before saving.'); return; } if (!patterns || patterns.length === 0) { - setError('A disease must contain at least one clinical pattern before saving.'); + showValidationError('A disease must contain at least one clinical pattern before saving.'); return; } + // Auto-commit any uncommitted chip inputs on the active pattern before validating + let patternsToSave = patterns; + if (customPointInput.trim()) { + const rawPt = customPointInput.trim().toUpperCase(); + const suggested = suggestHyphenatedPoint(rawPt); + if (suggested && suggested !== rawPt) { + setPendingPointSuggestion({ raw: rawPt, suggested }); + showValidationError( + `Please confirm whether to use "${suggested}" or keep "${rawPt}" in the Acupuncture Prescription before saving.`, + ); + return; + } + const pendingParts = rawPt.split(',').map(s => s.trim()).filter(Boolean); + const mergedPts = [...currentPoints]; + for (const pt of pendingParts) { + if (!mergedPts.includes(pt)) mergedPts.push(pt); + } + const nextPts = mergedPts.join(', '); + patternsToSave = patternsToSave.map((p, idx) => + idx === activePatternIndex + ? { ...p, clinical_data: { ...p.clinical_data, acupuncture: { points: nextPts, method: p.clinical_data?.acupuncture?.method || '' } } } + : p, + ); + setPatterns(patternsToSave); + setCustomPointInput(''); + } + if (customTongueInput.trim()) { + const nextTongue = [...currentTongueChips, ...parseCommaChips(customTongueInput)].join(', '); + patternsToSave = patternsToSave.map((p, idx) => + idx === activePatternIndex ? { ...p, clinical_data: { ...p.clinical_data, tongue: nextTongue } } : p, + ); + setPatterns(patternsToSave); + setCustomTongueInput(''); + } + if (customPulseInput.trim()) { + const nextPulse = [...currentPulseChips, ...parseCommaChips(customPulseInput)].join(', '); + patternsToSave = patternsToSave.map((p, idx) => + idx === activePatternIndex ? { ...p, clinical_data: { ...p.clinical_data, pulse: nextPulse } } : p, + ); + setPatterns(patternsToSave); + setCustomPulseInput(''); + } + // Validate Pattern Names & Duplicates const seenPatternNames = new Set(); - for (let i = 0; i < patterns.length; i++) { - const pName = patterns[i]?.name?.trim(); + for (let i = 0; i < patternsToSave.length; i++) { + const pName = patternsToSave[i]?.name?.trim(); if (!pName) { setActivePatternIndex(i); - setError(`Clinical Pattern #${i + 1} is missing a name. Please enter a pattern name.`); + showValidationError(`Clinical Pattern #${i + 1} is missing a name. Please enter a pattern name.`); return; } const lower = pName.toLowerCase(); if (seenPatternNames.has(lower)) { setActivePatternIndex(i); - setError(`Duplicate pattern name "${pName}". Each clinical pattern within a disease must have a distinct name.`); + showValidationError(`Duplicate pattern name "${pName}". Each clinical pattern within a disease must have a distinct name.`); return; } seenPatternNames.add(lower); } // Validate Symptoms exist - for (let i = 0; i < patterns.length; i++) { - const cleanSymptoms = (patterns[i].clinical_data?.clinical_manifestations || []).filter(s => s && s.trim().length > 0); + for (let i = 0; i < patternsToSave.length; i++) { + const cleanSymptoms = (patternsToSave[i].clinical_data?.clinical_manifestations || []).filter(s => s && s.trim().length > 0); if (cleanSymptoms.length === 0) { setActivePatternIndex(i); - setError(`Pattern "${patterns[i].name}" has no symptoms. Please enter at least one clinical symptom before saving.`); + showValidationError(`Pattern "${patternsToSave[i].name}" has no symptoms. Please enter at least one clinical symptom before saving.`); return; } } // Validate Points formula exist - for (let i = 0; i < patterns.length; i++) { - const pts = (patterns[i].clinical_data?.acupuncture?.points || '').trim(); + for (let i = 0; i < patternsToSave.length; i++) { + const pts = (patternsToSave[i].clinical_data?.acupuncture?.points || '').trim(); if (!pts) { setActivePatternIndex(i); - setError(`Pattern "${patterns[i].name}" has no acupuncture points. Please select or add at least one point before saving.`); + showValidationError(`Pattern "${patternsToSave[i].name}" has no acupuncture points. Please select or add at least one point before saving.`); return; } } @@ -698,7 +884,7 @@ export const ModuleBuilderTabContent: React.FC = () => { disease_code: effectiveDiseaseCode, name: effectiveDiseaseName, overview: diseaseOverview, - patterns: patterns.map((p, idx) => ({ + patterns: patternsToSave.map((p, idx) => ({ category_code: selectedCategoryCode, disease_code: effectiveDiseaseCode, pattern_code: toSnakeCase(p.name?.trim() || `pattern_${idx + 1}`), @@ -708,7 +894,13 @@ export const ModuleBuilderTabContent: React.FC = () => { clinical_manifestations: (p.clinical_data?.clinical_manifestations || []).filter(s => s && s.trim().length > 0), tongue: (p.clinical_data?.tongue || '').trim(), pulse: (p.clinical_data?.pulse || '').trim(), - treatment_principle: (p.clinical_data?.treatment_principle || '').trim(), + treatment_principle: ( + Array.isArray(p.clinical_data?.treatment_principle) + ? p.clinical_data.treatment_principle + : normalizeTreatmentPrinciple(p.clinical_data?.treatment_principle) + ) + .map(tp => tp.trim()) + .filter(Boolean), acupuncture: { points: (p.clinical_data?.acupuncture?.points || '').trim(), method: (p.clinical_data?.acupuncture?.method || '').trim(), @@ -1781,87 +1973,164 @@ export const ModuleBuilderTabContent: React.FC = () => { {/* Tongue */}
- - updateActivePattern(p => ({ - ...p, - clinical_data: { ...p.clinical_data, tongue: e.target.value }, - })) - } - placeholder="e.g. Pale and Thin." - className="w-full bg-slate-50 border border-slate-200 rounded-xl px-3 py-2 text-xs font-bold text-slate-800 focus:outline-none focus:border-indigo-500" - /> -
- {COMMON_TONGUE_SUGGESTIONS.map((t, idx) => ( - + {chip} + + ))} + setCustomTongueInput(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter' || e.key === ',') { + e.preventDefault(); + handleAddDiagnosisChip('tongue', customTongueInput); + } + }} + onBlur={() => { + if (customTongueInput.trim()) { + handleAddDiagnosisChip('tongue', customTongueInput); + } + }} + placeholder={currentTongueChips.length === 0 ? 'Type tongue finding and press Enter...' : '+ add...'} + className="flex-1 text-xs font-semibold text-slate-800 focus:outline-none bg-transparent min-w-[120px] px-1 py-0.5" + /> +
+
+ {COMMON_TONGUE_SUGGESTIONS.map((t, idx) => { + const isAdded = currentTongueChips.some(c => c.toLowerCase() === t.toLowerCase()); + return ( + + ); + })}
{/* Pulse */}
- - updateActivePattern(p => ({ - ...p, - clinical_data: { ...p.clinical_data, pulse: e.target.value }, - })) - } - placeholder="e.g. Choppy." - className="w-full bg-slate-50 border border-slate-200 rounded-xl px-3 py-2 text-xs font-bold text-slate-800 focus:outline-none focus:border-indigo-500" - /> -
- {COMMON_PULSE_SUGGESTIONS.map((pls, idx) => ( - + {chip} + + ))} + setCustomPulseInput(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter' || e.key === ',') { + e.preventDefault(); + handleAddDiagnosisChip('pulse', customPulseInput); + } + }} + onBlur={() => { + if (customPulseInput.trim()) { + handleAddDiagnosisChip('pulse', customPulseInput); + } + }} + placeholder={currentPulseChips.length === 0 ? 'Type pulse finding and press Enter...' : '+ add...'} + className="flex-1 text-xs font-semibold text-slate-800 focus:outline-none bg-transparent min-w-[120px] px-1 py-0.5" + /> +
+
+ {COMMON_PULSE_SUGGESTIONS.map((pls, idx) => { + const isAdded = currentPulseChips.some(c => c.toLowerCase() === pls.toLowerCase()); + return ( + + ); + })}
- {/* Treatment Principle */} -
- - - updateActivePattern(p => ({ - ...p, - clinical_data: { ...p.clinical_data, treatment_principle: e.target.value }, - })) - } - placeholder="e.g. Tonify Qi, nourish Blood, stop pain." - className="w-full bg-slate-50 border border-slate-200 rounded-xl px-3 py-2 text-xs font-bold text-slate-800 focus:outline-none focus:border-indigo-500" - /> + {/* Treatment Principle (Rows like Clinical Manifestations) */} +
+
+ + +
+
+ {activePrinciples.map((principle, pIdx) => ( +
+ {pIdx + 1}. + handlePrincipleChange(pIdx, e.target.value)} + placeholder="e.g. Tonify Qi and nourish Blood" + className="flex-1 bg-slate-50 border border-slate-200 rounded-xl px-3 py-1.5 text-xs font-medium text-slate-800 focus:outline-none focus:border-indigo-500" + /> + {activePrinciples.length > 1 && ( + + )} +
+ ))} +
{/* Acupuncture Formula & Points Chips */} @@ -1893,17 +2162,61 @@ export const ModuleBuilderTabContent: React.FC = () => { setCustomPointInput(e.target.value)} + onChange={(e) => { + setCustomPointInput(e.target.value); + if (pendingPointSuggestion) setPendingPointSuggestion(null); + }} onKeyDown={(e) => { - if (e.key === 'Enter') { + if (e.key === 'Enter' || e.key === ',') { e.preventDefault(); handleAddPointChip(customPointInput); } }} + onBlur={() => { + if (customPointInput.trim()) { + handleAddPointChip(customPointInput); + } + }} placeholder={currentPoints.length === 0 ? 'Type point (e.g. RN-6) and hit Enter...' : '+ add...'} - className="text-xs font-semibold text-slate-800 focus:outline-none bg-transparent min-w-[120px] px-1 py-0.5" + className="flex-1 text-xs font-semibold text-slate-800 focus:outline-none bg-transparent min-w-[120px] px-1 py-0.5" /> + {customPointInput.trim() && ( + + )}
+ {pendingPointSuggestion && ( +
+ + Acupuncture points use a hyphen format. Did you mean{' '} + {pendingPointSuggestion.suggested}? + +
+ + +
+
+ )} {/* Quick Suggestions for Points */} @@ -2136,10 +2449,23 @@ export const ModuleBuilderTabContent: React.FC = () => { {/* Treatment Principle */}
- Treatment Principle - - {patterns[previewPatternIdx].clinical_data?.treatment_principle || '—'} - + Treatment Principle + {(() => { + const tpList = normalizeTreatmentPrinciple( + patterns[previewPatternIdx].clinical_data?.treatment_principle, + ).filter(Boolean); + if (tpList.length === 0) return —; + return ( +
    + {tpList.map((tp, idx) => ( +
  • + • + {tp} +
  • + ))} +
+ ); + })()}
{/* Acupuncture Prescription */} diff --git a/src/services/moduleBuilderService.ts b/src/services/moduleBuilderService.ts index bfdd6f5..f54faf7 100644 --- a/src/services/moduleBuilderService.ts +++ b/src/services/moduleBuilderService.ts @@ -44,7 +44,7 @@ export interface PatternClinicalData { clinical_manifestations: string[]; tongue: string; pulse: string; - treatment_principle: string; + treatment_principle: string[] | string; acupuncture: { points: string; method: string;