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) => (
+
+ ))}
+
+
+
{
+ setShowModuleDropdown(false);
+ setNewModuleName('');
+ setNewModuleCode(getSuggestedNextModuleCode());
+ setNewModuleDesc('');
+ setModalModError(null);
+ setShowNewModuleModal(true);
+ }}
+ className="w-full py-2 px-3 bg-indigo-600 hover:bg-indigo-500 text-white rounded-xl text-xs font-bold flex items-center justify-center gap-1.5 shadow-sm transition-colors"
+ >
+
+ + Create New Module
+
+
+
+ >
+ )}
+
+
+
+ Author and customize disease categories, clinical patterns, and treatment formulas.
+
+
+
+
+ {/* Action Toolbar */}
+
+ {/* Quick Guide Toggle */}
+
setShowQuickGuide(!showQuickGuide)}
+ className="px-3 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 text-xs font-bold rounded-xl flex items-center gap-1.5 transition-colors"
+ >
+
+ Guide
+ {showQuickGuide ? : }
+
+
+ {/* Revert to Blank Form Button */}
+
+
+ Reset to Blank Form
+
+
+ {/* Live Clinical Preview Button */}
+
{
+ if (!isFormActive) {
+ setError('Please select or author a disease first to preview its clinical card.');
+ return;
+ }
+ setPreviewPatternIdx(0);
+ setShowPreviewModal(true);
+ }}
+ disabled={!isFormActive}
+ className="px-3.5 py-2 bg-slate-100 hover:bg-slate-200 disabled:bg-slate-100 disabled:text-slate-400 text-slate-700 text-xs font-bold rounded-xl flex items-center gap-1.5 transition-colors"
+ title="Preview clinical presentation card"
+ >
+
+ Preview Card
+
+
+ {/* Export & Package Menu */}
+
+
setShowExportMenu(!showExportMenu)}
+ disabled={downloading || exportingZip || syncingRepo || categories.length === 0}
+ className="px-3.5 py-2 bg-slate-900 hover:bg-slate-800 disabled:bg-slate-300 text-white text-xs font-bold rounded-xl flex items-center gap-1.5 shadow transition-colors"
+ title="Export or publish clinical module"
+ >
+ {exportingZip || syncingRepo ? (
+
+ ) : (
+
+ )}
+ Export & Publish
+
+
+
+ {showExportMenu && (
+ <>
+
setShowExportMenu(false)}
+ />
+
+
+ Production Packaging
+
+
+
+
+
+
+ Download Acupedia (.zip)
+
+
+ Complete package with module.json, templates/, & data/
+
+
+
+
+
+
+
+
+ Sync to acupedia-content
+
+
+ Save to disk & register in root config.json
+
+
+
+
+
+
+
{
+ setShowExportMenu(false);
+ handleDownloadJson();
+ }}
+ disabled={downloading}
+ className="w-full text-left px-3.5 py-2 hover:bg-slate-50 flex items-center gap-2.5 text-slate-600 text-xs font-semibold"
+ >
+
+ Download Raw JSON (Backup)
+
+
+ >
+ )}
+
+
+ {categories.length === 0 && (
+
+
+ Load Sample Template
+
+ )}
+
+ {/* Save Button */}
+
+ {saving ? : }
+ Save Changes
+
+
+
+
+ {/* Quick User Guide (Expandable) */}
+ {showQuickGuide && (
+
+
+
+ Quick Guide: How to Use the Module Builder
+
+ setShowQuickGuide(false)}
+ className="text-indigo-400 hover:text-indigo-700"
+ >
+
+
+
+
+
+
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 */}
+
+
+
+
+
{
+ setNewCategoryName('');
+ setModalCatError(null);
+ setShowNewCategoryModal(true);
+ }}
+ className="text-indigo-600 hover:text-indigo-800 text-[11px] font-bold flex items-center gap-0.5"
+ >
+ Add Category
+
+ {selectedCategoryCode && (
+
+
+
+ )}
+
+
+
+
+
+ {/* Disease Dropdown */}
+
+
+
+
+
{
+ if (!selectedCategoryCode) {
+ setError('Please select or create a category before adding a disease.');
+ return;
+ }
+ setNewDiseaseName('');
+ setModalDisError(null);
+ setShowNewDiseaseModal(true);
+ }}
+ disabled={!selectedCategoryCode}
+ className="text-indigo-600 hover:text-indigo-800 disabled:text-slate-400 text-[11px] font-bold flex items-center gap-0.5"
+ >
+ Add Disease
+
+ {selectedDiseaseCode && (
+
+
+
+ )}
+
+
+
+
+
+
+ {/* Feedback Banners with Dismiss Button */}
+ {error && (
+
+
+
setError(null)}
+ className="text-rose-400 hover:text-rose-700 p-1 shrink-0"
+ title="Dismiss error"
+ >
+
+
+
+ )}
+ {successMsg && (
+
+
+
+ {successMsg}
+
+
setSuccessMsg(null)}
+ className="text-emerald-400 hover:text-emerald-700 p-1 shrink-0"
+ title="Dismiss"
+ >
+
+
+
+ )}
+
+
+ {/* Main Phased Form Canvas */}
+ {isFormActive ? (
+
+ {/* Disease Pathology Card */}
+
+
+
+
+ Disease Pathology & Overview
+
+
+ {isCreatingNewDisease && (
+
+ Authoring New
+
+ )}
+
+ System Code: {toSnakeCase(diseaseName || selectedDiseaseCode || 'new_disease')}
+
+
+
+
+
+
+ {/* Disease Pathology Description */}
+
+
+
+
+
+ {/* Pattern Differentiation & Clinical Data Form */}
+
+ {/* Pattern Tabs Header */}
+
+
+
+
+ Clinical Patterns ({patterns.length})
+
+
+ Select a clinical pattern tab to customize manifestations, tongue, pulse, and acupuncture prescription.
+
+
+
+
+ Add Pattern
+
+
+
+ {/* Pattern Tabs Pills */}
+
+ {patterns.map((pat, idx) => (
+
{
+ setActivePatternIndex(idx);
+ if (error) setError(null);
+ }}
+ >
+ {pat?.name || `Pattern ${idx + 1}`}
+ {patterns.length > 1 && (
+ {
+ e.stopPropagation();
+ handleRemovePattern(idx);
+ }}
+ className={`h-4 w-4 rounded-full flex items-center justify-center hover:bg-black/10 transition-colors ml-1 ${
+ safePatternIndex === idx ? 'text-white' : 'text-slate-400 hover:text-slate-700'
+ }`}
+ title="Delete pattern"
+ >
+
+
+ )}
+
+ ))}
+
+
+ {/* Active Pattern Fields */}
+ {activePattern ? (
+
+ {/* Pattern Identification (Name only -> Code auto-generated) */}
+
+
+
+ {
+ const val = e.target.value;
+ updateActivePattern(p => ({
+ ...p,
+ name: val,
+ pattern_code: toSnakeCase(val || 'pattern'),
+ }));
+ if (error) setError(null);
+ }}
+ onBlur={() => {
+ if (activePattern.name?.trim()) {
+ updateActivePattern(p => ({
+ ...p,
+ name: toTitleCase(activePattern.name.trim()),
+ }));
+ }
+ }}
+ placeholder="e.g. Blood Deficiency"
+ 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"
+ />
+
+
+
+
+ {toSnakeCase(activePattern.name || 'primary_pattern')}
+
+
+
+
+
+
+ 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) */}
+
+
+
+
+ Add Symptom
+
+
+
+ {(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"
+ />
+ handleRemoveSymptom(sIdx)}
+ className="p-1.5 text-slate-400 hover:text-rose-500 transition-colors"
+ title="Remove Symptom"
+ >
+
+
+
+ ))}
+ {(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) => (
+
+ updateActivePattern(p => ({
+ ...p,
+ clinical_data: { ...p.clinical_data, tongue: t },
+ }))
+ }
+ className="text-[10px] px-2 py-0.5 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-600 font-medium"
+ >
+ {t}
+
+ ))}
+
+
+
+ {/* 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) => (
+
+ updateActivePattern(p => ({
+ ...p,
+ clinical_data: { ...p.clinical_data, pulse: pls },
+ }))
+ }
+ className="text-[10px] px-2 py-0.5 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-600 font-medium"
+ >
+ {pls}
+
+ ))}
+
+
+
+
+ {/* 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}
+ handleRemovePointChip(pt)}
+ className="text-indigo-400 hover:text-indigo-700"
+ title="Remove point"
+ >
+
+
+
+ ))}
+ 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 (
+ handleAddPointChip(pt)}
+ disabled={isAdded}
+ className={`text-[10px] font-bold px-2 py-0.5 rounded-lg border transition-all ${
+ isAdded
+ ? 'bg-slate-200 text-slate-400 border-slate-200 cursor-default'
+ : 'bg-white hover:bg-indigo-50 border-slate-200 hover:border-indigo-300 text-slate-700 hover:text-indigo-600'
+ }`}
+ >
+ +{pt}
+
+ );
+ })}
+
+
+ {/* Needling Method */}
+
+
+
+ updateActivePattern(p => ({
+ ...p,
+ clinical_data: {
+ ...p.clinical_data,
+ acupuncture: {
+ points: p.clinical_data?.acupuncture?.points || '',
+ 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 */}
+
+
+
+
+ Add Explanation
+
+
+
+ {(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"
+ />
+ handleRemoveExplanation(eIdx)}
+ className="p-1.5 text-slate-400 hover:text-rose-500 transition-colors"
+ title="Remove Explanation"
+ >
+
+
+
+ ))}
+ {(activePattern.clinical_data?.explanation || []).length === 0 && (
+
No explanations added yet.
+ )}
+
+
+
+ ) : (
+
+ No active pattern selected. Click "+ Add Pattern" above.
+
+ )}
+
+
+ ) : (
+
+
+
+
No Disease Selected
+
+ Choose an existing disease from the dropdown above, click + Add Disease, or start with a Blank Form to author a new condition.
+
+
+
+
{
+ if (!selectedCategoryCode) {
+ setError('Please select or create a Category first.');
+ return;
+ }
+ setNewDiseaseName('');
+ setModalDisError(null);
+ setShowNewDiseaseModal(true);
+ }}
+ disabled={!selectedCategoryCode}
+ className="px-4 py-2 bg-indigo-600 hover:bg-indigo-500 disabled:bg-slate-200 disabled:text-slate-400 text-white text-xs font-bold rounded-xl flex items-center gap-1.5 shadow transition-all"
+ >
+ Add Disease
+
+
+ Start Blank Form
+
+
+
+ )}
+
+ {/* MODAL: Clinical Card Preview */}
+ {showPreviewModal && (
+
+
+
+
+
+
+
+
+
{diseaseName || 'Untitled Disease'}
+
+ Category: {categories.find(c => c.category_code === selectedCategoryCode)?.name || selectedCategoryCode}
+
+
+
+
setShowPreviewModal(false)}
+ className="text-slate-400 hover:text-slate-600 p-1"
+ >
+
+
+
+
+ {/* Disease Pathology Overview */}
+ {diseaseOverview && (
+
+
Pathology & Etiology
+
{diseaseOverview}
+
+ )}
+
+ {/* Pattern Tabs */}
+ {patterns.length > 0 && (
+
+
+ {patterns.map((p, idx) => (
+ setPreviewPatternIdx(idx)}
+ className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all ${
+ previewPatternIdx === idx
+ ? 'bg-indigo-600 text-white shadow-xs'
+ : 'bg-slate-100 hover:bg-slate-200 text-slate-700'
+ }`}
+ >
+ {p.name || `Pattern ${idx + 1}`}
+
+ ))}
+
+
+ {patterns[previewPatternIdx] && (
+
+
+
{patterns[previewPatternIdx].name}
+ {patterns[previewPatternIdx].description && (
+
{patterns[previewPatternIdx].description}
+ )}
+
+
+ {/* Symptoms */}
+
+
Key Manifestations
+
+ {(patterns[previewPatternIdx].clinical_data?.clinical_manifestations || []).map((s, idx) => (
+ -
+ โข
+ {s}
+
+ ))}
+
+
+
+ {/* Tongue & Pulse Grid */}
+
+
+ Tongue
+
+ {patterns[previewPatternIdx].clinical_data?.tongue || 'โ'}
+
+
+
+ Pulse
+
+ {patterns[previewPatternIdx].clinical_data?.pulse || 'โ'}
+
+
+
+
+ {/* Treatment Principle */}
+
+ Treatment Principle
+
+ {patterns[previewPatternIdx].clinical_data?.treatment_principle || 'โ'}
+
+
+
+ {/* Acupuncture Prescription */}
+
+
Acupuncture Points
+
+ {(patterns[previewPatternIdx].clinical_data?.acupuncture?.points || '')
+ .split(',')
+ .map(s => s.trim())
+ .filter(Boolean)
+ .map((pt, idx) => (
+
+ {pt}
+
+ ))}
+
+ {patterns[previewPatternIdx].clinical_data?.acupuncture?.method && (
+
+ Method: {patterns[previewPatternIdx].clinical_data.acupuncture.method}
+
+ )}
+
+
+ {/* Point Explanations */}
+ {(patterns[previewPatternIdx].clinical_data?.explanation || []).length > 0 && (
+
+
Explanations
+
+ {(patterns[previewPatternIdx].clinical_data?.explanation || []).map((exp, idx) => (
+ -
+ โข
+ {exp}
+
+ ))}
+
+
+ )}
+
+ )}
+
+ )}
+
+
+
+ Download Full JSON
+
+ setShowPreviewModal(false)}
+ className="px-4 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 text-xs font-bold rounded-xl"
+ >
+ Close Preview
+
+
+
+
+ )}
+
+ {/* MODAL: New Category (Name only -> Code auto-generated) */}
+ {showNewCategoryModal && (
+
+
+
+
+ Add Disease Category
+
+ {
+ setShowNewCategoryModal(false);
+ setModalCatError(null);
+ }}
+ className="text-slate-400 hover:text-slate-600"
+ >
+
+
+
+
+ {modalCatError && (
+
+
+
setModalCatError(null)}
+ className="text-rose-400 hover:text-rose-700 p-0.5"
+ >
+
+
+
+ )}
+
+
+
+
+ )}
+
+ {/* Create New Module Modal */}
+ {showNewModuleModal && (
+
+
+
+
+
+
Create New Therapeutic Module
+
+
{
+ setShowNewModuleModal(false);
+ setModalModError(null);
+ }}
+ className="text-slate-400 hover:text-slate-600"
+ >
+
+
+
+
+ {modalModError && (
+
+
+
setModalModError(null)}
+ className="text-rose-400 hover:text-rose-700 p-0.5"
+ >
+
+
+
+ )}
+
+
+
+
+ )}
+
+ {/* MODAL: New Disease (Name only -> Code auto-generated) */}
+ {showNewDiseaseModal && (
+
+
+
+
+ Add Disease to Category
+
+ {
+ setShowNewDiseaseModal(false);
+ setModalDisError(null);
+ }}
+ className="text-slate-400 hover:text-slate-600"
+ >
+
+
+
+
+ {modalDisError && (
+
+
+
setModalDisError(null)}
+ className="text-rose-400 hover:text-rose-700 p-0.5"
+ >
+
+
+
+ )}
+
+
+
+
+ )}
+
+ );
+};
+
+export const ModuleBuilderTab: React.FC = () => (
+
+
+
+);
diff --git a/src/services/moduleBuilderService.ts b/src/services/moduleBuilderService.ts
new file mode 100644
index 0000000..bfdd6f5
--- /dev/null
+++ b/src/services/moduleBuilderService.ts
@@ -0,0 +1,228 @@
+import { api } from './api';
+
+export interface BuilderModuleSummary {
+ id?: string;
+ code: string;
+ name: string;
+ slug: string;
+ short_description?: string | null;
+ description?: string | null;
+ kind: string;
+ managed_by: string;
+ default_template_code?: string | null;
+ sort_order: number;
+ is_active: boolean;
+ category_count: number;
+ disease_count: number;
+ pattern_count: number;
+ created_at?: string;
+ updated_at?: string;
+}
+
+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 = {
+ // Modules
+ async getModules(): Promise
{
+ const res = await api.get('/api/admin/module-builder/modules');
+ return res.data;
+ },
+
+ async createModule(data: {
+ name: string;
+ code?: string;
+ slug?: string;
+ short_description?: string;
+ description?: string;
+ kind?: string;
+ managed_by?: string;
+ sort_order?: number;
+ }): Promise {
+ const res = await api.post('/api/admin/module-builder/modules', data);
+ return res.data;
+ },
+
+ async deleteModule(moduleCode: string): Promise {
+ const res = await api.delete(`/api/admin/module-builder/modules/${moduleCode}`);
+ return res.data?.status === 'deleted' || res.status === 200;
+ },
+
+ // 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; category_code?: string }
+ ): Promise {
+ const res = await api.post(
+ `/api/admin/module-builder/${moduleCode}/categories/${categoryCode}/diseases`,
+ { ...data, category_code: categoryCode }
+ );
+ 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;
+ },
+
+ // Export Production ZIP Package
+ async exportBundleZip(moduleCode: string): Promise<{ blob: Blob; filename: string }> {
+ const res = await api.get(`/api/admin/module-builder/${moduleCode}/export-bundle`, {
+ responseType: 'blob',
+ });
+ const disposition = res.headers['content-disposition'] || '';
+ let filename = `${moduleCode}_package.zip`;
+ const match = disposition.match(/filename="?([^";]+)"?/);
+ if (match && match[1]) {
+ filename = match[1];
+ }
+ return { blob: res.data, filename };
+ },
+
+ // Sync Directly to Content Repo
+ async syncContentRepo(moduleCode: string): Promise<{
+ status: string;
+ module_code: string;
+ module_name: string;
+ target_dir: string;
+ files_written: number;
+ config_updated: boolean;
+ message: string;
+ }> {
+ const res = await api.post(`/api/admin/module-builder/${moduleCode}/sync-content-repo`);
+ 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'