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' && (
= ({
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..d16f7be
--- /dev/null
+++ b/src/components/modules/ModuleBuilderTab.tsx
@@ -0,0 +1,1325 @@
+import React, { useState, useEffect } from 'react';
+import {
+ Layers, Plus, Trash2, Save, RefreshCw, AlertCircle, CheckCircle2,
+ FolderPlus, FilePlus, Sparkles, BookOpen, ChevronRight, X
+} from 'lucide-react';
+import {
+ moduleBuilderService,
+ type BuilderCategorySummary,
+ type BuilderDiseaseSummary,
+ type BuilderPattern,
+} from '../../services/moduleBuilderService';
+
+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'
+];
+
+export const ModuleBuilderTab: React.FC = () => {
+ const [moduleCode] = useState('m0042');
+ 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 [patterns, setPatterns] = useState([]);
+ const [activePatternIndex, setActivePatternIndex] = useState(0);
+
+ const [loading, setLoading] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState(null);
+ const [successMsg, setSuccessMsg] = useState(null);
+
+ // Modals for creating new category & disease
+ const [showNewCategoryModal, setShowNewCategoryModal] = useState(false);
+ const [newCategoryName, setNewCategoryName] = useState('');
+ const [newCategoryCode, setNewCategoryCode] = useState('');
+
+ const [showNewDiseaseModal, setShowNewDiseaseModal] = useState(false);
+ const [newDiseaseName, setNewDiseaseName] = useState('');
+ const [newDiseaseCode, setNewDiseaseCode] = useState('');
+
+ // Point input state
+ const [customPointInput, setCustomPointInput] = useState('');
+
+ // Auto-slugify helper
+ const slugify = (text: string) =>
+ text
+ .toLowerCase()
+ .trim()
+ .replace(/[^\w\s-]/g, '')
+ .replace(/[\s_-]+/g, '_')
+ .replace(/^-+|-+$/g, '');
+
+ // 1. Load Categories
+ const fetchCategories = async (selectCatCode?: string) => {
+ setLoading(true);
+ setError(null);
+ try {
+ const cats = await moduleBuilderService.getCategories(moduleCode);
+ setCategories(cats);
+ if (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('');
+ setDiseases([]);
+ setSelectedDiseaseCode('');
+ setPatterns([]);
+ }
+ } catch (err: any) {
+ setError(err?.response?.data?.detail || 'Failed to load categories');
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ useEffect(() => {
+ fetchCategories();
+ }, [moduleCode]);
+
+ // 2. Load Diseases when category changes
+ const fetchDiseases = async (catCode: string, selectDisCode?: string) => {
+ if (!catCode) return;
+ setLoading(true);
+ setError(null);
+ try {
+ const disList = await moduleBuilderService.getDiseases(moduleCode, catCode);
+ setDiseases(disList);
+ if (disList.length > 0) {
+ const nextDis = selectDisCode || disList[0].disease_code;
+ setSelectedDiseaseCode(nextDis);
+ } else {
+ setSelectedDiseaseCode('');
+ setDiseaseName('');
+ setDiseaseOverview('');
+ setPatterns([]);
+ }
+ } catch (err: any) {
+ setError(err?.response?.data?.detail || 'Failed to load diseases');
+ } 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) return;
+ setLoading(true);
+ setError(null);
+ try {
+ const detail = await moduleBuilderService.getDiseaseDetail(moduleCode, catCode, disCode);
+ setDiseaseName(detail.name || '');
+ setDiseaseOverview(detail.overview || '');
+
+ if (detail.patterns && detail.patterns.length > 0) {
+ // Ensure clinical_data has all required fields
+ const normalized = detail.patterns.map(p => ({
+ ...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: p.clinical_data?.explanation || [],
+ },
+ }));
+ setPatterns(normalized);
+ setActivePatternIndex(0);
+ } else {
+ // Create 1 default pattern to start with
+ const initialPattern: BuilderPattern = {
+ module_code: moduleCode,
+ category_code: catCode,
+ disease_code: disCode,
+ pattern_code: 'pattern_1',
+ name: 'Primary Pattern',
+ description: '',
+ clinical_data: {
+ clinical_manifestations: [''],
+ tongue: '',
+ pulse: '',
+ treatment_principle: '',
+ acupuncture: { points: '', method: '' },
+ explanation: [''],
+ },
+ sort_order: 0,
+ };
+ setPatterns([initialPattern]);
+ setActivePatternIndex(0);
+ }
+ } catch (err: any) {
+ setError(err?.response?.data?.detail || 'Failed to load disease details');
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ useEffect(() => {
+ if (selectedCategoryCode && selectedDiseaseCode) {
+ fetchDiseaseDetail(selectedCategoryCode, selectedDiseaseCode);
+ }
+ }, [selectedDiseaseCode]);
+
+ // Create Category Handler
+ const handleCreateCategory = async (e: React.FormEvent) => {
+ e.preventDefault();
+ if (!newCategoryName.trim()) return;
+ const code = newCategoryCode.trim() || slugify(newCategoryName);
+ setSaving(true);
+ setError(null);
+ try {
+ await moduleBuilderService.saveCategory(moduleCode, {
+ category_code: code,
+ name: newCategoryName.trim(),
+ overview: '',
+ sort_order: categories.length,
+ });
+ setShowNewCategoryModal(false);
+ setNewCategoryName('');
+ setNewCategoryCode('');
+ setSuccessMsg(`Category "${newCategoryName}" created!`);
+ await fetchCategories(code);
+ } catch (err: any) {
+ setError(err?.response?.data?.detail || 'Failed to create category');
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ // Delete Category Handler
+ const handleDeleteCategory = async () => {
+ if (!selectedCategoryCode) return;
+ if (!window.confirm(`Are you sure you want to delete this category and ALL its diseases/patterns?`)) return;
+ setSaving(true);
+ try {
+ await moduleBuilderService.deleteCategory(moduleCode, selectedCategoryCode);
+ setSuccessMsg('Category deleted.');
+ await fetchCategories();
+ } catch (err: any) {
+ setError(err?.response?.data?.detail || 'Failed to delete category');
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ // Create Disease Handler
+ const handleCreateDisease = async (e: React.FormEvent) => {
+ e.preventDefault();
+ if (!newDiseaseName.trim() || !selectedCategoryCode) return;
+ const code = newDiseaseCode.trim() || slugify(newDiseaseName);
+ setSaving(true);
+ setError(null);
+ try {
+ await moduleBuilderService.saveDisease(moduleCode, selectedCategoryCode, {
+ disease_code: code,
+ name: newDiseaseName.trim(),
+ overview: '',
+ sort_order: diseases.length,
+ });
+ setShowNewDiseaseModal(false);
+ setNewDiseaseName('');
+ setNewDiseaseCode('');
+ setSuccessMsg(`Disease "${newDiseaseName}" created!`);
+ await fetchDiseases(selectedCategoryCode, code);
+ } catch (err: any) {
+ setError(err?.response?.data?.detail || 'Failed to create disease');
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ // Delete Disease Handler
+ const handleDeleteDisease = async () => {
+ if (!selectedCategoryCode || !selectedDiseaseCode) return;
+ if (!window.confirm(`Are you sure you want to delete this disease and all its patterns?`)) return;
+ setSaving(true);
+ try {
+ await moduleBuilderService.deleteDisease(moduleCode, selectedCategoryCode, selectedDiseaseCode);
+ setSuccessMsg('Disease deleted.');
+ await fetchDiseases(selectedCategoryCode);
+ } catch (err: any) {
+ setError(err?.response?.data?.detail || 'Failed to delete disease');
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ // Pattern Manipulation Handlers
+ const activePattern = patterns[activePatternIndex] || null;
+
+ const updateActivePattern = (updater: (prev: BuilderPattern) => BuilderPattern) => {
+ setPatterns(prev => {
+ const copy = [...prev];
+ if (copy[activePatternIndex]) {
+ copy[activePatternIndex] = updater(copy[activePatternIndex]);
+ }
+ return copy;
+ });
+ };
+
+ const handleAddPattern = () => {
+ const nextIdx = patterns.length + 1;
+ const newPat: BuilderPattern = {
+ module_code: moduleCode,
+ category_code: selectedCategoryCode,
+ disease_code: selectedDiseaseCode,
+ pattern_code: `pattern_${nextIdx}`,
+ name: `Pattern ${nextIdx}`,
+ description: '',
+ clinical_data: {
+ clinical_manifestations: [''],
+ tongue: '',
+ pulse: '',
+ treatment_principle: '',
+ acupuncture: { points: '', method: '' },
+ explanation: [''],
+ },
+ sort_order: patterns.length,
+ };
+ setPatterns(prev => [...prev, newPat]);
+ setActivePatternIndex(patterns.length);
+ };
+
+ const handleRemovePattern = (idx: number) => {
+ if (patterns.length <= 1) {
+ alert('A disease must have at least one pattern.');
+ return;
+ }
+ if (!window.confirm(`Delete pattern "${patterns[idx].name}"?`)) return;
+ setPatterns(prev => prev.filter((_, i) => i !== idx));
+ setActivePatternIndex(Math.max(0, idx - 1));
+ };
+
+ // 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
+ const currentPoints = activePattern?.clinical_data.acupuncture.points
+ ? activePattern.clinical_data.acupuncture.points.split(',').map(s => s.trim()).filter(Boolean)
+ : [];
+
+ const handleAddPointChip = (point: string) => {
+ const trimmed = point.trim();
+ if (!trimmed) return;
+ if (currentPoints.includes(trimmed)) return;
+ const updated = [...currentPoints, trimmed].join(', ');
+ updateActivePattern(p => ({
+ ...p,
+ clinical_data: {
+ ...p.clinical_data,
+ acupuncture: { ...p.clinical_data.acupuncture, points: updated },
+ },
+ }));
+ setCustomPointInput('');
+ };
+
+ const handleRemovePointChip = (pointToRemove: string) => {
+ const updated = currentPoints.filter(p => p !== pointToRemove).join(', ');
+ updateActivePattern(p => ({
+ ...p,
+ clinical_data: {
+ ...p.clinical_data,
+ acupuncture: { ...p.clinical_data.acupuncture, points: updated },
+ },
+ }));
+ };
+
+ // 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
+ const handleSaveFullDisease = async () => {
+ if (!selectedCategoryCode || !selectedDiseaseCode) {
+ setError('Please select a Category and Disease first.');
+ return;
+ }
+ setSaving(true);
+ setError(null);
+ setSuccessMsg(null);
+ try {
+ // Also update category overview if changed
+ await moduleBuilderService.saveCategory(moduleCode, {
+ category_code: selectedCategoryCode,
+ name: categories.find(c => c.category_code === selectedCategoryCode)?.name || selectedCategoryCode,
+ overview: categoryOverview,
+ });
+
+ const payload = {
+ category_code: selectedCategoryCode,
+ disease_code: selectedDiseaseCode,
+ name: diseaseName.trim() || selectedDiseaseCode,
+ overview: diseaseOverview,
+ patterns: patterns.map((p, idx) => ({
+ category_code: selectedCategoryCode,
+ disease_code: selectedDiseaseCode,
+ pattern_code: p.pattern_code.trim() || `pattern_${idx}`,
+ name: p.name.trim() || `Pattern ${idx + 1}`,
+ description: p.description || '',
+ clinical_data: {
+ clinical_manifestations: p.clinical_data.clinical_manifestations.filter(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.trim().length > 0),
+ },
+ sort_order: idx,
+ })),
+ };
+
+ await moduleBuilderService.saveFullDisease(moduleCode, payload);
+ setSuccessMsg('All disease details and clinical patterns saved successfully!');
+ setTimeout(() => setSuccessMsg(null), 4000);
+ await fetchDiseases(selectedCategoryCode, selectedDiseaseCode);
+ } catch (err: any) {
+ setError(err?.response?.data?.detail || 'Failed to save changes');
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ // Seed sample Gynecological content if completely empty
+ const handleSeedSampleData = async () => {
+ 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 Chon 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(err?.response?.data?.detail || 'Failed to import sample data');
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ return (
+
+ {/* Top Banner & Context Bar */}
+
+
+
+
+
+
+
+
+ Clinical Module Builder
+
+ Gynecology (m0042)
+
+
+
+ Author and customize disease categories, clinical patterns, and treatment formulas.
+
+
+
+
+
+ {categories.length === 0 && (
+
+ )}
+
+
+
+
+
+ {/* Category & Disease Selector Controls */}
+
+ {/* Category Dropdown */}
+
+
+
+
+
+ {selectedCategoryCode && (
+
+ )}
+
+
+
+
+
+ {/* Disease Dropdown */}
+
+
+
+
+
+ {selectedDiseaseCode && (
+
+ )}
+
+
+
+
+
+
+ {/* Feedback Banners */}
+ {error && (
+
+ )}
+ {successMsg && (
+
+
+ {successMsg}
+
+ )}
+
+
+ {/* Main Phased Form Canvas */}
+ {selectedDiseaseCode ? (
+
+ {/* Disease Overview Card */}
+
+
+
+ Disease Pathology & Overview
+
+ Code: {selectedDiseaseCode}
+
+
+
+
+
+
+
+ {/* Pattern Differentiation & Clinical Data Form */}
+
+ {/* Pattern Tabs Header */}
+
+
+
+ Pattern Differentiation ({patterns.length})
+
+
+ Select a clinical pattern tab to customize symptoms, tongue, pulse, and acupuncture formula.
+
+
+
+
+
+ {/* Pattern Tabs Pills */}
+
+ {patterns.map((pat, idx) => (
+
setActivePatternIndex(idx)}
+ >
+ {pat.name || `Pattern ${idx + 1}`}
+ {patterns.length > 1 && (
+
+ )}
+
+ ))}
+
+
+ {/* Active Pattern Fields */}
+ {activePattern && (
+
+ {/* Pattern Identification */}
+
+
+
+
+ updateActivePattern(p => ({ ...p, description: e.target.value }))}
+ placeholder="Brief summary of key characteristics"
+ 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"
+ />
+
+
+ {/* Clinical Manifestations (Symptoms List) */}
+
+
+
+
+
+
+ {activePattern.clinical_data.clinical_manifestations.map((sym, sIdx) => (
+
+ {sIdx + 1}.
+ handleSymptomChange(sIdx, e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ handleAddSymptom();
+ }
+ }}
+ placeholder="e.g. Dull abdominal pain after childbirth relieved by pressure..."
+ className="flex-1 bg-slate-50 border border-slate-200 rounded-xl px-3 py-2 text-xs text-slate-800 focus:outline-none focus:border-indigo-500 font-medium"
+ />
+
+
+ ))}
+ {activePattern.clinical_data.clinical_manifestations.length === 0 && (
+
No symptoms added. Click "Add Symptom" above.
+ )}
+
+
+
+ {/* Tongue & Pulse Diagnosis */}
+
+ {/* 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) => (
+
+ ))}
+
+
+
+ {/* 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) => (
+
+ ))}
+
+
+
+
+ {/* 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"
+ />
+
+
+ {/* Acupuncture Formula & Points Chips */}
+
+
+ 📍 Acupuncture Prescription
+
+
+ {/* Active Point Chips */}
+
+
+
+ {currentPoints.map((pt, pIdx) => (
+
+ {pt}
+
+
+ ))}
+ setCustomPointInput(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ 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"
+ />
+
+
+
+ {/* Quick Suggestions for Points */}
+
+ Quick Add:
+ {COMMON_POINT_SUGGESTIONS.map((pt, idx) => {
+ const isAdded = currentPoints.includes(pt);
+ return (
+
+ );
+ })}
+
+
+ {/* Needling Method */}
+
+
+
+ updateActivePattern(p => ({
+ ...p,
+ clinical_data: {
+ ...p.clinical_data,
+ acupuncture: { ...p.clinical_data.acupuncture, method: e.target.value },
+ },
+ }))
+ }
+ placeholder="e.g. All with reinforcing method, moxa is applicable."
+ className="w-full bg-white border border-slate-200 rounded-xl px-3 py-2 text-xs font-semibold text-slate-800 focus:outline-none focus:border-indigo-500"
+ />
+
+
+
+ {/* Point Explanations */}
+
+
+
+
+
+
+ {activePattern.clinical_data.explanation.map((exp, eIdx) => (
+
+ •
+ handleExplanationChange(eIdx, e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ handleAddExplanation();
+ }
+ }}
+ placeholder="e.g. RN-6 tonifies Qi in general and moves Qi in the abdomen."
+ className="flex-1 bg-slate-50 border border-slate-200 rounded-xl px-3 py-2 text-xs text-slate-800 focus:outline-none focus:border-indigo-500 font-medium"
+ />
+
+
+ ))}
+ {activePattern.clinical_data.explanation.length === 0 && (
+
No explanations added yet.
+ )}
+
+
+
+ )}
+
+
+ ) : (
+
+
+
No Disease Selected
+
+ Choose an existing disease from the dropdown above, or click "+ Add Disease" to begin authoring clinical patterns.
+
+
+ )}
+
+ {/* MODAL: New Category */}
+ {showNewCategoryModal && (
+
+
+
+
+ Add Disease Category
+
+
+
+
+
+
+ )}
+
+ {/* MODAL: New Disease */}
+ {showNewDiseaseModal && (
+
+
+
+
+ Add Disease to Category
+
+
+
+
+
+
+ )}
+
+ );
+};
diff --git a/src/services/moduleBuilderService.ts b/src/services/moduleBuilderService.ts
new file mode 100644
index 0000000..e223616
--- /dev/null
+++ b/src/services/moduleBuilderService.ts
@@ -0,0 +1,155 @@
+import { api } from './api';
+
+export interface BuilderCategorySummary {
+ id?: string;
+ module_code: string;
+ category_code: string;
+ name: string;
+ overview?: string | null;
+ sort_order: number;
+ disease_count: number;
+}
+
+export interface BuilderDiseaseSummary {
+ id?: string;
+ module_code: string;
+ category_code: string;
+ disease_code: string;
+ name: string;
+ overview?: string | null;
+ sort_order: number;
+ pattern_count: number;
+}
+
+export interface PatternClinicalData {
+ clinical_manifestations: string[];
+ tongue: string;
+ pulse: string;
+ treatment_principle: string;
+ acupuncture: {
+ points: string;
+ method: string;
+ };
+ explanation: string[];
+}
+
+export interface BuilderPattern {
+ id?: string;
+ module_code: string;
+ category_code: string;
+ disease_code: string;
+ pattern_code: string;
+ name: string;
+ description?: string | null;
+ clinical_data: PatternClinicalData;
+ sort_order: number;
+}
+
+export interface BuilderDiseaseDetail {
+ id?: string;
+ module_code: string;
+ category_code: string;
+ disease_code: string;
+ name: string;
+ overview?: string | null;
+ sort_order: number;
+ patterns: BuilderPattern[];
+}
+
+export interface SaveFullDiseasePayload {
+ category_code: string;
+ disease_code: string;
+ name: string;
+ overview?: string | null;
+ patterns: {
+ category_code: string;
+ disease_code: string;
+ pattern_code: string;
+ name: string;
+ description?: string | null;
+ clinical_data: PatternClinicalData;
+ sort_order: number;
+ }[];
+}
+
+export const moduleBuilderService = {
+ // Categories
+ async getCategories(moduleCode: string): Promise {
+ const res = await api.get(`/api/admin/module-builder/${moduleCode}/categories`);
+ return res.data;
+ },
+
+ async saveCategory(
+ moduleCode: string,
+ data: { category_code: string; name: string; overview?: string; sort_order?: number }
+ ): Promise {
+ const res = await api.post(`/api/admin/module-builder/${moduleCode}/categories`, data);
+ return res.data;
+ },
+
+ async deleteCategory(moduleCode: string, categoryCode: string): Promise {
+ const res = await api.delete(`/api/admin/module-builder/${moduleCode}/categories/${categoryCode}`);
+ return res.data?.success ?? true;
+ },
+
+ // Diseases
+ async getDiseases(moduleCode: string, categoryCode: string): Promise {
+ const res = await api.get(`/api/admin/module-builder/${moduleCode}/categories/${categoryCode}/diseases`);
+ return res.data;
+ },
+
+ async getDiseaseDetail(
+ moduleCode: string,
+ categoryCode: string,
+ diseaseCode: string
+ ): Promise {
+ const res = await api.get(
+ `/api/admin/module-builder/${moduleCode}/categories/${categoryCode}/diseases/${diseaseCode}`
+ );
+ return res.data;
+ },
+
+ async saveDisease(
+ moduleCode: string,
+ categoryCode: string,
+ data: { disease_code: string; name: string; overview?: string; sort_order?: number }
+ ): Promise {
+ const res = await api.post(
+ `/api/admin/module-builder/${moduleCode}/categories/${categoryCode}/diseases`,
+ data
+ );
+ return res.data;
+ },
+
+ async deleteDisease(
+ moduleCode: string,
+ categoryCode: string,
+ diseaseCode: string
+ ): Promise {
+ const res = await api.delete(
+ `/api/admin/module-builder/${moduleCode}/categories/${categoryCode}/diseases/${diseaseCode}`
+ );
+ return res.data?.success ?? true;
+ },
+
+ // Save Full Disease with Patterns
+ async saveFullDisease(
+ moduleCode: string,
+ payload: SaveFullDiseasePayload
+ ): Promise {
+ const res = await api.post(`/api/admin/module-builder/${moduleCode}/save-full`, payload);
+ return res.data;
+ },
+
+ // Export JSON
+ async exportModuleJson(moduleCode: string): Promise {
+ const res = await api.get(`/api/admin/module-builder/${moduleCode}/export-json`);
+ return res.data;
+ },
+
+ // Import JSON
+ async importModuleJson(moduleCode: string, contents: any[]): Promise {
+ const res = await api.post(`/api/admin/module-builder/${moduleCode}/import-json`, { contents });
+ return res.data;
+ },
+};
diff --git a/src/types/index.ts b/src/types/index.ts
index 0851645..9acc3fe 100644
--- a/src/types/index.ts
+++ b/src/types/index.ts
@@ -1,6 +1,7 @@
export type AdminTabType =
| 'overview'
| 'modules'
+ | 'module_builder'
| 'plans'
| 'coupons'
| 'customers'