// ─── Admin Page ─────────────────────────────────────────────────────────────── // Quản lý Users + Groups. Chỉ admin mới truy cập được. const adminStyles = { page: { minHeight: '100vh', display: 'flex', flexDirection: 'column', background: 'var(--bg)' }, topbar: { height: '64px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', padding: '0 32px', gap: '20px', background: 'var(--bg-2)' }, brand: { display: 'flex', alignItems: 'center', gap: '10px', fontSize: '15px', fontWeight: 600, letterSpacing: '-0.01em' }, brandBadge: { fontSize: '10px', fontWeight: 500, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--text-mute)', padding: '3px 8px', border: '1px solid var(--border)', borderRadius: '999px' }, crumbs: { fontSize: '13px', color: 'var(--text-mute)', fontFamily: 'JetBrains Mono, monospace', marginLeft: '24px' }, backBtn: { marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: '6px', fontSize: '13px', color: 'var(--text-dim)', padding: '8px 14px', background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: '8px', cursor: 'pointer', transition: 'all 0.15s' }, main: { flex: 1, padding: '40px 32px 64px', maxWidth: '1100px', margin: '0 auto', width: '100%' }, head: { marginBottom: '32px' }, title: { fontSize: '28px', fontWeight: 600, letterSpacing: '-0.02em', margin: '0 0 8px 0' }, sub: { fontSize: '14px', color: 'var(--text-dim)', margin: 0 }, tabs: { display: 'flex', gap: '4px', marginBottom: '28px', background: 'var(--surface)', padding: '4px', borderRadius: '10px', border: '1px solid var(--border)', width: 'fit-content' }, tab: (active) => ({ padding: '8px 20px', fontSize: '13px', fontWeight: 500, borderRadius: '7px', cursor: 'pointer', transition: 'all 0.15s', background: active ? 'var(--accent-soft)' : 'transparent', color: active ? 'var(--accent-2)' : 'var(--text-mute)', border: active ? '1px solid rgba(76,141,255,0.25)' : '1px solid transparent' }), toolbar: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '16px' }, toolbarTitle: { fontSize: '15px', fontWeight: 500, color: 'var(--text)' }, addBtn: { display: 'flex', alignItems: 'center', gap: '6px', padding: '8px 16px', fontSize: '13px', fontWeight: 500, background: 'var(--accent)', color: '#fff', borderRadius: '8px', cursor: 'pointer', transition: 'all 0.15s', border: 'none' }, table: { width: '100%', borderCollapse: 'separate', borderSpacing: 0, background: 'var(--surface)', borderRadius: '12px', overflow: 'hidden', border: '1px solid var(--border)' }, th: { padding: '12px 16px', fontSize: '11px', fontWeight: 600, color: 'var(--text-mute)', textTransform: 'uppercase', letterSpacing: '0.08em', textAlign: 'left', borderBottom: '1px solid var(--border)', background: 'var(--bg-2)' }, td: { padding: '12px 16px', fontSize: '13px', color: 'var(--text)', borderBottom: '1px solid var(--border)', verticalAlign: 'middle' }, tdLast: { padding: '12px 16px', fontSize: '13px', color: 'var(--text)', verticalAlign: 'middle' }, avatar: { width: '28px', height: '28px', borderRadius: '50%', overflow: 'hidden', background: 'linear-gradient(135deg, #7aa7ff, #4c8dff)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: '11px', fontWeight: 600, color: '#0b1220', flexShrink: 0 }, userCell: { display: 'flex', alignItems: 'center', gap: '10px' }, nameEmail: { display: 'flex', flexDirection: 'column', gap: '1px' }, roleBadge: (role) => ({ display: 'inline-block', padding: '3px 10px', borderRadius: '999px', fontSize: '11px', fontWeight: 500, fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.04em', ...(role === 'admin' ? { background: 'rgba(76,141,255,0.15)', color: 'var(--accent-2)', border: '1px solid rgba(76,141,255,0.3)' } : { background: 'rgba(154,168,194,0.1)', color: 'var(--text-mute)', border: '1px solid var(--border)' }) }), actionBtn: { display: 'inline-flex', alignItems: 'center', gap: '4px', verticalAlign: 'middle', padding: '6px 10px', fontSize: '12px', borderRadius: '6px', cursor: 'pointer', transition: 'all 0.15s', border: '1px solid var(--border)', background: 'var(--surface)', color: 'var(--text-dim)', marginRight: '6px', whiteSpace: 'nowrap' }, dangerBtn: { display: 'inline-flex', alignItems: 'center', gap: '4px', verticalAlign: 'middle', padding: '6px 10px', fontSize: '12px', borderRadius: '6px', cursor: 'pointer', transition: 'all 0.15s', border: '1px solid rgba(255,106,106,0.3)', background: 'rgba(255,106,106,0.08)', color: 'var(--danger)', marginRight: 0, whiteSpace: 'nowrap' }, groupCard: { background: 'var(--surface)', borderRadius: '12px', border: '1px solid var(--border)', marginBottom: '12px', overflow: 'hidden' }, groupHeader: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '16px 20px', cursor: 'pointer', transition: 'background 0.15s' }, groupName: { fontSize: '15px', fontWeight: 600, display: 'flex', alignItems: 'center', gap: '10px' }, groupCount: { fontSize: '11px', color: 'var(--text-mute)', fontFamily: 'JetBrains Mono, monospace', padding: '2px 8px', background: 'var(--bg-2)', borderRadius: '999px' }, groupActions: { display: 'flex', gap: '6px', alignItems: 'center' }, groupBody: { padding: '0 20px 16px', borderTop: '1px solid var(--border)' }, memberRow: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 0', borderBottom: '1px solid var(--border)' }, memberInfo: { display: 'flex', alignItems: 'center', gap: '10px', fontSize: '13px' }, addMemberRow: { display: 'flex', alignItems: 'center', gap: '8px', paddingTop: '12px' }, addMemberSelect: { flex: 1, padding: '8px 12px', background: 'var(--bg-2)', border: '1px solid var(--border)', borderRadius: '8px', color: 'var(--text)', fontSize: '13px', outline: 'none' }, select: { padding: '8px 12px', background: 'var(--bg-2)', border: '1px solid var(--border)', borderRadius: '8px', color: 'var(--text)', fontSize: '13px', outline: 'none', cursor: 'pointer' }, input: { padding: '8px 12px', background: 'var(--bg-2)', border: '1px solid var(--border)', borderRadius: '8px', color: 'var(--text)', fontSize: '13px', outline: 'none' }, modal: { position: 'fixed', inset: 0, background: 'rgba(11,18,32,0.75)', backdropFilter: 'blur(8px)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 10000 }, modalCard: { background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: '16px', padding: '32px', width: '420px', maxWidth: '90vw' }, modalTitle: { fontSize: '18px', fontWeight: 600, margin: '0 0 20px 0' }, modalInput: { width: '100%', padding: '10px 14px', background: 'var(--bg-2)', border: '1px solid var(--border)', borderRadius: '8px', color: 'var(--text)', fontSize: '14px', outline: 'none', marginBottom: '16px' }, modalActions: { display: 'flex', gap: '10px', justifyContent: 'flex-end' }, modalCancel: { padding: '8px 18px', fontSize: '13px', borderRadius: '8px', background: 'var(--bg-2)', border: '1px solid var(--border)', color: 'var(--text-dim)', cursor: 'pointer' }, modalSubmit: { padding: '8px 18px', fontSize: '13px', fontWeight: 500, borderRadius: '8px', background: 'var(--accent)', border: 'none', color: '#fff', cursor: 'pointer' }, empty: { padding: '40px', textAlign: 'center', color: 'var(--text-mute)', fontSize: '13px', fontFamily: 'JetBrains Mono, monospace' }, error: { padding: '12px 16px', background: 'rgba(255,80,80,0.1)', border: '1px solid rgba(255,80,80,0.3)', borderRadius: '10px', fontSize: '13px', color: '#ff8080', marginBottom: '16px' }, loading: { display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '60px', gap: '12px', color: 'var(--text-mute)', fontSize: '13px' }, }; // ─── Users Tab ──────────────────────────────────────────────────────────────── function AdminUsersTab({ users, groups = [], onRefresh }) { const [error, setError] = React.useState(''); const [selectedUsers, setSelectedUsers] = React.useState(new Set()); const [bulkLoading, setBulkLoading] = React.useState(false); const [bulkGroupVal, setBulkGroupVal] = React.useState(''); const [bulkToolVal, setBulkToolVal] = React.useState(''); const [searchQuery, setSearchQuery] = React.useState(''); const filteredUsers = React.useMemo(() => { if (!searchQuery.trim()) return users; const lowerQ = searchQuery.toLowerCase(); return users.filter(u => (u.name && u.name.toLowerCase().includes(lowerQ)) || (u.email && u.email.toLowerCase().includes(lowerQ)) ); }, [users, searchQuery]); const toggleSelectAll = () => { if (selectedUsers.size === filteredUsers.length && filteredUsers.length > 0) { setSelectedUsers(new Set()); } else { setSelectedUsers(new Set(filteredUsers.map(u => u.id))); } }; const toggleSelect = (id) => { const newSet = new Set(selectedUsers); if (newSet.has(id)) newSet.delete(id); else newSet.add(id); setSelectedUsers(newSet); }; const handleBulkAddGroup = async () => { if (!bulkGroupVal || selectedUsers.size === 0) return; setBulkLoading(true); setError(''); try { await Promise.all([...selectedUsers].map(id => API.addGroupMember(bulkGroupVal, parseInt(id)))); setSelectedUsers(new Set()); setBulkGroupVal(''); onRefresh(); } catch (err) { setError(err.message); } finally { setBulkLoading(false); } }; const handleBulkRemoveGroup = async () => { if (!bulkGroupVal || selectedUsers.size === 0) return; setBulkLoading(true); setError(''); try { await Promise.all([...selectedUsers].map(id => API.removeGroupMember(bulkGroupVal, parseInt(id)))); setSelectedUsers(new Set()); setBulkGroupVal(''); onRefresh(); } catch (err) { setError(err.message); } finally { setBulkLoading(false); } }; const handleBulkEnableTool = async () => { if (!bulkToolVal || selectedUsers.size === 0) return; setBulkLoading(true); setError(''); try { await Promise.all([...selectedUsers].map(async id => { const u = users.find(x => x.id === id); const cur = u.allowed_tools || ['edit', 'resize', 'art_2d', 'art_3d', 'banner', 'banner_v2']; if (!cur.includes(bulkToolVal)) { await API.updateUserTools(id, [...cur, bulkToolVal]); } })); setSelectedUsers(new Set()); setBulkToolVal(''); onRefresh(); } catch (err) { setError(err.message); } finally { setBulkLoading(false); } }; const handleBulkDisableTool = async () => { if (!bulkToolVal || selectedUsers.size === 0) return; setBulkLoading(true); setError(''); try { await Promise.all([...selectedUsers].map(async id => { const u = users.find(x => x.id === id); const cur = u.allowed_tools || ['edit', 'resize', 'art_2d', 'art_3d', 'banner', 'banner_v2']; if (cur.includes(bulkToolVal)) { await API.updateUserTools(id, cur.filter(t => t !== bulkToolVal)); } })); setSelectedUsers(new Set()); setBulkToolVal(''); onRefresh(); } catch (err) { setError(err.message); } finally { setBulkLoading(false); } }; const handleBulkDelete = async () => { if (selectedUsers.size === 0) return; if (!window.confirm(`Bạn có chắc muốn xoá ${selectedUsers.size} users đã chọn? Tất cả jobs của họ sẽ bị xoá.`)) return; setBulkLoading(true); setError(''); try { await Promise.all([...selectedUsers].map(id => API.deleteUser(id))); setSelectedUsers(new Set()); onRefresh(); } catch (err) { setError(err.message); } finally { setBulkLoading(false); } }; const handleRoleChange = async (userId, currentRole) => { const newRole = currentRole === 'admin' ? 'user' : 'admin'; if (!window.confirm(`Đổi role thành "${newRole}"?`)) return; setError(''); try { await API.updateUserRole(userId, newRole); onRefresh(); } catch (err) { setError(err.message); } }; const handleToolToggle = async (userId, currentTools, tool) => { const hasIt = (currentTools || []).includes(tool); const newTools = hasIt ? (currentTools || []).filter(t => t !== tool) : [...(currentTools || []), tool]; setError(''); try { await API.updateUserTools(userId, newTools); onRefresh(); } catch (err) { setError(err.message); } }; const handleDelete = async (userId, name) => { if (!window.confirm(`Bạn có chắc muốn xoá user "${name}"? Tất cả jobs của user cũng sẽ bị xoá.`)) return; setError(''); try { await API.deleteUser(userId); onRefresh(); } catch (err) { setError(err.message); } }; const TOOL_LABELS = [ { key: 'edit', label: 'Sửa banner', color: '#3dd68c' }, { key: 'template', label: 'Tạo theo mẫu', color: '#e371ff' }, { key: 'resize', label: 'Resize', color: '#7aa7ff' }, { key: 'art_2d', label: 'Tạo art 2D', color: '#ffb347' }, { key: 'art_3d', label: 'Tạo art 3D', color: '#ff8c00' }, { key: 'banner', label: 'Tạo banner', color: '#ff6b9d' }, { key: 'banner_v2', label: 'Tạo banner V2', color: '#c850c0' }, ]; return (
{filteredUsers.length} users
setSearchQuery(e.target.value)} style={{ ...adminStyles.input, paddingLeft: '34px', width: '280px', margin: 0 }} />
{selectedUsers.size > 0 && (
Đã chọn {selectedUsers.size}
)}
{error &&
{error}
} {filteredUsers.map((u, i) => { const tools = u.allowed_tools || ['edit', 'resize', 'art_2d', 'art_3d', 'banner', 'banner_v2']; const isAdmin = u.role === 'admin'; const isSelected = selectedUsers.has(u.id); return ( ); })}
0} onChange={toggleSelectAll} style={{ cursor: 'pointer' }} /> User Role Groups Quyền sử dụng Đăng nhập lần cuối Actions
toggleSelect(u.id)} style={{ cursor: 'pointer' }} />
{u.avatar_url ? : (u.name || '?')[0].toUpperCase() }
{u.name} {u.email}
{u.role}
{(u.groups || []).map(g => ( {g.name} ))} {(!u.groups || u.groups.length === 0) && —}
{TOOL_LABELS.map(t => { const checked = isAdmin ? true : tools.includes(t.key); return ( ); })}
{isAdmin &&
Admin có tất cả quyền
}
{u.last_login ? new Date(u.last_login).toLocaleDateString('vi-VN') : '—'}
{users.length === 0 &&
Chưa có user nào.
}
); } // ─── Groups Tab ─────────────────────────────────────────────────────────────── function AdminGroupsTab({ groups, users, onRefresh }) { const [expanded, setExpanded] = React.useState(null); const [showCreate, setShowCreate] = React.useState(false); const [newGroupName, setNewGroupName] = React.useState(''); const [editingGroup, setEditingGroup] = React.useState(null); const [editName, setEditName] = React.useState(''); const [error, setError] = React.useState(''); const handleCreate = async () => { if (!newGroupName.trim()) return; setError(''); try { await API.createGroup(newGroupName.trim()); setNewGroupName(''); setShowCreate(false); onRefresh(); } catch (err) { setError(err.message); } }; const handleRename = async (groupId) => { if (!editName.trim()) return; setError(''); try { await API.updateGroup(groupId, editName.trim()); setEditingGroup(null); onRefresh(); } catch (err) { setError(err.message); } }; const handleDeleteGroup = async (groupId, name) => { if (!window.confirm(`Xoá group "${name}"? Members sẽ bị gỡ khỏi group.`)) return; setError(''); try { await API.deleteGroup(groupId); onRefresh(); } catch (err) { setError(err.message); } }; const handleAddMember = async (groupId, userId) => { setError(''); try { await API.addGroupMember(groupId, parseInt(userId)); onRefresh(); } catch (err) { setError(err.message); } }; const handleRemoveMember = async (groupId, userId, name) => { if (!window.confirm(`Gỡ "${name}" khỏi group?`)) return; setError(''); try { await API.removeGroupMember(groupId, userId); onRefresh(); } catch (err) { setError(err.message); } }; return (
{groups.length} groups
{error &&
{error}
} {groups.length === 0 &&
Chưa có group nào. Tạo group đầu tiên!
} {groups.map(g => { const isExpanded = expanded === g.id; const members = g.members || []; // Users not yet in this group const nonMembers = users.filter(u => !members.find(m => m.id === u.id)); return (
setExpanded(isExpanded ? null : g.id)} onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-2)'} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
{editingGroup === g.id ? ( setEditName(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') handleRename(g.id); if (e.key === 'Escape') setEditingGroup(null); }} onClick={e => e.stopPropagation()} autoFocus /> ) : ( {g.name} )} {members.length} members
e.stopPropagation()}> {editingGroup === g.id ? ( <> ) : ( <> )}
{isExpanded && (
{members.length === 0 && (
Chưa có member nào.
)} {members.map((m, i) => (
{m.avatar_url ? : (m.name || '?')[0].toUpperCase() }
{m.name}
{m.email}
))} {nonMembers.length > 0 && (
)}
)}
); })} {/* Create Group Modal */} {showCreate && (
setShowCreate(false)}>
e.stopPropagation()}>

