diff --git a/src/App.tsx b/src/App.tsx index 5b137a5..23854c1 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -9,6 +9,7 @@ import { AdminSidebar } from './components/layout/AdminSidebar'; import { SyncOverview } from './components/sync/SyncOverview'; import { ModulesTab } from './components/modules/ModulesTab'; import { EditModuleModal } from './components/modules/EditModuleModal'; +import { ModuleBuilderTab } from './components/modules/ModuleBuilderTab'; import { PlansTab } from './components/plans/PlansTab'; import { CreatePlanModal } from './components/plans/CreatePlanModal'; import { EditPriceModal } from './components/plans/EditPriceModal'; @@ -1019,6 +1020,7 @@ export default function App() {

{adminSubTab === 'overview' && 'System Overview & Audit Logs'} {adminSubTab === 'modules' && 'Curriculum Modules'} + {adminSubTab === 'module_builder' && 'Clinical Module Builder'} {adminSubTab === 'plans' && 'Subscription Plans & Pricing'} {adminSubTab === 'coupons' && 'Promotions & Coupons'} {adminSubTab === 'customers' && 'Customer Directory'} @@ -1031,6 +1033,7 @@ export default function App() {

{adminSubTab === 'overview' && 'Real-time telemetry, synchronized payment logs, and platform health metrics.'} {adminSubTab === 'modules' && 'Configure learning modules, categories, pricing, and availability states.'} + {adminSubTab === 'module_builder' && 'Author and customize disease categories, clinical patterns, and treatment formulas.'} {adminSubTab === 'plans' && 'Manage localized pricing tiers, curriculum module bundles, and active pricing.'} {adminSubTab === 'coupons' && 'Manage discount codes, percentage cuts, module restrictions, and expiry dates.'} {adminSubTab === 'customers' && 'Inspect practitioner accounts, credentials, countries, and purchased plans.'} @@ -1101,6 +1104,10 @@ export default function App() { /> )} + {adminSubTab === 'module_builder' && ( + + )} + {adminSubTab === 'plans' && ( { + public state: State = { + hasError: false, + error: null, + }; + + public static getDerivedStateFromError(error: Error): State { + return { hasError: true, error }; + } + + public componentDidCatch(error: Error, errorInfo: ErrorInfo) { + console.error('ErrorBoundary caught an error:', error, errorInfo); + } + + public handleReset = () => { + this.setState({ hasError: false, error: null }); + }; + + public render() { + if (this.state.hasError) { + return ( +

+
+ +
+
+

+ {this.props.fallbackTitle || 'Something went wrong in this section'} +

+

+ {this.state.error?.message || 'An unexpected rendering error occurred.'} +

+
+ +
+ ); + } + + return this.props.children; + } +} diff --git a/src/components/layout/AdminSidebar.tsx b/src/components/layout/AdminSidebar.tsx index 475eff6..e1b12fe 100644 --- a/src/components/layout/AdminSidebar.tsx +++ b/src/components/layout/AdminSidebar.tsx @@ -2,7 +2,7 @@ import React from 'react'; import { Sparkles, ChevronLeft, ChevronRight, LogOut, List, BookOpen, Tag, Ticket, Users, CheckCircle, - Receipt, Shield, Database, FileText, X + Receipt, Shield, Database, FileText, X, Layers } from 'lucide-react'; import type { LoggedInUser, AdminTabType } from '../../types'; @@ -64,6 +64,7 @@ export const AdminSidebar: React.FC = ({ const tabs: TabItem[] = [ { key: 'overview', label: 'Overview & Logs', icon: }, { key: 'modules', label: 'Modules', count: counts.modules, icon: }, + { key: 'module_builder', label: 'Module Builder', icon: }, { key: 'plans', label: 'Plans & Pricing', count: counts.plans, icon: }, { key: 'coupons', label: 'Coupons', count: counts.coupons, icon: }, { key: 'customers', label: 'Customers', count: counts.customers, icon: }, diff --git a/src/components/modules/ModuleBuilderTab.tsx b/src/components/modules/ModuleBuilderTab.tsx new file mode 100644 index 0000000..4282f1b --- /dev/null +++ b/src/components/modules/ModuleBuilderTab.tsx @@ -0,0 +1,2487 @@ +import React, { useState, useEffect } from 'react'; +import { + Layers, Plus, Trash2, Save, RefreshCw, AlertCircle, CheckCircle2, + FolderPlus, FilePlus, Sparkles, BookOpen, ChevronRight, X, RotateCcw, + HelpCircle, ChevronDown, ChevronUp, Stethoscope, HeartPulse, Download, Eye, + Package, UploadCloud, Check, FileArchive +} from 'lucide-react'; +import { + moduleBuilderService, + type BuilderModuleSummary, + type BuilderCategorySummary, + type BuilderDiseaseSummary, + type BuilderPattern, +} from '../../services/moduleBuilderService'; +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.', +]; + +const COMMON_PULSE_SUGGESTIONS = [ + 'Choppy.', + 'Wiry.', + 'Deep and Wiry.', + 'Deep and Weak.', + 'Choppy or Fine.', + 'Rapid and Slippery.', + 'Floating.', +]; + +const COMMON_POINT_SUGGESTIONS = [ + 'RN-6', 'RN-4', 'ST-36', 'SP-6', 'LR-8', 'SP-4', 'PC-6', + 'KI-14', 'ST-30', 'SP-10', 'BL-17', 'LR-3', 'ST-29', 'BL-23', 'BL-20', 'BL-18' +]; + +// Strictly convert human text to lowercase underscore format (e.g. "Period Pain" -> "period_pain") +const toSnakeCase = (text: string): string => + (text || '') + .toLowerCase() + .trim() + .replace(/['"]/g, '') + .replace(/[^\w\s-]/g, '_') + .replace(/[\s_-]+/g, '_') + .replace(/^_+|_+$/g, ''); + +// Convert text to Title Case (e.g. "period pain" -> "Period Pain") +const toTitleCase = (text: string): string => + (text || '').replace(/\w\S*/g, (txt) => txt.charAt(0).toUpperCase() + txt.substring(1).toLowerCase()); + +// Safely format API errors to ALWAYS return a plain string (never an object or array) +const formatApiError = (err: any, fallback: string): string => { + const detail = err?.response?.data?.detail; + if (!detail) return err?.message || fallback; + if (typeof detail === 'string') return detail; + if (Array.isArray(detail)) { + return detail.map((d: any) => d?.msg || d?.message || JSON.stringify(d)).join('; '); + } + if (typeof detail === 'object') { + return detail.message || detail.msg || JSON.stringify(detail); + } + return String(detail); +}; + +const createBlankPattern = (moduleCode: string, catCode: string, disCode: string): BuilderPattern => ({ + module_code: moduleCode, + category_code: catCode, + disease_code: disCode, + pattern_code: 'primary_pattern', + name: 'Primary Pattern', + description: '', + clinical_data: { + clinical_manifestations: [''], + tongue: '', + pulse: '', + treatment_principle: '', + acupuncture: { points: '', method: '' }, + explanation: [''], + }, + sort_order: 0, +}); + +export const ModuleBuilderTabContent: React.FC = () => { + // Modules management + const [modules, setModules] = useState([]); + const [moduleCode, setModuleCode] = useState(() => { + return localStorage.getItem('acupedia_active_module_builder_code') || 'm0042'; + }); + const [showModuleDropdown, setShowModuleDropdown] = useState(false); + const [showNewModuleModal, setShowNewModuleModal] = useState(false); + const [newModuleName, setNewModuleName] = useState(''); + const [newModuleCode, setNewModuleCode] = useState(''); + const [newModuleDesc, setNewModuleDesc] = useState(''); + const [modalModError, setModalModError] = useState(null); + const [creatingModule, setCreatingModule] = useState(false); + const [exportingZip, setExportingZip] = useState(false); + const [syncingRepo, setSyncingRepo] = useState(false); + const [showExportMenu, setShowExportMenu] = useState(false); + + const [categories, setCategories] = useState([]); + const [selectedCategoryCode, setSelectedCategoryCode] = useState(''); + const [categoryOverview, setCategoryOverview] = useState(''); + + const [diseases, setDiseases] = useState([]); + const [selectedDiseaseCode, setSelectedDiseaseCode] = useState(''); + const [diseaseName, setDiseaseName] = useState(''); + const [diseaseOverview, setDiseaseOverview] = useState(''); + const [isCreatingNewDisease, setIsCreatingNewDisease] = useState(false); + + const [patterns, setPatterns] = useState([]); + const [activePatternIndex, setActivePatternIndex] = useState(0); + + const [loading, setLoading] = useState(false); + const [saving, setSaving] = useState(false); + const [downloading, setDownloading] = useState(false); + const [error, setError] = useState(null); + const [successMsg, setSuccessMsg] = useState(null); + const [showQuickGuide, setShowQuickGuide] = useState(false); + const [showPreviewModal, setShowPreviewModal] = useState(false); + const [previewPatternIdx, setPreviewPatternIdx] = useState(0); + + // Modals for creating new category & disease (Name only, code generated automatically) + const [showNewCategoryModal, setShowNewCategoryModal] = useState(false); + const [newCategoryName, setNewCategoryName] = useState(''); + const [modalCatError, setModalCatError] = useState(null); + + const [showNewDiseaseModal, setShowNewDiseaseModal] = useState(false); + const [newDiseaseName, setNewDiseaseName] = useState(''); + const [modalDisError, setModalDisError] = useState(null); + + // Point input state + const [customPointInput, setCustomPointInput] = useState(''); + + // 0. Load Modules List + const fetchModules = async (selectCode?: string) => { + try { + const list = await moduleBuilderService.getModules(); + setModules(list || []); + if (selectCode) { + setModuleCode(selectCode); + localStorage.setItem('acupedia_active_module_builder_code', selectCode); + } else if (list && list.length > 0) { + const saved = localStorage.getItem('acupedia_active_module_builder_code'); + const match = list.find(m => m.code === saved); + const target = match ? match.code : list[0].code; + setModuleCode(target); + localStorage.setItem('acupedia_active_module_builder_code', target); + } + } catch (err: any) { + setError(formatApiError(err, 'Failed to load modules list.')); + } + }; + + useEffect(() => { + fetchModules(); + }, []); + + // Compute active module object + const activeModule = modules.find(m => m.code === moduleCode) || null; + + // 1. Load Categories + const fetchCategories = async (modCode = moduleCode, selectCatCode?: string) => { + setLoading(true); + setError(null); + try { + const cats = await moduleBuilderService.getCategories(modCode); + setCategories(cats || []); + if (cats && cats.length > 0) { + const nextCat = selectCatCode || (cats.some(c => c.category_code === selectedCategoryCode) ? selectedCategoryCode : cats[0].category_code); + setSelectedCategoryCode(nextCat); + const catObj = cats.find(c => c.category_code === nextCat); + setCategoryOverview(catObj?.overview || ''); + } else { + setSelectedCategoryCode(''); + setCategoryOverview(''); + setDiseases([]); + setSelectedDiseaseCode(''); + setDiseaseName(''); + setDiseaseOverview(''); + setPatterns([]); + setIsCreatingNewDisease(false); + } + } catch (err: any) { + setError(formatApiError(err, 'Failed to load disease categories. Please check your connection.')); + } finally { + setLoading(false); + } + }; + + useEffect(() => { + if (moduleCode) { + fetchCategories(moduleCode); + } + }, [moduleCode]); + + // 2. Load Diseases when category changes + const fetchDiseases = async (catCode: string, selectDisCode?: string) => { + if (!catCode) { + setDiseases([]); + setSelectedDiseaseCode(''); + setDiseaseName(''); + setDiseaseOverview(''); + setPatterns([]); + setIsCreatingNewDisease(false); + return; + } + setLoading(true); + setError(null); + try { + const disList = await moduleBuilderService.getDiseases(moduleCode, catCode); + setDiseases(disList || []); + if (selectDisCode && disList.some(d => d.disease_code === selectDisCode)) { + // Explicitly selected disease (e.g. after modal creation or save) + setSelectedDiseaseCode(selectDisCode); + setIsCreatingNewDisease(false); + } else { + // Keep blank by default on load so user actively picks or starts fresh + setSelectedDiseaseCode(''); + setDiseaseName(''); + setDiseaseOverview(''); + setPatterns([]); + setIsCreatingNewDisease(false); + } + } catch (err: any) { + setError(formatApiError(err, 'Failed to load diseases for this category.')); + } finally { + setLoading(false); + } + }; + + useEffect(() => { + if (selectedCategoryCode) { + const catObj = categories.find(c => c.category_code === selectedCategoryCode); + setCategoryOverview(catObj?.overview || ''); + fetchDiseases(selectedCategoryCode); + } + }, [selectedCategoryCode]); + + // 3. Load Disease Details & Patterns when disease changes + const fetchDiseaseDetail = async (catCode: string, disCode: string) => { + if (!catCode || !disCode) { + setPatterns([]); + return; + } + setLoading(true); + setError(null); + try { + const detail = await moduleBuilderService.getDiseaseDetail(moduleCode, catCode, disCode); + setDiseaseName(detail?.name || toTitleCase(disCode.replace(/_/g, ' '))); + setDiseaseOverview(detail?.overview || ''); + setIsCreatingNewDisease(false); + + if (detail && detail.patterns && detail.patterns.length > 0) { + const normalized: BuilderPattern[] = detail.patterns.map(p => ({ + ...p, + clinical_data: { + clinical_manifestations: Array.isArray(p.clinical_data?.clinical_manifestations) + ? p.clinical_data.clinical_manifestations + : [''], + tongue: p.clinical_data?.tongue || '', + pulse: p.clinical_data?.pulse || '', + treatment_principle: p.clinical_data?.treatment_principle || '', + acupuncture: { + points: p.clinical_data?.acupuncture?.points || '', + method: p.clinical_data?.acupuncture?.method || '', + }, + explanation: Array.isArray(p.clinical_data?.explanation) + ? p.clinical_data.explanation + : [''], + }, + })); + setPatterns(normalized); + setActivePatternIndex(0); + } else { + const initial = createBlankPattern(moduleCode, catCode, disCode); + setPatterns([initial]); + setActivePatternIndex(0); + } + } catch (err: any) { + setError(formatApiError(err, 'Failed to load clinical patterns for this disease.')); + } finally { + setLoading(false); + } + }; + + useEffect(() => { + if (selectedCategoryCode && selectedDiseaseCode && !isCreatingNewDisease) { + fetchDiseaseDetail(selectedCategoryCode, selectedDiseaseCode); + } + }, [selectedDiseaseCode]); + + // Revert / Reset to Blank Form + const handleResetToBlankForm = () => { + if (!selectedCategoryCode) { + setError('Please select or create a Category first before starting a blank form.'); + return; + } + if ( + (diseaseName || diseaseOverview) && + !window.confirm('Reset form to blank to start a new disease from scratch?\n\nAny unsaved edits to the current disease will be cleared.') + ) { + return; + } + + setSelectedDiseaseCode(''); + setDiseaseName(''); + setDiseaseOverview(''); + setIsCreatingNewDisease(true); + + const blank = createBlankPattern(moduleCode, selectedCategoryCode, ''); + setPatterns([blank]); + setActivePatternIndex(0); + setError(null); + setSuccessMsg('Blank form ready. Enter the disease name, pathology, and clinical patterns.'); + setTimeout(() => setSuccessMsg(null), 3500); + }; + + // Create Category Handler (Name only -> Code auto-generated) + const handleCreateCategory = async (e: React.FormEvent) => { + e.preventDefault(); + const cleanName = newCategoryName.trim(); + if (!cleanName) { + setModalCatError('Please enter a category name.'); + return; + } + const code = toSnakeCase(cleanName); + const title = toTitleCase(cleanName); + + if (categories.some(c => c.category_code === code || c.name.toLowerCase() === title.toLowerCase())) { + setModalCatError(`A category named "${title}" already exists. Please enter a distinct name.`); + return; + } + + setSaving(true); + setModalCatError(null); + setError(null); + try { + await moduleBuilderService.saveCategory(moduleCode, { + category_code: code, + name: title, + overview: '', + sort_order: categories.length, + }); + setShowNewCategoryModal(false); + setNewCategoryName(''); + setModalCatError(null); + setSuccessMsg(`Category "${title}" created successfully!`); + await fetchCategories(code); + } catch (err: any) { + setModalCatError(formatApiError(err, 'Failed to create category. Please try again.')); + } finally { + setSaving(false); + } + }; + + // Delete Category Handler + const handleDeleteCategory = async () => { + if (!selectedCategoryCode) { + setError('Please select a category to delete.'); + return; + } + const catName = categories.find(c => c.category_code === selectedCategoryCode)?.name || selectedCategoryCode; + const confirmed = window.confirm( + `Are you sure you want to permanently delete category "${catName}"?\n\n` + + `WARNING: This will delete ALL diseases and clinical patterns contained inside it. This action cannot be undone.` + ); + if (!confirmed) return; + + setSaving(true); + setError(null); + try { + await moduleBuilderService.deleteCategory(moduleCode, selectedCategoryCode); + setSuccessMsg(`Category "${catName}" deleted successfully.`); + await fetchCategories(); + } catch (err: any) { + setError(formatApiError(err, 'Failed to delete category.')); + } finally { + setSaving(false); + } + }; + + // Create Disease Handler (Name only -> Code auto-generated) + const handleCreateDisease = async (e: React.FormEvent) => { + e.preventDefault(); + const cleanName = newDiseaseName.trim(); + if (!cleanName) { + setModalDisError('Please enter a disease name.'); + return; + } + if (!selectedCategoryCode) { + setModalDisError('Please select or create a Category first.'); + return; + } + + const code = toSnakeCase(cleanName); + const title = toTitleCase(cleanName); + + if (diseases.some(d => d.disease_code === code || d.name.toLowerCase() === title.toLowerCase())) { + setModalDisError(`A disease named "${title}" already exists in this category. Please choose a different name.`); + return; + } + + setSaving(true); + setModalDisError(null); + setError(null); + try { + await moduleBuilderService.saveDisease(moduleCode, selectedCategoryCode, { + category_code: selectedCategoryCode, + disease_code: code, + name: title, + overview: '', + sort_order: diseases.length, + }); + setShowNewDiseaseModal(false); + setNewDiseaseName(''); + setModalDisError(null); + setIsCreatingNewDisease(false); + setSuccessMsg(`Disease "${title}" created successfully!`); + await fetchDiseases(selectedCategoryCode, code); + } catch (err: any) { + setModalDisError(formatApiError(err, 'Failed to create disease. Please try again.')); + } finally { + setSaving(false); + } + }; + + // Delete Disease Handler + const handleDeleteDisease = async () => { + if (!selectedCategoryCode || !selectedDiseaseCode) { + setError('Please select a disease to delete.'); + return; + } + const disName = diseaseName || selectedDiseaseCode; + const confirmed = window.confirm( + `Are you sure you want to permanently delete disease "${disName}" and all of its clinical patterns?\n\n` + + `This action cannot be undone.` + ); + if (!confirmed) return; + + setSaving(true); + setError(null); + try { + await moduleBuilderService.deleteDisease(moduleCode, selectedCategoryCode, selectedDiseaseCode); + setSuccessMsg(`Disease "${disName}" deleted.`); + await fetchDiseases(selectedCategoryCode); + } catch (err: any) { + setError(formatApiError(err, 'Failed to delete disease.')); + } finally { + setSaving(false); + } + }; + + // Active Pattern Safety + const safePatternIndex = patterns.length > 0 ? Math.min(Math.max(0, activePatternIndex), patterns.length - 1) : -1; + const activePattern = safePatternIndex >= 0 ? patterns[safePatternIndex] : null; + + const updateActivePattern = (updater: (prev: BuilderPattern) => BuilderPattern) => { + if (safePatternIndex < 0) return; + setPatterns(prev => { + const copy = [...prev]; + if (copy[safePatternIndex]) { + copy[safePatternIndex] = updater(copy[safePatternIndex]); + } + return copy; + }); + }; + + const handleAddPattern = () => { + const nextIdx = patterns.length + 1; + const patName = `Pattern ${nextIdx}`; + const newPat: BuilderPattern = { + module_code: moduleCode, + category_code: selectedCategoryCode, + disease_code: selectedDiseaseCode || toSnakeCase(diseaseName || 'new_disease'), + pattern_code: toSnakeCase(patName), + name: patName, + description: '', + clinical_data: { + clinical_manifestations: [''], + tongue: '', + pulse: '', + treatment_principle: '', + acupuncture: { points: '', method: '' }, + explanation: [''], + }, + sort_order: patterns.length, + }; + setPatterns(prev => [...prev, newPat]); + setActivePatternIndex(patterns.length); + setError(null); + }; + + const handleRemovePattern = (idx: number) => { + if (patterns.length <= 1) { + setError('A disease must have at least one clinical pattern. You cannot delete the only pattern.'); + return; + } + const patName = patterns[idx]?.name || `Pattern ${idx + 1}`; + if (!window.confirm(`Delete pattern "${patName}"? This will remove all its symptoms and prescription data.`)) { + return; + } + setPatterns(prev => prev.filter((_, i) => i !== idx)); + setActivePatternIndex(Math.max(0, idx - 1)); + setSuccessMsg(`Pattern "${patName}" deleted.`); + setTimeout(() => setSuccessMsg(null), 3000); + }; + + // Symptom List Helpers + const handleSymptomChange = (sIdx: number, val: string) => { + updateActivePattern(p => { + const list = [...(p.clinical_data?.clinical_manifestations || [])]; + list[sIdx] = val; + return { + ...p, + clinical_data: { ...p.clinical_data, clinical_manifestations: list }, + }; + }); + }; + + const handleAddSymptom = () => { + updateActivePattern(p => ({ + ...p, + clinical_data: { + ...p.clinical_data, + clinical_manifestations: [...(p.clinical_data?.clinical_manifestations || []), ''], + }, + })); + }; + + const handleRemoveSymptom = (sIdx: number) => { + updateActivePattern(p => ({ + ...p, + clinical_data: { + ...p.clinical_data, + clinical_manifestations: (p.clinical_data?.clinical_manifestations || []).filter((_, i) => i !== sIdx), + }, + })); + }; + + // 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).'); + return; + } + if (currentPoints.includes(trimmed)) { + setError(`Point "${trimmed}" is already added to this prescription.`); + return; + } + setError(null); + const updated = [...currentPoints, trimmed].join(', '); + updateActivePattern(p => ({ + ...p, + clinical_data: { + ...p.clinical_data, + acupuncture: { + points: updated, + method: p.clinical_data?.acupuncture?.method || '', + }, + }, + })); + setCustomPointInput(''); + }; + + const handleRemovePointChip = (pointToRemove: string) => { + const updated = currentPoints.filter(p => p !== pointToRemove).join(', '); + updateActivePattern(p => ({ + ...p, + clinical_data: { + ...p.clinical_data, + acupuncture: { + points: updated, + method: p.clinical_data?.acupuncture?.method || '', + }, + }, + })); + }; + + // Explanation Helpers + const handleExplanationChange = (eIdx: number, val: string) => { + updateActivePattern(p => { + const list = [...(p.clinical_data?.explanation || [])]; + list[eIdx] = val; + return { + ...p, + clinical_data: { ...p.clinical_data, explanation: list }, + }; + }); + }; + + const handleAddExplanation = () => { + updateActivePattern(p => ({ + ...p, + clinical_data: { + ...p.clinical_data, + explanation: [...(p.clinical_data?.explanation || []), ''], + }, + })); + }; + + const handleRemoveExplanation = (eIdx: number) => { + updateActivePattern(p => ({ + ...p, + clinical_data: { + ...p.clinical_data, + explanation: (p.clinical_data?.explanation || []).filter((_, i) => i !== eIdx), + }, + })); + }; + + // Save Full Disease & Patterns with Granular Validation + const handleSaveFullDisease = async () => { + if (!selectedCategoryCode) { + setError('Please select or create a Category before saving.'); + return; + } + + const effectiveDiseaseName = diseaseName.trim(); + if (!effectiveDiseaseName) { + setError('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.'); + return; + } + + // Validate Pattern Names & Duplicates + const seenPatternNames = new Set(); + for (let i = 0; i < patterns.length; i++) { + const pName = patterns[i]?.name?.trim(); + if (!pName) { + setActivePatternIndex(i); + setError(`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.`); + 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); + if (cleanSymptoms.length === 0) { + setActivePatternIndex(i); + setError(`Pattern "${patterns[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(); + if (!pts) { + setActivePatternIndex(i); + setError(`Pattern "${patterns[i].name}" has no acupuncture points. Please select or add at least one point before saving.`); + return; + } + } + + const effectiveDiseaseCode = toSnakeCase(effectiveDiseaseName); + + setSaving(true); + setError(null); + setSuccessMsg(null); + try { + // 1. Update category overview if changed + await moduleBuilderService.saveCategory(moduleCode, { + category_code: selectedCategoryCode, + name: categories.find(c => c.category_code === selectedCategoryCode)?.name || selectedCategoryCode, + overview: categoryOverview, + }); + + // 2. Prepare payload + const payload = { + category_code: selectedCategoryCode, + disease_code: effectiveDiseaseCode, + name: effectiveDiseaseName, + overview: diseaseOverview, + patterns: patterns.map((p, idx) => ({ + category_code: selectedCategoryCode, + disease_code: effectiveDiseaseCode, + pattern_code: toSnakeCase(p.name?.trim() || `pattern_${idx + 1}`), + name: p.name?.trim() || `Pattern ${idx + 1}`, + description: p.description || '', + clinical_data: { + 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(), + acupuncture: { + points: (p.clinical_data?.acupuncture?.points || '').trim(), + method: (p.clinical_data?.acupuncture?.method || '').trim(), + }, + explanation: (p.clinical_data?.explanation || []).filter(e => e && e.trim().length > 0), + }, + sort_order: idx, + })), + }; + + await moduleBuilderService.saveFullDisease(moduleCode, payload); + setIsCreatingNewDisease(false); + setSelectedDiseaseCode(effectiveDiseaseCode); + setSuccessMsg('All disease details and clinical patterns saved successfully!'); + setTimeout(() => setSuccessMsg(null), 4000); + await fetchDiseases(selectedCategoryCode, effectiveDiseaseCode); + } catch (err: any) { + setError(formatApiError(err, 'Failed to save changes. Please check all fields and try again.')); + } finally { + setSaving(false); + } + }; + + // Download Module JSON + const handleDownloadJson = async () => { + if (categories.length === 0) { + setError('No module content to download. Please create a category and disease, or load the sample template first.'); + return; + } + + setDownloading(true); + setError(null); + try { + const data = await moduleBuilderService.exportModuleJson(moduleCode); + const jsonStr = JSON.stringify(data, null, 2); + const blob = new Blob([jsonStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + const link = document.createElement('a'); + link.href = url; + link.download = `module_builder_${moduleCode}.json`; + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); + URL.revokeObjectURL(url); + setSuccessMsg(`Downloaded module_builder_${moduleCode}.json successfully!`); + setTimeout(() => setSuccessMsg(null), 4500); + } catch (err: any) { + setError(formatApiError(err, 'Failed to export module JSON. Please try again.')); + } finally { + setDownloading(false); + } + }; + + // Download Production ZIP Package + const handleExportZip = async () => { + if (categories.length === 0) { + setError('Cannot export package: Please add at least one category to this module first.'); + return; + } + setExportingZip(true); + setError(null); + setShowExportMenu(false); + try { + const { blob, filename } = await moduleBuilderService.exportBundleZip(moduleCode); + const url = URL.createObjectURL(blob); + const link = document.createElement('a'); + link.href = url; + link.download = filename; + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); + URL.revokeObjectURL(url); + setSuccessMsg(`Production bundle "${filename}" downloaded successfully!`); + setTimeout(() => setSuccessMsg(null), 4500); + } catch (err: any) { + setError(formatApiError(err, 'Failed to export module bundle package.')); + } finally { + setExportingZip(false); + } + }; + + // Sync Directly to acupedia-content Repository + const handleSyncContentRepo = async () => { + if (categories.length === 0) { + setError('Cannot sync repository: Please add at least one category to this module first.'); + return; + } + const confirmed = window.confirm( + `Compile and sync module "${activeModule?.name || moduleCode}" directly to the local acupedia-content repository?\n\n` + + `This will generate/update the module folder and register it in root config.json.` + ); + if (!confirmed) return; + + setSyncingRepo(true); + setError(null); + setShowExportMenu(false); + try { + const res = await moduleBuilderService.syncContentRepo(moduleCode); + setSuccessMsg(res.message || `Successfully synced ${moduleCode} to acupedia-content repository!`); + setTimeout(() => setSuccessMsg(null), 5000); + } catch (err: any) { + setError(formatApiError(err, 'Failed to sync module to content repository.')); + } finally { + setSyncingRepo(false); + } + }; + + // Switch Active Module + const handleSwitchModule = (newCode: string) => { + if (newCode === moduleCode) { + setShowModuleDropdown(false); + return; + } + setModuleCode(newCode); + localStorage.setItem('acupedia_active_module_builder_code', newCode); + setShowModuleDropdown(false); + setSelectedCategoryCode(''); + setSelectedDiseaseCode(''); + setDiseaseName(''); + setDiseaseOverview(''); + setPatterns([]); + setIsCreatingNewDisease(false); + }; + + // Auto-suggest next module code + const getSuggestedNextModuleCode = (): string => { + const codes = modules + .map(m => m.code) + .filter(c => /^m\d{4}$/.test(c)) + .map(c => parseInt(c.slice(1), 10)); + const nextNum = (codes.length > 0 ? Math.max(...codes) : 42) + 1; + return `m${String(nextNum).padStart(4, '0')}`; + }; + + // Create New Module Handler + const handleCreateModule = async (e: React.FormEvent) => { + e.preventDefault(); + const cleanName = newModuleName.trim(); + if (!cleanName) { + setModalModError('Please enter a module name.'); + return; + } + + const codeToUse = newModuleCode.trim().toLowerCase(); + if (codeToUse && !/^m[0-9]{4}$/.test(codeToUse)) { + setModalModError("Module code must start with 'm' followed by 4 digits (e.g. 'm0043')."); + return; + } + + if (codeToUse && modules.some(m => m.code === codeToUse)) { + setModalModError(`Module code "${codeToUse}" is already taken. Please choose another.`); + return; + } + + setCreatingModule(true); + setModalModError(null); + setError(null); + try { + const created = await moduleBuilderService.createModule({ + name: cleanName, + code: codeToUse || undefined, + short_description: newModuleDesc.trim() || undefined, + kind: 'therapeutic', + managed_by: 'module_builder', + }); + + setShowNewModuleModal(false); + setNewModuleName(''); + setNewModuleCode(''); + setNewModuleDesc(''); + setModalModError(null); + setSuccessMsg(`Module "${created.name}" (${created.code}) created successfully!`); + setTimeout(() => setSuccessMsg(null), 4000); + + // Refresh modules list and switch active module + await fetchModules(created.code); + } catch (err: any) { + setModalModError(formatApiError(err, 'Failed to create module.')); + } finally { + setCreatingModule(false); + } + }; + + // Delete Module Handler + const handleDeleteModule = async () => { + if (!activeModule) return; + const confirmed = window.confirm( + `Are you sure you want to permanently delete module "${activeModule.name}" (${activeModule.code})?\n\n` + + `WARNING: This will delete ALL ${activeModule.category_count} categories, ${activeModule.disease_count} diseases, and ${activeModule.pattern_count} patterns contained in this module. This action cannot be undone.` + ); + if (!confirmed) return; + + setLoading(true); + setError(null); + try { + await moduleBuilderService.deleteModule(moduleCode); + setSuccessMsg(`Module "${activeModule.name}" deleted successfully.`); + setTimeout(() => setSuccessMsg(null), 4000); + await fetchModules(); + } catch (err: any) { + setError(formatApiError(err, 'Failed to delete module.')); + } finally { + setLoading(false); + } + }; + + // Seed sample Gynecological content if completely empty + const handleSeedSampleData = async () => { + if (categories.length > 0 && !window.confirm('Sample template will add standard Gynecological Disorders to the current database. Continue?')) { + return; + } + + setLoading(true); + setError(null); + try { + const sampleContents = [ + { + name: 'Diseases after Childbirth', + code: 'diseases_after_childbirth', + overview: 'Pathologies arising during the puerperium, typically categorized as blood deficiency or blood stasis.', + diseases: [ + { + name: 'Abdominal Pain after Childbirth', + code: 'abdominal_pain_after_childbirth', + overview: 'The pathology of Abdominal Pain after Childbirth is characterized by either a deficiency or an excess condition. Deficient Blood and Qi cause mild abdominal pain better with pressure and eating. Excess conditions like Blood stasis cause severe stabbing pain worse with pressure.', + patterns: [ + { + name: 'Blood deficiency', + code: 'blood_deficiency', + description: 'Dull abdominal pain relieved by pressure and after eating', + clinical_manifestations: [ + 'Dull abdominal pain after childbirth which is relieved by pressure and after eating', + 'Scanty, but continuous uterine bleeding which is pale in color', + 'Dizziness', + 'Tiredness', + 'Blurred vision', + 'Constipation', + ], + tongue: 'Pale and Thin.', + pulse: 'Choppy.', + treatment_principle: 'Tonify Qi, nourish Blood, stop pain.', + acupuncture: { + points: 'RN-6, RN-4, ST-36, SP-6, LR-8', + method: 'All with reinforcing method, moxa is applicable.', + }, + explanation: [ + 'RN-6 tonifies Qi in general and moves Qi in the abdomen.', + 'RN-4 nourishes Blood and strengthens the Uterus.', + 'ST-36 and SP-6 tonify Qi and Blood.', + 'LR-8 nourishes Liver-Blood.', + ], + }, + { + name: 'Blood Stasis', + code: 'blood_stasis', + description: 'Sharp, stabbing abdominal pain worse with pressure', + clinical_manifestations: [ + 'Abdominal pain after childbirth that is worse with pressure and worse after eating', + 'Discharge of dark lochia', + 'Dark complexion', + 'Cold limbs', + ], + tongue: 'Purple.', + pulse: 'Deep and Wiry.', + treatment_principle: 'Invigorate Blood, eliminate stasis, scatter Cold, stop pain.', + acupuncture: { + points: 'SP-4, PC-6, ST-30, KI-14, SP-10, BL-17, SP-6, LR-3, ST-29', + method: 'All with reducing or even method. Moxa can be used if there are symptoms of Cold.', + }, + explanation: [ + 'SP-4 and PC-6 regulate the Penetrating Vessel, subdue rebellious Qi and eliminate stasis in the abdomen.', + 'ST-30 regulates Qi and Blood in this vessel.', + 'KI-14 moves Qi and Blood in this vessel and stops abdominal pain.', + ], + }, + ], + }, + { + name: 'Fever after Childbirth', + code: 'fever_after_childbirth', + overview: 'Postpartum fever can be due to external infection, blood deficiency, blood stasis, or food stagnation.', + patterns: [ + { + name: 'Blood deficiency with mild fever', + code: 'fever_blood_deficiency', + description: 'Low-grade fever in the afternoon or evening accompanied by palpitations and dizziness.', + clinical_manifestations: [ + 'Low-grade fever', + 'Dizziness and blurred vision', + 'Palpitations', + 'Insomnia', + 'Pale complexion', + ], + tongue: 'Pale.', + pulse: 'Fine and Rapid.', + treatment_principle: 'Nourish Blood, clear heat.', + acupuncture: { + points: 'ST-36, SP-6, BL-20, BL-17, RN-4', + method: 'Reinforcing method.', + }, + explanation: [ + 'ST-36 and SP-6 nourish Qi and Blood to clear deficient heat.', + 'RN-4 tonifies the Uterus and replenishes postpartum Blood.', + ], + }, + ], + }, + ], + }, + { + name: 'Diseases of Pregnancy', + code: 'diseases_of_pregnancy', + overview: 'Conditions affecting women during gestational periods requiring careful point selection avoiding contraindicated points.', + diseases: [ + { + name: 'Morning Sickness (Nausea and Vomiting)', + code: 'morning_sickness', + overview: 'Nausea and vomiting during early pregnancy due to rebellious Qi in the Penetrating Vessel.', + patterns: [ + { + name: 'Disharmony of Stomach and Chong Mai', + code: 'disharmony_stomach_chong', + description: 'Nausea and vomiting of clear fluid soon after eating.', + clinical_manifestations: [ + 'Nausea and vomiting', + 'Fullness in the epigastrium', + 'Tiredness', + 'Poor appetite', + ], + tongue: 'Pale with white coating.', + pulse: 'Slippery and Weak.', + treatment_principle: 'Subdue rebellious Qi, harmonize Stomach.', + acupuncture: { + points: 'PC-6, CV-12, ST-36, SP-4', + method: 'Even or mild reinforcing method.', + }, + explanation: [ + 'PC-6 opens the chest and subdues rebellious Stomach Qi.', + 'CV-12 harmonizes the Middle Burner.', + ], + }, + ], + }, + ], + }, + ]; + + await moduleBuilderService.importModuleJson(moduleCode, sampleContents); + setSuccessMsg('Sample Gynecological Disorders template imported successfully!'); + await fetchCategories(); + } catch (err: any) { + setError(formatApiError(err, 'Failed to import sample template data.')); + } finally { + setLoading(false); + } + }; + + const isFormActive = Boolean(selectedDiseaseCode || isCreatingNewDisease); + + return ( +
+ {/* Top Banner & Context Bar */} +
+
+
+
+ +
+
+

+ Clinical Module Builder + {/* Module Selector Dropdown */} +
+ + + {showModuleDropdown && ( + <> +
setShowModuleDropdown(false)} + /> +
+
+ Active Clinical Modules +
+
+ {modules.map((m) => ( + + )} +
+ + ))} +
+
+ +
+
+ + )} +
+

+

+ Author and customize disease categories, clinical patterns, and treatment formulas. +

+
+
+ + {/* Action Toolbar */} +
+ {/* Quick Guide Toggle */} + + + {/* Revert to Blank Form Button */} + + + {/* Live Clinical Preview Button */} + + + {/* Export & Package Menu */} +
+ + + {showExportMenu && ( + <> +
setShowExportMenu(false)} + /> +
+
+ Production Packaging +
+ + + + + +
+ + +
+ + )} +
+ + {categories.length === 0 && ( + + )} + + {/* Save Button */} + +
+
+ + {/* Quick User Guide (Expandable) */} + {showQuickGuide && ( +
+
+

+ Quick Guide: How to Use the Module Builder +

+ +
+
+
+ 1 +

Disease Category

+

+ Select a category or click + Add Category. Enter the human name; system codes are generated automatically in lowercase underscore format. +

+
+
+ 2 +

Choose or Blank Form

+

+ Pick an existing disease or click Reset to Blank Form. Enter the disease name; the code is created automatically as underscore_format. +

+
+
+ 3 +

Clinical Patterns

+

+ Click pattern tabs. Type symptoms (hit Enter for next row), pick tongue & pulse pills, and click point badges. +

+
+
+ 4 +

Download & Seed

+

+ Save your changes, then click Download JSON to get the verified module_builder.json file to place into Acupedia content. +

+
+
+
+ )} + + {/* Category & Disease Selector Controls */} +
+ {/* Category Dropdown */} +
+
+ +
+ + {selectedCategoryCode && ( + + )} +
+
+ +
+ + {/* Disease Dropdown */} +
+
+ +
+ + {selectedDiseaseCode && ( + + )} +
+
+ +
+
+ + {/* Feedback Banners with Dismiss Button */} + {error && ( +
+
+ + {error} +
+ +
+ )} + {successMsg && ( +
+
+ + {successMsg} +
+ +
+ )} +
+ + {/* Main Phased Form Canvas */} + {isFormActive ? ( +
+ {/* Disease Pathology Card */} +
+
+

+ + Disease Pathology & Overview +

+
+ {isCreatingNewDisease && ( + + Authoring New + + )} + + System Code: {toSnakeCase(diseaseName || selectedDiseaseCode || 'new_disease')} + +
+
+ +
+ {/* Disease Name Only (Code generated internally) */} +
+ + { + setDiseaseName(e.target.value); + if (error) setError(null); + }} + onBlur={() => { + if (diseaseName.trim()) { + setDiseaseName(toTitleCase(diseaseName.trim())); + } + }} + 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" + placeholder="e.g. Period Pain" + /> +
+ + {/* Category Overview */} +
+ + setCategoryOverview(e.target.value)} + className="w-full bg-slate-50 border border-slate-200 rounded-xl px-3 py-2 text-xs font-medium text-slate-800 focus:outline-none focus:border-indigo-500" + placeholder="General category notes" + /> +
+
+ + {/* Disease Pathology Description */} +
+ +