feat(module-builder): add multi-module switcher, create modal, and export actions

This commit is contained in:
Urvish Prajapati 2026-11-13 15:21:59 +05:30
parent 68d802c4ce
commit 07ab27827d
2 changed files with 571 additions and 20 deletions

View File

@ -2,10 +2,12 @@ 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
HelpCircle, ChevronDown, ChevronUp, Stethoscope, HeartPulse, Download, Eye,
Package, UploadCloud, Check, FileArchive
} from 'lucide-react';
import {
moduleBuilderService,
type BuilderModuleSummary,
type BuilderCategorySummary,
type BuilderDiseaseSummary,
type BuilderPattern,
@ -83,7 +85,22 @@ const createBlankPattern = (moduleCode: string, catCode: string, disCode: string
});
export const ModuleBuilderTabContent: React.FC = () => {
const [moduleCode] = useState('m0042');
// Modules management
const [modules, setModules] = useState<BuilderModuleSummary[]>([]);
const [moduleCode, setModuleCode] = useState<string>(() => {
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<string | null>(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<BuilderCategorySummary[]>([]);
const [selectedCategoryCode, setSelectedCategoryCode] = useState<string>('');
const [categoryOverview, setCategoryOverview] = useState<string>('');
@ -118,12 +135,39 @@ export const ModuleBuilderTabContent: React.FC = () => {
// 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 (selectCatCode?: string) => {
const fetchCategories = async (modCode = moduleCode, selectCatCode?: string) => {
setLoading(true);
setError(null);
try {
const cats = await moduleBuilderService.getCategories(moduleCode);
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);
@ -132,9 +176,13 @@ export const ModuleBuilderTabContent: React.FC = () => {
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.'));
@ -144,7 +192,9 @@ export const ModuleBuilderTabContent: React.FC = () => {
};
useEffect(() => {
fetchCategories();
if (moduleCode) {
fetchCategories(moduleCode);
}
}, [moduleCode]);
// 2. Load Diseases when category changes
@ -707,6 +757,159 @@ export const ModuleBuilderTabContent: React.FC = () => {
}
};
// 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?')) {
@ -870,11 +1073,90 @@ export const ModuleBuilderTabContent: React.FC = () => {
<Layers className="h-5 w-5" />
</div>
<div>
<h3 className="text-lg font-black text-slate-900 tracking-tight flex items-center gap-2">
<h3 className="text-lg font-black text-slate-900 tracking-tight flex flex-wrap items-center gap-2">
Clinical Module Builder
<span className="text-xs px-2.5 py-0.5 rounded-full bg-indigo-50 border border-indigo-200 text-indigo-700 font-bold uppercase tracking-wider">
Gynecology (m0042)
</span>
{/* Module Selector Dropdown */}
<div className="relative inline-block">
<button
type="button"
onClick={() => setShowModuleDropdown(!showModuleDropdown)}
className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-indigo-50 hover:bg-indigo-100 border border-indigo-200 text-indigo-700 font-bold text-xs transition-colors shadow-2xs"
>
<span>{activeModule?.name || 'Gynecological Disorders'} ({moduleCode.toUpperCase()})</span>
<ChevronDown className="h-3.5 w-3.5 text-indigo-500" />
</button>
{showModuleDropdown && (
<>
<div
className="fixed inset-0 z-40"
onClick={() => setShowModuleDropdown(false)}
/>
<div className="absolute left-0 mt-2 w-72 bg-white rounded-2xl shadow-xl border border-slate-200 py-2 z-50">
<div className="px-3.5 py-1.5 text-[10px] font-black uppercase tracking-wider text-slate-400">
Active Clinical Modules
</div>
<div className="max-h-60 overflow-y-auto divide-y divide-slate-100">
{modules.map((m) => (
<button
key={m.code}
type="button"
onClick={() => handleSwitchModule(m.code)}
className={`w-full text-left px-3.5 py-2.5 flex items-center justify-between hover:bg-indigo-50/50 transition-colors ${
m.code === moduleCode ? 'bg-indigo-50/70 text-indigo-900 font-bold' : 'text-slate-700'
}`}
>
<div>
<div className="text-xs font-bold flex items-center gap-1.5">
<span>{m.name}</span>
<span className="font-mono text-[10px] px-1.5 py-0.2 rounded bg-slate-100 text-slate-600 uppercase">
{m.code}
</span>
</div>
<div className="text-[10px] text-slate-400 font-medium">
{m.category_count} categories · {m.disease_count} diseases
</div>
</div>
<div className="flex items-center gap-1.5 shrink-0">
{m.code === moduleCode && <Check className="h-4 w-4 text-indigo-600" />}
{m.code !== 'm0042' && (
<button
type="button"
onClick={(e) => {
e.stopPropagation();
handleDeleteModule();
}}
className="p-1 hover:bg-rose-100 text-slate-300 hover:text-rose-600 rounded-lg transition-colors"
title={`Delete module ${m.name}`}
>
<Trash2 className="h-3 w-3" />
</button>
)}
</div>
</button>
))}
</div>
<div className="p-2 border-t border-slate-100 mt-1">
<button
type="button"
onClick={() => {
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"
>
<Plus className="h-3.5 w-3.5" />
<span>+ Create New Module</span>
</button>
</div>
</div>
</>
)}
</div>
</h3>
<p className="text-xs text-slate-500 font-medium">
Author and customize disease categories, clinical patterns, and treatment formulas.
@ -926,17 +1208,87 @@ export const ModuleBuilderTabContent: React.FC = () => {
Preview Card
</button>
{/* Download JSON Button */}
<button
type="button"
onClick={handleDownloadJson}
disabled={downloading || 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="Download full module JSON ready for seeding"
>
{downloading ? <RefreshCw className="h-3.5 w-3.5 animate-spin" /> : <Download className="h-3.5 w-3.5" />}
Download JSON
</button>
{/* Export & Package Menu */}
<div className="relative inline-block">
<button
type="button"
onClick={() => 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 ? (
<RefreshCw className="h-3.5 w-3.5 animate-spin" />
) : (
<Package className="h-3.5 w-3.5" />
)}
<span>Export & Publish</span>
<ChevronDown className="h-3 w-3 opacity-70" />
</button>
{showExportMenu && (
<>
<div
className="fixed inset-0 z-40"
onClick={() => setShowExportMenu(false)}
/>
<div className="absolute right-0 mt-2 w-64 bg-white rounded-2xl shadow-xl border border-slate-200 py-2 z-50">
<div className="px-3.5 py-1.5 text-[10px] font-black uppercase tracking-wider text-slate-400">
Production Packaging
</div>
<button
type="button"
onClick={handleExportZip}
disabled={exportingZip}
className="w-full text-left px-3.5 py-2.5 hover:bg-indigo-50/50 flex items-start gap-2.5 transition-colors group"
>
<FileArchive className="h-4 w-4 text-indigo-600 mt-0.5 shrink-0" />
<div>
<div className="text-xs font-bold text-slate-800 group-hover:text-indigo-600">
Download Acupedia (.zip)
</div>
<div className="text-[10px] text-slate-400">
Complete package with module.json, templates/, & data/
</div>
</div>
</button>
<button
type="button"
onClick={handleSyncContentRepo}
disabled={syncingRepo}
className="w-full text-left px-3.5 py-2.5 hover:bg-emerald-50/50 flex items-start gap-2.5 transition-colors group"
>
<UploadCloud className="h-4 w-4 text-emerald-600 mt-0.5 shrink-0" />
<div>
<div className="text-xs font-bold text-slate-800 group-hover:text-emerald-600">
Sync to acupedia-content
</div>
<div className="text-[10px] text-slate-400">
Save to disk & register in root config.json
</div>
</div>
</button>
<div className="my-1 border-t border-slate-100" />
<button
type="button"
onClick={() => {
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 className="h-3.5 w-3.5 text-slate-400" />
<span>Download Raw JSON (Backup)</span>
</button>
</div>
</>
)}
</div>
{categories.length === 0 && (
<button
@ -1913,6 +2265,133 @@ export const ModuleBuilderTabContent: React.FC = () => {
</div>
)}
{/* Create New Module Modal */}
{showNewModuleModal && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/40 backdrop-blur-xs">
<div className="bg-white rounded-2xl max-w-md w-full p-6 shadow-2xl border border-slate-200 space-y-4">
<div className="flex items-center justify-between pb-2 border-b border-slate-100">
<div className="flex items-center gap-2">
<div className="p-2 rounded-xl bg-indigo-50 text-indigo-600">
<Package className="h-4 w-4" />
</div>
<h4 className="text-sm font-black text-slate-900">Create New Therapeutic Module</h4>
</div>
<button
type="button"
onClick={() => {
setShowNewModuleModal(false);
setModalModError(null);
}}
className="text-slate-400 hover:text-slate-600"
>
<X className="h-4 w-4" />
</button>
</div>
{modalModError && (
<div className="p-3 bg-rose-50 border border-rose-200 text-rose-700 text-xs rounded-xl font-semibold flex items-center justify-between gap-2">
<div className="flex items-center gap-2">
<AlertCircle className="h-4 w-4 shrink-0 text-rose-600" />
<span>{modalModError}</span>
</div>
<button
type="button"
onClick={() => setModalModError(null)}
className="text-rose-400 hover:text-rose-700 p-0.5"
>
<X className="h-3 w-3" />
</button>
</div>
)}
<form onSubmit={handleCreateModule} className="space-y-4">
<div className="space-y-2">
<label className="text-[11px] uppercase font-bold text-slate-700">
Module Name <span className="text-rose-500">*</span>
</label>
<input
type="text"
required
autoFocus
value={newModuleName}
onChange={(e) => {
setNewModuleName(e.target.value);
if (modalModError) setModalModError(null);
}}
placeholder="e.g. Pediatric Disorders"
className="w-full bg-slate-50 border border-slate-200 rounded-xl px-3 py-2.5 text-xs font-bold text-slate-800 focus:outline-none focus:border-indigo-500"
/>
</div>
<div className="space-y-2">
<label className="text-[11px] uppercase font-bold text-slate-700">
Module Code (e.g. m0043)
</label>
<input
type="text"
value={newModuleCode}
onChange={(e) => {
setNewModuleCode(e.target.value.toLowerCase().trim());
if (modalModError) setModalModError(null);
}}
placeholder="e.g. m0043"
className="w-full bg-slate-50 border border-slate-200 rounded-xl px-3 py-2.5 text-xs font-mono font-bold text-indigo-600 focus:outline-none focus:border-indigo-500"
/>
<p className="text-[11px] text-slate-400">
Must start with 'm' followed by 4 digits. Leave as suggested or customize.
</p>
</div>
<div className="space-y-2">
<label className="text-[11px] uppercase font-bold text-slate-700">
Short Description
</label>
<input
type="text"
value={newModuleDesc}
onChange={(e) => setNewModuleDesc(e.target.value)}
placeholder="e.g. TCM pediatrics and children's health"
className="w-full 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"
/>
</div>
<div className="text-[11px] text-slate-500 flex items-center justify-between font-mono bg-slate-100 px-3 py-1.5 rounded-lg border border-slate-200">
<span className="text-slate-400">System Slug:</span>
<span className="font-bold text-indigo-600">
{toSnakeCase(newModuleName).replace(/_/g, '-') || '...'}
</span>
</div>
<div className="flex items-center justify-between text-[11px] bg-emerald-50/60 border border-emerald-200 text-emerald-800 px-3 py-1.5 rounded-lg font-mono">
<span>Kind: <strong className="uppercase">therapeutic</strong></span>
<span className="text-slate-300">|</span>
<span>Managed By: <strong>module_builder</strong></span>
</div>
<div className="flex justify-end gap-2 pt-2">
<button
type="button"
onClick={() => {
setShowNewModuleModal(false);
setModalModError(null);
}}
className="px-4 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 text-xs font-bold rounded-xl"
>
Cancel
</button>
<button
type="submit"
disabled={creatingModule || !newModuleName.trim()}
className="px-4 py-2 bg-indigo-600 hover:bg-indigo-500 disabled:bg-slate-300 text-white text-xs font-bold rounded-xl shadow"
>
{creatingModule ? 'Creating Module...' : 'Create Module'}
</button>
</div>
</form>
</div>
</div>
)}
{/* MODAL: New Disease (Name only -> Code auto-generated) */}
{showNewDiseaseModal && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/50 backdrop-blur-xs">

View File

@ -1,5 +1,24 @@
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;
@ -73,6 +92,31 @@ export interface SaveFullDiseasePayload {
}
export const moduleBuilderService = {
// Modules
async getModules(): Promise<BuilderModuleSummary[]> {
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<BuilderModuleSummary> {
const res = await api.post('/api/admin/module-builder/modules', data);
return res.data;
},
async deleteModule(moduleCode: string): Promise<boolean> {
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<BuilderCategorySummary[]> {
const res = await api.get(`/api/admin/module-builder/${moduleCode}/categories`);
@ -147,6 +191,34 @@ export const moduleBuilderService = {
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<any> {
const res = await api.post(`/api/admin/module-builder/${moduleCode}/import-json`, { contents });