Tạo group mới

setNewGroupName(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') handleCreate(); }} autoFocus />
)}
); } // ─── Prompts Tab ────────────────────────────────────────────────────────────── const FEATURE_ORDER = ['resize', 'edit', 'edit_rules', 'template_stage1', 'template_stage2', 'banner_prompt_a', 'banner_prompt_a_user', 'banner_prompt_b', 'banner_v2_prompt_a', 'banner_v2_prompt_b', 'art_styles', 'banner_styles']; const FEATURE_ICONS = { resize: , edit: , edit_rules: , template_stage1: , template_stage2: , banner_prompt_a: , banner_prompt_a_user: , banner_prompt_b: , banner_v2_prompt_a: , banner_v2_prompt_b: , art_styles: , banner_styles: , }; function ConfirmModal({ title, message, onConfirm, onCancel, danger = false }) { return (
e.stopPropagation()}>

{title}

{message}

); } function AdminPromptsTab({ onRefresh }) { const [prompts, setPrompts] = React.useState({}); const [artStyles, setArtStyles] = React.useState({}); const [bannerStyles, setBannerStyles] = React.useState({}); const [modelConfigs, setModelConfigs] = React.useState([]); const [selectedFeature, setSelectedFeature] = React.useState('resize'); const [loading, setLoading] = React.useState(true); const [error, setError] = React.useState(''); // For version edits const [editing, setEditing] = React.useState(null); // For group edits (Art Styles / Banner Styles) const [editingGroup, setEditingGroup] = React.useState(null); const [saving, setSaving] = React.useState(false); const [backupMsg, setBackupMsg] = React.useState(''); const [confirmObj, setConfirmObj] = React.useState(null); const [showRestoreModal, setShowRestoreModal] = React.useState(false); const fetchPrompts = async () => { setLoading(true); setError(''); try { const [res, artRes, bannerRes, modelRes] = await Promise.all([ API.getAdminPrompts(), API.getAdminArtStyles(), API.getAdminBannerStyles(), API.getModelConfigs(), ]); setPrompts(res.prompts || {}); setArtStyles(artRes.art_styles || {}); setBannerStyles(bannerRes.banner_styles || {}); setModelConfigs(modelRes.configs || []); } catch (err) { setError(err.message); } finally { setLoading(false); } }; React.useEffect(() => { fetchPrompts(); }, []); const isArtStyle = !!artStyles[selectedFeature]; const isBannerStyle = !!bannerStyles[selectedFeature]; const feature = isBannerStyle ? bannerStyles[selectedFeature] : isArtStyle ? artStyles[selectedFeature] : (prompts[selectedFeature] || { versions: [], label: selectedFeature, description: '', variables: [] }); const versions = feature.versions || []; const handleActivate = async (promptId) => { setConfirmObj({ title: 'Kích hoạt', message: 'Kích hoạt version này?', onConfirm: async () => { setConfirmObj(null); setError(''); try { if (isBannerStyle) { await API.activateBannerStyleVersion(promptId); } else if (isArtStyle) { await API.activateArtStyleVersion(promptId); } else { await API.activatePrompt(promptId); } fetchPrompts(); } catch (err) { setError(err.message); } } }); }; const handleDeleteVersion = async (promptId, name) => { setConfirmObj({ title: 'Xoá version', message: `Xoá version "${name}"? Không thể hoàn tác.`, danger: true, onConfirm: async () => { setConfirmObj(null); setError(''); try { if (isBannerStyle) { await API.deleteBannerStyleVersion(promptId); } else if (isArtStyle) { await API.deleteArtStyleVersion(promptId); } else { await API.deletePrompt(promptId); } fetchPrompts(); } catch (err) { setError(err.message); } } }); }; const handleDeleteGroup = async (styleCode, name) => { setConfirmObj({ title: 'Xoá Style Group', message: `Xoá toàn bộ style "${name}" (gồm tất cả versions)? Không thể hoàn tác.`, danger: true, onConfirm: async () => { setConfirmObj(null); setError(''); try { if (isBannerStyle) { await API.deleteBannerStyleGroup(styleCode); } else { await API.deleteArtStyleGroup(styleCode); } setSelectedFeature('resize'); fetchPrompts(); } catch (err) { setError(err.message); } } }); }; const handleReorderArtStyle = async (e, currentStyle, adjacentStyle) => { e.stopPropagation(); if (!adjacentStyle) return; try { setLoading(true); let newCurrentOrder = currentStyle.sort_order; let newAdjacentOrder = adjacentStyle.sort_order; // If both have the same sort order (e.g. both 0), we need to ensure they swap cleanly. if (newCurrentOrder === newAdjacentOrder) { // Just re-assign sequential sort orders for all styles of this type const sortedStyles = Object.values(artStyles) .filter(s => s.art_type === currentStyle.art_type) .sort((a, b) => a.sort_order - b.sort_order); const currIndex = sortedStyles.findIndex(s => s.style_code === currentStyle.style_code); const adjIndex = sortedStyles.findIndex(s => s.style_code === adjacentStyle.style_code); // Swap them in the array const temp = sortedStyles[currIndex]; sortedStyles[currIndex] = sortedStyles[adjIndex]; sortedStyles[adjIndex] = temp; // Update all sort_order sequentially await Promise.all(sortedStyles.map((s, idx) => API.updateArtStyleGroup(s.style_code, { ...s, sort_order: idx }) )); } else { // Normal swap await Promise.all([ API.updateArtStyleGroup(currentStyle.style_code, { ...currentStyle, sort_order: newAdjacentOrder }), API.updateArtStyleGroup(adjacentStyle.style_code, { ...adjacentStyle, sort_order: newCurrentOrder }) ]); } await fetchPrompts(); } catch (err) { alert('Lỗi khi sắp xếp: ' + err.message); setLoading(false); } }; const handleReorderBannerStyle = async (e, currentStyle, adjacentStyle) => { e.stopPropagation(); if (!adjacentStyle) return; try { setLoading(true); let newCurrentOrder = currentStyle.sort_order; let newAdjacentOrder = adjacentStyle.sort_order; if (newCurrentOrder === newAdjacentOrder) { const sortedStyles = Object.values(bannerStyles).sort((a, b) => a.sort_order - b.sort_order); const currIndex = sortedStyles.findIndex(s => s.style_code === currentStyle.style_code); const adjIndex = sortedStyles.findIndex(s => s.style_code === adjacentStyle.style_code); const temp = sortedStyles[currIndex]; sortedStyles[currIndex] = sortedStyles[adjIndex]; sortedStyles[adjIndex] = temp; await Promise.all(sortedStyles.map((s, idx) => API.updateBannerStyleGroup(s.style_code, { ...s, sort_order: idx }) )); } else { await Promise.all([ API.updateBannerStyleGroup(currentStyle.style_code, { ...currentStyle, sort_order: newAdjacentOrder }), API.updateBannerStyleGroup(adjacentStyle.style_code, { ...adjacentStyle, sort_order: newCurrentOrder }) ]); } await fetchPrompts(); } catch (err) { alert('Lỗi khi sắp xếp: ' + err.message); setLoading(false); } }; const handleSetDefaultStyle = async (styleCode) => { try { if (isBannerStyle) { await API.setDefaultBannerStyle(styleCode); } else { await API.setDefaultArtStyle(styleCode); } fetchPrompts(); } catch (err) { setError(err.message); } }; const handleSaveVersion = async () => { if (!editing) return; setSaving(true); setError(''); try { if (editing.id === 'new') { if (isBannerStyle) { await API.createBannerStyle({ name: feature.name, description: feature.description, prompt_b: editing.content, required_images: feature.required_images || ['character_art'], required_inputs: feature.required_inputs || ['main_text', 'sub_text', 'cta'], optional_inputs: feature.optional_inputs || [], layout_elements: feature.layout_elements || [], is_enabled: feature.is_enabled, sort_order: feature.sort_order, style_code: feature.style_code }); } else if (isArtStyle) { await API.createArtStyle({ art_type: feature.art_type, name: feature.name, description: feature.description, prompt: editing.content, is_enabled: feature.is_enabled, sort_order: feature.sort_order, style_code: feature.style_code }); } else { await API.createPrompt({ feature: selectedFeature, name: editing.name, content: editing.content, }); } } else { if (isBannerStyle) { await API.updateBannerStyleVersion(editing.id, { prompt_b: editing.content, }); } else if (isArtStyle) { await API.updateArtStyleVersion(editing.id, { prompt: editing.content, }); } else { await API.updatePrompt(editing.id, { name: editing.name, content: editing.content, }); } } setEditing(null); fetchPrompts(); } catch (err) { setError(err.message); } finally { setSaving(false); } }; const handleSaveGroup = async () => { if (!editingGroup) return; setSaving(true); setError(''); try { if (editingGroup.isNew) { if (editingGroup.isBanner) { const res = await API.createBannerStyle({ name: editingGroup.name, description: editingGroup.description, prompt_b: 'Banner Prompt B content here...', is_enabled: editingGroup.is_enabled, sort_order: parseInt(editingGroup.sort_order) || 0, required_images: editingGroup.required_images || ['character_art'], required_inputs: editingGroup.required_inputs || ['main_text', 'sub_text', 'cta'], optional_inputs: editingGroup.optional_inputs || [], layout_elements: editingGroup.layout_elements || ['character_zone', 'main_text_zone', 'sub_text_zone', 'cta_zone'], prompt_a_provider: editingGroup.prompt_a_provider || null, prompt_a_model: editingGroup.prompt_a_model || null, example_image: editingGroup.example_image || '', max_character_arts: parseInt(editingGroup.max_character_arts) || 1, max_screenshots: parseInt(editingGroup.max_screenshots) || 1, }); setSelectedFeature(res.style.style_code); } else { const res = await API.createArtStyle({ art_type: editingGroup.art_type, name: editingGroup.name, description: editingGroup.description, prompt: 'System prompt content here...', is_enabled: editingGroup.is_enabled, sort_order: parseInt(editingGroup.sort_order) || 0, }); setSelectedFeature(res.style.style_code); } } else { if (isBannerStyle) { await API.updateBannerStyleGroup(feature.style_code, { name: editingGroup.name, description: editingGroup.description, is_enabled: editingGroup.is_enabled, sort_order: parseInt(editingGroup.sort_order) || 0, required_images: editingGroup.required_images || feature.required_images || ['character_art'], required_inputs: editingGroup.required_inputs || feature.required_inputs || ['main_text', 'sub_text', 'cta'], optional_inputs: editingGroup.optional_inputs || feature.optional_inputs || [], layout_elements: editingGroup.layout_elements || feature.layout_elements || [], prompt_a_provider: editingGroup.prompt_a_provider || null, prompt_a_model: editingGroup.prompt_a_model || null, example_image: editingGroup.example_image || '', max_character_arts: parseInt(editingGroup.max_character_arts) || 1, max_screenshots: parseInt(editingGroup.max_screenshots) || 1, }); } else { await API.updateArtStyleGroup(feature.style_code, { name: editingGroup.name, description: editingGroup.description, is_enabled: editingGroup.is_enabled, sort_order: parseInt(editingGroup.sort_order) || 0, }); } } setEditingGroup(null); fetchPrompts(); } catch (err) { setError(err.message); } finally { setSaving(false); } }; const handleBackup = async () => { setBackupMsg(''); setError(''); try { const res = await API.backupPrompts(); setBackupMsg( Backup {res.total} prompts, {res.total_art_styles || 0} art styles, {res.total_banner_styles || 0} banner styles thành công! ({res.timestamp})); } catch (err) { setError(err.message); } }; const handleRestore = () => { setShowRestoreModal(true); }; const handleRestoreDone = (msg) => { setShowRestoreModal(false); setBackupMsg(msg); fetchPrompts(); }; const handleClone = (v) => { setEditing({ id: 'new', name: `${v.name || feature.name} (copy)`, content: v.content || v.prompt || v.prompt_b, }); }; if (loading && Object.keys(prompts).length === 0) { return (
Đang tải hệ thống...
); } return (
{/* Toolbar */}
Quản lý Prompts, Art Styles & Banner Styles
{error &&
{error}
} {backupMsg &&
{backupMsg}
} {/* Layout: sidebar + main */}
{/* Feature Sidebar */}
System Configs
System Prompts
{FEATURE_ORDER.filter(fk => fk !== 'art_styles' && fk !== 'banner_styles').map(fk => { const f = prompts[fk] || { label: fk, versions: [] }; const active = fk === selectedFeature; const hasActive = f.versions?.some(v => v.is_active); return ( ); })}
Art Styles 3D
{Object.values(artStyles).filter(s => s.art_type === '3d').sort((a, b) => a.sort_order - b.sort_order).map((s, index, arr) => { const active = s.style_code === selectedFeature; const hasActive = s.versions?.some(v => v.is_active); return (
setSelectedFeature(s.style_code)} style={{ display: 'flex', alignItems: 'center', gap: '10px', padding: '10px 14px', background: active ? 'var(--accent-soft)' : 'var(--surface)', border: active ? '1px solid rgba(76,141,255,0.35)' : '1px solid var(--border)', borderRadius: '10px', cursor: 'pointer', textAlign: 'left', transition: 'all 0.15s', color: active ? 'var(--accent-2)' : 'var(--text-dim)', }} onMouseEnter={e => { if (!active) e.currentTarget.style.background = 'var(--bg-2)'; }} onMouseLeave={e => { if (!active) e.currentTarget.style.background = 'var(--surface)'; }}>
{s.name} {s.is_default && }
{s.versions?.length || 0} version{s.versions?.length !== 1 ? 's' : ''} {hasActive && s.is_enabled && đang bật} {(!s.is_enabled) && đã tắt}
); })}
Art Styles 2D
{Object.values(artStyles).filter(s => s.art_type === '2d').sort((a, b) => a.sort_order - b.sort_order).map((s, index, arr) => { const active = s.style_code === selectedFeature; const hasActive = s.versions?.some(v => v.is_active); return (
setSelectedFeature(s.style_code)} style={{ display: 'flex', alignItems: 'center', gap: '10px', padding: '10px 14px', background: active ? 'var(--accent-soft)' : 'var(--surface)', border: active ? '1px solid rgba(76,141,255,0.35)' : '1px solid var(--border)', borderRadius: '10px', cursor: 'pointer', textAlign: 'left', transition: 'all 0.15s', color: active ? 'var(--accent-2)' : 'var(--text-dim)', }} onMouseEnter={e => { if (!active) e.currentTarget.style.background = 'var(--bg-2)'; }} onMouseLeave={e => { if (!active) e.currentTarget.style.background = 'var(--surface)'; }}>
{s.name} {s.is_default && }
{s.versions?.length || 0} version{s.versions?.length !== 1 ? 's' : ''} {hasActive && s.is_enabled && đang bật} {(!s.is_enabled) && đã tắt}
); })}
Banner Styles
{Object.values(bannerStyles).sort((a, b) => a.sort_order - b.sort_order).map((s, index, arr) => { const active = s.style_code === selectedFeature; const hasActive = s.versions?.some(v => v.is_active); return (
setSelectedFeature(s.style_code)} style={{ display: 'flex', alignItems: 'center', gap: '10px', padding: '10px 14px', background: active ? 'var(--accent-soft)' : 'var(--surface)', border: active ? '1px solid rgba(76,141,255,0.35)' : '1px solid var(--border)', borderRadius: '10px', cursor: 'pointer', textAlign: 'left', transition: 'all 0.15s', color: active ? 'var(--accent-2)' : 'var(--text-dim)', }} onMouseEnter={e => { if (!active) e.currentTarget.style.background = 'var(--bg-2)'; }} onMouseLeave={e => { if (!active) e.currentTarget.style.background = 'var(--surface)'; }}>
{s.name} {s.is_default && }
{s.versions?.length || 0} version{s.versions?.length !== 1 ? 's' : ''} {hasActive && s.is_enabled && đang bật} {(!s.is_enabled) && đã tắt}
); })}
{/* Main Content Area */}
{selectedFeature === 'model_configs' ? (

AI Model Configurations

{modelConfigs.map(c => (
{c.feature.toUpperCase()}
Provider: {c.provider}
))}
) : ( <> {/* Header Info */}
{feature.name || feature.label}
{(isArtStyle || isBannerStyle) && feature.is_default && MẶC ĐỊNH} {(isArtStyle || isBannerStyle) && feature.is_enabled && BẬT} {(isArtStyle || isBannerStyle) && !feature.is_enabled && TẮT} {isBannerStyle && BANNER}
{feature.description || 'Không có mô tả'}
{isBannerStyle && (
Model override cho Prompt A: {feature.prompt_a_model ? `${feature.prompt_a_model} (${feature.prompt_a_provider?.toUpperCase()})` : 'Mặc định hệ thống'}
)} {!isArtStyle && !isBannerStyle && feature.variables?.length > 0 && (
Biến: {feature.variables.join(', ')}
)}
{(isArtStyle || isBannerStyle) && ( <> {!feature.is_default && ( )} )}
{versions.length === 0 ? (
Chưa có prompt version nào.
Hệ thống đang dùng prompt mặc định từ code hoặc không hoạt động.
) : ( {versions.map((v, i) => ( ))}
Version Tên / Info Trạng thái Người tạo Ngày tạo Actions
v{v.version} {v.name || 'Art Version ' + v.version} {v.is_active ? ( Đang bật ) : ( Bản nháp )} {v.created_by || '—'} {v.created_at ? new Date(v.created_at).toLocaleDateString('vi-VN') : '—'} {!v.is_active && ( <> )}
)} )}
{/* Edit Version Modal */} {editing && (
!saving && setEditing(null)}>
e.stopPropagation()}>

{editing.id === 'new' ? `Tạo version mới — ${feature.name || feature.label}` : `Sửa version — ${editing.name || ('v' + versions.find(v => v.id === editing.id)?.version)}`}

{!isArtStyle && !isBannerStyle && ( setEditing({ ...editing, name: e.target.value })} /> )} {!isArtStyle && !isBannerStyle && feature.variables?.length > 0 && (
ⓘ Biến template khả dụng: {feature.variables.join(', ')} — giữ nguyên khi sửa
)} {isArtStyle && (
ⓘ Biến template khả dụng: {'{character_name}'} — được dùng thay thế tên nhân vật.
)}