Compare commits
15 commits
ec4592c056
...
2a09579f45
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2a09579f45 | ||
|
|
24150f36d5 | ||
|
|
3710172e65 | ||
|
|
d0c1484136 | ||
|
|
dcd1182521 | ||
|
|
13f4574098 | ||
|
|
d814a76660 | ||
|
|
2e00f3ac44 | ||
|
|
5f71ba04d4 | ||
|
|
73a0ba151b | ||
|
|
7ab2cdff2d | ||
|
|
c431fe28bc | ||
|
|
dbec57d647 | ||
|
|
4c959538ac | ||
|
|
74d0ce429a |
93 changed files with 3945 additions and 1167 deletions
|
|
@ -31,6 +31,7 @@ import { LanguageProvider } from './providers/language/LanguageContext';
|
|||
import { ToastProvider } from './contexts/ToastContext';
|
||||
import { WorkflowSelectionProvider } from './contexts/WorkflowSelectionContext';
|
||||
import { FileProvider } from './contexts/FileContext';
|
||||
import { VoiceCatalogProvider } from './contexts/VoiceCatalogContext';
|
||||
import { MainLayout } from './layouts/MainLayout';
|
||||
import { FeatureLayout } from './layouts/FeatureLayout';
|
||||
import { DashboardPage } from './pages/Dashboard';
|
||||
|
|
@ -39,7 +40,7 @@ import { GDPRPage } from './pages/GDPR';
|
|||
import StorePage from './pages/Store';
|
||||
import { IntegrationsOverviewPage } from './pages/IntegrationsOverviewPage';
|
||||
import { FeatureViewPage } from './pages/FeatureView';
|
||||
import { AccessManagementHub, AdminMandatesPage, AdminUsersPage, AdminUserMandatesPage, AdminFeatureAccessPage, AdminInvitationsPage, AdminMandateRolesPage, AdminFeatureRolesPage, AdminFeatureInstanceUsersPage, AdminMandateRolePermissionsPage, AdminUserAccessOverviewPage, AdminLogsPage, AdminDemoConfigPage } from './pages/admin';
|
||||
import { AccessManagementHub, AdminMandatesPage, AdminUsersPage, AdminUserMandatesPage, AdminFeatureAccessPage, AdminInvitationsPage, AdminMandateRolesPage, AdminFeatureRolesPage, AdminFeatureInstanceUsersPage, AdminMandateRolePermissionsPage, AdminUserAccessOverviewPage, AdminLogsPage, AdminDemoConfigPage, AdminDatabaseHealthPage } from './pages/admin';
|
||||
import { AdminMandateWizardPage, AdminInvitationWizardPage } from './pages/admin/wizards';
|
||||
import { PromptsPage, FilesPage, ConnectionsPage } from './pages/basedata';
|
||||
import { BillingDataView, BillingAdmin, BillingMandateView, AdminSubscriptionsPage } from './pages/billing';
|
||||
|
|
@ -72,6 +73,7 @@ function App() {
|
|||
<LanguageProvider>
|
||||
<AuthProvider>
|
||||
<ToastProvider>
|
||||
<VoiceCatalogProvider>
|
||||
<WorkflowSelectionProvider>
|
||||
<Router>
|
||||
<Routes>
|
||||
|
|
@ -213,6 +215,7 @@ function App() {
|
|||
<Route path="subscriptions" element={<AdminSubscriptionsPage />} />
|
||||
<Route path="logs" element={<AdminLogsPage />} />
|
||||
<Route path="languages" element={null} />
|
||||
<Route path="database-health" element={<AdminDatabaseHealthPage />} />
|
||||
<Route path="demo-config" element={<AdminDemoConfigPage />} />
|
||||
<Route path="mandate-wizard" element={<AdminMandateWizardPage />} />
|
||||
<Route path="invitation-wizard" element={<AdminInvitationWizardPage />} />
|
||||
|
|
@ -230,6 +233,7 @@ function App() {
|
|||
</Routes>
|
||||
</Router>
|
||||
</WorkflowSelectionProvider>
|
||||
</VoiceCatalogProvider>
|
||||
</ToastProvider>
|
||||
</AuthProvider>
|
||||
</LanguageProvider>
|
||||
|
|
|
|||
|
|
@ -101,6 +101,7 @@ export interface AuthUser {
|
|||
roleLabels?: string[];
|
||||
authenticationAuthority: string;
|
||||
isSysAdmin?: boolean;
|
||||
isPlatformAdmin?: boolean;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ import type {
|
|||
InstancePermissions,
|
||||
AccessLevel,
|
||||
} from '../types/mandate';
|
||||
import { mandateDisplayLabel } from '../utils/mandateDisplayUtils';
|
||||
|
||||
// =============================================================================
|
||||
// MOCK DATA (Temporär bis Backend bereit)
|
||||
|
|
@ -71,7 +72,8 @@ const MOCK_RESPONSE: FeaturesMyResponse = {
|
|||
mandates: [
|
||||
{
|
||||
id: 'mand-soha',
|
||||
name: 'Soha Treuhand',
|
||||
name: 'soha-treuhand',
|
||||
label: 'Soha Treuhand',
|
||||
code: 'soha',
|
||||
features: [
|
||||
{
|
||||
|
|
@ -119,7 +121,8 @@ const MOCK_RESPONSE: FeaturesMyResponse = {
|
|||
},
|
||||
{
|
||||
id: 'mand-swiss',
|
||||
name: 'SwissTreu',
|
||||
name: 'swisstreu',
|
||||
label: 'SwissTreu',
|
||||
code: 'swisstreu',
|
||||
features: [
|
||||
{
|
||||
|
|
@ -189,7 +192,7 @@ export async function fetchMyFeatures(): Promise<FeaturesMyResponse> {
|
|||
if (feature.code === 'chatbot') {
|
||||
console.log('🔍 [DEBUG] featuresApi: Found chatbot feature', {
|
||||
mandateId: mandate.id,
|
||||
mandateName: mandate.label || mandate.name,
|
||||
mandateName: mandateDisplayLabel(mandate),
|
||||
featureCode: feature.code,
|
||||
instanceCount: feature.instances.length,
|
||||
});
|
||||
|
|
|
|||
|
|
@ -212,6 +212,8 @@ export interface FolderInfo {
|
|||
mandateId?: string;
|
||||
featureInstanceId?: string;
|
||||
createdAt?: number;
|
||||
scope?: string;
|
||||
neutralize?: boolean;
|
||||
}
|
||||
|
||||
export async function fetchFolders(
|
||||
|
|
|
|||
|
|
@ -4,11 +4,40 @@ import { ApiRequestOptions } from '../hooks/useApi';
|
|||
// TYPES & INTERFACES
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Mandate (Mandant) — represents one tenant in PowerOn PORTA.
|
||||
*
|
||||
* Field semantics (must stay in sync with the backend `Mandate` Pydantic model):
|
||||
* - `id` — UUID, immutable.
|
||||
* - `name` — Kurzzeichen / slug. Globally unique, lowercase [a-z0-9] with
|
||||
* hyphen-separated segments (length 2–32). Used for audit/tracking
|
||||
* and stable references. Only PlatformAdmin can change it after
|
||||
* creation.
|
||||
* - `label` — Voller Name. Mandatory, human-readable display name shown in the
|
||||
* UI. Freely changeable by a Mandate-Admin.
|
||||
*/
|
||||
export interface Mandate {
|
||||
id: string;
|
||||
name: string;
|
||||
label: string;
|
||||
enabled?: boolean;
|
||||
isSystem?: boolean;
|
||||
deletedAt?: number | null;
|
||||
[key: string]: any; // Allow additional properties from backend
|
||||
}
|
||||
|
||||
/** Payload for creating a mandate. `label` is required, `name` is optional. */
|
||||
export interface MandateCreateData {
|
||||
label: string;
|
||||
name?: string;
|
||||
enabled?: boolean;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
/**
|
||||
* Payload for updating a mandate. Only PlatformAdmin may change `name`;
|
||||
* Mandate-Admin can update `label` and other UI fields.
|
||||
*/
|
||||
export type MandateUpdateData = Partial<Omit<Mandate, 'id'>>;
|
||||
|
||||
export interface PaginationParams {
|
||||
|
|
@ -112,7 +141,7 @@ export async function updateMandate(
|
|||
*/
|
||||
export async function createMandate(
|
||||
request: ApiRequestFunction,
|
||||
mandateData: Partial<Mandate>
|
||||
mandateData: MandateCreateData | Partial<Mandate>
|
||||
): Promise<Mandate> {
|
||||
return await request({
|
||||
url: '/api/mandates/',
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import api from '../api';
|
||||
import type { VoiceOption } from './voiceCatalogApi';
|
||||
|
||||
// ============================================================================
|
||||
// TYPES & INTERFACES
|
||||
|
|
@ -102,18 +103,11 @@ export interface ConfigUpdateRequest {
|
|||
debugMode?: boolean;
|
||||
}
|
||||
|
||||
// Voice/Language Types (from Google TTS API)
|
||||
export interface VoiceLanguage {
|
||||
code: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface VoiceOption {
|
||||
name: string;
|
||||
languageCodes: string[];
|
||||
ssmlGender: string;
|
||||
naturalSampleRateHertz: number;
|
||||
}
|
||||
// Voice option type re-exported from the central voice catalog API
|
||||
// (imported above so it's also in scope for local signatures below).
|
||||
// The legacy teamsbot-specific {code,name} language type is gone — consumers
|
||||
// should use VoiceLanguage from voiceCatalogApi (catalog SSOT).
|
||||
export type { VoiceOption };
|
||||
|
||||
// Auth Detection Test Types
|
||||
export interface StepScreenshot {
|
||||
|
|
@ -313,25 +307,19 @@ export async function testVoice(
|
|||
}
|
||||
|
||||
/**
|
||||
* Fetch available TTS languages from Google Cloud.
|
||||
* Returns array of language codes (e.g. ["de-DE", "en-US", ...])
|
||||
* Fetch the curated voice/language catalog (single source of truth).
|
||||
* Re-exports the central voiceCatalogApi.fetchVoiceCatalog so legacy
|
||||
* teamsbot consumers stay on one import surface.
|
||||
*/
|
||||
export async function fetchLanguages(): Promise<string[]> {
|
||||
try {
|
||||
const response = await api.get('/voice-google/languages');
|
||||
return response.data?.languages || [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
export { fetchVoiceCatalog as fetchLanguages } from './voiceCatalogApi';
|
||||
|
||||
/**
|
||||
* Fetch available TTS voices for a language from Google Cloud.
|
||||
*/
|
||||
export async function fetchVoices(languageCode: string): Promise<VoiceOption[]> {
|
||||
try {
|
||||
const response = await api.get('/voice-google/voices', {
|
||||
params: { languageCode },
|
||||
const response = await api.get('/api/voice/voices', {
|
||||
params: { language: languageCode },
|
||||
});
|
||||
return response.data?.voices || [];
|
||||
} catch {
|
||||
|
|
|
|||
|
|
@ -13,7 +13,8 @@ export interface User {
|
|||
enabled: boolean;
|
||||
roleLabels?: string[]; // Array of role labels from backend (e.g., ["user"])
|
||||
authenticationAuthority: string;
|
||||
isSysAdmin?: boolean; // System-Administrator Flag
|
||||
isSysAdmin?: boolean; // Infrastructure/System Operator (RBAC bypass)
|
||||
isPlatformAdmin?: boolean; // Cross-Mandate Governance (no RBAC bypass)
|
||||
// mandateId ist nicht mehr Teil des User-Objekts (Multi-Tenant-Konzept)
|
||||
// Der Mandant-Kontext wird über Feature-Instanzen bestimmt
|
||||
[key: string]: any; // Allow additional properties
|
||||
|
|
|
|||
47
src/api/voiceCatalogApi.ts
Normal file
47
src/api/voiceCatalogApi.ts
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
/**
|
||||
* Voice / Language Catalog API.
|
||||
*
|
||||
* Single source of truth for every voice-language picker, default-voice
|
||||
* lookup, and ISO ⇄ BCP-47 mapping in the frontend. Mirrors
|
||||
* gateway/modules/shared/voiceCatalog.py 1:1.
|
||||
*
|
||||
* Hard-coded language lists or ad-hoc maps in components are forbidden —
|
||||
* consume `useVoiceCatalog()` instead.
|
||||
*/
|
||||
|
||||
import api from '../api';
|
||||
|
||||
export interface VoiceLanguage {
|
||||
bcp47: string;
|
||||
iso: string;
|
||||
label: string;
|
||||
flag: string;
|
||||
defaultVoice: string | null;
|
||||
}
|
||||
|
||||
export interface VoiceOption {
|
||||
name: string;
|
||||
languageCodes: string[];
|
||||
ssmlGender: string;
|
||||
naturalSampleRateHertz: number;
|
||||
}
|
||||
|
||||
interface CatalogResponse {
|
||||
languages: VoiceLanguage[];
|
||||
}
|
||||
|
||||
interface VoicesResponse {
|
||||
voices: VoiceOption[];
|
||||
}
|
||||
|
||||
export async function fetchVoiceCatalog(): Promise<VoiceLanguage[]> {
|
||||
const response = await api.get<CatalogResponse>('/api/voice/languages');
|
||||
return response.data?.languages ?? [];
|
||||
}
|
||||
|
||||
export async function fetchVoicesForLanguage(bcp47: string): Promise<VoiceOption[]> {
|
||||
const response = await api.get<VoicesResponse>('/api/voice/voices', {
|
||||
params: { language: bcp47 },
|
||||
});
|
||||
return response.data?.voices ?? [];
|
||||
}
|
||||
|
|
@ -60,6 +60,8 @@ export interface NodeType {
|
|||
meta?: {
|
||||
icon?: string;
|
||||
color?: string;
|
||||
/** True if this node performs an LLM / AI call (credits). */
|
||||
usesAi?: boolean;
|
||||
method?: string;
|
||||
action?: string;
|
||||
};
|
||||
|
|
|
|||
|
|
@ -152,8 +152,18 @@
|
|||
min-width: 0;
|
||||
}
|
||||
|
||||
.nodeItemLabelRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.35rem;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.nodeItemLabel {
|
||||
display: block;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
color: var(--text-primary, #333);
|
||||
|
|
@ -267,7 +277,7 @@
|
|||
overflow: hidden;
|
||||
border-radius: 8px;
|
||||
/* Infinite grid: on viewport, moves with pan/zoom via inline style */
|
||||
background-image: radial-gradient(circle, var(--border-color, #e0e0e0) 1px, transparent 1px);
|
||||
background-image: radial-gradient(circle, var(--canvas-grid, var(--border-color, #e0e0e0)) 1px, transparent 1px);
|
||||
background-repeat: repeat;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -48,6 +48,7 @@ import { Automation2DataFlowProvider } from '../context/Automation2DataFlowConte
|
|||
import { usePrompt } from '../../../hooks/usePrompt';
|
||||
import { EditorChatPanel } from './EditorChatPanel';
|
||||
import type { PendingFile, EditorDataSource, EditorFeatureDataSource } from './EditorChatPanel';
|
||||
import { EditorWorkflowChatList } from './EditorWorkflowChatList';
|
||||
import { RunTracingPanel } from './RunTracingPanel';
|
||||
import { UnifiedDataBar } from '../../../components/UnifiedDataBar';
|
||||
import type { UdbContext, UdbTab } from '../../../components/UnifiedDataBar';
|
||||
|
|
@ -114,7 +115,8 @@ export const Automation2FlowEditor: React.FC<Automation2FlowEditorProps> = ({ in
|
|||
const [tracingRunId, setTracingRunId] = useState<string | null>(null);
|
||||
const [tracingNodeStatuses, setTracingNodeStatuses] = useState<Record<string, string>>({});
|
||||
const [rightTab, setRightTab] = useState<'nodes' | 'tracing'>('nodes');
|
||||
const [udbTab, setUdbTab] = useState<UdbTab>('chats');
|
||||
type LeftTab = UdbTab | 'ai';
|
||||
const [udbTab, setUdbTab] = useState<LeftTab>('ai');
|
||||
|
||||
const udbContext: UdbContext = useMemo(() => ({
|
||||
instanceId,
|
||||
|
|
@ -649,19 +651,30 @@ export const Automation2FlowEditor: React.FC<Automation2FlowEditorProps> = ({ in
|
|||
{leftPanelOpen && (<>
|
||||
<div style={{ width: leftPanelWidth, flexShrink: 0, display: 'flex', flexDirection: 'column', overflow: 'hidden', background: 'var(--bg-primary, #fff)' }}>
|
||||
<div className={styles.rightTabBar}>
|
||||
{(['chats', 'files', 'sources'] as const).map((tab) => (
|
||||
{(['ai', 'chats', 'files', 'sources'] as const).map((tab) => (
|
||||
<button
|
||||
key={tab}
|
||||
className={`${styles.rightTab} ${udbTab === tab ? styles.rightTabActive : ''}`}
|
||||
onClick={() => setUdbTab(tab)}
|
||||
>
|
||||
{{ chats: t('Chats'), files: t('Dateien'), sources: t('Quellen') }[tab]}
|
||||
{{ ai: t('KI'), chats: t('Chats'), files: t('Dateien'), sources: t('Quellen') }[tab]}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div style={{ flex: 1, overflow: 'hidden' }}>
|
||||
{udbTab === 'chats' ? (
|
||||
<div style={{ flex: 1, overflow: 'hidden', position: 'relative' }}>
|
||||
{/*
|
||||
KI-Panel bleibt gemountet, damit der Chatverlauf beim Tab-Wechsel
|
||||
(Chats / Dateien / Quellen) erhalten bleibt. Nur per CSS umblenden.
|
||||
`key={currentWorkflowId}` setzt den Verlauf sauber zurück, wenn der
|
||||
Nutzer einen anderen Workflow wählt.
|
||||
*/}
|
||||
<div style={{
|
||||
display: udbTab === 'ai' ? 'flex' : 'none',
|
||||
flexDirection: 'column',
|
||||
height: '100%',
|
||||
}}>
|
||||
<EditorChatPanel
|
||||
key={currentWorkflowId || '__noWorkflow__'}
|
||||
instanceId={instanceId}
|
||||
workflowId={currentWorkflowId}
|
||||
onGraphUpdated={() => { if (currentWorkflowId) handleLoad(currentWorkflowId); }}
|
||||
|
|
@ -670,11 +683,21 @@ export const Automation2FlowEditor: React.FC<Automation2FlowEditorProps> = ({ in
|
|||
dataSources={dataSources}
|
||||
featureDataSources={featureDataSources}
|
||||
/>
|
||||
) : (
|
||||
</div>
|
||||
{udbTab === 'chats' && (
|
||||
<EditorWorkflowChatList
|
||||
workflows={workflows}
|
||||
currentWorkflowId={currentWorkflowId}
|
||||
onSelect={handleWorkflowSelect}
|
||||
onNew={handleNew}
|
||||
t={t}
|
||||
/>
|
||||
)}
|
||||
{(udbTab === 'files' || udbTab === 'sources') && (
|
||||
<UnifiedDataBar
|
||||
context={udbContext}
|
||||
activeTab={udbTab}
|
||||
onTabChange={setUdbTab}
|
||||
activeTab={udbTab as UdbTab}
|
||||
onTabChange={(tab) => setUdbTab(tab as LeftTab)}
|
||||
hideTabs={['chats']}
|
||||
onFileSelect={onFileSelect}
|
||||
onSourcesChanged={onSourcesChanged}
|
||||
|
|
|
|||
|
|
@ -7,11 +7,25 @@
|
|||
* - Files: drag & drop from FolderTree onto input area, or click in UDB
|
||||
* - Data Sources: 🔗 picker button next to input (toggle-select from active sources)
|
||||
*/
|
||||
import React, { useState, useCallback, useRef } from 'react';
|
||||
import React, { useState, useCallback, useEffect, useRef } from 'react';
|
||||
import { startSseStream } from '../../../utils/sseClient';
|
||||
import { ChatMessageList } from '../../Chat';
|
||||
import type { ChatMessage } from '../../Chat';
|
||||
import { getPageIcon } from '../../../config/pageRegistry';
|
||||
import api from '../../../api';
|
||||
|
||||
interface PersistedEditorChatMessage {
|
||||
id: string;
|
||||
role: 'user' | 'assistant' | 'system';
|
||||
content: string;
|
||||
timestamp?: number;
|
||||
sequenceNr?: number;
|
||||
}
|
||||
|
||||
interface PersistedEditorChatResponse {
|
||||
chatWorkflowId: string | null;
|
||||
messages: PersistedEditorChatMessage[];
|
||||
}
|
||||
|
||||
import { useLanguage } from '../../../providers/language/LanguageContext';
|
||||
|
||||
|
|
@ -58,16 +72,55 @@ export const EditorChatPanel: React.FC<EditorChatPanelProps> = ({ instanceId,
|
|||
}) => {
|
||||
const { t } = useLanguage();
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||
const [historyLoading, setHistoryLoading] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [prompt, setPrompt] = useState('');
|
||||
const [attachedDataSourceIds, setAttachedDataSourceIds] = useState<string[]>([]);
|
||||
const [attachedFeatureDataSourceIds, setAttachedFeatureDataSourceIds] = useState<string[]>([]);
|
||||
const [showSourcePicker, setShowSourcePicker] = useState(false);
|
||||
const [treeDropOver, setTreeDropOver] = useState(false);
|
||||
const [stopping, setStopping] = useState(false);
|
||||
const abortRef = useRef<(() => void) | null>(null);
|
||||
const assistantIdRef = useRef<string | null>(null);
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
const pickerRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Load persisted chat history from the backend whenever the workflow changes.
|
||||
// The chat is stored in `ChatWorkflow.linkedWorkflowId == workflowId` and is
|
||||
// returned by `GET /api/workflows/{instanceId}/{workflowId}/chat/messages`.
|
||||
// For an unsaved workflow (workflowId == null) we just clear the panel.
|
||||
useEffect(() => {
|
||||
if (!workflowId) {
|
||||
setMessages([]);
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
const _loadHistory = async () => {
|
||||
setHistoryLoading(true);
|
||||
try {
|
||||
const res = await api.get<PersistedEditorChatResponse>(
|
||||
`/api/workflows/${instanceId}/${workflowId}/chat/messages`,
|
||||
);
|
||||
if (cancelled) return;
|
||||
const persisted = (res.data?.messages || []).map((m): ChatMessage => ({
|
||||
id: m.id || `persisted-${++_msgCounter}`,
|
||||
role: m.role,
|
||||
content: m.content,
|
||||
timestamp: m.timestamp ? Math.round(Number(m.timestamp) * 1000) : Date.now(),
|
||||
}));
|
||||
setMessages(persisted);
|
||||
} catch (err) {
|
||||
if (cancelled) return;
|
||||
console.warn('EditorChatPanel: failed to load chat history', err);
|
||||
setMessages([]);
|
||||
} finally {
|
||||
if (!cancelled) setHistoryLoading(false);
|
||||
}
|
||||
};
|
||||
_loadHistory();
|
||||
return () => { cancelled = true; };
|
||||
}, [instanceId, workflowId]);
|
||||
|
||||
const _toggleDataSource = useCallback((dsId: string) => {
|
||||
setAttachedDataSourceIds(prev =>
|
||||
prev.includes(dsId) ? prev.filter(id => id !== dsId) : [...prev, dsId],
|
||||
|
|
@ -85,9 +138,10 @@ export const EditorChatPanel: React.FC<EditorChatPanelProps> = ({ instanceId,
|
|||
if (!workflowId || loading || !trimmed) return;
|
||||
|
||||
const fileIds = pendingFiles.map(f => f.fileId);
|
||||
// Note: conversationHistory is no longer sent — the backend loads it
|
||||
// server-side from the persisted ChatWorkflow (linkedWorkflowId).
|
||||
const body: Record<string, unknown> = {
|
||||
message: trimmed,
|
||||
conversationHistory: messages.map(m => ({ role: m.role, message: m.content })),
|
||||
userLanguage: navigator.language?.slice(0, 2) || 'de',
|
||||
};
|
||||
if (fileIds.length > 0) body.fileIds = fileIds;
|
||||
|
|
@ -106,11 +160,13 @@ export const EditorChatPanel: React.FC<EditorChatPanelProps> = ({ instanceId,
|
|||
setLoading(true);
|
||||
|
||||
const assistantId = `asst-${++_msgCounter}`;
|
||||
assistantIdRef.current = assistantId;
|
||||
let accumulated = '';
|
||||
setMessages(prev => [...prev, { id: assistantId, role: 'assistant', content: '', timestamp: Date.now() }]);
|
||||
|
||||
const baseURL = api.defaults.baseURL || '';
|
||||
const cleanup = startSseStream({
|
||||
url: `/api/workflows/${instanceId}/${workflowId}/chat/stream`,
|
||||
url: `${baseURL}/api/workflows/${instanceId}/${workflowId}/chat/stream`,
|
||||
body,
|
||||
handlers: {
|
||||
onChunk: (event) => {
|
||||
|
|
@ -142,17 +198,40 @@ export const EditorChatPanel: React.FC<EditorChatPanelProps> = ({ instanceId,
|
|||
}
|
||||
setLoading(false);
|
||||
},
|
||||
onStopped: () => setLoading(false),
|
||||
onStopped: () => {
|
||||
setMessages(prev => prev.map(m => m.id === assistantId
|
||||
? { ...m, content: (m.content ? m.content + '\n\n' : '') + `_${t('Gestoppt.')}_` }
|
||||
: m));
|
||||
setLoading(false);
|
||||
setStopping(false);
|
||||
},
|
||||
},
|
||||
onConnectionError: (err) => {
|
||||
setMessages(prev => prev.map(m => m.id === assistantId ? { ...m, content: `${t('Fehler')}: ${err.message}` } : m));
|
||||
setLoading(false);
|
||||
setStopping(false);
|
||||
},
|
||||
onStreamEnd: () => setLoading(false),
|
||||
onStreamEnd: () => { setLoading(false); setStopping(false); },
|
||||
});
|
||||
|
||||
abortRef.current = cleanup;
|
||||
}, [prompt, loading, workflowId, instanceId, messages, onGraphUpdated, pendingFiles, attachedDataSourceIds, attachedFeatureDataSourceIds, t]);
|
||||
}, [prompt, loading, workflowId, instanceId, onGraphUpdated, pendingFiles, attachedDataSourceIds, attachedFeatureDataSourceIds, t]);
|
||||
|
||||
const _handleStop = useCallback(async () => {
|
||||
if (!workflowId || stopping) return;
|
||||
setStopping(true);
|
||||
const assistantId = assistantIdRef.current;
|
||||
if (assistantId) {
|
||||
setMessages(prev => prev.map(m => m.id === assistantId
|
||||
? { ...m, content: (m.content ? m.content + '\n\n' : '') + `_${t('Stoppen…')}_` }
|
||||
: m));
|
||||
}
|
||||
try {
|
||||
await api.post(`/api/workflows/${instanceId}/${workflowId}/chat/stop`);
|
||||
} catch {
|
||||
}
|
||||
abortRef.current?.();
|
||||
}, [workflowId, instanceId, stopping, t]);
|
||||
|
||||
const _handleKeyDown = useCallback((e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
|
|
@ -188,8 +267,8 @@ export const EditorChatPanel: React.FC<EditorChatPanelProps> = ({ instanceId,
|
|||
<div style={{ display: 'flex', flexDirection: 'column', height: '100%', background: 'var(--bg-secondary, #fafafa)' }}>
|
||||
<ChatMessageList
|
||||
messages={messages}
|
||||
isProcessing={loading}
|
||||
emptyMessage={t('Beschreiben Sie, was Sie tun möchten')}
|
||||
isProcessing={loading || historyLoading}
|
||||
emptyMessage={historyLoading ? t('Lade Verlauf…') : t('Beschreiben Sie, was Sie tun möchten')}
|
||||
/>
|
||||
|
||||
{/* Pending files (from UDB drag/click) */}
|
||||
|
|
@ -391,10 +470,12 @@ export const EditorChatPanel: React.FC<EditorChatPanelProps> = ({ instanceId,
|
|||
)}
|
||||
|
||||
{loading ? (
|
||||
<button onClick={() => abortRef.current?.()} style={{
|
||||
<button onClick={_handleStop} disabled={stopping} title={stopping ? t('Stoppen…') : t('Anfrage stoppen')} style={{
|
||||
padding: '8px 14px', borderRadius: 8, border: 'none',
|
||||
background: '#f44336', color: '#fff', cursor: 'pointer', fontWeight: 600, fontSize: 12,
|
||||
}}>{t('Stopp')}</button>
|
||||
background: stopping ? '#9e9e9e' : '#f44336', color: '#fff',
|
||||
cursor: stopping ? 'wait' : 'pointer', fontWeight: 600, fontSize: 12,
|
||||
opacity: stopping ? 0.7 : 1,
|
||||
}}>{stopping ? t('Stoppen…') : t('Stopp')}</button>
|
||||
) : (
|
||||
<button onClick={_handleSend} disabled={!prompt.trim() || !workflowId} style={{
|
||||
padding: '8px 14px', borderRadius: 8, border: 'none',
|
||||
|
|
|
|||
127
src/components/FlowEditor/editor/EditorWorkflowChatList.tsx
Normal file
127
src/components/FlowEditor/editor/EditorWorkflowChatList.tsx
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
/**
|
||||
* EditorWorkflowChatList
|
||||
*
|
||||
* UDB "Chats" tab content for the GraphicalEditor: each AutoWorkflow is treated
|
||||
* as one editor chat session. Lists workflows already loaded by the parent
|
||||
* editor (no extra fetch), supports search and "+ Neu" to start a fresh
|
||||
* workflow chat. Mirrors the spirit of the Workspace ChatsTab but uses
|
||||
* GraphicalEditor data instead of the workspace endpoint.
|
||||
*/
|
||||
import React, { useMemo, useState } from 'react';
|
||||
import type { Automation2Workflow } from '../../../api/workflowApi';
|
||||
|
||||
interface EditorWorkflowChatListProps {
|
||||
workflows: Automation2Workflow[];
|
||||
currentWorkflowId: string | null;
|
||||
onSelect: (workflowId: string | null) => void;
|
||||
onNew: () => void;
|
||||
t: (key: string) => string;
|
||||
}
|
||||
|
||||
function _formatRelative(ts?: number): string {
|
||||
if (!ts) return '';
|
||||
const date = new Date(ts * 1000);
|
||||
if (isNaN(date.getTime())) return '';
|
||||
const diffMs = Date.now() - date.getTime();
|
||||
const diffMin = Math.floor(diffMs / 60_000);
|
||||
const diffH = Math.floor(diffMs / 3_600_000);
|
||||
const diffDays = Math.floor(diffMs / 86_400_000);
|
||||
if (diffMin < 1) return 'gerade eben';
|
||||
if (diffMin < 60) return `${diffMin}m`;
|
||||
if (diffH < 24) return `${diffH}h`;
|
||||
if (diffDays === 1) return 'gestern';
|
||||
if (diffDays < 7) return `vor ${diffDays}d`;
|
||||
return date.toLocaleDateString([], { month: 'short', day: 'numeric' });
|
||||
}
|
||||
|
||||
export const EditorWorkflowChatList: React.FC<EditorWorkflowChatListProps> = ({
|
||||
workflows,
|
||||
currentWorkflowId,
|
||||
onSelect,
|
||||
onNew,
|
||||
t,
|
||||
}) => {
|
||||
const [search, setSearch] = useState('');
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
const q = search.trim().toLowerCase();
|
||||
const list = q
|
||||
? workflows.filter((w) => (w.label || '').toLowerCase().includes(q))
|
||||
: [...workflows];
|
||||
list.sort((a, b) => (b.lastStartedAt || b.createdAt || 0) - (a.lastStartedAt || a.createdAt || 0));
|
||||
return list;
|
||||
}, [workflows, search]);
|
||||
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', height: '100%', background: 'var(--bg-primary, #fff)' }}>
|
||||
<div style={{ padding: '8px 10px', display: 'flex', gap: 6, borderBottom: '1px solid var(--border-color, #e0e0e0)' }}>
|
||||
<input
|
||||
type="search"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder={t('Workflow suchen…')}
|
||||
style={{
|
||||
flex: 1, padding: '6px 8px', borderRadius: 6,
|
||||
border: '1px solid var(--border-color, #ddd)', fontSize: 12, outline: 'none',
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
onClick={onNew}
|
||||
title={t('Neuer Workflow')}
|
||||
style={{
|
||||
padding: '6px 10px', borderRadius: 6, border: '1px solid var(--border-color, #ddd)',
|
||||
background: 'var(--secondary-bg, #f5f5f5)', cursor: 'pointer', fontSize: 12, fontWeight: 600,
|
||||
}}
|
||||
>+ {t('Neu')}</button>
|
||||
</div>
|
||||
|
||||
<div style={{ flex: 1, overflowY: 'auto' }}>
|
||||
{filtered.length === 0 ? (
|
||||
<div style={{ padding: 16, fontSize: 12, color: '#999', textAlign: 'center' }}>
|
||||
{workflows.length === 0
|
||||
? t('Noch keine Workflows. Klicken Sie auf „+ Neu", um einen Workflow-Chat zu starten.')
|
||||
: t('Keine Treffer.')}
|
||||
</div>
|
||||
) : (
|
||||
filtered.map((wf) => {
|
||||
const isActive = wf.id === currentWorkflowId;
|
||||
const ts = wf.lastStartedAt || wf.createdAt;
|
||||
return (
|
||||
<div
|
||||
key={wf.id}
|
||||
onClick={() => onSelect(wf.id)}
|
||||
style={{
|
||||
padding: '10px 12px', cursor: 'pointer',
|
||||
borderBottom: '1px solid var(--border-color-soft, #f0f0f0)',
|
||||
background: isActive ? 'rgba(242, 88, 67, 0.08)' : 'transparent',
|
||||
borderLeft: isActive ? '3px solid var(--primary-color, #F25843)' : '3px solid transparent',
|
||||
}}
|
||||
onMouseEnter={(e) => { if (!isActive) e.currentTarget.style.background = '#f7f7f7'; }}
|
||||
onMouseLeave={(e) => { if (!isActive) e.currentTarget.style.background = 'transparent'; }}
|
||||
>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
|
||||
<span style={{ fontSize: 13, fontWeight: 500, color: '#333', flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{wf.label || t('(unbenannt)')}
|
||||
</span>
|
||||
{wf.isRunning && (
|
||||
<span title={t('läuft')} style={{
|
||||
width: 8, height: 8, borderRadius: '50%', background: '#4caf50', flexShrink: 0,
|
||||
}} />
|
||||
)}
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 8, marginTop: 4, fontSize: 11, color: '#999' }}>
|
||||
{typeof wf.runCount === 'number' && (
|
||||
<span>{wf.runCount} {wf.runCount === 1 ? t('Lauf') : t('Läufe')}</span>
|
||||
)}
|
||||
{ts ? <span>· {_formatRelative(ts)}</span> : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default EditorWorkflowChatList;
|
||||
|
|
@ -8,6 +8,7 @@ import type { NodeType } from '../../../api/workflowApi';
|
|||
import styles from './Automation2FlowEditor.module.css';
|
||||
|
||||
import { useLanguage } from '../../../providers/language/LanguageContext';
|
||||
import { AiBadge } from '../nodes/shared/AiBadge';
|
||||
|
||||
export interface CanvasNode {
|
||||
id: string;
|
||||
|
|
@ -798,6 +799,12 @@ export const FlowCanvas: React.FC<FlowCanvasProps> = ({ nodes,
|
|||
handleNodeMouseDown(e, node.id);
|
||||
}}
|
||||
>
|
||||
{nt?.meta?.usesAi === true && (
|
||||
<AiBadge
|
||||
variant="canvas"
|
||||
title={t('Dieser Schritt nutzt AI und verbraucht Credits')}
|
||||
/>
|
||||
)}
|
||||
{handles.map(({ index, isOutput }) => {
|
||||
const pos = getHandlePosition(node, index);
|
||||
const used = !isOutput && getUsedTargetHandles.has(`${node.id}-${index}`);
|
||||
|
|
|
|||
|
|
@ -5,9 +5,11 @@
|
|||
|
||||
import React from 'react';
|
||||
import type { NodeType } from '../../../api/workflowApi';
|
||||
import { useLanguage } from '../../../providers/language/LanguageContext';
|
||||
import { getCategoryIcon } from '../nodes/shared/utils';
|
||||
import type { GetLabelFn } from '../nodes/shared/utils';
|
||||
import styles from './Automation2FlowEditor.module.css';
|
||||
import { AiBadge } from '../nodes/shared/AiBadge';
|
||||
|
||||
interface NodeListItemProps {
|
||||
node: NodeType;
|
||||
|
|
@ -22,6 +24,7 @@ export const NodeListItem: React.FC<NodeListItemProps> = ({
|
|||
getLabel,
|
||||
getCategoryIcon: getIcon = getCategoryIcon,
|
||||
}) => {
|
||||
const { t } = useLanguage();
|
||||
const desc = getLabel(node.description, language);
|
||||
return (
|
||||
<div
|
||||
|
|
@ -44,7 +47,15 @@ export const NodeListItem: React.FC<NodeListItemProps> = ({
|
|||
{getIcon(node.category)}
|
||||
</div>
|
||||
<div className={styles.nodeItemInfo}>
|
||||
<span className={styles.nodeItemLabel}>{getLabel(node.label, language)}</span>
|
||||
<span className={styles.nodeItemLabelRow}>
|
||||
<span className={styles.nodeItemLabel}>{getLabel(node.label, language)}</span>
|
||||
{node.meta?.usesAi === true && (
|
||||
<AiBadge
|
||||
variant="palette"
|
||||
title={t('Dieser Schritt nutzt AI und verbraucht Credits')}
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
<span className={styles.nodeItemDesc}>{desc}</span>
|
||||
</div>
|
||||
{desc && <div className={styles.nodeItemTooltip}>{desc}</div>}
|
||||
|
|
|
|||
24
src/components/FlowEditor/nodes/shared/AiBadge.module.css
Normal file
24
src/components/FlowEditor/nodes/shared/AiBadge.module.css
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
.badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0.12rem 0.38rem;
|
||||
border-radius: 4px;
|
||||
font-size: 0.62rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.06em;
|
||||
text-transform: uppercase;
|
||||
background: linear-gradient(135deg, #7c4dff 0%, #9c27b0 100%);
|
||||
color: #fff;
|
||||
line-height: 1;
|
||||
flex-shrink: 0;
|
||||
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
.badgeCanvas {
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
right: 6px;
|
||||
z-index: 3;
|
||||
pointer-events: auto;
|
||||
}
|
||||
25
src/components/FlowEditor/nodes/shared/AiBadge.tsx
Normal file
25
src/components/FlowEditor/nodes/shared/AiBadge.tsx
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
/**
|
||||
* Small label for workflow nodes that consume AI credits (LLM calls).
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import badgeStyles from './AiBadge.module.css';
|
||||
|
||||
export interface AiBadgeProps {
|
||||
/** Tooltip (e.g. cost / credits hint). */
|
||||
title: string;
|
||||
/** Canvas nodes: fixed top-right on the node card. */
|
||||
variant?: 'canvas' | 'palette';
|
||||
}
|
||||
|
||||
export const AiBadge: React.FC<AiBadgeProps> = ({ title, variant = 'palette' }) => {
|
||||
const cls =
|
||||
variant === 'canvas'
|
||||
? `${badgeStyles.badge} ${badgeStyles.badgeCanvas}`
|
||||
: badgeStyles.badge;
|
||||
return (
|
||||
<span className={cls} title={title} aria-label={title}>
|
||||
AI
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
|
@ -12,9 +12,11 @@ export const CATEGORY_ORDER = [
|
|||
'input',
|
||||
'flow',
|
||||
'data',
|
||||
'context',
|
||||
'ai',
|
||||
'file',
|
||||
'email',
|
||||
'sharepoint',
|
||||
'clickup',
|
||||
'trustee',
|
||||
] as const;
|
||||
|
|
|
|||
|
|
@ -86,10 +86,21 @@
|
|||
min-width: 0;
|
||||
}
|
||||
|
||||
/* Right zone: contains dynamic on-hover actions + always-visible stable trio.
|
||||
* The stable trio (chat / scope / neutralize) sits at the right edge in a
|
||||
* fixed slot order so icons never jump. Dynamic actions appear on hover
|
||||
* to the left of the trio without displacing it. */
|
||||
.rightZone {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
margin-left: auto;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: none;
|
||||
gap: 2px;
|
||||
margin-left: auto;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
|
|
@ -97,6 +108,26 @@
|
|||
display: flex;
|
||||
}
|
||||
|
||||
.stableActions {
|
||||
display: flex;
|
||||
gap: 2px;
|
||||
flex-shrink: 0;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.iconSlot {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 22px;
|
||||
height: 20px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.iconSlot.placeholder {
|
||||
visibility: hidden;
|
||||
}
|
||||
|
||||
.actionBtn {
|
||||
background: none;
|
||||
border: none;
|
||||
|
|
@ -148,25 +179,6 @@
|
|||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.scopeIcons {
|
||||
display: flex;
|
||||
gap: 2px;
|
||||
flex-shrink: 0;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.rightZone {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
margin-left: auto;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.rightZone .actions {
|
||||
margin-left: 0;
|
||||
}
|
||||
|
||||
.rootActions {
|
||||
display: flex;
|
||||
gap: 2px;
|
||||
|
|
|
|||
|
|
@ -29,6 +29,8 @@ export interface FolderNode {
|
|||
isProtected?: boolean;
|
||||
isReadonly?: boolean;
|
||||
icon?: string;
|
||||
neutralize?: boolean;
|
||||
scope?: string;
|
||||
}
|
||||
|
||||
export interface FileNode {
|
||||
|
|
@ -75,6 +77,9 @@ export interface FolderTreeProps {
|
|||
onDownloadFolder?: (folderId: string, folderName: string) => Promise<void>;
|
||||
onScopeChange?: (fileId: string, newScope: string) => void;
|
||||
onNeutralizeToggle?: (fileId: string, newValue: boolean) => void;
|
||||
onFolderScopeChange?: (folderId: string, newScope: string) => void;
|
||||
onFolderNeutralizeToggle?: (folderId: string, newValue: boolean) => void;
|
||||
onSendToChat?: (items: Array<{ id: string; type: 'file' | 'folder'; name: string }>) => void;
|
||||
}
|
||||
|
||||
/* ── Helpers ───────────────────────────────────────────────────────────── */
|
||||
|
|
@ -180,6 +185,79 @@ interface SelectionCtx {
|
|||
onDeleteFolders?: (folderIds: string[]) => Promise<void>;
|
||||
onScopeChange?: (fileId: string, newScope: string) => void;
|
||||
onNeutralizeToggle?: (fileId: string, newValue: boolean) => void;
|
||||
onSendToChat?: (items: Array<{ id: string; type: 'file' | 'folder'; name: string }>) => void;
|
||||
}
|
||||
|
||||
/* ── Stable trio (chat | scope | neutralize) ──────────────────────────────
|
||||
* Always rendered in this order, always at the right edge of the row.
|
||||
* Each slot has a fixed width so missing actions render an invisible
|
||||
* placeholder — icons never jump position between rows. */
|
||||
|
||||
interface StableTrioProps {
|
||||
scope?: string;
|
||||
neutralize?: boolean;
|
||||
scopeLabels: Record<string, string>;
|
||||
onChat?: () => void;
|
||||
onScopeChange?: (newScope: string) => void;
|
||||
onNeutralizeToggle?: (newValue: boolean) => void;
|
||||
chatTitle: string;
|
||||
}
|
||||
|
||||
function _StableTrio({
|
||||
scope, neutralize,
|
||||
scopeLabels,
|
||||
onChat, onScopeChange, onNeutralizeToggle,
|
||||
chatTitle,
|
||||
}: StableTrioProps) {
|
||||
const { t } = useLanguage();
|
||||
const _cycleScope = (current: string | undefined) => {
|
||||
const idx = _SCOPE_CYCLE.indexOf(current ?? 'personal');
|
||||
return _SCOPE_CYCLE[(idx + 1) % _SCOPE_CYCLE.length];
|
||||
};
|
||||
|
||||
return (
|
||||
<span className={styles.stableActions}>
|
||||
{/* Slot 1: Chat */}
|
||||
{onChat ? (
|
||||
<button
|
||||
className={`${styles.actionBtn} ${styles.iconSlot}`}
|
||||
onClick={(e) => { e.stopPropagation(); onChat(); }}
|
||||
title={chatTitle}
|
||||
style={{ fontSize: 12 }}
|
||||
>
|
||||
{'\u{1F4AC}'}
|
||||
</button>
|
||||
) : (
|
||||
<span className={`${styles.iconSlot} ${styles.placeholder}`} aria-hidden="true">{'\u{1F4AC}'}</span>
|
||||
)}
|
||||
{/* Slot 2: Scope */}
|
||||
{onScopeChange && scope != null ? (
|
||||
<button
|
||||
className={`${styles.actionBtn} ${styles.iconSlot}`}
|
||||
onClick={(e) => { e.stopPropagation(); onScopeChange(_cycleScope(scope)); }}
|
||||
title={`${t('Scope')}: ${scopeLabels[scope] || scope} (${t('klicken zum Wechseln')})`}
|
||||
style={{ fontSize: 14 }}
|
||||
>
|
||||
{_SCOPE_ICONS[scope] || _SCOPE_ICONS.personal}
|
||||
</button>
|
||||
) : (
|
||||
<span className={`${styles.iconSlot} ${styles.placeholder}`} aria-hidden="true">{_SCOPE_ICONS.personal}</span>
|
||||
)}
|
||||
{/* Slot 3: Neutralize */}
|
||||
{onNeutralizeToggle ? (
|
||||
<button
|
||||
className={`${styles.actionBtn} ${styles.iconSlot}`}
|
||||
onClick={(e) => { e.stopPropagation(); onNeutralizeToggle(!neutralize); }}
|
||||
title={neutralize ? t('Neutralisierung aktiv, klicken zum Deaktivieren') : t('Neutralisierung aus, klicken zum Aktivieren')}
|
||||
style={{ fontSize: 14, opacity: neutralize ? 1 : 0.4 }}
|
||||
>
|
||||
{'\uD83D\uDD12'}
|
||||
</button>
|
||||
) : (
|
||||
<span className={`${styles.iconSlot} ${styles.placeholder}`} aria-hidden="true">{'\uD83D\uDD12'}</span>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/* ── File node (leaf) ─────────────────────────────────────────────────── */
|
||||
|
|
@ -261,6 +339,11 @@ function _FileItem({ file, sel }: { file: FileNode; sel: SelectionCtx }) {
|
|||
)}
|
||||
{!renaming && (
|
||||
<span className={styles.rightZone}>
|
||||
{file.fileSize != null && (
|
||||
<span className={styles.fileSize}>
|
||||
{(file.fileSize / 1024).toFixed(0)}K
|
||||
</span>
|
||||
)}
|
||||
<span className={styles.actions}>
|
||||
{sel.onRenameFile && !multiSelected && (
|
||||
<button className={styles.actionBtn} onClick={(e) => { e.stopPropagation(); setRenameValue(file.fileName); setRenaming(true); }} title={t('Umbenennen')}>
|
||||
|
|
@ -290,40 +373,15 @@ function _FileItem({ file, sel }: { file: FileNode; sel: SelectionCtx }) {
|
|||
)
|
||||
)}
|
||||
</span>
|
||||
{file.fileSize != null && (
|
||||
<span className={styles.fileSize}>
|
||||
{(file.fileSize / 1024).toFixed(0)}K
|
||||
</span>
|
||||
)}
|
||||
{file.scope != null && (
|
||||
<span className={styles.scopeIcons}>
|
||||
<button
|
||||
className={styles.actionBtn}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
if (!sel.onScopeChange) return;
|
||||
const idx = _SCOPE_CYCLE.indexOf(file.scope!);
|
||||
const next = _SCOPE_CYCLE[(idx + 1) % _SCOPE_CYCLE.length];
|
||||
sel.onScopeChange(file.id, next);
|
||||
}}
|
||||
title={`${t('Scope')}: ${scopeLabels[file.scope!] || file.scope} (${t('klicken zum Wechseln')})`}
|
||||
style={{ fontSize: 14 }}
|
||||
>
|
||||
{_SCOPE_ICONS[file.scope!] || '\uD83D\uDC64'}
|
||||
</button>
|
||||
<button
|
||||
className={styles.actionBtn}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
sel.onNeutralizeToggle?.(file.id, !file.neutralize);
|
||||
}}
|
||||
title={file.neutralize ? t('Neutralisierung aktiv, klicken zum Deaktivieren') : t('Neutralisierung aus, klicken zum Aktivieren')}
|
||||
style={{ fontSize: 14, opacity: file.neutralize ? 1 : 0.4 }}
|
||||
>
|
||||
{'\uD83D\uDD12'}
|
||||
</button>
|
||||
</span>
|
||||
)}
|
||||
<_StableTrio
|
||||
scope={file.scope}
|
||||
neutralize={file.neutralize}
|
||||
scopeLabels={scopeLabels}
|
||||
onChat={sel.onSendToChat ? () => sel.onSendToChat!([{ id: file.id, type: 'file', name: file.fileName }]) : undefined}
|
||||
onScopeChange={sel.onScopeChange ? (next) => sel.onScopeChange!(file.id, next) : undefined}
|
||||
onNeutralizeToggle={sel.onNeutralizeToggle ? (next) => sel.onNeutralizeToggle!(file.id, next) : undefined}
|
||||
chatTitle={t('In Chat senden')}
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
|
@ -351,6 +409,8 @@ interface TreeNodeProps {
|
|||
onMoveFile?: (fileId: string, targetFolderId: string | null) => Promise<void>;
|
||||
onMoveFiles?: (fileIds: string[], targetFolderId: string | null) => Promise<void>;
|
||||
onDownloadFolder?: (folderId: string, folderName: string) => Promise<void>;
|
||||
onFolderScopeChange?: (folderId: string, newScope: string) => void;
|
||||
onFolderNeutralizeToggle?: (folderId: string, newValue: boolean) => void;
|
||||
}
|
||||
|
||||
function _TreeNode({
|
||||
|
|
@ -358,9 +418,15 @@ function _TreeNode({
|
|||
promptFolderName,
|
||||
onToggle, onSelect,
|
||||
onCreateFolder, onRenameFolder, onDeleteFolder, onMoveFolder, onMoveFolders, onMoveFile, onMoveFiles,
|
||||
onDownloadFolder,
|
||||
onDownloadFolder, onFolderScopeChange, onFolderNeutralizeToggle,
|
||||
}: TreeNodeProps) {
|
||||
const { t } = useLanguage();
|
||||
const scopeLabels = useMemo((): Record<string, string> => ({
|
||||
personal: t('Persönlich'),
|
||||
featureInstance: t('Instanz'),
|
||||
mandate: t('Mandant'),
|
||||
global: t('Global'),
|
||||
}), [t]);
|
||||
const [renaming, setRenaming] = useState(false);
|
||||
const [renameValue, setRenameValue] = useState(node.name);
|
||||
const [dropOver, setDropOver] = useState(false);
|
||||
|
|
@ -513,42 +579,53 @@ function _TreeNode({
|
|||
<span className={styles.folderName} style={notEditable ? { fontWeight: 600 } : undefined}>{node.name}</span>
|
||||
)}
|
||||
{!isProtected && (
|
||||
<span className={styles.actions}>
|
||||
{!notEditable && onDownloadFolder && !(isMultiSelected && sel.selectedItemIds.size > 1) && (
|
||||
<button className={styles.actionBtn} onClick={(e) => { e.stopPropagation(); onDownloadFolder(node.id, node.name); }} title={t('Ordner herunterladen (ZIP)')}>
|
||||
<FaDownload />
|
||||
</button>
|
||||
)}
|
||||
{onCreateFolder && !(isMultiSelected && sel.selectedItemIds.size > 1) && (
|
||||
<button className={styles.actionBtn} onClick={_handleAdd} title={t('Neuer Unterordner')}>
|
||||
<FaPlus />
|
||||
</button>
|
||||
)}
|
||||
{!notEditable && onRenameFolder && !(isMultiSelected && sel.selectedItemIds.size > 1) && (
|
||||
<button className={styles.actionBtn} onClick={(e) => { e.stopPropagation(); setRenameValue(node.name); setRenaming(true); }} title={t('Umbenennen')}>
|
||||
<FaPen />
|
||||
</button>
|
||||
)}
|
||||
{isMultiSelected && sel.selectedItemIds.size > 1 ? (
|
||||
<>
|
||||
{sel.selectedFolderIds.length > 0 && sel.onDeleteFolders && (
|
||||
<button className={`${styles.actionBtn} ${styles.danger}`} onClick={_handleDeleteFolders} title={`${sel.selectedFolderIds.length} ${t('Ordner löschen')}`}>
|
||||
<FaFolder style={{ fontSize: 8, marginRight: 1 }} /><FaTrash />
|
||||
<span style={{ fontSize: 9, marginLeft: 2, fontWeight: 600 }}>{sel.selectedFolderIds.length}</span>
|
||||
</button>
|
||||
)}
|
||||
{sel.selectedFileIds.length > 0 && sel.onDeleteFiles && (
|
||||
<button className={`${styles.actionBtn} ${styles.danger}`} onClick={_handleDeleteFiles} title={`${sel.selectedFileIds.length} ${t('Dateien löschen')}`}>
|
||||
<FaTrash />
|
||||
<span style={{ fontSize: 9, marginLeft: 2, fontWeight: 600 }}>{sel.selectedFileIds.length}</span>
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
) : !notEditable && onDeleteFolder && (
|
||||
<button className={`${styles.actionBtn} ${styles.danger}`} onClick={_handleDeleteSingle} title={t('Löschen')}>
|
||||
<FaTrash />
|
||||
</button>
|
||||
)}
|
||||
<span className={styles.rightZone}>
|
||||
<span className={styles.actions}>
|
||||
{!notEditable && onDownloadFolder && !(isMultiSelected && sel.selectedItemIds.size > 1) && (
|
||||
<button className={styles.actionBtn} onClick={(e) => { e.stopPropagation(); onDownloadFolder(node.id, node.name); }} title={t('Ordner herunterladen (ZIP)')}>
|
||||
<FaDownload />
|
||||
</button>
|
||||
)}
|
||||
{onCreateFolder && !(isMultiSelected && sel.selectedItemIds.size > 1) && (
|
||||
<button className={styles.actionBtn} onClick={_handleAdd} title={t('Neuer Unterordner')}>
|
||||
<FaPlus />
|
||||
</button>
|
||||
)}
|
||||
{!notEditable && onRenameFolder && !(isMultiSelected && sel.selectedItemIds.size > 1) && (
|
||||
<button className={styles.actionBtn} onClick={(e) => { e.stopPropagation(); setRenameValue(node.name); setRenaming(true); }} title={t('Umbenennen')}>
|
||||
<FaPen />
|
||||
</button>
|
||||
)}
|
||||
{isMultiSelected && sel.selectedItemIds.size > 1 ? (
|
||||
<>
|
||||
{sel.selectedFolderIds.length > 0 && sel.onDeleteFolders && (
|
||||
<button className={`${styles.actionBtn} ${styles.danger}`} onClick={_handleDeleteFolders} title={`${sel.selectedFolderIds.length} ${t('Ordner löschen')}`}>
|
||||
<FaFolder style={{ fontSize: 8, marginRight: 1 }} /><FaTrash />
|
||||
<span style={{ fontSize: 9, marginLeft: 2, fontWeight: 600 }}>{sel.selectedFolderIds.length}</span>
|
||||
</button>
|
||||
)}
|
||||
{sel.selectedFileIds.length > 0 && sel.onDeleteFiles && (
|
||||
<button className={`${styles.actionBtn} ${styles.danger}`} onClick={_handleDeleteFiles} title={`${sel.selectedFileIds.length} ${t('Dateien löschen')}`}>
|
||||
<FaTrash />
|
||||
<span style={{ fontSize: 9, marginLeft: 2, fontWeight: 600 }}>{sel.selectedFileIds.length}</span>
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
) : !notEditable && onDeleteFolder && (
|
||||
<button className={`${styles.actionBtn} ${styles.danger}`} onClick={_handleDeleteSingle} title={t('Löschen')}>
|
||||
<FaTrash />
|
||||
</button>
|
||||
)}
|
||||
</span>
|
||||
<_StableTrio
|
||||
scope={node.scope}
|
||||
neutralize={node.neutralize}
|
||||
scopeLabels={scopeLabels}
|
||||
onChat={(sel.onSendToChat && !(isMultiSelected && sel.selectedItemIds.size > 1)) ? () => sel.onSendToChat!([{ id: node.id, type: 'folder', name: node.name }]) : undefined}
|
||||
onScopeChange={(onFolderScopeChange && !(isMultiSelected && sel.selectedItemIds.size > 1)) ? (next) => onFolderScopeChange(node.id, next) : undefined}
|
||||
onNeutralizeToggle={(onFolderNeutralizeToggle && !(isMultiSelected && sel.selectedItemIds.size > 1)) ? (next) => onFolderNeutralizeToggle(node.id, next) : undefined}
|
||||
chatTitle={t('In Chat senden')}
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
|
@ -575,6 +652,8 @@ function _TreeNode({
|
|||
onMoveFile={onMoveFile}
|
||||
onMoveFiles={onMoveFiles}
|
||||
onDownloadFolder={onDownloadFolder}
|
||||
onFolderScopeChange={onFolderScopeChange}
|
||||
onFolderNeutralizeToggle={onFolderNeutralizeToggle}
|
||||
/>
|
||||
))}
|
||||
{folderFiles.map((file) => (
|
||||
|
|
@ -594,7 +673,7 @@ export default function FolderTree({
|
|||
expandedIds: externalExpandedIds, onToggleExpand,
|
||||
onCreateFolder, onRenameFolder, onDeleteFolder, onMoveFolder, onMoveFolders, onMoveFile, onMoveFiles,
|
||||
onRenameFile, onDeleteFile, onDeleteFiles, onDeleteFolders, onRefresh, onDownloadFolder,
|
||||
onScopeChange, onNeutralizeToggle,
|
||||
onScopeChange, onNeutralizeToggle, onFolderScopeChange, onFolderNeutralizeToggle, onSendToChat,
|
||||
}: FolderTreeProps) {
|
||||
const { t } = useLanguage();
|
||||
|
||||
|
|
@ -735,8 +814,9 @@ export default function FolderTree({
|
|||
onDeleteFolders,
|
||||
onScopeChange,
|
||||
onNeutralizeToggle,
|
||||
onSendToChat,
|
||||
};
|
||||
}, [selectedItemIds, allFileIds, allFolderIds, _handleItemClick, _handleItemDragStart, onRenameFile, onDeleteFile, onDeleteFiles, onDeleteFolders, onScopeChange, onNeutralizeToggle]);
|
||||
}, [selectedItemIds, allFileIds, allFolderIds, _handleItemClick, _handleItemDragStart, onRenameFile, onDeleteFile, onDeleteFiles, onDeleteFolders, onScopeChange, onNeutralizeToggle, onSendToChat]);
|
||||
|
||||
// Root drop handler: items dropped on the empty area go to root (null)
|
||||
const _handleRootDrop = useCallback(async (e: React.DragEvent) => {
|
||||
|
|
@ -821,6 +901,8 @@ export default function FolderTree({
|
|||
onMoveFile={onMoveFile}
|
||||
onMoveFiles={onMoveFiles}
|
||||
onDownloadFolder={onDownloadFolder}
|
||||
onFolderScopeChange={onFolderScopeChange}
|
||||
onFolderNeutralizeToggle={onFolderNeutralizeToggle}
|
||||
/>
|
||||
))}
|
||||
{rootFiles.map((file) => (
|
||||
|
|
|
|||
|
|
@ -15,6 +15,21 @@ import {
|
|||
getDefaultValueForType
|
||||
} from '../../../utils/attributeTypeMapper';
|
||||
import type { AttributeType } from '../../../utils/attributeTypeMapper';
|
||||
import {
|
||||
SLUG_HINT,
|
||||
maskSlugInput,
|
||||
slugify,
|
||||
validateSlug,
|
||||
} from '../../../utils/slugUtils';
|
||||
|
||||
const _isSlugType = (attrType: AttributeType | undefined): boolean => attrType === 'slug';
|
||||
|
||||
/**
|
||||
* Default source field used to auto-derive a slug in `create` mode. A specific
|
||||
* attribute can override this by setting `slugSource` in its definition
|
||||
* (json_schema_extra.slug_source on the backend).
|
||||
*/
|
||||
const _DEFAULT_SLUG_SOURCE_FIELD = 'label';
|
||||
|
||||
const isTextMultilingual = (value: any): boolean => {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value) || value instanceof Date) {
|
||||
|
|
@ -370,33 +385,58 @@ export function FormGeneratorForm<T extends Record<string, any>>({
|
|||
}));
|
||||
};
|
||||
|
||||
// Tracks slug fields that have been touched manually so we don't override them
|
||||
// when the user keeps editing the source label afterwards.
|
||||
const slugFieldsManuallyEdited = useRef<Set<string>>(new Set());
|
||||
|
||||
// Handle field value changes
|
||||
// For timestamp fields: Convert datetime-local string to Unix timestamp (float in seconds)
|
||||
const handleFieldChange = (fieldName: string, value: any, fieldType?: AttributeType) => {
|
||||
let processedValue = value;
|
||||
|
||||
// If field type is timestamp, convert datetime-local string to Unix timestamp
|
||||
|
||||
if (fieldType === 'timestamp' && typeof value === 'string' && value) {
|
||||
const date = new Date(value);
|
||||
if (!isNaN(date.getTime())) {
|
||||
// Convert to Unix timestamp in seconds (float)
|
||||
processedValue = date.getTime() / 1000;
|
||||
}
|
||||
}
|
||||
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
[fieldName]: processedValue
|
||||
}));
|
||||
|
||||
// Clear error for this field when user starts typing
|
||||
if (errors[fieldName]) {
|
||||
setErrors(prev => {
|
||||
const newErrors = { ...prev };
|
||||
delete newErrors[fieldName];
|
||||
return newErrors;
|
||||
});
|
||||
if (_isSlugType(fieldType)) {
|
||||
processedValue = maskSlugInput(String(value ?? ''));
|
||||
slugFieldsManuallyEdited.current.add(fieldName);
|
||||
}
|
||||
|
||||
const autoFilledSlugFields = new Set<string>();
|
||||
|
||||
setFormData(prev => {
|
||||
const next: any = { ...prev, [fieldName]: processedValue };
|
||||
|
||||
// Generic auto-suggest: any slug attribute can declare its source field
|
||||
// via attr.slugSource (default: 'label'). When that source changes in
|
||||
// create mode and the slug is still untouched, derive a suggestion.
|
||||
if (mode === 'create' && !_isSlugType(fieldType)) {
|
||||
const attrs = attributes ?? [];
|
||||
for (const a of attrs) {
|
||||
if (!_isSlugType(a.type as AttributeType)) continue;
|
||||
const source = (a as any).slugSource || _DEFAULT_SLUG_SOURCE_FIELD;
|
||||
if (source !== fieldName) continue;
|
||||
if (slugFieldsManuallyEdited.current.has(a.name)) continue;
|
||||
const sourceStr = typeof processedValue === 'string' ? processedValue : '';
|
||||
if (sourceStr.trim().length === 0) continue;
|
||||
next[a.name] = slugify(sourceStr);
|
||||
autoFilledSlugFields.add(a.name);
|
||||
}
|
||||
}
|
||||
return next;
|
||||
});
|
||||
|
||||
setErrors(prev => {
|
||||
if (!prev[fieldName] && autoFilledSlugFields.size === 0) return prev;
|
||||
const newErrors = { ...prev };
|
||||
if (newErrors[fieldName]) delete newErrors[fieldName];
|
||||
autoFilledSlugFields.forEach(n => delete newErrors[n]);
|
||||
return newErrors;
|
||||
});
|
||||
};
|
||||
|
||||
// Convert Unix timestamp (seconds) to datetime-local input format
|
||||
|
|
@ -509,6 +549,14 @@ export function FormGeneratorForm<T extends Record<string, any>>({
|
|||
}
|
||||
}
|
||||
|
||||
if (_isSlugType(attr.type as AttributeType)) {
|
||||
const slugErr = validateSlug(String(value));
|
||||
if (slugErr) {
|
||||
newErrors[attr.name] = t(slugErr);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Select/Multiselect option validation
|
||||
if (isSelectType(attr.type)) {
|
||||
const options = normalizeOptions(attr);
|
||||
|
|
@ -1019,6 +1067,38 @@ export function FormGeneratorForm<T extends Record<string, any>>({
|
|||
);
|
||||
}
|
||||
|
||||
if (_isSlugType(attr.type as AttributeType)) {
|
||||
const slugValue = typeof value === 'string' ? value : (value == null ? '' : String(value));
|
||||
return (
|
||||
<div className={styles.floatingLabelInput} key={attr.name}>
|
||||
<input
|
||||
type="text"
|
||||
value={slugValue}
|
||||
inputMode="text"
|
||||
autoCapitalize="none"
|
||||
autoCorrect="off"
|
||||
spellCheck={false}
|
||||
pattern="^[a-z0-9]+(-[a-z0-9]+)*$"
|
||||
onChange={(e) => handleFieldChange(attr.name, e.target.value, 'slug')}
|
||||
onFocus={() => handleFieldFocus(attr.name, true)}
|
||||
onBlur={() => handleFieldFocus(attr.name, false)}
|
||||
className={`${styles.fieldInput} ${hasError ? styles.fieldError : ''}`}
|
||||
/>
|
||||
<label className={getLabelClass(attr.name, slugValue)}>
|
||||
{attr.label}
|
||||
{attr.required && <span className={styles.required}>*</span>}
|
||||
</label>
|
||||
<span
|
||||
className={styles.helperText ?? ''}
|
||||
style={{ fontSize: '0.75rem', color: 'var(--text-secondary, #666)', marginTop: '4px', display: 'block' }}
|
||||
>
|
||||
{t(SLUG_HINT)}
|
||||
</span>
|
||||
{hasError && <span className={styles.errorText}>{hasError}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Default input field (text, email, date, time, url, password, number, integer, float, timestamp)
|
||||
const inputType = attributeTypeToInputType(attr.type);
|
||||
|
||||
|
|
|
|||
|
|
@ -1553,62 +1553,95 @@ export function FormGeneratorTable<T extends Record<string, any>>({
|
|||
return isCheckboxType(column.type);
|
||||
}, []);
|
||||
|
||||
// Handle inline toggle for boolean fields
|
||||
// Always-current snapshot of `data` so a queued toggle reads the freshly
|
||||
// refetched row (server truth from the previous PUT+refetch) instead of the
|
||||
// stale `row` captured by React at render time.
|
||||
const dataRef = useRef<T[]>(data);
|
||||
useEffect(() => { dataRef.current = data; }, [data]);
|
||||
|
||||
// Per-row update queue: every toggle on the same row awaits the previous
|
||||
// one so PUT + refetch are strictly serialized. Combined with a refetch
|
||||
// after every PUT, this guarantees that the next queued PUT merges its
|
||||
// payload from confirmed server state — never from an unconfirmed UI guess.
|
||||
const inlineUpdateQueueRef = useRef<Map<string, Promise<void>>>(new Map());
|
||||
|
||||
// Handle inline toggle for boolean fields.
|
||||
//
|
||||
// Design contract (no optimistic UI):
|
||||
// 1. The cell shows a spinner immediately on click.
|
||||
// 2. We send the PUT.
|
||||
// 3. We always trigger a refetch — the table only ever displays values
|
||||
// that the backend has returned.
|
||||
// 4. The cell re-renders from the refetched server data.
|
||||
//
|
||||
// We deliberately do NOT call ``hookData.updateOptimistically`` here:
|
||||
// flipping the cell client-side before the backend confirmed leads to
|
||||
// (a) misleading UX (a click that silently reverts on error) and
|
||||
// (b) clobber-PUTs when the user toggles a sibling cell while the previous
|
||||
// change is still in flight (its payload would be merged from the
|
||||
// unconfirmed local state).
|
||||
const handleInlineToggle = useCallback(async (row: T, column: ColumnConfig, currentValue: boolean) => {
|
||||
if (!canInlineEdit || !isInlineEditableColumn(column)) return;
|
||||
|
||||
|
||||
const rowId = row[idField];
|
||||
const cellKey = `${rowId}-${column.key}`;
|
||||
|
||||
// Check if update function is available (either from prop or hookData)
|
||||
|
||||
const updateFn = onInlineUpdate || hookData?.handleInlineUpdate;
|
||||
if (!updateFn) {
|
||||
// Silent return - inline editing is optional, no warning needed
|
||||
// Inline editing is optional — silently noop when no handler is wired.
|
||||
return;
|
||||
}
|
||||
|
||||
// Mark cell as updating
|
||||
|
||||
setUpdatingCells(prev => new Set(prev).add(cellKey));
|
||||
|
||||
const newValue = !currentValue;
|
||||
const hasOptimisticUpdate = !!hookData?.updateOptimistically;
|
||||
|
||||
// If updateOptimistically is available, use it for immediate UI feedback
|
||||
if (hasOptimisticUpdate) {
|
||||
hookData.updateOptimistically(rowId, { [column.key]: newValue });
|
||||
}
|
||||
|
||||
try {
|
||||
// Call the update function (generic - no entity-specific logic)
|
||||
if (onInlineUpdate) {
|
||||
await onInlineUpdate(row, column.key, newValue);
|
||||
} else if (hookData?.handleInlineUpdate) {
|
||||
// Pass row as third parameter for hooks that need to merge changes with existing data
|
||||
await hookData.handleInlineUpdate(rowId, { [column.key]: newValue }, row);
|
||||
}
|
||||
|
||||
// Only refetch if we DON'T have optimistic update (to get fresh data)
|
||||
// With optimistic update, local state is already correct
|
||||
if (!hasOptimisticUpdate && hookData?.refetch) {
|
||||
await hookData.refetch();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('FormGeneratorTable: Inline update failed:', error);
|
||||
// Revert optimistic update on error
|
||||
if (hasOptimisticUpdate) {
|
||||
hookData.updateOptimistically(rowId, { [column.key]: currentValue });
|
||||
}
|
||||
// Refetch to restore consistent state on error
|
||||
if (hookData?.refetch) {
|
||||
await hookData.refetch();
|
||||
}
|
||||
} finally {
|
||||
// Remove cell from updating state
|
||||
setUpdatingCells(prev => {
|
||||
const newSet = new Set(prev);
|
||||
newSet.delete(cellKey);
|
||||
return newSet;
|
||||
|
||||
const previous = inlineUpdateQueueRef.current.get(String(rowId)) || Promise.resolve();
|
||||
|
||||
const work: Promise<void> = previous
|
||||
.catch(() => undefined)
|
||||
.then(async () => {
|
||||
try {
|
||||
// Re-resolve the row from the latest refetched snapshot so the
|
||||
// merged payload reflects every server-confirmed change made by
|
||||
// earlier queued toggles on this row.
|
||||
const latestRow = (dataRef.current.find(
|
||||
(r: any) => String(r?.[idField]) === String(rowId),
|
||||
) as T | undefined) ?? row;
|
||||
|
||||
if (onInlineUpdate) {
|
||||
await onInlineUpdate(latestRow, column.key, newValue);
|
||||
} else if (hookData?.handleInlineUpdate) {
|
||||
await hookData.handleInlineUpdate(rowId, { [column.key]: newValue }, latestRow);
|
||||
}
|
||||
|
||||
// Always refetch on success — the cell only ever shows backend truth.
|
||||
if (hookData?.refetch) {
|
||||
await hookData.refetch();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('FormGeneratorTable: Inline update failed:', error);
|
||||
// Refetch on error too: restores the row to confirmed server state
|
||||
// (the cell snaps back to the original value).
|
||||
if (hookData?.refetch) {
|
||||
try { await hookData.refetch(); } catch { /* swallow */ }
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
setUpdatingCells(prev => {
|
||||
const newSet = new Set(prev);
|
||||
newSet.delete(cellKey);
|
||||
return newSet;
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
inlineUpdateQueueRef.current.set(String(rowId), work);
|
||||
try {
|
||||
await work;
|
||||
} finally {
|
||||
if (inlineUpdateQueueRef.current.get(String(rowId)) === work) {
|
||||
inlineUpdateQueueRef.current.delete(String(rowId));
|
||||
}
|
||||
}
|
||||
}, [canInlineEdit, isInlineEditableColumn, idField, onInlineUpdate, hookData]);
|
||||
|
||||
|
|
|
|||
|
|
@ -140,8 +140,8 @@ export const UserSection: React.FC = () => {
|
|||
|
||||
{/* Legal Modal */}
|
||||
{showLegalModal && (
|
||||
<div className={styles.modalOverlay} onClick={() => setShowLegalModal(false)}>
|
||||
<div className={styles.modal} onClick={(e) => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modal}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2>{t('Legal notices')}</h2>
|
||||
<button
|
||||
|
|
|
|||
|
|
@ -0,0 +1,36 @@
|
|||
.wrapper {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
padding: 0.25rem 0.5rem;
|
||||
border: 1px solid var(--color-border, rgba(0, 0, 0, 0.15));
|
||||
border-radius: 6px;
|
||||
background: var(--color-surface, rgba(255, 255, 255, 0.6));
|
||||
color: var(--color-text, #1f2937);
|
||||
}
|
||||
|
||||
.icon {
|
||||
font-size: 0.85rem;
|
||||
opacity: 0.7;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.select {
|
||||
appearance: none;
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: inherit;
|
||||
font-size: 0.8rem;
|
||||
font-family: inherit;
|
||||
cursor: pointer;
|
||||
padding: 0.05rem 0.5rem 0.05rem 0.15rem;
|
||||
border-radius: 4px;
|
||||
opacity: 0.95;
|
||||
transition: opacity 0.15s;
|
||||
}
|
||||
|
||||
.select:hover,
|
||||
.select:focus {
|
||||
opacity: 1;
|
||||
outline: none;
|
||||
}
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
import { FaGlobe } from 'react-icons/fa';
|
||||
import { useLanguage } from '../../../providers/language/LanguageContext';
|
||||
import styles from './LanguageSelector.module.css';
|
||||
|
||||
export function LanguageSelector() {
|
||||
const { currentLanguage, setLanguage, availableLanguages } = useLanguage();
|
||||
|
||||
// Always show the selector. If the backend has not (yet) returned a list,
|
||||
// fall back to a static option for the currently active language so the
|
||||
// control is visible even on pre-login screens / before the codes endpoint
|
||||
// resolves.
|
||||
const optionList = availableLanguages.length > 0
|
||||
? availableLanguages
|
||||
: [{ code: currentLanguage, label: currentLanguage.toUpperCase() } as { code: string; label: string }];
|
||||
|
||||
return (
|
||||
<div className={styles.wrapper}>
|
||||
<FaGlobe className={styles.icon} />
|
||||
<select
|
||||
className={styles.select}
|
||||
value={currentLanguage}
|
||||
onChange={(e) => setLanguage(e.target.value as typeof currentLanguage)}
|
||||
aria-label="Sprache / Language"
|
||||
>
|
||||
{optionList.map((lang) => (
|
||||
<option key={lang.code} value={lang.code}>
|
||||
{lang.label || lang.code.toUpperCase()}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default LanguageSelector;
|
||||
2
src/components/UiComponents/LanguageSelector/index.ts
Normal file
2
src/components/UiComponents/LanguageSelector/index.ts
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
export { LanguageSelector } from './LanguageSelector';
|
||||
export { default } from './LanguageSelector';
|
||||
77
src/components/UiComponents/Modal/Modal.module.css
Normal file
77
src/components/UiComponents/Modal/Modal.module.css
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
.overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.modal {
|
||||
background: var(--surface-color);
|
||||
border-radius: 12px;
|
||||
width: 90%;
|
||||
max-width: 600px;
|
||||
max-height: 90vh;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
.sizeSm { max-width: 420px; }
|
||||
.sizeMd { max-width: 600px; }
|
||||
.sizeLg { max-width: 880px; }
|
||||
.sizeXl { max-width: 1200px; }
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 1rem 1.5rem;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.title {
|
||||
font-size: 1.125rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.closeButton {
|
||||
background: none;
|
||||
border: none;
|
||||
font-size: 1.25rem;
|
||||
color: var(--text-secondary);
|
||||
cursor: pointer;
|
||||
padding: 0.25rem;
|
||||
line-height: 1;
|
||||
transition: color 0.2s;
|
||||
}
|
||||
|
||||
.closeButton:hover {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.content {
|
||||
padding: 1.5rem;
|
||||
overflow-y: auto;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.footer {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 0.75rem;
|
||||
padding: 1rem 1.5rem;
|
||||
border-top: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
:global(.dark-theme) .overlay {
|
||||
background: rgba(0, 0, 0, 0.7);
|
||||
}
|
||||
133
src/components/UiComponents/Modal/Modal.tsx
Normal file
133
src/components/UiComponents/Modal/Modal.tsx
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
/**
|
||||
* Modal — central, consistent dialog component for the whole UI.
|
||||
*
|
||||
* Behavior contract (intentional, documented):
|
||||
* - The dialog stays open until the user explicitly closes it via the X button
|
||||
* (top-right) or an explicit Cancel/OK button rendered by the consumer.
|
||||
* - Clicking on the dimmed overlay does NOT close the dialog (default: false).
|
||||
* - Pressing Escape does NOT close the dialog (default: false).
|
||||
* - Both behaviors can be opted-in via ``closeOnOverlayClick`` /
|
||||
* ``closeOnEscape`` for the rare cases where this is desired.
|
||||
*
|
||||
* Layout: standard 3-row flex (header / scrollable content / optional footer).
|
||||
* The component traps body scroll while open and is accessible via ``role=dialog``.
|
||||
*/
|
||||
import React, { useEffect, useRef } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import styles from './Modal.module.css';
|
||||
|
||||
export type ModalSize = 'sm' | 'md' | 'lg' | 'xl';
|
||||
|
||||
export interface ModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
title?: React.ReactNode;
|
||||
children: React.ReactNode;
|
||||
footer?: React.ReactNode;
|
||||
size?: ModalSize;
|
||||
closeOnOverlayClick?: boolean;
|
||||
closeOnEscape?: boolean;
|
||||
hideCloseButton?: boolean;
|
||||
ariaLabel?: string;
|
||||
className?: string;
|
||||
contentClassName?: string;
|
||||
testId?: string;
|
||||
}
|
||||
|
||||
const _SIZE_CLASS: Record<ModalSize, string> = {
|
||||
sm: styles.sizeSm,
|
||||
md: styles.sizeMd,
|
||||
lg: styles.sizeLg,
|
||||
xl: styles.sizeXl,
|
||||
};
|
||||
|
||||
export const Modal: React.FC<ModalProps> = ({
|
||||
open,
|
||||
onClose,
|
||||
title,
|
||||
children,
|
||||
footer,
|
||||
size = 'md',
|
||||
closeOnOverlayClick = false,
|
||||
closeOnEscape = false,
|
||||
hideCloseButton = false,
|
||||
ariaLabel,
|
||||
className,
|
||||
contentClassName,
|
||||
testId,
|
||||
}) => {
|
||||
const dialogRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const previousOverflow = document.body.style.overflow;
|
||||
document.body.style.overflow = 'hidden';
|
||||
return () => {
|
||||
document.body.style.overflow = previousOverflow;
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !closeOnEscape) return;
|
||||
const handleKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') {
|
||||
e.stopPropagation();
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', handleKey);
|
||||
return () => window.removeEventListener('keydown', handleKey);
|
||||
}, [open, closeOnEscape, onClose]);
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
const handleOverlayClick = (e: React.MouseEvent<HTMLDivElement>) => {
|
||||
if (!closeOnOverlayClick) return;
|
||||
if (e.target === e.currentTarget) onClose();
|
||||
};
|
||||
|
||||
const titleId = title ? 'modal-title' : undefined;
|
||||
|
||||
const node = (
|
||||
<div
|
||||
className={styles.overlay}
|
||||
onClick={handleOverlayClick}
|
||||
data-testid={testId}
|
||||
>
|
||||
<div
|
||||
ref={dialogRef}
|
||||
className={`${styles.modal} ${_SIZE_CLASS[size]} ${className ?? ''}`.trim()}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby={titleId}
|
||||
aria-label={!title ? ariaLabel : undefined}
|
||||
>
|
||||
{(title || !hideCloseButton) && (
|
||||
<div className={styles.header}>
|
||||
{title ? (
|
||||
<h2 id={titleId} className={styles.title}>{title}</h2>
|
||||
) : <span aria-hidden="true" />}
|
||||
{!hideCloseButton && (
|
||||
<button
|
||||
type="button"
|
||||
className={styles.closeButton}
|
||||
onClick={onClose}
|
||||
aria-label="Close"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className={`${styles.content} ${contentClassName ?? ''}`.trim()}>
|
||||
{children}
|
||||
</div>
|
||||
{footer && <div className={styles.footer}>{footer}</div>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return createPortal(node, document.body);
|
||||
};
|
||||
|
||||
export default Modal;
|
||||
3
src/components/UiComponents/Modal/index.ts
Normal file
3
src/components/UiComponents/Modal/index.ts
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
export { Modal } from './Modal';
|
||||
export type { ModalProps, ModalSize } from './Modal';
|
||||
export { default } from './Modal';
|
||||
|
|
@ -23,6 +23,8 @@ export interface PopupProps {
|
|||
className?: string;
|
||||
size?: 'small' | 'medium' | 'large' | 'fullscreen';
|
||||
closable?: boolean;
|
||||
closeOnBackdropClick?: boolean;
|
||||
closeOnEscape?: boolean;
|
||||
actions?: PopupAction[];
|
||||
}
|
||||
|
||||
|
|
@ -36,6 +38,8 @@ export function Popup({
|
|||
className = '',
|
||||
size = 'medium',
|
||||
closable = true,
|
||||
closeOnBackdropClick = false,
|
||||
closeOnEscape = true,
|
||||
actions = []
|
||||
}: PopupProps) {
|
||||
const { t } = useLanguage();
|
||||
|
|
@ -43,7 +47,7 @@ export function Popup({
|
|||
// Handle escape key
|
||||
React.useEffect(() => {
|
||||
const handleEscape = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape' && closable) {
|
||||
if (e.key === 'Escape' && closable && closeOnEscape) {
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
|
@ -58,13 +62,13 @@ export function Popup({
|
|||
document.removeEventListener('keydown', handleEscape);
|
||||
document.body.style.overflow = 'unset';
|
||||
};
|
||||
}, [isOpen, closable, onClose]);
|
||||
}, [isOpen, closable, closeOnEscape, onClose]);
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
// Handle backdrop click
|
||||
const handleBackdropClick = (e: React.MouseEvent) => {
|
||||
if (e.target === e.currentTarget && closable) {
|
||||
if (e.target === e.currentTarget && closable && closeOnBackdropClick) {
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,67 +1,29 @@
|
|||
/**
|
||||
* VoiceLanguageSelect
|
||||
*
|
||||
* Reusable component for selecting voice/speech recognition language.
|
||||
* Defaults to user's profile language.
|
||||
* Can be used for speech-to-text, text-to-speech, and translation features.
|
||||
*
|
||||
* Reusable picker for voice/speech-recognition language. Reads the language
|
||||
* list from the central VoiceCatalog (single source of truth) — never
|
||||
* hard-coded here.
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { useLanguage } from '../../../providers/language/LanguageContext';
|
||||
import { useVoiceCatalog, useDefaultVoiceLocale } from '../../../contexts/VoiceCatalogContext';
|
||||
import type { VoiceLanguage } from '../../../api/voiceCatalogApi';
|
||||
import styles from './VoiceLanguageSelect.module.css';
|
||||
|
||||
// Voice language options with full locale codes for Google Cloud Speech
|
||||
export interface VoiceLanguageOption {
|
||||
code: string; // Full locale code (e.g., 'de-DE')
|
||||
label: string; // Display label
|
||||
shortCode: string; // Short code for mapping (e.g., 'de')
|
||||
flag?: string; // Optional flag emoji
|
||||
}
|
||||
|
||||
// Supported languages for speech recognition
|
||||
export const voiceLanguages: VoiceLanguageOption[] = [
|
||||
{ code: 'de-DE', label: 'Deutsch', shortCode: 'de', flag: '🇩🇪' },
|
||||
{ code: 'de-CH', label: 'Deutsch (Schweiz)', shortCode: 'de', flag: '🇨🇭' },
|
||||
{ code: 'en-US', label: 'English (US)', shortCode: 'en', flag: '🇺🇸' },
|
||||
{ code: 'en-GB', label: 'English (UK)', shortCode: 'en', flag: '🇬🇧' },
|
||||
{ code: 'fr-FR', label: 'Français', shortCode: 'fr', flag: '🇫🇷' },
|
||||
{ code: 'fr-CH', label: 'Français (Suisse)', shortCode: 'fr', flag: '🇨🇭' },
|
||||
{ code: 'it-IT', label: 'Italiano', shortCode: 'it', flag: '🇮🇹' },
|
||||
{ code: 'it-CH', label: 'Italiano (Svizzera)', shortCode: 'it', flag: '🇨🇭' },
|
||||
{ code: 'es-ES', label: 'Español', shortCode: 'es', flag: '🇪🇸' },
|
||||
{ code: 'pt-BR', label: 'Português', shortCode: 'pt', flag: '🇧🇷' },
|
||||
];
|
||||
|
||||
// Map user profile language (short code) to default voice language (full code)
|
||||
const profileToVoiceLanguage: Record<string, string> = {
|
||||
'de': 'de-DE',
|
||||
'en': 'en-US',
|
||||
'fr': 'fr-FR',
|
||||
'it': 'it-IT',
|
||||
'es': 'es-ES',
|
||||
'pt': 'pt-BR',
|
||||
};
|
||||
export type VoiceLanguageOption = VoiceLanguage;
|
||||
|
||||
export interface VoiceLanguageSelectProps {
|
||||
value: string;
|
||||
onChange: (languageCode: string) => void;
|
||||
disabled?: boolean;
|
||||
compact?: boolean; // Compact mode shows only flag/short code
|
||||
showFlags?: boolean; // Show flag emojis
|
||||
compact?: boolean;
|
||||
showFlags?: boolean;
|
||||
className?: string;
|
||||
title?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the default voice language based on user's profile language
|
||||
*/
|
||||
export const getDefaultVoiceLanguage = (profileLanguage?: string): string => {
|
||||
if (profileLanguage && profileToVoiceLanguage[profileLanguage]) {
|
||||
return profileToVoiceLanguage[profileLanguage];
|
||||
}
|
||||
return 'de-DE'; // Default fallback
|
||||
};
|
||||
|
||||
export const VoiceLanguageSelect: React.FC<VoiceLanguageSelectProps> = ({
|
||||
value,
|
||||
onChange,
|
||||
|
|
@ -71,23 +33,25 @@ export const VoiceLanguageSelect: React.FC<VoiceLanguageSelectProps> = ({
|
|||
className = '',
|
||||
title = 'Sprache für Spracherkennung',
|
||||
}) => {
|
||||
const { languages, isLoading } = useVoiceCatalog();
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
|
||||
onChange(e.target.value);
|
||||
};
|
||||
|
||||
|
||||
return (
|
||||
<div className={`${styles.container} ${compact ? styles.compact : ''} ${className}`}>
|
||||
<select
|
||||
className={styles.select}
|
||||
value={value}
|
||||
onChange={handleChange}
|
||||
disabled={disabled}
|
||||
disabled={disabled || isLoading}
|
||||
title={title}
|
||||
>
|
||||
{voiceLanguages.map((lang) => (
|
||||
<option key={lang.code} value={lang.code}>
|
||||
{languages.map((lang) => (
|
||||
<option key={lang.bcp47} value={lang.bcp47}>
|
||||
{showFlags && lang.flag ? `${lang.flag} ` : ''}
|
||||
{compact ? lang.code.split('-')[0].toUpperCase() : lang.label}
|
||||
{compact ? lang.iso.toUpperCase() : lang.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
|
@ -96,37 +60,34 @@ export const VoiceLanguageSelect: React.FC<VoiceLanguageSelectProps> = ({
|
|||
};
|
||||
|
||||
/**
|
||||
* Hook to manage voice language state with user profile default
|
||||
* Hook to manage voice language state with user profile default.
|
||||
* Initial value falls back to the catalog-derived default for the profile language.
|
||||
*/
|
||||
export const useVoiceLanguage = (initialValue?: string) => {
|
||||
const { currentLanguage } = useLanguage();
|
||||
|
||||
// Track if user has manually changed the language
|
||||
const { languages } = useVoiceCatalog();
|
||||
const defaultLocale = useDefaultVoiceLocale(currentLanguage);
|
||||
|
||||
const hasManuallyChanged = React.useRef(false);
|
||||
|
||||
// Initialize with user's profile language (or provided initial value)
|
||||
const [voiceLanguage, setVoiceLanguage] = React.useState<string>(
|
||||
initialValue || getDefaultVoiceLanguage(currentLanguage)
|
||||
initialValue || defaultLocale,
|
||||
);
|
||||
|
||||
// Update voice language when user profile language changes (only if not manually set)
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!initialValue && !hasManuallyChanged.current) {
|
||||
const newDefault = getDefaultVoiceLanguage(currentLanguage);
|
||||
setVoiceLanguage(newDefault);
|
||||
setVoiceLanguage(defaultLocale);
|
||||
}
|
||||
}, [currentLanguage, initialValue]);
|
||||
|
||||
// Wrapper to track manual changes
|
||||
}, [defaultLocale, initialValue]);
|
||||
|
||||
const handleSetVoiceLanguage = React.useCallback((newLanguage: string) => {
|
||||
hasManuallyChanged.current = true;
|
||||
setVoiceLanguage(newLanguage);
|
||||
}, []);
|
||||
|
||||
|
||||
return {
|
||||
voiceLanguage,
|
||||
setVoiceLanguage: handleSetVoiceLanguage,
|
||||
voiceLanguages,
|
||||
voiceLanguages: languages,
|
||||
};
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -1,8 +1,6 @@
|
|||
export {
|
||||
VoiceLanguageSelect,
|
||||
useVoiceLanguage,
|
||||
getDefaultVoiceLanguage,
|
||||
voiceLanguages,
|
||||
export {
|
||||
VoiceLanguageSelect,
|
||||
useVoiceLanguage,
|
||||
type VoiceLanguageOption,
|
||||
type VoiceLanguageSelectProps
|
||||
type VoiceLanguageSelectProps,
|
||||
} from './VoiceLanguageSelect';
|
||||
|
|
|
|||
|
|
@ -20,4 +20,5 @@ export * from './AutoScroll';
|
|||
export * from './Tabs';
|
||||
export type { TabsProps, Tab } from './Tabs';
|
||||
export * from './Toast';
|
||||
export * from './VoiceLanguageSelect';
|
||||
export * from './VoiceLanguageSelect';
|
||||
export * from './Modal';
|
||||
|
|
@ -52,6 +52,22 @@ function _formatRelativeTime(dateStr?: string | number): string {
|
|||
return d.toLocaleDateString([], { month: 'short', day: 'numeric' });
|
||||
}
|
||||
|
||||
/**
|
||||
* Timestamp der letzten Aktivität eines Chats: `lastMessageAt` (Backend liefert
|
||||
* den Zeitstempel der letzten Nachricht) bevorzugt, sonst Fallback auf
|
||||
* `updatedAt` (Workflow-Lifecycle-Zeit). Wird sowohl für Anzeige als auch
|
||||
* Sortierung verwendet, damit Liste und Label konsistent sind.
|
||||
*/
|
||||
function _lastTouchValue(chat: ChatItem): string | number | undefined {
|
||||
return chat.lastMessageAt ?? chat.updatedAt;
|
||||
}
|
||||
|
||||
function _lastTouchTs(chat: ChatItem): number {
|
||||
const v = _lastTouchValue(chat);
|
||||
if (v === undefined || v === null) return 0;
|
||||
return typeof v === 'number' ? v : new Date(v).getTime();
|
||||
}
|
||||
|
||||
const ChatsTab: React.FC<ChatsTabProps> = ({ context,
|
||||
onSelectChat,
|
||||
onDragStart,
|
||||
|
|
@ -113,13 +129,7 @@ const ChatsTab: React.FC<ChatsTabProps> = ({ context,
|
|||
}
|
||||
|
||||
const sorted = Array.from(groupMap.values());
|
||||
sorted.forEach(g =>
|
||||
g.chats.sort((a, b) => {
|
||||
const ta = typeof a.updatedAt === 'number' ? a.updatedAt : new Date(a.updatedAt || 0).getTime();
|
||||
const tb = typeof b.updatedAt === 'number' ? b.updatedAt : new Date(b.updatedAt || 0).getTime();
|
||||
return tb - ta;
|
||||
}),
|
||||
);
|
||||
sorted.forEach(g => g.chats.sort((a, b) => _lastTouchTs(b) - _lastTouchTs(a)));
|
||||
setGroups(sorted);
|
||||
|
||||
if (expandedGroups.size === 0 && sorted.length > 0) {
|
||||
|
|
@ -218,16 +228,9 @@ const ChatsTab: React.FC<ChatsTabProps> = ({ context,
|
|||
.map(g => ({ ...g, chats: _applyFilter(g.chats) }))
|
||||
.filter(g => g.chats.length > 0);
|
||||
|
||||
const _toTs = (v?: string | number): number =>
|
||||
typeof v === 'number' ? v : new Date(v || 0).getTime();
|
||||
|
||||
const _allChats = _filteredGroups
|
||||
.flatMap(g => g.chats)
|
||||
.sort((a, b) => {
|
||||
const ta = _toTs(a.lastMessageAt ?? a.updatedAt);
|
||||
const tb = _toTs(b.lastMessageAt ?? b.updatedAt);
|
||||
return tb - ta;
|
||||
});
|
||||
.sort((a, b) => _lastTouchTs(b) - _lastTouchTs(a));
|
||||
|
||||
const _activeCount = groups.reduce((n, g) => n + g.chats.filter(c => !_isArchived(c)).length, 0);
|
||||
const _archivedCount = groups.reduce((n, g) => n + g.chats.filter(c => _isArchived(c)).length, 0);
|
||||
|
|
@ -270,7 +273,7 @@ const ChatsTab: React.FC<ChatsTabProps> = ({ context,
|
|||
) : (
|
||||
<>
|
||||
<span className={styles.chatDate}>
|
||||
{_formatRelativeTime(chat.updatedAt)}
|
||||
{_formatRelativeTime(_lastTouchValue(chat))}
|
||||
</span>
|
||||
<span
|
||||
className={styles.chatLabel}
|
||||
|
|
|
|||
|
|
@ -10,9 +10,10 @@ import { useLanguage } from '../../providers/language/LanguageContext';
|
|||
interface FilesTabProps {
|
||||
context: UdbContext;
|
||||
onFileSelect?: (fileId: string, fileName?: string) => void;
|
||||
onSendToChat?: (items: Array<{ id: string; type: 'file' | 'folder'; name: string }>) => void;
|
||||
}
|
||||
|
||||
const FilesTab: React.FC<FilesTabProps> = ({ context, onFileSelect }) => {
|
||||
const FilesTab: React.FC<FilesTabProps> = ({ context, onFileSelect, onSendToChat }) => {
|
||||
const { t } = useLanguage();
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [isDragOver, setIsDragOver] = useState(false);
|
||||
|
|
@ -46,6 +47,8 @@ const FilesTab: React.FC<FilesTabProps> = ({ context, onFileSelect }) => {
|
|||
name: f.name,
|
||||
parentId: f.parentId ?? null,
|
||||
fileCount: f.fileCount ?? 0,
|
||||
neutralize: f.neutralize ?? false,
|
||||
scope: f.scope ?? 'personal',
|
||||
}));
|
||||
}, [folders]);
|
||||
|
||||
|
|
@ -166,6 +169,26 @@ const FilesTab: React.FC<FilesTabProps> = ({ context, onFileSelect }) => {
|
|||
}
|
||||
}, [updateTreeFileNode, refreshTreeFiles]);
|
||||
|
||||
const _onFolderNeutralizeToggle = useCallback(async (folderId: string, newValue: boolean) => {
|
||||
try {
|
||||
await api.patch(`/api/files/folders/${folderId}/neutralize`, { neutralize: newValue });
|
||||
await refreshFolders();
|
||||
await refreshTreeFiles();
|
||||
} catch (err) {
|
||||
console.error('Failed to toggle folder neutralize:', err);
|
||||
}
|
||||
}, [refreshFolders, refreshTreeFiles]);
|
||||
|
||||
const _onFolderScopeChange = useCallback(async (folderId: string, newScope: string) => {
|
||||
try {
|
||||
await api.patch(`/api/files/folders/${folderId}/scope`, { scope: newScope });
|
||||
await refreshFolders();
|
||||
await refreshTreeFiles();
|
||||
} catch (err) {
|
||||
console.error('Failed to change folder scope:', err);
|
||||
}
|
||||
}, [refreshFolders, refreshTreeFiles]);
|
||||
|
||||
if (treeFilesLoading && treeFileNodes.length === 0) {
|
||||
return <div className={styles.loading}>{t('Dateien laden')}</div>;
|
||||
}
|
||||
|
|
@ -256,6 +279,9 @@ const FilesTab: React.FC<FilesTabProps> = ({ context, onFileSelect }) => {
|
|||
onDownloadFolder={handleDownloadFolder}
|
||||
onScopeChange={_onScopeChange}
|
||||
onNeutralizeToggle={_onNeutralizeToggle}
|
||||
onFolderScopeChange={_onFolderScopeChange}
|
||||
onFolderNeutralizeToggle={_onFolderNeutralizeToggle}
|
||||
onSendToChat={onSendToChat}
|
||||
/>
|
||||
|
||||
{_fileNodes.length === 0 && (
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -14,6 +14,20 @@ export interface UdbContext {
|
|||
userId?: string;
|
||||
}
|
||||
|
||||
export interface AddToChat_FileItem {
|
||||
id: string;
|
||||
type: 'file' | 'folder';
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface AddToChat_FeatureSource {
|
||||
featureInstanceId: string;
|
||||
featureCode: string;
|
||||
tableName?: string;
|
||||
objectKey: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
interface UnifiedDataBarProps {
|
||||
context: UdbContext;
|
||||
activeTab?: UdbTab;
|
||||
|
|
@ -27,6 +41,9 @@ interface UnifiedDataBarProps {
|
|||
onChatDragStart?: (chatId: string, event: React.DragEvent) => void;
|
||||
onFileSelect?: (fileId: string, fileName?: string) => void;
|
||||
onSourcesChanged?: () => void;
|
||||
onSendToChat_Files?: (items: AddToChat_FileItem[]) => void;
|
||||
onSendToChat_FeatureSource?: (params: AddToChat_FeatureSource) => void;
|
||||
onAttachDataSource?: (dsId: string) => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
|
|
@ -52,6 +69,9 @@ const UnifiedDataBar: React.FC<UnifiedDataBarProps> = ({
|
|||
onChatDragStart,
|
||||
onFileSelect,
|
||||
onSourcesChanged,
|
||||
onSendToChat_Files,
|
||||
onSendToChat_FeatureSource,
|
||||
onAttachDataSource,
|
||||
className,
|
||||
}) => {
|
||||
const { t } = useLanguage();
|
||||
|
|
@ -95,10 +115,16 @@ const UnifiedDataBar: React.FC<UnifiedDataBarProps> = ({
|
|||
<FilesTab
|
||||
context={context}
|
||||
onFileSelect={onFileSelect}
|
||||
onSendToChat={onSendToChat_Files}
|
||||
/>
|
||||
)}
|
||||
{currentTab === 'sources' && !hideTabs?.includes('sources') && (
|
||||
<SourcesTab context={context} onSourcesChanged={onSourcesChanged} />
|
||||
<SourcesTab
|
||||
context={context}
|
||||
onSourcesChanged={onSourcesChanged}
|
||||
onSendToChat_FeatureSource={onSendToChat_FeatureSource}
|
||||
onAttachDataSource={onAttachDataSource}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -1,3 +1,3 @@
|
|||
export { default as UnifiedDataBar } from './UnifiedDataBar';
|
||||
export type { UdbContext, UdbTab } from './UnifiedDataBar';
|
||||
export type { UdbContext, UdbTab, AddToChat_FileItem, AddToChat_FeatureSource } from './UnifiedDataBar';
|
||||
export { useUdlContext } from './useUdlContext';
|
||||
|
|
|
|||
|
|
@ -83,6 +83,8 @@ export const PAGE_ICONS: Record<string, React.ReactNode> = {
|
|||
'page.admin.automation-logs': <FaClipboardList />,
|
||||
'page.admin.logs': <FaFileAlt />,
|
||||
'page.admin.languages': <FaGlobe />,
|
||||
'page.admin.databaseHealth': <FaDatabase />,
|
||||
'page.admin.database-health': <FaDatabase />,
|
||||
'page.admin.demoConfig': <FaCubes />,
|
||||
'page.admin.demo-config': <FaCubes />,
|
||||
'page.admin.mandate-wizard': <FaHatWizard />,
|
||||
|
|
|
|||
151
src/contexts/VoiceCatalogContext.tsx
Normal file
151
src/contexts/VoiceCatalogContext.tsx
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
/**
|
||||
* VoiceCatalogContext
|
||||
*
|
||||
* Loads the central voice/language catalog from the backend exactly once and
|
||||
* makes it available to every component via `useVoiceCatalog()`.
|
||||
*
|
||||
* Provides convenience helpers for ISO ⇄ BCP-47 lookups and curated default
|
||||
* voices, mirroring the backend `voiceCatalog` API. Components MUST NOT keep
|
||||
* their own static language lists.
|
||||
*/
|
||||
|
||||
import React, {
|
||||
createContext,
|
||||
ReactNode,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
} from 'react';
|
||||
import { fetchVoiceCatalog, VoiceLanguage } from '../api/voiceCatalogApi';
|
||||
|
||||
interface VoiceCatalogContextType {
|
||||
languages: VoiceLanguage[];
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
getByBcp47: (code: string | null | undefined) => VoiceLanguage | undefined;
|
||||
getByIso: (iso: string | null | undefined) => VoiceLanguage | undefined;
|
||||
isoToBcp47: (iso: string | null | undefined) => string | undefined;
|
||||
getDefaultVoice: (bcp47: string | null | undefined) => string | null;
|
||||
}
|
||||
|
||||
const VoiceCatalogContext = createContext<VoiceCatalogContextType | undefined>(undefined);
|
||||
|
||||
interface VoiceCatalogProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export const VoiceCatalogProvider: React.FC<VoiceCatalogProviderProps> = ({ children }) => {
|
||||
const [languages, setLanguages] = useState<VoiceLanguage[]>([]);
|
||||
const [isLoading, setIsLoading] = useState<boolean>(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
try {
|
||||
const data = await fetchVoiceCatalog();
|
||||
if (!cancelled) {
|
||||
setLanguages(data);
|
||||
setError(null);
|
||||
}
|
||||
} catch (err: any) {
|
||||
if (!cancelled) {
|
||||
setError(err?.message || 'Failed to load voice catalog');
|
||||
setLanguages([]);
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) setIsLoading(false);
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const byBcp47 = useMemo(() => {
|
||||
const map = new Map<string, VoiceLanguage>();
|
||||
for (const v of languages) map.set(v.bcp47.toLowerCase(), v);
|
||||
return map;
|
||||
}, [languages]);
|
||||
|
||||
const byIso = useMemo(() => {
|
||||
const map = new Map<string, VoiceLanguage>();
|
||||
for (const v of languages) {
|
||||
if (!map.has(v.iso.toLowerCase())) map.set(v.iso.toLowerCase(), v);
|
||||
}
|
||||
return map;
|
||||
}, [languages]);
|
||||
|
||||
const getByBcp47 = useCallback(
|
||||
(code: string | null | undefined) =>
|
||||
code ? byBcp47.get(code.trim().toLowerCase()) : undefined,
|
||||
[byBcp47],
|
||||
);
|
||||
|
||||
const getByIso = useCallback(
|
||||
(iso: string | null | undefined) =>
|
||||
iso ? byIso.get(iso.trim().toLowerCase()) : undefined,
|
||||
[byIso],
|
||||
);
|
||||
|
||||
const isoToBcp47 = useCallback(
|
||||
(iso: string | null | undefined): string | undefined => {
|
||||
if (!iso) return undefined;
|
||||
const trimmed = iso.trim();
|
||||
if (!trimmed) return undefined;
|
||||
if (trimmed.includes('-')) {
|
||||
const canonical = byBcp47.get(trimmed.toLowerCase());
|
||||
return canonical ? canonical.bcp47 : trimmed;
|
||||
}
|
||||
const entry = byIso.get(trimmed.toLowerCase());
|
||||
if (entry) return entry.bcp47;
|
||||
return `${trimmed.toLowerCase()}-${trimmed.toUpperCase()}`;
|
||||
},
|
||||
[byBcp47, byIso],
|
||||
);
|
||||
|
||||
const getDefaultVoice = useCallback(
|
||||
(bcp47: string | null | undefined): string | null => {
|
||||
const entry = getByBcp47(bcp47);
|
||||
return entry?.defaultVoice ?? null;
|
||||
},
|
||||
[getByBcp47],
|
||||
);
|
||||
|
||||
const value = useMemo<VoiceCatalogContextType>(
|
||||
() => ({
|
||||
languages,
|
||||
isLoading,
|
||||
error,
|
||||
getByBcp47,
|
||||
getByIso,
|
||||
isoToBcp47,
|
||||
getDefaultVoice,
|
||||
}),
|
||||
[languages, isLoading, error, getByBcp47, getByIso, isoToBcp47, getDefaultVoice],
|
||||
);
|
||||
|
||||
return (
|
||||
<VoiceCatalogContext.Provider value={value}>{children}</VoiceCatalogContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const useVoiceCatalog = (): VoiceCatalogContextType => {
|
||||
const ctx = useContext(VoiceCatalogContext);
|
||||
if (!ctx) {
|
||||
throw new Error('useVoiceCatalog must be used within VoiceCatalogProvider');
|
||||
}
|
||||
return ctx;
|
||||
};
|
||||
|
||||
/**
|
||||
* Map a profile language (ISO short code) to a default voice locale.
|
||||
* Returns the catalog's BCP-47 for the ISO if available, else falls back to
|
||||
* `de-DE` so the UI always has a deterministic starting value.
|
||||
*/
|
||||
export const useDefaultVoiceLocale = (profileLanguage?: string | null): string => {
|
||||
const { isoToBcp47 } = useVoiceCatalog();
|
||||
return isoToBcp47(profileLanguage) || 'de-DE';
|
||||
};
|
||||
|
|
@ -17,14 +17,16 @@ import {
|
|||
deleteMandate as deleteMandateApi,
|
||||
hardDeleteMandate as hardDeleteMandateApi,
|
||||
type Mandate,
|
||||
type MandateCreateData,
|
||||
type MandateUpdateData,
|
||||
type PaginationParams
|
||||
} from '../api/mandateApi';
|
||||
import type { AttributeDefinition as FormGenAttr } from '../components/FormGenerator/FormGeneratorForm';
|
||||
import { getMandateBillingFormAttributes } from '../utils/mandateBillingFormMerge';
|
||||
import { validateMandateName } from '../utils/mandateNameUtils';
|
||||
|
||||
// Re-export types
|
||||
export type { Mandate, MandateUpdateData, PaginationParams };
|
||||
export type { Mandate, MandateCreateData, MandateUpdateData, PaginationParams };
|
||||
|
||||
export interface AttributeDefinition {
|
||||
name: string;
|
||||
|
|
@ -169,7 +171,19 @@ export function useAdminMandates() {
|
|||
// Create mandate
|
||||
const handleCreate = useCallback(async (mandateData: Partial<Mandate>): Promise<Mandate | null> => {
|
||||
try {
|
||||
const created = await createMandateApi(request, mandateData);
|
||||
const label = typeof mandateData.label === 'string' ? mandateData.label.trim() : '';
|
||||
if (!label) {
|
||||
console.error('createMandate: label (Voller Name) is required');
|
||||
return null;
|
||||
}
|
||||
if (typeof mandateData.name === 'string' && mandateData.name.length > 0) {
|
||||
const slugErr = validateMandateName(mandateData.name);
|
||||
if (slugErr) {
|
||||
console.error(`createMandate: invalid Kurzzeichen — ${slugErr}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
const created = await createMandateApi(request, { ...mandateData, label } as MandateCreateData);
|
||||
await fetchMandates();
|
||||
return created ?? null;
|
||||
} catch (error: any) {
|
||||
|
|
@ -181,6 +195,21 @@ export function useAdminMandates() {
|
|||
// Update mandate
|
||||
const handleUpdate = useCallback(async (mandateId: string, updateData: MandateUpdateData): Promise<boolean> => {
|
||||
try {
|
||||
if ('label' in updateData) {
|
||||
const lbl = typeof updateData.label === 'string' ? updateData.label.trim() : '';
|
||||
if (!lbl) {
|
||||
console.error('updateMandate: label (Voller Name) must not be empty');
|
||||
return false;
|
||||
}
|
||||
updateData = { ...updateData, label: lbl };
|
||||
}
|
||||
if ('name' in updateData && typeof updateData.name === 'string') {
|
||||
const slugErr = validateMandateName(updateData.name);
|
||||
if (slugErr) {
|
||||
console.error(`updateMandate: invalid Kurzzeichen — ${slugErr}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
updateOptimistically(mandateId, updateData);
|
||||
await updateMandateApi(request, mandateId, updateData);
|
||||
return true;
|
||||
|
|
@ -295,9 +324,17 @@ export function useMandateFormAttributes() {
|
|||
}, [load]);
|
||||
|
||||
const formAttributes: FormGenAttr[] = useMemo(() => {
|
||||
return attributes
|
||||
const list = attributes
|
||||
.filter(attr => attr.name !== 'id')
|
||||
.map(attr => ({ ...attr, type: attr.type })) as FormGenAttr[];
|
||||
|
||||
const labelIdx = list.findIndex(a => a.name === 'label');
|
||||
const nameIdx = list.findIndex(a => a.name === 'name');
|
||||
if (labelIdx >= 0 && nameIdx >= 0 && nameIdx < labelIdx) {
|
||||
const [labelAttr] = list.splice(labelIdx, 1);
|
||||
list.splice(nameIdx, 0, labelAttr);
|
||||
}
|
||||
return list;
|
||||
}, [attributes]);
|
||||
|
||||
const createFormAttributes: FormGenAttr[] = useMemo(
|
||||
|
|
|
|||
|
|
@ -19,12 +19,23 @@ import {
|
|||
} from '../api/storeApi';
|
||||
import { useFeatureStore } from '../stores/featureStore';
|
||||
|
||||
/**
|
||||
* Build a stable key identifying a single Store action button so the spinner
|
||||
* can be scoped to exactly that button (one feature × one mandate / instance)
|
||||
* instead of greying out every button of the feature.
|
||||
*/
|
||||
export const _storeActionKey = {
|
||||
activate: (featureCode: string, mandateId?: string) => `activate:${featureCode}:${mandateId ?? ''}`,
|
||||
deactivate: (featureCode: string, instanceId: string) => `deactivate:${featureCode}:${instanceId}`,
|
||||
};
|
||||
|
||||
interface UseStoreReturn {
|
||||
features: StoreFeature[];
|
||||
mandates: UserMandate[];
|
||||
subscriptionInfo: SubscriptionInfo | null;
|
||||
loading: boolean;
|
||||
actionLoading: string | null;
|
||||
/** Set of in-flight action keys (see ``_storeActionKey``) — one entry per button currently processing. */
|
||||
actionLoading: Set<string>;
|
||||
error: string | null;
|
||||
loadStore: () => Promise<void>;
|
||||
loadSubscriptionInfo: (mandateId?: string) => Promise<void>;
|
||||
|
|
@ -37,10 +48,27 @@ export function useStore(): UseStoreReturn {
|
|||
const [mandates, setMandates] = useState<UserMandate[]>([]);
|
||||
const [subscriptionInfo, setSubscriptionInfo] = useState<SubscriptionInfo | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [actionLoading, setActionLoading] = useState<string | null>(null);
|
||||
const [actionLoading, setActionLoading] = useState<Set<string>>(() => new Set());
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const featureStore = useFeatureStore();
|
||||
|
||||
const _markBusy = useCallback((key: string) => {
|
||||
setActionLoading(prev => {
|
||||
const next = new Set(prev);
|
||||
next.add(key);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const _markIdle = useCallback((key: string) => {
|
||||
setActionLoading(prev => {
|
||||
if (!prev.has(key)) return prev;
|
||||
const next = new Set(prev);
|
||||
next.delete(key);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const loadSubscriptionInfo = useCallback(async (mandateId?: string) => {
|
||||
try {
|
||||
const info = await fetchSubscriptionInfo(mandateId);
|
||||
|
|
@ -81,7 +109,8 @@ export function useStore(): UseStoreReturn {
|
|||
}, [featureStore, loadStore]);
|
||||
|
||||
const activate = useCallback(async (featureCode: string, mandateId?: string) => {
|
||||
setActionLoading(featureCode);
|
||||
const key = _storeActionKey.activate(featureCode, mandateId);
|
||||
_markBusy(key);
|
||||
setError(null);
|
||||
try {
|
||||
await activateStoreFeature(featureCode, mandateId);
|
||||
|
|
@ -90,12 +119,13 @@ export function useStore(): UseStoreReturn {
|
|||
const msg = err instanceof Error ? err.message : 'Activation failed';
|
||||
setError(msg);
|
||||
} finally {
|
||||
setActionLoading(null);
|
||||
_markIdle(key);
|
||||
}
|
||||
}, [_refreshAfterAction]);
|
||||
}, [_refreshAfterAction, _markBusy, _markIdle]);
|
||||
|
||||
const deactivate = useCallback(async (featureCode: string, mandateId: string, instanceId: string) => {
|
||||
setActionLoading(featureCode);
|
||||
const key = _storeActionKey.deactivate(featureCode, instanceId);
|
||||
_markBusy(key);
|
||||
setError(null);
|
||||
try {
|
||||
await deactivateStoreFeature(featureCode, mandateId, instanceId);
|
||||
|
|
@ -104,9 +134,9 @@ export function useStore(): UseStoreReturn {
|
|||
const msg = err instanceof Error ? err.message : 'Deactivation failed';
|
||||
setError(msg);
|
||||
} finally {
|
||||
setActionLoading(null);
|
||||
_markIdle(key);
|
||||
}
|
||||
}, [_refreshAfterAction]);
|
||||
}, [_refreshAfterAction, _markBusy, _markIdle]);
|
||||
|
||||
return { features, mandates, subscriptionInfo, loading, actionLoading, error, loadStore, loadSubscriptionInfo, activate, deactivate };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -32,11 +32,12 @@ export function useCurrentUser() {
|
|||
const cachedUser = getUserDataCache();
|
||||
if (cachedUser && cachedUser.username) {
|
||||
// Use cached user data - permissions are checked via RBAC API, not client-side
|
||||
// Note: roleLabels is deprecated in Multi-Tenant architecture - use isSysAdmin flag instead
|
||||
// Note: roleLabels is deprecated in Multi-Tenant architecture - use isSysAdmin/isPlatformAdmin flags instead
|
||||
setUser(cachedUser);
|
||||
console.log('✅ Using cached user data from sessionStorage (persists during session):', {
|
||||
username: cachedUser.username,
|
||||
isSysAdmin: cachedUser.isSysAdmin
|
||||
isSysAdmin: cachedUser.isSysAdmin,
|
||||
isPlatformAdmin: cachedUser.isPlatformAdmin
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
|
@ -72,6 +73,7 @@ export function useCurrentUser() {
|
|||
console.log('📦 User data received from API:', {
|
||||
username: data?.username,
|
||||
isSysAdmin: data?.isSysAdmin,
|
||||
isPlatformAdmin: data?.isPlatformAdmin,
|
||||
allKeys: data ? Object.keys(data) : []
|
||||
});
|
||||
|
||||
|
|
@ -85,11 +87,12 @@ export function useCurrentUser() {
|
|||
}
|
||||
|
||||
// Cache user data (permissions are checked via RBAC API)
|
||||
// Note: roleLabels is deprecated - use isSysAdmin flag for admin checks
|
||||
// Note: roleLabels is deprecated - use isSysAdmin/isPlatformAdmin flags for admin checks
|
||||
setUserDataCache(data);
|
||||
console.log('✅ User data fetched from API and cached:', {
|
||||
username: data.username,
|
||||
isSysAdmin: data.isSysAdmin
|
||||
isSysAdmin: data.isSysAdmin,
|
||||
isPlatformAdmin: data.isPlatformAdmin
|
||||
});
|
||||
setUser(data);
|
||||
} catch (error: any) {
|
||||
|
|
@ -215,11 +218,12 @@ export function useCurrentUser() {
|
|||
const cachedUser = getUserDataCache();
|
||||
if (cachedUser && cachedUser.username) {
|
||||
// Use cached user data - permissions are checked via RBAC API
|
||||
// Note: roleLabels is deprecated in Multi-Tenant architecture - use isSysAdmin flag instead
|
||||
// Note: roleLabels is deprecated in Multi-Tenant architecture - use isSysAdmin/isPlatformAdmin flags instead
|
||||
setUser(cachedUser);
|
||||
console.log('✅ Using cached user data from sessionStorage on mount:', {
|
||||
username: cachedUser.username,
|
||||
isSysAdmin: cachedUser.isSysAdmin
|
||||
isSysAdmin: cachedUser.isSysAdmin,
|
||||
isPlatformAdmin: cachedUser.isPlatformAdmin
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -800,24 +804,26 @@ export function useUserOperations() {
|
|||
}
|
||||
};
|
||||
|
||||
// Generic inline update handler for FormGeneratorTable
|
||||
// Must merge changes with existing row data because backend requires full object
|
||||
// The existingRow parameter is passed from FormGeneratorTable which has access to row data
|
||||
const handleInlineUpdate = async (userId: string, changes: Partial<UserUpdateData>, existingRow?: any) => {
|
||||
if (!existingRow) {
|
||||
throw new Error(`Existing row data required for inline update`);
|
||||
// Generic inline update handler for FormGeneratorTable.
|
||||
//
|
||||
// The User PUT endpoint accepts PARTIAL payloads — only fields explicitly
|
||||
// present are applied; missing fields keep their stored value. We therefore
|
||||
// forward ONLY the changed cells. This avoids two classes of bugs:
|
||||
// 1. Stale snapshot: spreading ``existingRow`` onto the payload would
|
||||
// overwrite fields with whatever the client last loaded, even if the
|
||||
// backend has been updated since (e.g. by a parallel admin action).
|
||||
// 2. Missing-field default-flip: previously, any non-listed field (e.g.
|
||||
// ``isSysAdmin`` while toggling ``isPlatformAdmin``) was absent from
|
||||
// the merged payload and the Pydantic ``User`` body on the backend
|
||||
// filled it with ``False``, silently dropping the other privileged flag.
|
||||
//
|
||||
// ``existingRow`` is kept in the signature for forward-compat with table
|
||||
// hooks but is no longer consulted to build the payload.
|
||||
const handleInlineUpdate = async (userId: string, changes: Partial<UserUpdateData>, _existingRow?: any) => {
|
||||
if (!changes || Object.keys(changes).length === 0) {
|
||||
throw new Error('No fields to update');
|
||||
}
|
||||
|
||||
// Merge changes with existing row data (backend requires full object with required fields)
|
||||
const mergedData: UserUpdateData = {
|
||||
username: existingRow.username,
|
||||
email: existingRow.email,
|
||||
enabled: existingRow.enabled,
|
||||
roleLabels: existingRow.roleLabels,
|
||||
...changes
|
||||
};
|
||||
|
||||
const result = await handleUserUpdate(userId, mergedData);
|
||||
const result = await handleUserUpdate(userId, changes);
|
||||
if (!result.success) {
|
||||
throw new Error(result.error || 'Failed to update');
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import { useCurrentInstance } from '../hooks/useCurrentInstance';
|
|||
import { useFeaturesInitialized, useFeaturesLoading } from '../stores/featureStore';
|
||||
import useNavigation from '../hooks/useNavigation';
|
||||
import styles from './FeatureLayout.module.css';
|
||||
import { mandateDisplayLabel } from '../utils/mandateDisplayUtils';
|
||||
|
||||
import { useLanguage } from '../providers/language/LanguageContext';
|
||||
|
||||
|
|
@ -115,7 +116,9 @@ export const FeatureLayout: React.FC = () => {
|
|||
{/* Header mit Instanz-Info */}
|
||||
<header className={styles.featureHeader}>
|
||||
<div className={styles.breadcrumb}>
|
||||
<span className={styles.mandateName}>{navLabels?.mandate || mandate?.label || mandate?.name}</span>
|
||||
<span className={styles.mandateName}>
|
||||
{navLabels?.mandate || (mandate ? mandateDisplayLabel(mandate) : '')}
|
||||
</span>
|
||||
<span className={styles.separator}>/</span>
|
||||
<span className={styles.featureName}>{navLabels?.feature || feature?.code}</span>
|
||||
<span className={styles.separator}>/</span>
|
||||
|
|
|
|||
|
|
@ -320,11 +320,10 @@ const _RunTracingModal: React.FC<_RunTracingModalProps> = ({ run, onClose }) =>
|
|||
}, [steps]);
|
||||
|
||||
return (
|
||||
<div className={styles.modalOverlay} onClick={onClose}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div
|
||||
className={styles.modal}
|
||||
style={{ maxWidth: 800, height: '80vh' }}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className={styles.modalHeader}>
|
||||
<div>
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ import { useUserMandates } from '../hooks/useUserMandates';
|
|||
import { useConfirm } from '../hooks/useConfirm';
|
||||
import { FormGeneratorTable, ColumnConfig } from '../components/FormGenerator/FormGeneratorTable';
|
||||
import styles from './ComplianceAuditPage.module.css';
|
||||
import { mandateDisplayLabel } from '../utils/mandateDisplayUtils';
|
||||
|
||||
const CHART_COLORS = ['#1976d2', '#00897b', '#6a1b9a', '#e65100', '#5d4037', '#455a64', '#c62828', '#2e7d32'];
|
||||
|
||||
|
|
@ -110,7 +111,11 @@ interface AuditStats {
|
|||
neutralizationPercent: number;
|
||||
}
|
||||
|
||||
interface Mandate { id: string; name?: string; label?: string; }
|
||||
interface Mandate {
|
||||
id: string;
|
||||
name?: string;
|
||||
label?: string;
|
||||
}
|
||||
|
||||
interface ContentModalData {
|
||||
row: any;
|
||||
|
|
@ -554,7 +559,7 @@ export const ComplianceAuditPage: React.FC = () => {
|
|||
>
|
||||
<option value="">{mandatesLoading ? t('Lade…') : t('— Mandant wählen —')}</option>
|
||||
{mandates.map(m => (
|
||||
<option key={m.id} value={m.id}>{m.label || m.name || m.id}</option>
|
||||
<option key={m.id} value={m.id}>{mandateDisplayLabel(m)}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
|
@ -815,8 +820,8 @@ export const ComplianceAuditPage: React.FC = () => {
|
|||
|
||||
{/* ── Content View Modal ── */}
|
||||
{contentModal && (
|
||||
<div className={styles.modalOverlay} onClick={() => setContentModal(null)}>
|
||||
<div className={styles.modalContainer} onClick={e => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modalContainer}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h3 className={styles.modalTitle}>{t('AI-Audit Inhalt')}</h3>
|
||||
<div className={styles.modalMeta}>
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import { PENDING_INVITATION_KEY } from './InvitePage';
|
|||
import OnboardingWizard from '../components/OnboardingWizard';
|
||||
|
||||
import styles from './Login.module.css';
|
||||
|
||||
import { LanguageSelector } from '../components/UiComponents/LanguageSelector';
|
||||
|
||||
import { useLanguage } from '../providers/language/LanguageContext';
|
||||
|
||||
|
|
@ -131,6 +131,9 @@ function Login() {
|
|||
return (
|
||||
<div className={styles.container}>
|
||||
<div className={styles.mainContent}>
|
||||
<div style={{ display: 'flex', justifyContent: 'flex-end', padding: '1rem 1rem 0' }}>
|
||||
<LanguageSelector />
|
||||
</div>
|
||||
<div className={styles.logo}>
|
||||
<img
|
||||
src="/logos/poweron-logo.png"
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { useNavigate } from 'react-router-dom';
|
|||
import styles from './PasswordResetRequest.module.css';
|
||||
import { usePasswordResetRequest } from '../hooks/useAuthentication';
|
||||
import { generateAndStoreCSRFToken } from '../utils/csrfUtils';
|
||||
import { LanguageSelector } from '../components/UiComponents/LanguageSelector';
|
||||
|
||||
import { useLanguage } from '../providers/language/LanguageContext';
|
||||
|
||||
|
|
@ -57,6 +58,9 @@ function PasswordResetRequest() {
|
|||
return (
|
||||
<div className={styles.container}>
|
||||
<div className={styles.mainContent}>
|
||||
<div style={{ display: 'flex', justifyContent: 'flex-end', padding: '1rem 1rem 0' }}>
|
||||
<LanguageSelector />
|
||||
</div>
|
||||
<div className={styles.logo}>
|
||||
<img
|
||||
src="/logos/poweron-logo.png"
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import styles from './Register.module.css';
|
|||
import { useRegister, useMsalRegister, useUsernameAvailability } from '../hooks/useAuthentication';
|
||||
import { generateAndStoreCSRFToken } from '../utils/csrfUtils';
|
||||
import { PENDING_INVITATION_KEY } from './InvitePage';
|
||||
import { LanguageSelector } from '../components/UiComponents/LanguageSelector';
|
||||
|
||||
import { useLanguage } from '../providers/language/LanguageContext';
|
||||
|
||||
|
|
@ -16,7 +17,7 @@ interface RegisterFormData {
|
|||
}
|
||||
|
||||
function Register() {
|
||||
const { t } = useLanguage();
|
||||
const { t, currentLanguage } = useLanguage();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const { register, error: registerError, isLoading } = useRegister();
|
||||
|
|
@ -91,7 +92,7 @@ function Register() {
|
|||
return;
|
||||
}
|
||||
|
||||
await register({ ...formData, registrationType: 'personal' });
|
||||
await register({ ...formData, language: currentLanguage, registrationType: 'personal' });
|
||||
|
||||
let message = t('Registrierung erfolgreich! Bitte prüfen Sie Ihre E-Mail (auch den Spam-Ordner) für den Link zum Setzen Ihres Passworts.');
|
||||
if (hasPendingInvitation) {
|
||||
|
|
@ -125,6 +126,9 @@ function Register() {
|
|||
return (
|
||||
<div className={styles.container}>
|
||||
<div className={styles.mainContent}>
|
||||
<div style={{ display: 'flex', justifyContent: 'flex-end', padding: '1rem 1rem 0' }}>
|
||||
<LanguageSelector />
|
||||
</div>
|
||||
<div className={styles.logo}>
|
||||
<img
|
||||
src="/logos/poweron-logo.png"
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { useNavigate, useSearchParams } from 'react-router-dom';
|
|||
import styles from './Reset.module.css';
|
||||
import { usePasswordReset } from '../hooks/useAuthentication';
|
||||
import { generateAndStoreCSRFToken } from '../utils/csrfUtils';
|
||||
import { LanguageSelector } from '../components/UiComponents/LanguageSelector';
|
||||
|
||||
import { useLanguage } from '../providers/language/LanguageContext';
|
||||
|
||||
|
|
@ -98,6 +99,9 @@ function Reset() {
|
|||
return (
|
||||
<div className={styles.container}>
|
||||
<div className={styles.mainContent}>
|
||||
<div style={{ display: 'flex', justifyContent: 'flex-end', padding: '1rem 1rem 0' }}>
|
||||
<LanguageSelector />
|
||||
</div>
|
||||
<div className={styles.logo}>
|
||||
<img
|
||||
src="/logos/poweron-logo.png"
|
||||
|
|
@ -138,6 +142,9 @@ function Reset() {
|
|||
return (
|
||||
<div className={styles.container}>
|
||||
<div className={styles.mainContent}>
|
||||
<div style={{ display: 'flex', justifyContent: 'flex-end', padding: '1rem 1rem 0' }}>
|
||||
<LanguageSelector />
|
||||
</div>
|
||||
<div className={styles.logo}>
|
||||
<img
|
||||
src="/logos/poweron-logo.png"
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import { setUserDataCache, getUserDataCache } from '../utils/userCache';
|
|||
import { FormGeneratorForm } from '../components/FormGenerator/FormGeneratorForm/FormGeneratorForm';
|
||||
import type { AttributeDefinition } from '../components/FormGenerator/FormGeneratorForm/FormGeneratorForm';
|
||||
import { useApiRequest } from '../hooks/useApi';
|
||||
import { useVoiceCatalog } from '../contexts/VoiceCatalogContext';
|
||||
import styles from './Settings.module.css';
|
||||
|
||||
// =============================================================================
|
||||
|
|
@ -68,8 +69,8 @@ const ProfileEditModal: React.FC<ProfileEditModalProps> = ({ isOpen, onClose, us
|
|||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<div className={styles.modalOverlay} onClick={onClose}>
|
||||
<div className={styles.modalContent} onClick={(e) => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modalContent}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2>{t('Profil bearbeiten')}</h2>
|
||||
<button className={styles.closeButton} onClick={onClose}>×</button>
|
||||
|
|
@ -92,6 +93,7 @@ interface VoiceMapEntry { language: string; voiceName: string; }
|
|||
const VoiceSettingsTab: React.FC = () => {
|
||||
const { t } = useLanguage();
|
||||
const { request } = useApiRequest();
|
||||
const { languages: voiceCatalog } = useVoiceCatalog();
|
||||
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
|
@ -100,7 +102,6 @@ const VoiceSettingsTab: React.FC = () => {
|
|||
const [success, setSuccess] = useState<string | null>(null);
|
||||
|
||||
const [sttLanguage, setSttLanguage] = useState('de-DE');
|
||||
const [languages, setLanguages] = useState<any[]>([]);
|
||||
const [voiceMap, setVoiceMap] = useState<VoiceMapEntry[]>([]);
|
||||
|
||||
const [addLanguage, setAddLanguage] = useState('de-DE');
|
||||
|
|
@ -111,13 +112,7 @@ const VoiceSettingsTab: React.FC = () => {
|
|||
const _loadSettings = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [prefsData, languagesData] = await Promise.all([
|
||||
request({ url: '/api/voice/preferences', method: 'get' }),
|
||||
request({ url: '/api/voice/languages', method: 'get' }),
|
||||
]);
|
||||
|
||||
const langList = (languagesData as any)?.languages || [];
|
||||
setLanguages(langList);
|
||||
const prefsData = await request({ url: '/api/voice/preferences', method: 'get' });
|
||||
|
||||
const prefs = prefsData as any;
|
||||
setSttLanguage(prefs?.sttLanguage || 'de-DE');
|
||||
|
|
@ -203,16 +198,9 @@ const VoiceSettingsTab: React.FC = () => {
|
|||
}, [request]);
|
||||
|
||||
const _getLanguageName = useCallback((code: string) => {
|
||||
const found = languages.find((l: any) => (l.code || l) === code);
|
||||
return found?.name || found?.code || code;
|
||||
}, [languages]);
|
||||
|
||||
const _defaultLangs = [
|
||||
{ code: 'de-DE', name: 'Deutsch' }, { code: 'en-US', name: 'English (US)' },
|
||||
{ code: 'fr-FR', name: 'Francais' }, { code: 'it-IT', name: 'Italiano' },
|
||||
{ code: 'es-ES', name: 'Espanol' },
|
||||
];
|
||||
const _displayLanguages = languages.length > 0 ? languages : _defaultLangs;
|
||||
const entry = voiceCatalog.find(l => l.bcp47.toLowerCase() === code.toLowerCase());
|
||||
return entry ? `${entry.flag ? entry.flag + ' ' : ''}${entry.label}` : code;
|
||||
}, [voiceCatalog]);
|
||||
|
||||
if (loading) return <div style={{ padding: '1rem', color: '#888' }}>{t('Einstellungen werden geladen')}</div>;
|
||||
|
||||
|
|
@ -230,8 +218,10 @@ const VoiceSettingsTab: React.FC = () => {
|
|||
</div>
|
||||
<div className={styles.settingControl}>
|
||||
<select className={styles.select} value={sttLanguage} onChange={e => setSttLanguage(e.target.value)}>
|
||||
{_displayLanguages.map((lang: any) => (
|
||||
<option key={lang.code || lang} value={lang.code || lang}>{lang.name || lang.code || lang}</option>
|
||||
{voiceCatalog.map(lang => (
|
||||
<option key={lang.bcp47} value={lang.bcp47}>
|
||||
{lang.flag ? `${lang.flag} ` : ''}{lang.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
|
@ -274,8 +264,10 @@ const VoiceSettingsTab: React.FC = () => {
|
|||
<div>
|
||||
<label className={styles.settingLabel} style={{ fontSize: '0.8rem' }}>{t('Sprache')}</label>
|
||||
<select className={styles.select} value={addLanguage} onChange={e => setAddLanguage(e.target.value)}>
|
||||
{_displayLanguages.map((lang: any) => (
|
||||
<option key={lang.code || lang} value={lang.code || lang}>{lang.name || lang.code || lang}</option>
|
||||
{voiceCatalog.map(lang => (
|
||||
<option key={lang.bcp47} value={lang.bcp47}>
|
||||
{lang.flag ? `${lang.flag} ` : ''}{lang.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -5,9 +5,9 @@
|
|||
.store {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
max-width: 1000px;
|
||||
max-width: 1600px;
|
||||
margin: 0 auto;
|
||||
padding: 2rem;
|
||||
padding: 2rem clamp(1rem, 2vw, 2.5rem);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
|
|
@ -78,8 +78,9 @@
|
|||
/* Grid */
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
|
||||
gap: 1.25rem;
|
||||
grid-template-columns: repeat(auto-fill, minmax(clamp(260px, 22vw, 340px), 1fr));
|
||||
gap: 1.5rem;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* Card */
|
||||
|
|
@ -171,18 +172,47 @@
|
|||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
padding: 0.75rem;
|
||||
background: var(--surface-alt, rgba(0, 0, 0, 0.025));
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.instanceRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.5rem;
|
||||
gap: 0.75rem;
|
||||
padding: 0.4rem 0.6rem;
|
||||
background: var(--surface-color, #ffffff);
|
||||
border: 1px solid var(--border-color, #e5e7eb);
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.instanceInfo {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.1rem;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.instanceLabel {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary, #1a1a1a);
|
||||
line-height: 1.3;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.instanceMandate {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary, #555);
|
||||
font-weight: 400;
|
||||
line-height: 1.3;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.deactivateButtonSmall {
|
||||
|
|
@ -326,6 +356,23 @@
|
|||
color: var(--success-color, #34d399);
|
||||
}
|
||||
|
||||
:global(.dark-theme) .instanceList {
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
}
|
||||
|
||||
:global(.dark-theme) .instanceRow {
|
||||
background: var(--surface-dark, #1f1f1f);
|
||||
border-color: var(--border-dark, #333);
|
||||
}
|
||||
|
||||
:global(.dark-theme) .instanceLabel {
|
||||
color: var(--text-primary-dark, #ffffff);
|
||||
}
|
||||
|
||||
:global(.dark-theme) .instanceMandate {
|
||||
color: var(--text-secondary-dark, #aaa);
|
||||
}
|
||||
|
||||
:global(.dark-theme) .statusInactive {
|
||||
background: var(--surface-dark, #2a2a2a);
|
||||
color: var(--text-secondary-dark, #aaa);
|
||||
|
|
|
|||
|
|
@ -5,9 +5,10 @@
|
|||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { FaCogs, FaComments, FaHeadset, FaProjectDiagram } from 'react-icons/fa';
|
||||
import { FaCogs, FaComments, FaHeadset, FaProjectDiagram, FaShieldAlt } from 'react-icons/fa';
|
||||
import { useLanguage } from '../providers/language/LanguageContext';
|
||||
import { useStore } from '../hooks/useStore';
|
||||
import { mandateDisplayLabel } from '../utils/mandateDisplayUtils';
|
||||
import { useStore, _storeActionKey } from '../hooks/useStore';
|
||||
import type { StoreFeature, UserMandate } from '../api/storeApi';
|
||||
import { formatBinaryDataSizeFromMebibytes } from '../utils/formatDataSize';
|
||||
import styles from './Store.module.css';
|
||||
|
|
@ -18,6 +19,7 @@ const FEATURE_ICONS: Record<string, React.ReactNode> = {
|
|||
teamsbot: <FaHeadset />,
|
||||
workspace: <FaComments />,
|
||||
commcoach: <FaComments />,
|
||||
trustee: <FaShieldAlt />,
|
||||
};
|
||||
|
||||
/** Fallback when GET /store/features omits description (German i18n keys). */
|
||||
|
|
@ -27,6 +29,7 @@ const STORE_FEATURE_DESCRIPTION_FALLBACK: Record<string, string> = {
|
|||
teamsbot: 'Integriere einen AI-Bot in deine Microsoft Teams Meetings und Channels.',
|
||||
workspace: 'Nutze den gemeinsamen AI Workspace: Chats, Tools und Kontext pro Instanz.',
|
||||
commcoach: 'CommCoach: Kommunikation trainieren mit KI-gestütztem Coaching und Feedback.',
|
||||
trustee: 'Trustee: Intelligentes Dokumentenmanagement mit KI-gestützter Analyse und Verarbeitung.',
|
||||
};
|
||||
|
||||
function _storeCardDescription(feature: StoreFeature): string {
|
||||
|
|
@ -37,7 +40,7 @@ function _storeCardDescription(feature: StoreFeature): string {
|
|||
interface FeatureCardProps {
|
||||
feature: StoreFeature;
|
||||
mandates: UserMandate[];
|
||||
actionLoading: string | null;
|
||||
actionLoading: Set<string>;
|
||||
onActivate: (code: string, mandateId?: string) => void;
|
||||
onDeactivate: (code: string, mandateId: string, instanceId: string) => void;
|
||||
}
|
||||
|
|
@ -50,7 +53,6 @@ const FeatureCard: React.FC<FeatureCardProps> = ({
|
|||
onDeactivate,
|
||||
}) => {
|
||||
const { t } = useLanguage();
|
||||
const isProcessing = actionLoading === feature.featureCode;
|
||||
const icon = FEATURE_ICONS[feature.featureCode];
|
||||
const activeInstances = feature.instances.filter(inst => inst.isActive);
|
||||
const hasActive = activeInstances.length > 0;
|
||||
|
|
@ -72,23 +74,37 @@ const FeatureCard: React.FC<FeatureCardProps> = ({
|
|||
|
||||
{activeInstances.length > 0 && (
|
||||
<div className={styles.instanceList}>
|
||||
{activeInstances.map((inst) => (
|
||||
<div key={inst.instanceId} className={styles.instanceRow}>
|
||||
<div className={styles.instanceInfo}>
|
||||
<span className={`${styles.statusBadge} ${styles.statusActive}`}>
|
||||
<span className={styles.statusDot} />
|
||||
{inst.mandateName || inst.label}
|
||||
</span>
|
||||
{activeInstances.map((inst) => {
|
||||
const instanceLabel = (inst.label && inst.label.trim()) || feature.label;
|
||||
const mandateLabel = inst.mandateName || '';
|
||||
const deactivateKey = _storeActionKey.deactivate(feature.featureCode, inst.instanceId);
|
||||
const isDeactivating = actionLoading.has(deactivateKey);
|
||||
return (
|
||||
<div key={inst.instanceId} className={styles.instanceRow}>
|
||||
<div className={styles.instanceInfo}>
|
||||
<span className={styles.instanceLabel}>
|
||||
<span
|
||||
className={`${styles.statusDot} ${styles.statusActive}`}
|
||||
aria-label={t('Aktiv')}
|
||||
/>
|
||||
{instanceLabel}
|
||||
</span>
|
||||
{mandateLabel && (
|
||||
<span className={styles.instanceMandate}>
|
||||
{t('Mandant')}: {mandateLabel}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
className={styles.deactivateButtonSmall}
|
||||
onClick={() => onDeactivate(feature.featureCode, inst.mandateId, inst.instanceId)}
|
||||
disabled={isDeactivating}
|
||||
>
|
||||
{isDeactivating ? '…' : t('Deaktivieren')}
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
className={styles.deactivateButtonSmall}
|
||||
onClick={() => onDeactivate(feature.featureCode, inst.mandateId, inst.instanceId)}
|
||||
disabled={isProcessing}
|
||||
>
|
||||
{isProcessing ? '...' : t('Deaktivieren')}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
|
@ -102,18 +118,22 @@ const FeatureCard: React.FC<FeatureCardProps> = ({
|
|||
)}
|
||||
|
||||
<div className={styles.cardActions}>
|
||||
{feature.canActivate && mandates.map((m) => (
|
||||
<button
|
||||
key={m.id}
|
||||
className={styles.activateButton}
|
||||
onClick={() => onActivate(feature.featureCode, m.id)}
|
||||
disabled={isProcessing}
|
||||
>
|
||||
{isProcessing
|
||||
? t('Wird aktiviert…')
|
||||
: t('Aktivieren für {name}', { name: String(m.label || m.name) })}
|
||||
</button>
|
||||
))}
|
||||
{feature.canActivate && mandates.map((m) => {
|
||||
const activateKey = _storeActionKey.activate(feature.featureCode, m.id);
|
||||
const isActivating = actionLoading.has(activateKey);
|
||||
return (
|
||||
<button
|
||||
key={m.id}
|
||||
className={styles.activateButton}
|
||||
onClick={() => onActivate(feature.featureCode, m.id)}
|
||||
disabled={isActivating}
|
||||
>
|
||||
{isActivating
|
||||
? t('Wird aktiviert…')
|
||||
: t('Aktivieren für {name}', { name: mandateDisplayLabel(m) })}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -24,9 +24,10 @@ import { FeatureInstanceWizard } from './wizards/FeatureInstanceWizard';
|
|||
import { InstanceHierarchyView } from './InstanceHierarchyView';
|
||||
|
||||
import { useLanguage } from '../../providers/language/LanguageContext';
|
||||
import { mandateDisplayLabel } from '../../utils/mandateDisplayUtils';
|
||||
|
||||
function getMandateName(mandate: Mandate): string {
|
||||
return mandate.label || mandate.name || mandate.id;
|
||||
return mandateDisplayLabel(mandate);
|
||||
}
|
||||
|
||||
function getFeatureLabel(feature: Feature): string {
|
||||
|
|
|
|||
6
src/pages/admin/AdminDatabaseHealthPage.module.css
Normal file
6
src/pages/admin/AdminDatabaseHealthPage.module.css
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
/**
|
||||
* AdminDatabaseHealthPage Styles
|
||||
*
|
||||
* Minimal — table rendering is handled by FormGeneratorTable.
|
||||
* Only page-specific overrides live here.
|
||||
*/
|
||||
638
src/pages/admin/AdminDatabaseHealthPage.tsx
Normal file
638
src/pages/admin/AdminDatabaseHealthPage.tsx
Normal file
|
|
@ -0,0 +1,638 @@
|
|||
/**
|
||||
* AdminDatabaseHealthPage
|
||||
*
|
||||
* SysAdmin-only page with two tabs:
|
||||
* 1. Table Statistics — pg_stat data for every table across all databases
|
||||
* 2. Orphan Cleanup — FK orphan detection with per-relation + batch cleanup
|
||||
*
|
||||
* Both tabs use FormGeneratorTable with a client-side pagination/sort/filter
|
||||
* adapter (the backend returns all rows at once; the dataset is small enough).
|
||||
*/
|
||||
|
||||
import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
|
||||
import { FaSync, FaTrashAlt, FaBroom, FaExclamationTriangle } from 'react-icons/fa';
|
||||
import api from '../../api';
|
||||
import styles from './Admin.module.css';
|
||||
import { useLanguage } from '../../providers/language/LanguageContext';
|
||||
import { useToast } from '../../contexts/ToastContext';
|
||||
import { useConfirm } from '../../hooks/useConfirm';
|
||||
import { Tabs } from '../../components/UiComponents/Tabs/Tabs';
|
||||
import { FormGeneratorTable, type ColumnConfig } from '../../components/FormGenerator/FormGeneratorTable';
|
||||
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface TableStat {
|
||||
id: string;
|
||||
db: string;
|
||||
table: string;
|
||||
estimatedRows: number;
|
||||
totalSizeBytes: number;
|
||||
indexSizeBytes: number;
|
||||
lastVacuum: string | null;
|
||||
lastAnalyze: string | null;
|
||||
}
|
||||
|
||||
interface OrphanEntry {
|
||||
id: string;
|
||||
sourceDb: string;
|
||||
sourceTable: string;
|
||||
sourceColumn: string;
|
||||
targetDb: string;
|
||||
targetTable: string;
|
||||
targetColumn: string;
|
||||
orphanCount: number;
|
||||
}
|
||||
|
||||
interface CleanResult {
|
||||
db: string;
|
||||
table: string;
|
||||
column: string;
|
||||
deleted: number;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
interface PaginationParams {
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
search?: string;
|
||||
filters?: Record<string, any>;
|
||||
sort?: Array<{ field: string; direction: 'asc' | 'desc' }>;
|
||||
}
|
||||
|
||||
interface PaginationMeta {
|
||||
currentPage: number;
|
||||
pageSize: number;
|
||||
totalItems: number;
|
||||
totalPages: number;
|
||||
}
|
||||
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function _formatBytes(bytes: number): string {
|
||||
if (bytes === 0) return '0 B';
|
||||
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(1024));
|
||||
const value = bytes / Math.pow(1024, i);
|
||||
return `${value.toFixed(i === 0 ? 0 : 1)} ${units[i]}`;
|
||||
}
|
||||
|
||||
function _formatNumber(n: number): string {
|
||||
return n.toLocaleString('de-CH');
|
||||
}
|
||||
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// useClientPagination — adapts a static array to FormGeneratorTable's
|
||||
// hookData.refetch / hookData.pagination contract.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function _useClientPagination<T extends Record<string, any>>(allData: T[]) {
|
||||
const [visibleData, setVisibleData] = useState<T[]>([]);
|
||||
const [pagination, setPagination] = useState<PaginationMeta>({
|
||||
currentPage: 1, pageSize: 50, totalItems: 0, totalPages: 1,
|
||||
});
|
||||
|
||||
const allDataRef = useRef(allData);
|
||||
allDataRef.current = allData;
|
||||
|
||||
const lastParamsRef = useRef<PaginationParams>({});
|
||||
|
||||
const fetchFilterValues = useCallback(async (columnKey: string, crossFilters?: Record<string, any>) => {
|
||||
let source = allDataRef.current;
|
||||
if (crossFilters && Object.keys(crossFilters).length > 0) {
|
||||
source = source.filter(row => {
|
||||
for (const [key, val] of Object.entries(crossFilters)) {
|
||||
if (val === undefined || val === null || val === '') continue;
|
||||
const cell = String(row[key] ?? '');
|
||||
if (Array.isArray(val)) {
|
||||
if (val.length > 0 && !val.includes(cell)) return false;
|
||||
} else {
|
||||
if (cell !== String(val)) return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
const seen = new Set<string>();
|
||||
for (const row of source) {
|
||||
const v = row[columnKey];
|
||||
if (v !== undefined && v !== null && String(v).trim()) {
|
||||
seen.add(String(v));
|
||||
}
|
||||
}
|
||||
return Array.from(seen).sort();
|
||||
}, []);
|
||||
|
||||
const refetch = useCallback(async (params?: PaginationParams) => {
|
||||
const p = params || lastParamsRef.current;
|
||||
lastParamsRef.current = p;
|
||||
const source = allDataRef.current;
|
||||
|
||||
const page = p.page || 1;
|
||||
const pageSize = p.pageSize || 50;
|
||||
const search = (p.search || '').toLowerCase();
|
||||
const filters = p.filters || {};
|
||||
const sorts = p.sort || [];
|
||||
|
||||
// 1) Filter
|
||||
let filtered = source.filter(row => {
|
||||
for (const [key, val] of Object.entries(filters)) {
|
||||
if (val === undefined || val === null || val === '') continue;
|
||||
const cell = String(row[key] ?? '');
|
||||
if (Array.isArray(val)) {
|
||||
if (val.length > 0 && !val.includes(cell)) return false;
|
||||
} else {
|
||||
if (cell !== String(val)) return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
// 2) Search
|
||||
if (search) {
|
||||
filtered = filtered.filter(row =>
|
||||
Object.values(row).some(v => String(v ?? '').toLowerCase().includes(search)),
|
||||
);
|
||||
}
|
||||
|
||||
// 3) Sort
|
||||
if (sorts.length > 0) {
|
||||
filtered.sort((a, b) => {
|
||||
for (const s of sorts) {
|
||||
const aVal = a[s.field];
|
||||
const bVal = b[s.field];
|
||||
let cmp = 0;
|
||||
if (typeof aVal === 'number' && typeof bVal === 'number') {
|
||||
cmp = aVal - bVal;
|
||||
} else {
|
||||
cmp = String(aVal ?? '').localeCompare(String(bVal ?? ''));
|
||||
}
|
||||
if (cmp !== 0) return s.direction === 'desc' ? -cmp : cmp;
|
||||
}
|
||||
return 0;
|
||||
});
|
||||
}
|
||||
|
||||
// 4) Paginate
|
||||
const totalItems = filtered.length;
|
||||
const totalPages = Math.max(1, Math.ceil(totalItems / pageSize));
|
||||
const safePage = Math.min(page, totalPages);
|
||||
const start = (safePage - 1) * pageSize;
|
||||
const paged = filtered.slice(start, start + pageSize);
|
||||
|
||||
setVisibleData(paged);
|
||||
setPagination({ currentPage: safePage, pageSize, totalItems, totalPages });
|
||||
}, []);
|
||||
|
||||
// Re-apply whenever allData changes
|
||||
useEffect(() => {
|
||||
refetch(lastParamsRef.current);
|
||||
}, [allData, refetch]);
|
||||
|
||||
return { visibleData, pagination, refetch, fetchFilterValues };
|
||||
}
|
||||
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// StatsTab
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const StatsTab: React.FC = () => {
|
||||
const { t } = useLanguage();
|
||||
const [allStats, setAllStats] = useState<TableStat[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [dbFilter, setDbFilter] = useState<string>('');
|
||||
|
||||
const _fetchStats = useCallback(async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const params = dbFilter ? `?db=${encodeURIComponent(dbFilter)}` : '';
|
||||
const res = await api.get(`/api/admin/database-health/stats${params}`);
|
||||
const rows = (res.data.stats || []).map((s: any, i: number) => ({
|
||||
...s,
|
||||
id: `${s.db}-${s.table}-${i}`,
|
||||
}));
|
||||
setAllStats(rows);
|
||||
} catch {
|
||||
setAllStats([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [dbFilter]);
|
||||
|
||||
useEffect(() => { _fetchStats(); }, [_fetchStats]);
|
||||
|
||||
const { visibleData, pagination, refetch, fetchFilterValues } = _useClientPagination(allStats);
|
||||
|
||||
const databases = useMemo(
|
||||
() => Array.from(new Set(allStats.map(s => s.db))).sort(),
|
||||
[allStats],
|
||||
);
|
||||
|
||||
const totals = useMemo(() => {
|
||||
let rows = 0, size = 0, idx = 0;
|
||||
for (const s of allStats) {
|
||||
rows += s.estimatedRows;
|
||||
size += s.totalSizeBytes;
|
||||
idx += s.indexSizeBytes;
|
||||
}
|
||||
return { rows, size, idx, tables: allStats.length, dbs: databases.length };
|
||||
}, [allStats, databases]);
|
||||
|
||||
const columns: ColumnConfig[] = useMemo(() => [
|
||||
{
|
||||
key: 'db',
|
||||
label: t('Datenbank'),
|
||||
sortable: true,
|
||||
filterable: true,
|
||||
searchable: true,
|
||||
width: 200,
|
||||
filterOptions: databases,
|
||||
},
|
||||
{
|
||||
key: 'table',
|
||||
label: t('Tabelle'),
|
||||
sortable: true,
|
||||
searchable: true,
|
||||
width: 200,
|
||||
},
|
||||
{
|
||||
key: 'estimatedRows',
|
||||
label: t('Zeilen (ca.)'),
|
||||
type: 'number',
|
||||
sortable: true,
|
||||
width: 120,
|
||||
formatter: (v: number) => _formatNumber(v),
|
||||
},
|
||||
{
|
||||
key: 'totalSizeBytes',
|
||||
label: t('Total Size'),
|
||||
type: 'number',
|
||||
sortable: true,
|
||||
width: 120,
|
||||
formatter: (v: number) => _formatBytes(v),
|
||||
},
|
||||
{
|
||||
key: 'indexSizeBytes',
|
||||
label: t('Index Size'),
|
||||
type: 'number',
|
||||
sortable: true,
|
||||
width: 120,
|
||||
formatter: (v: number) => _formatBytes(v),
|
||||
},
|
||||
{
|
||||
key: 'lastVacuum',
|
||||
label: t('Last Vacuum'),
|
||||
sortable: true,
|
||||
width: 170,
|
||||
formatter: (v: string | null) => v ?? '—',
|
||||
},
|
||||
{
|
||||
key: 'lastAnalyze',
|
||||
label: t('Last Analyze'),
|
||||
sortable: true,
|
||||
width: 170,
|
||||
formatter: (v: string | null) => v ?? '—',
|
||||
},
|
||||
], [t, databases]);
|
||||
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', flex: 1, minHeight: 0 }}>
|
||||
{/* Controls */}
|
||||
<div className={styles.filterSection}>
|
||||
<div className={styles.filterGroup}>
|
||||
<label className={styles.filterLabel}>{t('Datenbank')}</label>
|
||||
<select
|
||||
className={styles.filterSelect}
|
||||
value={dbFilter}
|
||||
onChange={e => setDbFilter(e.target.value)}
|
||||
>
|
||||
<option value="">{t('Alle')}</option>
|
||||
{databases.map(db => <option key={db} value={db}>{db}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<button className={styles.secondaryButton} onClick={_fetchStats} disabled={loading}>
|
||||
<FaSync className={loading ? 'spinning' : ''} /> {t('Aktualisieren')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Summary */}
|
||||
<div className={styles.filterSection} style={{ gap: '0.75rem', flexWrap: 'wrap' }}>
|
||||
<span className={styles.filterLabel}>{t('{dbs} Datenbanken', { dbs: totals.dbs })}</span>
|
||||
<span className={styles.filterLabel}>{t('{tables} Tabellen', { tables: totals.tables })}</span>
|
||||
<span className={styles.filterLabel}>{t('{rows} Zeilen (ca.)', { rows: _formatNumber(totals.rows) })}</span>
|
||||
<span className={styles.filterLabel}>{t('Total {size}', { size: _formatBytes(totals.size) })}</span>
|
||||
<span className={styles.filterLabel}>{t('Index {size}', { size: _formatBytes(totals.idx) })}</span>
|
||||
</div>
|
||||
|
||||
<div className={styles.tableContainer}>
|
||||
<FormGeneratorTable
|
||||
data={visibleData}
|
||||
columns={columns}
|
||||
loading={loading}
|
||||
sortable={true}
|
||||
searchable={true}
|
||||
filterable={true}
|
||||
pagination={true}
|
||||
pageSize={50}
|
||||
selectable={false}
|
||||
hookData={{
|
||||
refetch,
|
||||
pagination,
|
||||
fetchFilterValues,
|
||||
}}
|
||||
emptyMessage={t('Keine Tabellen gefunden')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// OrphansTab
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const OrphansTab: React.FC = () => {
|
||||
const { t } = useLanguage();
|
||||
const toast = useToast();
|
||||
const { confirm, ConfirmDialog } = useConfirm();
|
||||
|
||||
const [allOrphans, setAllOrphans] = useState<OrphanEntry[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [cleaning, setCleaning] = useState<string | null>(null);
|
||||
const [cleaningAll, setCleaningAll] = useState(false);
|
||||
const [onlyProblems, setOnlyProblems] = useState(true);
|
||||
const [dbFilter, setDbFilter] = useState<string>('');
|
||||
|
||||
const _fetchOrphans = useCallback(async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const params = dbFilter ? `?db=${encodeURIComponent(dbFilter)}` : '';
|
||||
const res = await api.get(`/api/admin/database-health/orphans${params}`);
|
||||
const rows = (res.data.orphans || []).map((o: any, i: number) => ({
|
||||
...o,
|
||||
id: `${o.sourceDb}.${o.sourceTable}.${o.sourceColumn}-${i}`,
|
||||
}));
|
||||
setAllOrphans(rows);
|
||||
} catch {
|
||||
setAllOrphans([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [dbFilter]);
|
||||
|
||||
useEffect(() => { _fetchOrphans(); }, [_fetchOrphans]);
|
||||
|
||||
const displayed = useMemo(
|
||||
() => onlyProblems ? allOrphans.filter(o => o.orphanCount > 0) : allOrphans,
|
||||
[allOrphans, onlyProblems],
|
||||
);
|
||||
|
||||
const { visibleData, pagination, refetch, fetchFilterValues } = _useClientPagination(displayed);
|
||||
|
||||
const databases = useMemo(
|
||||
() => Array.from(new Set(allOrphans.map(o => o.sourceDb))).sort(),
|
||||
[allOrphans],
|
||||
);
|
||||
|
||||
const totalOrphans = useMemo(() => allOrphans.reduce((s, o) => s + o.orphanCount, 0), [allOrphans]);
|
||||
|
||||
const _cleanOne = async (o: OrphanEntry) => {
|
||||
const ok = await confirm(
|
||||
t('{count} verwaiste Einträge in {table}.{column} löschen?', { count: o.orphanCount, table: o.sourceTable, column: o.sourceColumn }),
|
||||
{ title: t('Orphans bereinigen'), variant: 'danger' },
|
||||
);
|
||||
if (!ok) return;
|
||||
const key = `${o.sourceDb}.${o.sourceTable}.${o.sourceColumn}`;
|
||||
setCleaning(key);
|
||||
try {
|
||||
const res = await api.post('/api/admin/database-health/orphans/clean', {
|
||||
db: o.sourceDb,
|
||||
table: o.sourceTable,
|
||||
column: o.sourceColumn,
|
||||
});
|
||||
toast.showSuccess(t('{deleted} Einträge gelöscht', { deleted: res.data.deleted }));
|
||||
_fetchOrphans();
|
||||
} catch (err: any) {
|
||||
toast.showError(err.response?.data?.detail || t('Fehler beim Bereinigen'));
|
||||
} finally {
|
||||
setCleaning(null);
|
||||
}
|
||||
};
|
||||
|
||||
const _cleanAll = async () => {
|
||||
const ok = await confirm(
|
||||
t('{count} verwaiste Einträge in {relations} Beziehungen löschen?', {
|
||||
count: totalOrphans,
|
||||
relations: allOrphans.filter(o => o.orphanCount > 0).length,
|
||||
}),
|
||||
{ title: t('Alle Orphans bereinigen'), variant: 'danger' },
|
||||
);
|
||||
if (!ok) return;
|
||||
setCleaningAll(true);
|
||||
try {
|
||||
const res = await api.post('/api/admin/database-health/orphans/clean-all');
|
||||
const results: CleanResult[] = res.data.results || [];
|
||||
const totalDeleted = results.reduce((s, r) => s + r.deleted, 0);
|
||||
const errors = results.filter(r => r.error);
|
||||
if (errors.length > 0) {
|
||||
toast.showWarning(t('{deleted} gelöscht, {errors} Fehler', { deleted: totalDeleted, errors: errors.length }));
|
||||
} else {
|
||||
toast.showSuccess(t('{deleted} Einträge gelöscht', { deleted: totalDeleted }));
|
||||
}
|
||||
_fetchOrphans();
|
||||
} catch (err: any) {
|
||||
toast.showError(err.response?.data?.detail || t('Fehler beim Bereinigen'));
|
||||
} finally {
|
||||
setCleaningAll(false);
|
||||
}
|
||||
};
|
||||
|
||||
const columns: ColumnConfig[] = useMemo(() => [
|
||||
{
|
||||
key: 'sourceDb',
|
||||
label: t('Source DB'),
|
||||
sortable: true,
|
||||
filterable: true,
|
||||
searchable: true,
|
||||
width: 180,
|
||||
filterOptions: databases,
|
||||
},
|
||||
{
|
||||
key: 'sourceTable',
|
||||
label: t('Tabelle'),
|
||||
sortable: true,
|
||||
searchable: true,
|
||||
width: 180,
|
||||
},
|
||||
{
|
||||
key: 'sourceColumn',
|
||||
label: t('FK-Spalte'),
|
||||
sortable: true,
|
||||
searchable: true,
|
||||
width: 150,
|
||||
},
|
||||
{
|
||||
key: 'targetTable',
|
||||
label: t('Referenz'),
|
||||
sortable: true,
|
||||
width: 220,
|
||||
formatter: (_val: string, row: OrphanEntry) => {
|
||||
const isCrossDb = row.sourceDb !== row.targetDb;
|
||||
return (
|
||||
<span>
|
||||
<code>{row.targetTable}.{row.targetColumn}</code>
|
||||
{isCrossDb && (
|
||||
<span style={{
|
||||
marginLeft: '0.4rem',
|
||||
padding: '0.125rem 0.375rem',
|
||||
borderRadius: '4px',
|
||||
fontSize: '0.625rem',
|
||||
fontWeight: 600,
|
||||
textTransform: 'uppercase',
|
||||
letterSpacing: '0.03em',
|
||||
background: 'var(--primary-dark-bg, rgba(242, 88, 67, 0.12))',
|
||||
color: 'var(--primary-color, #f25843)',
|
||||
}}>
|
||||
{t('cross-db')}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'orphanCount',
|
||||
label: t('Orphans'),
|
||||
type: 'number',
|
||||
sortable: true,
|
||||
width: 100,
|
||||
formatter: (v: number) => (
|
||||
<span style={v > 0 ? { color: 'var(--danger-color, #e53e3e)', fontWeight: 600 } : undefined}>
|
||||
{_formatNumber(v)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
], [t, databases]);
|
||||
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', flex: 1, minHeight: 0 }}>
|
||||
<ConfirmDialog />
|
||||
|
||||
{/* Controls */}
|
||||
<div className={styles.filterSection}>
|
||||
<div className={styles.filterGroup}>
|
||||
<label className={styles.filterLabel}>{t('Datenbank')}</label>
|
||||
<select
|
||||
className={styles.filterSelect}
|
||||
value={dbFilter}
|
||||
onChange={e => setDbFilter(e.target.value)}
|
||||
>
|
||||
<option value="">{t('Alle')}</option>
|
||||
{databases.map(db => <option key={db} value={db}>{db}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div className={styles.filterGroup}>
|
||||
<label className={styles.checkboxLabel}>
|
||||
<input type="checkbox" checked={onlyProblems} onChange={e => setOnlyProblems(e.target.checked)} />
|
||||
{t('Nur Probleme')}
|
||||
</label>
|
||||
</div>
|
||||
<div className={styles.headerActions}>
|
||||
<button className={styles.secondaryButton} onClick={_fetchOrphans} disabled={loading}>
|
||||
<FaSync className={loading ? 'spinning' : ''} /> {t('Scan')}
|
||||
</button>
|
||||
{totalOrphans > 0 && (
|
||||
<button className={styles.dangerButton} onClick={_cleanAll} disabled={cleaningAll || loading}>
|
||||
<FaBroom className={cleaningAll ? 'spinning' : ''} /> {t('Alle bereinigen')} ({_formatNumber(totalOrphans)})
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{totalOrphans > 0 && (
|
||||
<div className={styles.infoBox} style={{ background: 'var(--warning-bg, #fffbeb)', borderColor: 'var(--warning-color, #d69e2e)' }}>
|
||||
<FaExclamationTriangle style={{ marginRight: 8, color: 'var(--warning-color, #d69e2e)' }} />
|
||||
{t('{count} verwaiste Einträge in {relations} Beziehungen gefunden', {
|
||||
count: _formatNumber(totalOrphans),
|
||||
relations: allOrphans.filter(o => o.orphanCount > 0).length,
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={styles.tableContainer}>
|
||||
<FormGeneratorTable
|
||||
data={visibleData}
|
||||
columns={columns}
|
||||
loading={loading}
|
||||
sortable={true}
|
||||
searchable={true}
|
||||
filterable={true}
|
||||
pagination={true}
|
||||
pageSize={50}
|
||||
selectable={false}
|
||||
customActions={[
|
||||
{
|
||||
id: 'clean',
|
||||
icon: <FaTrashAlt />,
|
||||
onClick: (row: OrphanEntry) => _cleanOne(row),
|
||||
visible: (row: OrphanEntry) => row.orphanCount > 0,
|
||||
loading: (row: OrphanEntry) => cleaning === `${row.sourceDb}.${row.sourceTable}.${row.sourceColumn}` || cleaningAll,
|
||||
title: t('Orphans löschen'),
|
||||
},
|
||||
]}
|
||||
hookData={{
|
||||
refetch,
|
||||
pagination,
|
||||
fetchFilterValues,
|
||||
}}
|
||||
emptyMessage={onlyProblems ? t('Keine Orphans gefunden') : t('Keine FK-Beziehungen gefunden')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Page
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const AdminDatabaseHealthPage: React.FC = () => {
|
||||
const { t } = useLanguage();
|
||||
|
||||
const tabs = useMemo(() => [
|
||||
{
|
||||
id: 'stats',
|
||||
label: t('Statistiken'),
|
||||
content: <StatsTab />,
|
||||
},
|
||||
{
|
||||
id: 'orphans',
|
||||
label: t('Orphan Cleanup'),
|
||||
content: <OrphansTab />,
|
||||
},
|
||||
], [t]);
|
||||
|
||||
return (
|
||||
<div className={`${styles.adminPage} ${styles.adminPageFill}`}>
|
||||
<div className={styles.pageHeader}>
|
||||
<div>
|
||||
<h1 className={styles.pageTitle}>{t('Datenbank-Gesundheit')}</h1>
|
||||
<p className={styles.pageSubtitle}>{t('Tabellenstatistiken und verwaiste Datensätze')}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Tabs tabs={tabs} defaultTabId="stats" />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AdminDatabaseHealthPage;
|
||||
|
|
@ -15,11 +15,11 @@ import { FaPlus, FaSync, FaCube, FaBuilding, FaCogs, FaEdit } from 'react-icons/
|
|||
import { useToast } from '../../contexts/ToastContext';
|
||||
import api from '../../api';
|
||||
import { ChatbotConfigSection } from './ChatbotConfigSection';
|
||||
import { DropdownSelect } from '../../components/UiComponents/DropdownSelect';
|
||||
import { TextField } from '../../components/UiComponents/TextField';
|
||||
import styles from './Admin.module.css';
|
||||
|
||||
import { useLanguage } from '../../providers/language/LanguageContext';
|
||||
import { mandateDisplayLabel } from '../../utils/mandateDisplayUtils';
|
||||
|
||||
export const AdminFeatureAccessPage: React.FC = () => {
|
||||
const { t } = useLanguage();
|
||||
|
|
@ -337,11 +337,6 @@ export const AdminFeatureAccessPage: React.FC = () => {
|
|||
}
|
||||
};
|
||||
|
||||
// Get mandate name
|
||||
const getMandateName = (mandate: Mandate) => {
|
||||
return mandate.label || mandate.name || mandate.id;
|
||||
};
|
||||
|
||||
// Get feature label
|
||||
const getFeatureLabel = (code: string) => {
|
||||
const feature = features.find(f => f.code === code);
|
||||
|
|
@ -386,7 +381,7 @@ export const AdminFeatureAccessPage: React.FC = () => {
|
|||
<option value="">{t('Mandant wählen')}</option>
|
||||
{mandates.map(m => (
|
||||
<option key={m.id} value={m.id}>
|
||||
{getMandateName(m)}
|
||||
{mandateDisplayLabel(m)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
|
@ -512,8 +507,8 @@ export const AdminFeatureAccessPage: React.FC = () => {
|
|||
|
||||
{/* Create Instance Modal */}
|
||||
{showCreateModal && (
|
||||
<div className={styles.modalOverlay} onClick={() => setShowCreateModal(false)}>
|
||||
<div className={styles.modal} onClick={e => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modal}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2 className={styles.modalTitle}>{t('Neue Feature-Instanz erstellen')}</h2>
|
||||
<button
|
||||
|
|
@ -533,35 +528,38 @@ export const AdminFeatureAccessPage: React.FC = () => {
|
|||
</div>
|
||||
) : (
|
||||
<div>
|
||||
{/* Feature Code Selector - Required for chatbot config */}
|
||||
{/* Feature Code Selector — buttons instead of dropdown */}
|
||||
<div className={styles.configField} style={{ marginBottom: '1.5rem', paddingBottom: '1rem', borderBottom: '1px solid var(--border-color)' }}>
|
||||
<label className={styles.configLabel} style={{ fontWeight: 600 }}>
|
||||
{t('Feature auswählen')}: <span style={{ color: 'var(--error-color)' }}>*</span>
|
||||
</label>
|
||||
<DropdownSelect
|
||||
items={features.map(f => ({
|
||||
id: f.code,
|
||||
label: f.label || f.code,
|
||||
value: f.code
|
||||
}))}
|
||||
selectedItemId={createFeatureCode}
|
||||
onSelect={(item) => {
|
||||
const selectedCode = item?.value || '';
|
||||
setCreateFeatureCode(selectedCode);
|
||||
// Reset chatbot config when switching
|
||||
setChatbotConnectors(['preprocessor']);
|
||||
setChatbotSystemPrompt('');
|
||||
setChatbotEnableWebResearch(true);
|
||||
setChatbotAllowedProviders([]);
|
||||
}}
|
||||
placeholder={t('Feature-Auswahl erforderlich')}
|
||||
className={styles.configSelect}
|
||||
/>
|
||||
{!createFeatureCode && (
|
||||
<p style={{ fontSize: '0.75rem', color: 'var(--text-secondary)', marginTop: '0.5rem' }}>
|
||||
{t('Bitte wählen Sie ein Feature aus, um fortzufahren.')}
|
||||
</p>
|
||||
)}
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.5rem', marginTop: '0.5rem' }}>
|
||||
{features.map(f => (
|
||||
<button
|
||||
key={f.code}
|
||||
type="button"
|
||||
className={styles.secondaryButton}
|
||||
style={{
|
||||
padding: '0.5rem 1rem',
|
||||
borderRadius: '6px',
|
||||
cursor: 'pointer',
|
||||
fontWeight: createFeatureCode === f.code ? 600 : 400,
|
||||
background: createFeatureCode === f.code ? 'var(--primary-color)' : undefined,
|
||||
color: createFeatureCode === f.code ? '#fff' : undefined,
|
||||
borderColor: createFeatureCode === f.code ? 'var(--primary-color)' : undefined,
|
||||
}}
|
||||
onClick={() => {
|
||||
setCreateFeatureCode(f.code);
|
||||
setChatbotConnectors(['preprocessor']);
|
||||
setChatbotSystemPrompt('');
|
||||
setChatbotEnableWebResearch(true);
|
||||
setChatbotAllowedProviders([]);
|
||||
}}
|
||||
>
|
||||
{f.label || f.code}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Chatbot Configuration Title - Show when chatbot is selected */}
|
||||
|
|
@ -634,8 +632,8 @@ export const AdminFeatureAccessPage: React.FC = () => {
|
|||
|
||||
{/* Edit Instance Modal */}
|
||||
{showEditModal && editingInstance && (
|
||||
<div className={styles.modalOverlay} onClick={() => { setShowEditModal(false); setEditingInstance(null); }}>
|
||||
<div className={styles.modal} onClick={e => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modal}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2 className={styles.modalTitle}>{t('Feature-Instanz bearbeiten')}</h2>
|
||||
<button
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ import api from '../../api';
|
|||
import styles from './Admin.module.css';
|
||||
|
||||
import { useLanguage } from '../../providers/language/LanguageContext';
|
||||
import { mandateDisplayLabel } from '../../utils/mandateDisplayUtils';
|
||||
|
||||
export const AdminFeatureInstanceUsersPage: React.FC = () => {
|
||||
const { t } = useLanguage();
|
||||
|
|
@ -92,7 +93,7 @@ export const AdminFeatureInstanceUsersPage: React.FC = () => {
|
|||
allOptions.push({
|
||||
mandateId: mandate.id,
|
||||
instanceId: inst.id,
|
||||
mandateName: mandate.label || mandate.name || mandate.id,
|
||||
mandateName: mandateDisplayLabel(mandate),
|
||||
instanceLabel: inst.label || inst.id,
|
||||
featureCode: inst.featureCode,
|
||||
combinedKey: `${mandate.id}:${inst.id}`,
|
||||
|
|
@ -561,8 +562,8 @@ export const AdminFeatureInstanceUsersPage: React.FC = () => {
|
|||
|
||||
{/* Add User Modal */}
|
||||
{showAddModal && (
|
||||
<div className={styles.modalOverlay} onClick={() => setShowAddModal(false)}>
|
||||
<div className={styles.modal} onClick={e => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modal}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2 className={styles.modalTitle}>{t('Benutzer zur Feature-Instanz hinzufügen')}</h2>
|
||||
<button
|
||||
|
|
@ -594,8 +595,8 @@ export const AdminFeatureInstanceUsersPage: React.FC = () => {
|
|||
|
||||
{/* Edit Roles Modal */}
|
||||
{editingUser && (
|
||||
<div className={styles.modalOverlay} onClick={() => setEditingUser(null)}>
|
||||
<div className={styles.modal} onClick={e => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modal}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2 className={styles.modalTitle}>
|
||||
{t('Rollen bearbeiten')}: {editingUser.username}
|
||||
|
|
|
|||
|
|
@ -397,8 +397,8 @@ export const AdminFeatureRolesPage: React.FC = () => {
|
|||
|
||||
{/* Create Role Modal */}
|
||||
{showCreateModal && (
|
||||
<div className={styles.modalOverlay} onClick={() => setShowCreateModal(false)}>
|
||||
<div className={styles.modal} onClick={e => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modal}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2 className={styles.modalTitle}>{t('Neue Feature-Rolle erstellen')}</h2>
|
||||
<button
|
||||
|
|
@ -430,8 +430,8 @@ export const AdminFeatureRolesPage: React.FC = () => {
|
|||
|
||||
{/* Edit Role Modal */}
|
||||
{editingRole && (
|
||||
<div className={styles.modalOverlay} onClick={() => setEditingRole(null)}>
|
||||
<div className={styles.modal} onClick={e => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modal}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2 className={styles.modalTitle}>{t('Feature-Rolle bearbeiten')}</h2>
|
||||
<button
|
||||
|
|
@ -462,8 +462,8 @@ export const AdminFeatureRolesPage: React.FC = () => {
|
|||
|
||||
{/* Permissions Modal */}
|
||||
{permissionsRole && (
|
||||
<div className={styles.modalOverlay} onClick={() => setPermissionsRole(null)}>
|
||||
<div className={styles.modal} style={{ maxWidth: '900px', width: '90%' }} onClick={e => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modal} style={{ maxWidth: '900px', width: '90%' }}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2 className={styles.modalTitle}>
|
||||
<FaShieldAlt style={{ marginRight: 8 }} />
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ import api from '../../api';
|
|||
import styles from './Admin.module.css';
|
||||
|
||||
import { useLanguage } from '../../providers/language/LanguageContext';
|
||||
import { mandateDisplayLabel } from '../../utils/mandateDisplayUtils';
|
||||
|
||||
export const AdminInvitationsPage: React.FC = () => {
|
||||
const { t } = useLanguage();
|
||||
|
|
@ -235,10 +236,6 @@ export const AdminInvitationsPage: React.FC = () => {
|
|||
}
|
||||
};
|
||||
|
||||
// Get mandate name
|
||||
const getMandateName = (mandate: Mandate) => {
|
||||
return mandate.label || mandate.name || mandate.id;
|
||||
};
|
||||
|
||||
if (error && !selectedMandateId) {
|
||||
return (
|
||||
|
|
@ -280,7 +277,7 @@ export const AdminInvitationsPage: React.FC = () => {
|
|||
<option value="">{t('Mandant wählen')}</option>
|
||||
{mandates.map(m => (
|
||||
<option key={m.id} value={m.id}>
|
||||
{getMandateName(m)}
|
||||
{mandateDisplayLabel(m)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
|
@ -372,8 +369,8 @@ export const AdminInvitationsPage: React.FC = () => {
|
|||
|
||||
{/* Create Invitation Modal */}
|
||||
{showCreateModal && (
|
||||
<div className={styles.modalOverlay} onClick={() => setShowCreateModal(false)}>
|
||||
<div className={styles.modal} onClick={e => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modal}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2 className={styles.modalTitle}>{t('Neue Einladung erstellen')}</h2>
|
||||
<button
|
||||
|
|
@ -411,8 +408,8 @@ export const AdminInvitationsPage: React.FC = () => {
|
|||
|
||||
{/* URL Display Modal */}
|
||||
{showUrlModal && (
|
||||
<div className={styles.modalOverlay} onClick={() => setShowUrlModal(null)}>
|
||||
<div className={styles.modal} onClick={e => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modal}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2 className={styles.modalTitle}>{t('Einladungs-Link')}</h2>
|
||||
<button
|
||||
|
|
|
|||
|
|
@ -36,6 +36,7 @@ import {
|
|||
import styles from './Admin.module.css';
|
||||
|
||||
import { useLanguage } from '../../providers/language/LanguageContext';
|
||||
import { mandateDisplayLabel } from '../../utils/mandateDisplayUtils';
|
||||
|
||||
// Types for cleanup result
|
||||
interface DuplicateGroup {
|
||||
|
|
@ -279,7 +280,7 @@ export const AdminMandateRolePermissionsPage: React.FC = () => {
|
|||
>
|
||||
{mandates.map(mandate => (
|
||||
<option key={mandate.id} value={mandate.id}>
|
||||
{mandate.label || getTextValue(mandate.name)}
|
||||
{mandateDisplayLabel(mandate)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
|
@ -388,8 +389,8 @@ export const AdminMandateRolePermissionsPage: React.FC = () => {
|
|||
|
||||
{/* Cleanup Duplicates Modal */}
|
||||
{showCleanupModal && (
|
||||
<div className={styles.modalOverlay} onClick={_closeCleanupModal}>
|
||||
<div className={styles.modal} style={{ maxWidth: '750px' }} onClick={(e) => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modal} style={{ maxWidth: '750px' }}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h3 className={styles.modalTitle}>
|
||||
<FaBroom style={{ marginRight: '0.5rem' }} />
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ import api from '../../api';
|
|||
import styles from './Admin.module.css';
|
||||
|
||||
import { useLanguage } from '../../providers/language/LanguageContext';
|
||||
import { mandateDisplayLabel } from '../../utils/mandateDisplayUtils';
|
||||
|
||||
export const AdminMandateRolesPage: React.FC = () => {
|
||||
const { t, currentLanguage } = useLanguage();
|
||||
|
|
@ -273,11 +274,6 @@ export const AdminMandateRolesPage: React.FC = () => {
|
|||
setEditingRole(role);
|
||||
};
|
||||
|
||||
// Get mandate name
|
||||
const getMandateName = (mandate: Mandate) => {
|
||||
return mandate.label || mandate.name || mandate.id;
|
||||
};
|
||||
|
||||
if (error && !selectedMandateId) {
|
||||
return (
|
||||
<div className={`${styles.adminPage} ${styles.adminPageFill}`}>
|
||||
|
|
@ -334,7 +330,7 @@ export const AdminMandateRolesPage: React.FC = () => {
|
|||
<option value="">{t('Mandant wählen')}</option>
|
||||
{mandates.map(m => (
|
||||
<option key={m.id} value={m.id}>
|
||||
{getMandateName(m)}
|
||||
{mandateDisplayLabel(m)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
|
@ -434,8 +430,8 @@ export const AdminMandateRolesPage: React.FC = () => {
|
|||
|
||||
{/* Create Role Modal */}
|
||||
{showCreateModal && (
|
||||
<div className={styles.modalOverlay} onClick={() => setShowCreateModal(false)}>
|
||||
<div className={styles.modal} onClick={e => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modal}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2 className={styles.modalTitle}>{t('Neue Rolle erstellen')}</h2>
|
||||
<button
|
||||
|
|
@ -468,8 +464,8 @@ export const AdminMandateRolesPage: React.FC = () => {
|
|||
|
||||
{/* Edit Role Modal */}
|
||||
{editingRole && (
|
||||
<div className={styles.modalOverlay} onClick={() => setEditingRole(null)}>
|
||||
<div className={styles.modal} onClick={e => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modal}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2 className={styles.modalTitle}>
|
||||
{t('Rolle bearbeiten')}: {editingRole.roleLabel}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@
|
|||
* Admin page for managing Mandates (tenants) using FormGeneratorTable.
|
||||
*/
|
||||
|
||||
import React, { useState } from 'react';
|
||||
import React, { useState, useMemo } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useAdminMandates, useMandateFormAttributes, type Mandate } from '../../hooks/useMandates';
|
||||
import { useApiRequest } from '../../hooks/useApi';
|
||||
|
|
@ -16,8 +16,9 @@ import {
|
|||
import { useToast } from '../../contexts/ToastContext';
|
||||
import { usePrompt } from '../../hooks/usePrompt';
|
||||
import { FormGeneratorTable } from '../../components/FormGenerator/FormGeneratorTable';
|
||||
import { FormGeneratorForm } from '../../components/FormGenerator/FormGeneratorForm';
|
||||
import { FormGeneratorForm, type AttributeDefinition } from '../../components/FormGenerator/FormGeneratorForm';
|
||||
import { FaPlus, FaSync, FaUsers, FaLock, FaSkullCrossbones } from 'react-icons/fa';
|
||||
import { getUserDataCache } from '../../utils/userCache';
|
||||
import styles from './Admin.module.css';
|
||||
|
||||
import { useLanguage } from '../../providers/language/LanguageContext';
|
||||
|
|
@ -59,6 +60,17 @@ export const AdminMandatesPage: React.FC = () => {
|
|||
const [editingFormData, setEditingFormData] = useState<Record<string, unknown> | null>(null);
|
||||
const [editingBillingWarning, setEditingBillingWarning] = useState<string | null>(null);
|
||||
|
||||
const isPlatformAdmin = getUserDataCache()?.isPlatformAdmin === true;
|
||||
|
||||
// MandateAdmin: only label + billing fields editable; rest readonly
|
||||
const _MANDATE_ADMIN_EDITABLE = new Set(['label', 'warningThresholdPercent', 'notifyOnWarning', 'notifyEmails']);
|
||||
const editFormAttrs: AttributeDefinition[] = useMemo(() => {
|
||||
if (isPlatformAdmin) return formAttributesWithBilling;
|
||||
return formAttributesWithBilling.map(attr =>
|
||||
_MANDATE_ADMIN_EDITABLE.has(attr.name) ? attr : { ...attr, editable: false, readonly: true }
|
||||
);
|
||||
}, [formAttributesWithBilling, isPlatformAdmin]);
|
||||
|
||||
// Check if user can create
|
||||
const canCreate = permissions?.create !== 'n';
|
||||
const canUpdate = permissions?.update !== 'n';
|
||||
|
|
@ -106,7 +118,10 @@ export const AdminMandatesPage: React.FC = () => {
|
|||
const mandateId = String(editingFormData.id);
|
||||
const { mandatePayload, billingUpdate } = splitMandateAndBillingFromForm(data);
|
||||
const mandateOk = await handleUpdate(mandateId, mandatePayload as Partial<Mandate>);
|
||||
if (!mandateOk) return;
|
||||
if (!mandateOk) {
|
||||
showWarning(t('Fehler'), t('Mandant konnte nicht gespeichert werden. Fehlende Berechtigung oder Serverfehler.'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await updateSettingsAdmin(request, mandateId, billingUpdate);
|
||||
showSuccess(t('Gespeichert'), t('Mandant und Abrechnung aktualisiert.'));
|
||||
|
|
@ -123,12 +138,15 @@ export const AdminMandatesPage: React.FC = () => {
|
|||
return;
|
||||
}
|
||||
const entered = await prompt(
|
||||
t('Um den Mandanten "{name}" zu deaktivieren (Soft-Delete), geben Sie den Namen ein:', { name: mandate.name }),
|
||||
t(
|
||||
'Um den Mandanten zu deaktivieren (Soft-Delete), geben Sie das Kurzzeichen «{slug}» exakt ein (Anzeigename: «{label}»).',
|
||||
{ slug: mandate.name, label: mandate.label || mandate.name }
|
||||
),
|
||||
{ title: t('Mandat deaktivieren'), confirmLabel: t('Deaktivieren'), variant: 'danger', placeholder: mandate.name },
|
||||
);
|
||||
if (entered === null) return;
|
||||
if (entered !== mandate.name) {
|
||||
showWarning(t('Abgebrochen'), t('Der eingegebene Name stimmt nicht überein.'));
|
||||
showWarning(t('Abgebrochen'), t('Das eingegebene Kurzzeichen stimmt nicht überein.'));
|
||||
return;
|
||||
}
|
||||
await handleDelete(mandate.id);
|
||||
|
|
@ -140,17 +158,23 @@ export const AdminMandatesPage: React.FC = () => {
|
|||
return;
|
||||
}
|
||||
const entered = await prompt(
|
||||
t('ACHTUNG: Dies löscht den Mandanten "{name}" unwiderruflich inkl. aller Subscriptions, Features, Benutzer-Zuweisungen und Daten. Geben Sie den exakten Namen ein:', { name: mandate.name }),
|
||||
t(
|
||||
'ACHTUNG: Dies löscht den Mandanten unwiderruflich inkl. aller Subscriptions, Features, Benutzer-Zuweisungen und Daten. Geben Sie das Kurzzeichen «{slug}» exakt ein (Anzeigename: «{label}»).',
|
||||
{ slug: mandate.name, label: mandate.label || mandate.name }
|
||||
),
|
||||
{ title: t('Unwiderrufliches Löschen'), confirmLabel: t('Dauerhaft löschen'), variant: 'danger', placeholder: mandate.name },
|
||||
);
|
||||
if (entered === null) return;
|
||||
if (entered !== mandate.name) {
|
||||
showWarning(t('Abgebrochen'), t('Der eingegebene Name stimmt nicht überein.'));
|
||||
showWarning(t('Abgebrochen'), t('Das eingegebene Kurzzeichen stimmt nicht überein.'));
|
||||
return;
|
||||
}
|
||||
const ok = await handleHardDelete(mandate.id, entered);
|
||||
if (ok) {
|
||||
showSuccess(t('Gelöscht'), t('Mandant "{name}" wurde endgültig gelöscht.', { name: mandate.name }));
|
||||
showSuccess(
|
||||
t('Gelöscht'),
|
||||
t('Mandant «{name}» wurde endgültig gelöscht.', { name: mandate.label || mandate.name })
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -175,7 +199,13 @@ export const AdminMandatesPage: React.FC = () => {
|
|||
<div className={styles.pageHeader}>
|
||||
<div>
|
||||
<h1 className={styles.pageTitle}>{t('Mandanten')}</h1>
|
||||
<p className={styles.pageSubtitle}>{t('Verwalten Sie alle Mandanten im')}</p>
|
||||
<p className={styles.pageSubtitle}>
|
||||
{t('Verwalten Sie alle Mandanten im')}
|
||||
{' '}
|
||||
{t(
|
||||
'Der Volle Name erscheint in der Oberfläche; das Kurzzeichen ist systemweit eindeutig und dient Referenzierung und Bestätigungsabfragen.'
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<div className={styles.headerActions}>
|
||||
<button
|
||||
|
|
@ -253,8 +283,8 @@ export const AdminMandatesPage: React.FC = () => {
|
|||
|
||||
{/* Create Modal */}
|
||||
{showCreateModal && (
|
||||
<div className={styles.modalOverlay} onClick={() => setShowCreateModal(false)}>
|
||||
<div className={styles.modal} onClick={e => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modal}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2 className={styles.modalTitle}>{t('Neuer Mandant')}</h2>
|
||||
<button
|
||||
|
|
@ -293,14 +323,8 @@ export const AdminMandatesPage: React.FC = () => {
|
|||
|
||||
{/* Edit Modal */}
|
||||
{editingFormData && (
|
||||
<div
|
||||
className={styles.modalOverlay}
|
||||
onClick={() => {
|
||||
setEditingFormData(null);
|
||||
setEditingBillingWarning(null);
|
||||
}}
|
||||
>
|
||||
<div className={styles.modal} onClick={e => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modal}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2 className={styles.modalTitle}>{t('Mandant bearbeiten')}</h2>
|
||||
<button
|
||||
|
|
@ -319,7 +343,9 @@ export const AdminMandatesPage: React.FC = () => {
|
|||
<FaLock style={{ marginRight: 8, color: 'var(--warning-color, #d69e2e)' }} />
|
||||
<span>
|
||||
{t('Dies ist ein')} <strong>{t('System-Mandant')}</strong>.{' '}
|
||||
{t('Er kann nicht gelöscht werden und der Name sollte nicht geändert werden.')}
|
||||
{t(
|
||||
'Er kann nicht gelöscht werden. Das Kurzzeichen (technischer Identifier) soll nicht geändert werden; der Volle Name kann bei Bedarf angepasst werden.'
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
|
@ -338,7 +364,7 @@ export const AdminMandatesPage: React.FC = () => {
|
|||
</div>
|
||||
) : (
|
||||
<FormGeneratorForm
|
||||
attributes={formAttributesWithBilling}
|
||||
attributes={editFormAttrs}
|
||||
data={editingFormData}
|
||||
mode="edit"
|
||||
onSubmit={handleEditSubmit}
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import api from '../../api';
|
|||
import styles from './Admin.module.css';
|
||||
|
||||
import { useLanguage } from '../../providers/language/LanguageContext';
|
||||
import { mandateDisplayLineLabelThenSlug } from '../../utils/mandateDisplayUtils';
|
||||
|
||||
interface UserOption {
|
||||
id: string;
|
||||
|
|
@ -18,6 +19,7 @@ interface UserOption {
|
|||
email: string;
|
||||
fullName: string;
|
||||
isSysAdmin: boolean;
|
||||
isPlatformAdmin: boolean;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
|
|
@ -60,14 +62,6 @@ interface MandateInfo {
|
|||
}[];
|
||||
}
|
||||
|
||||
function _mandateNameLine(mandate: MandateInfo): string {
|
||||
const label = mandate.label?.trim();
|
||||
if (label) {
|
||||
return `${mandate.name} (${label})`;
|
||||
}
|
||||
return mandate.name;
|
||||
}
|
||||
|
||||
function _roleDescriptionLine(role: RoleInfo): string {
|
||||
return role.description?.trim() || '';
|
||||
}
|
||||
|
|
@ -75,6 +69,7 @@ function _roleDescriptionLine(role: RoleInfo): string {
|
|||
interface UserAccessOverview {
|
||||
user: UserOption;
|
||||
isSysAdmin: boolean;
|
||||
isPlatformAdmin: boolean;
|
||||
sysAdminNote?: string;
|
||||
roles: RoleInfo[];
|
||||
mandates: MandateInfo[];
|
||||
|
|
@ -201,7 +196,13 @@ export const AdminUserAccessOverviewPage: React.FC = () => {
|
|||
{overview.isSysAdmin && (
|
||||
<div className={styles.infoBox} style={{ background: '#fef3c7', borderColor: '#f59e0b' }}>
|
||||
<FaInfoCircle style={{ marginRight: '0.5rem', color: '#f59e0b' }} />
|
||||
<span>{overview.sysAdminNote || t('Dieser Benutzer ist SysAdmin und hat vollen Systemzugriff.')}</span>
|
||||
<span>{overview.sysAdminNote || t('Dieser Benutzer ist Systemadmin (Infrastruktur-Operator) und hat vollen Datenzugriff (RBAC-Bypass).')}</span>
|
||||
</div>
|
||||
)}
|
||||
{overview.isPlatformAdmin && (
|
||||
<div className={styles.infoBox} style={{ background: '#dbeafe', borderColor: '#3b82f6' }}>
|
||||
<FaInfoCircle style={{ marginRight: '0.5rem', color: '#3b82f6' }} />
|
||||
<span>{t('Dieser Benutzer ist Plattformadmin und kann mandantsübergreifend User, Mandate und RBAC-Regeln verwalten (kein RBAC-Bypass).')}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
|
@ -223,7 +224,7 @@ export const AdminUserAccessOverviewPage: React.FC = () => {
|
|||
) : (
|
||||
<FaChevronRight className={styles.expandIcon} />
|
||||
)}
|
||||
<span className={styles.roleLabel}>{_mandateNameLine(mandate)}</span>
|
||||
<span className={styles.roleLabel}>{mandateDisplayLineLabelThenSlug(mandate)}</span>
|
||||
<span className={styles.roleDescription}>
|
||||
{t('{r} Mandantenrolle(n) · {i} Feature-Instanz(en)', {
|
||||
r: mandateRoles.length,
|
||||
|
|
@ -623,6 +624,7 @@ export const AdminUserAccessOverviewPage: React.FC = () => {
|
|||
<option key={user.id} value={user.id}>
|
||||
{user.fullName || user.username} ({user.email})
|
||||
{user.isSysAdmin && ` [${t('SysAdmin')}]`}
|
||||
{user.isPlatformAdmin && ` [${t('PlatformAdmin')}]`}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
|
@ -668,6 +670,14 @@ export const AdminUserAccessOverviewPage: React.FC = () => {
|
|||
</span>
|
||||
</>
|
||||
)}
|
||||
{overview.isPlatformAdmin && (
|
||||
<>
|
||||
<span style={{ margin: '0 1rem', color: 'var(--text-secondary)' }}>|</span>
|
||||
<span className={styles.badge} style={{ background: '#3b82f6', color: 'white' }}>
|
||||
{t('PlatformAdmin')}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Tabs */}
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ import api from '../../api';
|
|||
import styles from './Admin.module.css';
|
||||
|
||||
import { useLanguage } from '../../providers/language/LanguageContext';
|
||||
import { mandateDisplayLabel } from '../../utils/mandateDisplayUtils';
|
||||
|
||||
export const AdminUserMandatesPage: React.FC = () => {
|
||||
const { t } = useLanguage();
|
||||
|
|
@ -250,11 +251,6 @@ export const AdminUserMandatesPage: React.FC = () => {
|
|||
setEditingUser(user);
|
||||
};
|
||||
|
||||
// Get mandate name
|
||||
const getMandateName = (mandate: Mandate) => {
|
||||
return mandate.label || mandate.name || mandate.id;
|
||||
};
|
||||
|
||||
if (error && !selectedMandateId) {
|
||||
return (
|
||||
<div className={`${styles.adminPage} ${styles.adminPageFill}`}>
|
||||
|
|
@ -295,7 +291,7 @@ export const AdminUserMandatesPage: React.FC = () => {
|
|||
<option value="">{t('Mandant wählen')}</option>
|
||||
{mandates.map(m => (
|
||||
<option key={m.id} value={m.id}>
|
||||
{getMandateName(m)}
|
||||
{mandateDisplayLabel(m)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
|
@ -375,8 +371,8 @@ export const AdminUserMandatesPage: React.FC = () => {
|
|||
|
||||
{/* Add User Modal */}
|
||||
{showAddModal && (
|
||||
<div className={styles.modalOverlay} onClick={() => setShowAddModal(false)}>
|
||||
<div className={styles.modal} onClick={e => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modal}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2 className={styles.modalTitle}>{t('Benutzer zum Mandanten hinzufügen')}</h2>
|
||||
<button
|
||||
|
|
@ -411,8 +407,8 @@ export const AdminUserMandatesPage: React.FC = () => {
|
|||
|
||||
{/* Edit Roles Modal */}
|
||||
{editingUser && (
|
||||
<div className={styles.modalOverlay} onClick={() => setEditingUser(null)}>
|
||||
<div className={styles.modal} onClick={e => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modal}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2 className={styles.modalTitle}>
|
||||
{t('Rollen bearbeiten')}: {editingUser.username}
|
||||
|
|
|
|||
|
|
@ -11,9 +11,12 @@ import { FormGeneratorTable } from '../../components/FormGenerator/FormGenerator
|
|||
import { FormGeneratorForm } from '../../components/FormGenerator/FormGeneratorForm';
|
||||
import { FaPlus, FaSync, FaKey, FaEnvelopeOpenText, FaUserShield } from 'react-icons/fa';
|
||||
import styles from './Admin.module.css';
|
||||
import { getUserDataCache } from '../../utils/userCache';
|
||||
|
||||
import { useLanguage } from '../../providers/language/LanguageContext';
|
||||
|
||||
const _PRIVILEGED_FLAGS = ['isSysAdmin', 'isPlatformAdmin'] as const;
|
||||
|
||||
interface User {
|
||||
id: string;
|
||||
username: string;
|
||||
|
|
@ -21,6 +24,7 @@ interface User {
|
|||
fullName: string;
|
||||
enabled: boolean;
|
||||
isSysAdmin?: boolean;
|
||||
isPlatformAdmin?: boolean;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
|
|
@ -115,17 +119,41 @@ export const AdminUsersPage: React.FC = () => {
|
|||
await handleSendPasswordLink(user.id);
|
||||
};
|
||||
|
||||
// Form attributes from backend - filter for create/edit forms
|
||||
const formAttributes = useMemo(() => {
|
||||
// Privileged-flag gating mirrors the backend rules in routeDataUsers.update_user
|
||||
// and create_user: only a Platform-Admin may set isSysAdmin / isPlatformAdmin,
|
||||
// and even then never on themselves (Self-Protection).
|
||||
const currentUserCache = getUserDataCache();
|
||||
const callerIsPlatformAdmin = currentUserCache?.isPlatformAdmin === true;
|
||||
const callerId = currentUserCache?.id;
|
||||
|
||||
const _buildFormAttributes = (mode: 'create' | 'edit', targetUserId?: string) => {
|
||||
const excludedFields = ['id', 'hashedPassword', 'authenticationAuthority'];
|
||||
const isSelfEdit = mode === 'edit' && targetUserId !== undefined && targetUserId === callerId;
|
||||
// Caller may flip flags only when PlatformAdmin AND not editing themselves.
|
||||
const flagsEditable = callerIsPlatformAdmin && !isSelfEdit;
|
||||
|
||||
return (attributes || [])
|
||||
.filter(attr => !excludedFields.includes(attr.name))
|
||||
.map(attr => ({
|
||||
...attr,
|
||||
// Mark username as readonly for edit mode (will be handled by FormGeneratorForm)
|
||||
editable: attr.name === 'username' ? false : attr.editable,
|
||||
}));
|
||||
}, [attributes]);
|
||||
.map(attr => {
|
||||
if (_PRIVILEGED_FLAGS.includes(attr.name as any) && !flagsEditable) {
|
||||
return { ...attr, editable: false };
|
||||
}
|
||||
if (attr.name === 'username') {
|
||||
return { ...attr, editable: false };
|
||||
}
|
||||
return attr;
|
||||
});
|
||||
};
|
||||
|
||||
const formAttributesCreate = useMemo(
|
||||
() => _buildFormAttributes('create'),
|
||||
[attributes, callerIsPlatformAdmin],
|
||||
);
|
||||
|
||||
const formAttributesEdit = useMemo(
|
||||
() => _buildFormAttributes('edit', editingUser?.id),
|
||||
[attributes, callerIsPlatformAdmin, callerId, editingUser?.id],
|
||||
);
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
|
|
@ -230,8 +258,8 @@ export const AdminUsersPage: React.FC = () => {
|
|||
|
||||
{/* Create Modal */}
|
||||
{showCreateModal && (
|
||||
<div className={styles.modalOverlay} onClick={() => setShowCreateModal(false)}>
|
||||
<div className={styles.modal} onClick={e => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modal}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2 className={styles.modalTitle}>{t('Neuer Benutzer')}</h2>
|
||||
<button
|
||||
|
|
@ -242,14 +270,14 @@ export const AdminUsersPage: React.FC = () => {
|
|||
</button>
|
||||
</div>
|
||||
<div className={styles.modalContent}>
|
||||
{formAttributes.length === 0 ? (
|
||||
{formAttributesCreate.length === 0 ? (
|
||||
<div className={styles.loadingContainer}>
|
||||
<div className={styles.spinner} />
|
||||
<span>{t('Lade Formular')}</span>
|
||||
</div>
|
||||
) : (
|
||||
<FormGeneratorForm
|
||||
attributes={formAttributes}
|
||||
attributes={formAttributesCreate}
|
||||
mode="create"
|
||||
onSubmit={handleCreateSubmit}
|
||||
onCancel={() => setShowCreateModal(false)}
|
||||
|
|
@ -264,8 +292,8 @@ export const AdminUsersPage: React.FC = () => {
|
|||
|
||||
{/* Edit Modal */}
|
||||
{editingUser && (
|
||||
<div className={styles.modalOverlay} onClick={() => setEditingUser(null)}>
|
||||
<div className={styles.modal} onClick={e => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modal}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2 className={styles.modalTitle}>{t('Benutzer bearbeiten')}</h2>
|
||||
<button
|
||||
|
|
@ -276,14 +304,14 @@ export const AdminUsersPage: React.FC = () => {
|
|||
</button>
|
||||
</div>
|
||||
<div className={styles.modalContent}>
|
||||
{formAttributes.length === 0 ? (
|
||||
{formAttributesEdit.length === 0 ? (
|
||||
<div className={styles.loadingContainer}>
|
||||
<div className={styles.spinner} />
|
||||
<span>{t('Lade Formular')}</span>
|
||||
</div>
|
||||
) : (
|
||||
<FormGeneratorForm
|
||||
attributes={formAttributes}
|
||||
attributes={formAttributesEdit}
|
||||
data={editingUser}
|
||||
mode="edit"
|
||||
onSubmit={handleEditSubmit}
|
||||
|
|
|
|||
|
|
@ -292,8 +292,8 @@ export const InstanceDetailModal: React.FC<InstanceDetailModalProps> = ({ instan
|
|||
];
|
||||
|
||||
return (
|
||||
<div className={styles.modalOverlay} onClick={onClose}>
|
||||
<div className={`${styles.modal} ${modalStyles.modal}`} onClick={(e) => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={`${styles.modal} ${modalStyles.modal}`}>
|
||||
<div className={styles.modalHeader}>
|
||||
<div>
|
||||
<h2 className={styles.modalTitle}>{instance.label}</h2>
|
||||
|
|
@ -311,8 +311,8 @@ export const InstanceDetailModal: React.FC<InstanceDetailModalProps> = ({ instan
|
|||
</div>
|
||||
|
||||
{showAddModal && (
|
||||
<div className={styles.modalOverlay} onClick={() => setShowAddModal(false)}>
|
||||
<div className={styles.modal} onClick={(e) => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modal}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2 className={styles.modalTitle}>{t('Benutzer hinzufügen')}</h2>
|
||||
<button type="button" className={styles.modalClose} onClick={() => setShowAddModal(false)}>
|
||||
|
|
@ -340,8 +340,8 @@ export const InstanceDetailModal: React.FC<InstanceDetailModalProps> = ({ instan
|
|||
)}
|
||||
|
||||
{editingUser && (
|
||||
<div className={styles.modalOverlay} onClick={() => setEditingUser(null)}>
|
||||
<div className={styles.modal} onClick={(e) => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modal}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2 className={styles.modalTitle}>
|
||||
{t('Rollen')}: {editingUser.username}
|
||||
|
|
|
|||
|
|
@ -18,3 +18,4 @@ export { AdminUserAccessOverviewPage } from './AdminUserAccessOverviewPage';
|
|||
export { AdminLogsPage } from './AdminLogsPage';
|
||||
export { AdminLanguagesPage } from './AdminLanguagesPage';
|
||||
export { AdminDemoConfigPage } from './AdminDemoConfigPage';
|
||||
export { AdminDatabaseHealthPage } from './AdminDatabaseHealthPage';
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ import { useToast } from '../../../contexts/ToastContext';
|
|||
import styles from '../Admin.module.css';
|
||||
|
||||
import { useLanguage } from '../../../providers/language/LanguageContext';
|
||||
import { mandateDisplayLabel } from '../../../utils/mandateDisplayUtils';
|
||||
|
||||
type InviteType = 'mandate' | 'featureInstance';
|
||||
|
||||
|
|
@ -114,9 +115,7 @@ export const AdminInvitationWizardPage: React.FC = () => {
|
|||
// HELPERS
|
||||
// ==========================================================================
|
||||
|
||||
const getMandateName = (m: Mandate): string => {
|
||||
return m.label || m.name || m.id;
|
||||
};
|
||||
const getMandateName = (m: Mandate): string => mandateDisplayLabel(m);
|
||||
|
||||
// ==========================================================================
|
||||
// DATA LOADING
|
||||
|
|
|
|||
|
|
@ -15,13 +15,14 @@ import {
|
|||
import { useToast } from '../../../contexts/ToastContext';
|
||||
import { useApiRequest } from '../../../hooks/useApi';
|
||||
import { useMandateFormAttributes } from '../../../hooks/useMandates';
|
||||
import { createMandate } from '../../../api/mandateApi';
|
||||
import { createMandate, type MandateCreateData } from '../../../api/mandateApi';
|
||||
import { updateSettingsAdmin } from '../../../api/billingApi';
|
||||
import { splitMandateAndBillingFromForm } from '../../../utils/mandateBillingFormMerge';
|
||||
import { FormGeneratorForm } from '../../../components/FormGenerator/FormGeneratorForm';
|
||||
import styles from '../Admin.module.css';
|
||||
|
||||
import { useLanguage } from '../../../providers/language/LanguageContext';
|
||||
import { mandateDisplayLabel } from '../../../utils/mandateDisplayUtils';
|
||||
|
||||
const TOTAL_STEPS = 4;
|
||||
|
||||
|
|
@ -103,9 +104,8 @@ export const AdminMandateWizardPage: React.FC = () => {
|
|||
// HELPERS
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
|
||||
const getMandateName = (m: Mandate | Record<string, any>): string => {
|
||||
return m.label || m.name || m.id;
|
||||
};
|
||||
const getMandateName = (m: Mandate | Record<string, any>): string =>
|
||||
mandateDisplayLabel(m as { label?: string | null; name?: string | null; id?: string });
|
||||
|
||||
const getFeatureLabel = (code: string): string => {
|
||||
const f = features.find(feat => feat.code === code);
|
||||
|
|
@ -216,9 +216,10 @@ export const AdminMandateWizardPage: React.FC = () => {
|
|||
setError(null);
|
||||
try {
|
||||
const { mandatePayload, billingUpdate } = splitMandateAndBillingFromForm(data);
|
||||
const body = {
|
||||
...mandatePayload,
|
||||
enabled: mandatePayload.enabled !== undefined ? mandatePayload.enabled : true,
|
||||
const body: MandateCreateData = {
|
||||
...(mandatePayload as Record<string, unknown>),
|
||||
label: String(mandatePayload.label ?? '').trim(),
|
||||
enabled: typeof mandatePayload.enabled === 'boolean' ? mandatePayload.enabled : true,
|
||||
};
|
||||
const created = await createMandate(request, body);
|
||||
let billingSaved = false;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,100 @@
|
|||
.modal {
|
||||
max-width: 520px;
|
||||
max-width: 640px;
|
||||
}
|
||||
|
||||
/* Step 1 — selectable cards (mandate / feature) */
|
||||
|
||||
.fieldLabel {
|
||||
display: block;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
color: var(--text-secondary);
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.required {
|
||||
color: var(--primary-color, #f25843);
|
||||
margin-left: 0.25rem;
|
||||
}
|
||||
|
||||
.cardGrid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.cardButton {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
text-align: center;
|
||||
padding: 0.75rem 0.875rem;
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--border-color);
|
||||
background: var(--bg-secondary, rgba(255, 255, 255, 0.03));
|
||||
color: var(--text-primary);
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s ease;
|
||||
min-height: 44px;
|
||||
}
|
||||
|
||||
.cardButton:hover {
|
||||
border-color: rgba(242, 88, 67, 0.5);
|
||||
background: rgba(242, 88, 67, 0.06);
|
||||
}
|
||||
|
||||
.cardButton:focus-visible {
|
||||
outline: 2px solid var(--primary-color, #f25843);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.cardButtonActive {
|
||||
border-color: rgba(242, 88, 67, 0.7);
|
||||
background: rgba(242, 88, 67, 0.18);
|
||||
color: var(--primary-color, #f25843);
|
||||
box-shadow: 0 0 0 1px rgba(242, 88, 67, 0.3) inset;
|
||||
}
|
||||
|
||||
.cardButton:disabled {
|
||||
opacity: 0.45;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.textInput {
|
||||
width: 100%;
|
||||
padding: 0.55rem 0.75rem;
|
||||
border-radius: 6px;
|
||||
border: 1px solid var(--border-color);
|
||||
background: var(--bg-primary);
|
||||
color: var(--text-primary);
|
||||
font-size: 0.9rem;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.textInput:focus {
|
||||
outline: none;
|
||||
border-color: var(--primary-color, #f25843);
|
||||
}
|
||||
|
||||
.fieldError {
|
||||
margin-top: 0.35rem;
|
||||
font-size: 0.8rem;
|
||||
color: var(--primary-color, #f25843);
|
||||
}
|
||||
|
||||
.fieldGroup {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.fieldHint {
|
||||
margin-top: 0.35rem;
|
||||
font-size: 0.78rem;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.steps {
|
||||
|
|
|
|||
|
|
@ -6,7 +6,6 @@
|
|||
|
||||
import React, { useState, useMemo } from 'react';
|
||||
import { useFeatureAccess } from '../../../hooks/useFeatureAccess';
|
||||
import { FormGeneratorForm, type AttributeDefinition } from '../../../components/FormGenerator/FormGeneratorForm';
|
||||
import { useToast } from '../../../contexts/ToastContext';
|
||||
import api from '../../../api';
|
||||
import type { Mandate } from '../../../hooks/useUserMandates';
|
||||
|
|
@ -15,9 +14,10 @@ import styles from '../Admin.module.css';
|
|||
import wizardStyles from './FeatureInstanceWizard.module.css';
|
||||
|
||||
import { useLanguage } from '../../../providers/language/LanguageContext';
|
||||
import { mandateDisplayLabel } from '../../../utils/mandateDisplayUtils';
|
||||
|
||||
function getMandateName(m: Mandate): string {
|
||||
return m.label || m.name || m.id;
|
||||
return mandateDisplayLabel(m);
|
||||
}
|
||||
|
||||
export interface FeatureInstanceWizardProps {
|
||||
|
|
@ -55,45 +55,25 @@ export const FeatureInstanceWizard: React.FC<FeatureInstanceWizardProps> = ({ ma
|
|||
const [mandateUsers, setMandateUsers] = useState<Array<{ id: string; username: string; email?: string }>>([]);
|
||||
const [instanceRoles, setInstanceRoles] = useState<Array<{ id: string; roleLabel: string }>>([]);
|
||||
const [selectedUserRoles, setSelectedUserRoles] = useState<Array<{ userId: string; roleIds: string[] }>>([]);
|
||||
const [labelTouched, setLabelTouched] = useState(false);
|
||||
|
||||
const featureOptions = useMemo(
|
||||
() => features.map((f) => ({ value: f.code, label: f.label || f.code })),
|
||||
[features]
|
||||
);
|
||||
const mandateOptions = useMemo(
|
||||
() => mandates.map((m) => ({ value: m.id, label: getMandateName(m) })),
|
||||
[mandates]
|
||||
);
|
||||
const trimmedLabel = label.trim();
|
||||
const labelMissing = trimmedLabel.length === 0;
|
||||
const canSubmitStep1 = !!mandateId && !!featureCode && !labelMissing && !submitting;
|
||||
|
||||
const createFields: AttributeDefinition[] = useMemo(
|
||||
() => [
|
||||
{ name: 'mandateId', label: t('Mandant'), type: 'enum' as const, required: true, options: mandateOptions },
|
||||
{ name: 'featureCode', label: t('Feature'), type: 'enum' as const, required: true, options: featureOptions },
|
||||
{ name: 'label', label: t('Bezeichnung'), type: 'string' as const, required: true, editable: true },
|
||||
{ name: 'enabled', label: t('Aktiv'), type: 'boolean' as const, required: false, editable: true },
|
||||
],
|
||||
[mandateOptions, featureOptions]
|
||||
);
|
||||
|
||||
const handleStep1Submit = async (data: {
|
||||
mandateId: string;
|
||||
featureCode: string;
|
||||
label: string;
|
||||
enabled?: boolean;
|
||||
}) => {
|
||||
const handleStep1Submit = async () => {
|
||||
setLabelTouched(true);
|
||||
if (!canSubmitStep1) return;
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const result = await createInstance(data.mandateId, {
|
||||
featureCode: data.featureCode,
|
||||
label: data.label,
|
||||
enabled: data.enabled !== false,
|
||||
copyTemplateRoles: copyTemplateRoles,
|
||||
const result = await createInstance(mandateId, {
|
||||
featureCode,
|
||||
label: trimmedLabel,
|
||||
enabled,
|
||||
copyTemplateRoles,
|
||||
});
|
||||
if (result.success && result.data) {
|
||||
setMandateId(data.mandateId);
|
||||
setFeatureCode(data.featureCode);
|
||||
setLabel(data.label);
|
||||
setEnabled(data.enabled !== false);
|
||||
setLabel(trimmedLabel);
|
||||
setCreatedInstanceId(result.data.id);
|
||||
setStep(1);
|
||||
} else {
|
||||
|
|
@ -165,8 +145,8 @@ export const FeatureInstanceWizard: React.FC<FeatureInstanceWizardProps> = ({ ma
|
|||
const currentStepId = steps[step]?.id;
|
||||
|
||||
return (
|
||||
<div className={styles.modalOverlay} onClick={onClose}>
|
||||
<div className={`${styles.modal} ${wizardStyles.modal}`} onClick={(e) => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={`${styles.modal} ${wizardStyles.modal}`}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2 className={styles.modalTitle}>{t('Neue Feature-Instanz')}</h2>
|
||||
<button type="button" className={styles.modalClose} onClick={onClose} aria-label={t('Schließen')}>
|
||||
|
|
@ -189,20 +169,86 @@ export const FeatureInstanceWizard: React.FC<FeatureInstanceWizardProps> = ({ ma
|
|||
<div className={styles.modalContent}>
|
||||
{currentStepId === 'create' && (
|
||||
<div className={wizardStyles.stepContent}>
|
||||
<FormGeneratorForm
|
||||
attributes={createFields}
|
||||
mode="create"
|
||||
data={{
|
||||
mandateId: mandateId || (mandates[0]?.id ?? ''),
|
||||
featureCode: featureCode || (features[0]?.code ?? ''),
|
||||
label,
|
||||
enabled,
|
||||
}}
|
||||
onSubmit={handleStep1Submit}
|
||||
onCancel={onClose}
|
||||
submitButtonText={t('Weiter')}
|
||||
cancelButtonText={t('Abbrechen')}
|
||||
/>
|
||||
<div className={wizardStyles.fieldGroup}>
|
||||
<span className={wizardStyles.fieldLabel}>
|
||||
{t('Mandant')}<span className={wizardStyles.required}>*</span>
|
||||
</span>
|
||||
{mandates.length === 0 ? (
|
||||
<p className={wizardStyles.fieldHint}>{t('Keine Mandanten verfügbar')}</p>
|
||||
) : (
|
||||
<div className={wizardStyles.cardGrid}>
|
||||
{mandates.map((m) => {
|
||||
const isActive = mandateId === m.id;
|
||||
return (
|
||||
<button
|
||||
key={m.id}
|
||||
type="button"
|
||||
className={`${wizardStyles.cardButton} ${isActive ? wizardStyles.cardButtonActive : ''}`}
|
||||
onClick={() => setMandateId(m.id)}
|
||||
aria-pressed={isActive}
|
||||
>
|
||||
{getMandateName(m)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className={wizardStyles.fieldGroup}>
|
||||
<span className={wizardStyles.fieldLabel}>
|
||||
{t('Feature')}<span className={wizardStyles.required}>*</span>
|
||||
</span>
|
||||
{features.length === 0 ? (
|
||||
<p className={wizardStyles.fieldHint}>{t('Keine Features verfügbar')}</p>
|
||||
) : (
|
||||
<div className={wizardStyles.cardGrid}>
|
||||
{features.map((f) => {
|
||||
const isActive = featureCode === f.code;
|
||||
return (
|
||||
<button
|
||||
key={f.code}
|
||||
type="button"
|
||||
className={`${wizardStyles.cardButton} ${isActive ? wizardStyles.cardButtonActive : ''}`}
|
||||
onClick={() => setFeatureCode(f.code)}
|
||||
aria-pressed={isActive}
|
||||
>
|
||||
{f.label || f.code}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className={wizardStyles.fieldGroup}>
|
||||
<label className={wizardStyles.fieldLabel} htmlFor="featureInstanceLabel">
|
||||
{t('Bezeichnung')}<span className={wizardStyles.required}>*</span>
|
||||
</label>
|
||||
<input
|
||||
id="featureInstanceLabel"
|
||||
type="text"
|
||||
className={wizardStyles.textInput}
|
||||
value={label}
|
||||
onChange={(e) => setLabel(e.target.value)}
|
||||
onBlur={() => setLabelTouched(true)}
|
||||
placeholder={t('z. B. Vertrieb DE')}
|
||||
autoComplete="off"
|
||||
/>
|
||||
{labelTouched && labelMissing && (
|
||||
<p className={wizardStyles.fieldError}>{t('Bezeichnung ist erforderlich.')}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<label className={wizardStyles.checkLabel}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={enabled}
|
||||
onChange={(e) => setEnabled(e.target.checked)}
|
||||
/>
|
||||
{t('Aktiv')}
|
||||
</label>
|
||||
|
||||
<label className={wizardStyles.checkLabel}>
|
||||
<input
|
||||
type="checkbox"
|
||||
|
|
@ -211,6 +257,21 @@ export const FeatureInstanceWizard: React.FC<FeatureInstanceWizardProps> = ({ ma
|
|||
/>
|
||||
{t('Rollen von Feature-Vorlage übernehmen (empfohlen)')}
|
||||
</label>
|
||||
|
||||
<div className={wizardStyles.stepActions}>
|
||||
<button type="button" className={styles.secondaryButton} onClick={onClose}>
|
||||
{t('Abbrechen')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.primaryButton}
|
||||
onClick={handleStep1Submit}
|
||||
disabled={!canSubmitStep1}
|
||||
title={!canSubmitStep1 ? t('Bitte Mandant, Feature und Bezeichnung wählen.') : undefined}
|
||||
>
|
||||
{submitting ? t('Speichern…') : t('Weiter')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
|
|
|||
|
|
@ -363,8 +363,8 @@ export const ConnectionsPage: React.FC = () => {
|
|||
|
||||
{/* Edit Modal */}
|
||||
{editingConnection && (
|
||||
<div className={styles.modalOverlay} onClick={() => setEditingConnection(null)}>
|
||||
<div className={styles.modal} onClick={e => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modal}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2 className={styles.modalTitle}>{t('Verbindung bearbeiten')}</h2>
|
||||
<button
|
||||
|
|
|
|||
|
|
@ -142,6 +142,24 @@ export const FilesPage: React.FC = () => {
|
|||
}
|
||||
}, [updateTreeFileNode, refreshTreeFiles, _tableRefetch]);
|
||||
|
||||
const _handleFolderScopeChange = useCallback(async (folderId: string, newScope: string) => {
|
||||
try {
|
||||
await api.patch(`/api/files/folders/${folderId}/scope`, { scope: newScope });
|
||||
await Promise.all([refreshFolders(), refreshTreeFiles(), _tableRefetch()]);
|
||||
} catch (err) {
|
||||
console.error('Failed to update folder scope:', err);
|
||||
}
|
||||
}, [refreshFolders, refreshTreeFiles, _tableRefetch]);
|
||||
|
||||
const _handleFolderNeutralizeToggle = useCallback(async (folderId: string, newValue: boolean) => {
|
||||
try {
|
||||
await api.patch(`/api/files/folders/${folderId}/neutralize`, { neutralize: newValue });
|
||||
await Promise.all([refreshFolders(), refreshTreeFiles(), _tableRefetch()]);
|
||||
} catch (err) {
|
||||
console.error('Failed to toggle folder neutralize:', err);
|
||||
}
|
||||
}, [refreshFolders, refreshTreeFiles, _tableRefetch]);
|
||||
|
||||
// ── Folder nodes for tree (real folders only) ────────────────────────
|
||||
const folderNodes = useMemo(() => {
|
||||
return folders.map(f => ({
|
||||
|
|
@ -149,6 +167,8 @@ export const FilesPage: React.FC = () => {
|
|||
name: f.name,
|
||||
parentId: f.parentId ?? null,
|
||||
fileCount: f.fileCount ?? 0,
|
||||
neutralize: f.neutralize ?? false,
|
||||
scope: f.scope ?? 'personal',
|
||||
}));
|
||||
}, [folders]);
|
||||
|
||||
|
|
@ -426,6 +446,8 @@ export const FilesPage: React.FC = () => {
|
|||
onDownloadFolder={handleDownloadFolder}
|
||||
onScopeChange={_handleScopeChange}
|
||||
onNeutralizeToggle={_handleNeutralizeToggle}
|
||||
onFolderScopeChange={_handleFolderScopeChange}
|
||||
onFolderNeutralizeToggle={_handleFolderNeutralizeToggle}
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
|
@ -529,8 +551,8 @@ export const FilesPage: React.FC = () => {
|
|||
</div>
|
||||
|
||||
{editingFile && (
|
||||
<div className={styles.modalOverlay} onClick={() => setEditingFile(null)}>
|
||||
<div className={styles.modal} onClick={e => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modal}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2 className={styles.modalTitle}>{t('Datei bearbeiten')}</h2>
|
||||
<button className={styles.modalClose} onClick={() => setEditingFile(null)}>✕</button>
|
||||
|
|
|
|||
|
|
@ -242,8 +242,8 @@ export const PromptsPage: React.FC = () => {
|
|||
|
||||
{/* Create Modal */}
|
||||
{showCreateModal && (
|
||||
<div className={styles.modalOverlay} onClick={() => setShowCreateModal(false)}>
|
||||
<div className={styles.modal} onClick={e => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modal}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2 className={styles.modalTitle}>{t('Neuer Prompt')}</h2>
|
||||
<button
|
||||
|
|
@ -276,8 +276,8 @@ export const PromptsPage: React.FC = () => {
|
|||
|
||||
{/* Edit Modal */}
|
||||
{editingPrompt && (
|
||||
<div className={styles.modalOverlay} onClick={() => setEditingPrompt(null)}>
|
||||
<div className={styles.modal} onClick={e => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modal}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2 className={styles.modalTitle}>{t('Prompt bearbeiten')}</h2>
|
||||
<button
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ import { SubscriptionTab } from './SubscriptionTab';
|
|||
import api from '../../api';
|
||||
import { getUserDataCache } from '../../utils/userCache';
|
||||
import { useLanguage } from '../../providers/language/LanguageContext';
|
||||
import { mandateDisplayLabel } from '../../utils/mandateDisplayUtils';
|
||||
import styles from './Billing.module.css';
|
||||
|
||||
type AdminTabType = 'subscription' | 'settings' | 'credit';
|
||||
|
|
@ -28,9 +29,6 @@ const _formatCurrency = (amount: number) => {
|
|||
}).format(amount);
|
||||
};
|
||||
|
||||
const _mandateDisplayLabel = (m: UserMandateRow): string => {
|
||||
return m.label || m.name || m.id;
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// MANDATE SELECTOR
|
||||
|
|
@ -62,7 +60,7 @@ const MandateSelector: React.FC<MandateSelectorProps> = ({
|
|||
<option value="">{t('Mandant wählen')}</option>
|
||||
{mandates.map(mandate => (
|
||||
<option key={mandate.id} value={mandate.id}>
|
||||
{_mandateDisplayLabel(mandate)}
|
||||
{mandateDisplayLabel(mandate)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
|
@ -446,7 +444,7 @@ export const BillingAdmin: React.FC = () => {
|
|||
const { t } = useLanguage();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const { user: currentUser } = useCurrentUser();
|
||||
const isSysAdmin = currentUser?.isSysAdmin === true;
|
||||
const isSysAdmin = currentUser?.isPlatformAdmin === true;
|
||||
|
||||
const [selectedMandateId, setSelectedMandateId] = useState<string | null>(
|
||||
searchParams.get('mandate') || null
|
||||
|
|
|
|||
|
|
@ -646,8 +646,8 @@ const PlaygroundTab: React.FC = () => {
|
|||
</div>
|
||||
|
||||
{browseTarget && (
|
||||
<div className={styles.modalOverlay} onClick={handleCloseBrowse}>
|
||||
<div className={styles.modalContent} onClick={(e) => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modalContent}>
|
||||
<h3 className={styles.modalTitle}>
|
||||
{browseTarget === 'source'
|
||||
? t('SharePoint-Quellordner durchsuchen')
|
||||
|
|
|
|||
|
|
@ -211,8 +211,8 @@ export const RealEstateParcelsView: React.FC = () => {
|
|||
</div>
|
||||
|
||||
{(editingParcel || isCreateMode) && (
|
||||
<div className={styles.modalOverlay} onClick={handleCloseModal}>
|
||||
<div className={styles.modal} onClick={e => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modal}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2 className={styles.modalTitle}>
|
||||
{isCreateMode ? t('Neue Parzelle') : t('Parzelle bearbeiten')}
|
||||
|
|
|
|||
|
|
@ -174,8 +174,8 @@ export const RealEstateProjectsView: React.FC = () => {
|
|||
</div>
|
||||
|
||||
{(editingProject || isCreateMode) && (
|
||||
<div className={styles.modalOverlay} onClick={handleCloseModal}>
|
||||
<div className={styles.modal} onClick={e => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modal}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2 className={styles.modalTitle}>{isCreateMode ? t('Neues Projekt') : t('Projekt bearbeiten')}</h2>
|
||||
<button className={styles.modalClose} onClick={handleCloseModal}>✕</button>
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import React, { useState, useEffect, useCallback, useRef } from 'react';
|
|||
import { useCurrentInstance } from '../../../hooks/useCurrentInstance';
|
||||
import * as teamsbotApi from '../../../api/teamsbotApi';
|
||||
import type { TeamsbotConfig, ConfigUpdateRequest, VoiceOption } from '../../../api/teamsbotApi';
|
||||
import type { VoiceLanguage } from '../../../api/voiceCatalogApi';
|
||||
import { FaPlay, FaSpinner } from 'react-icons/fa';
|
||||
import styles from './Teamsbot.module.css';
|
||||
|
||||
|
|
@ -36,8 +37,8 @@ export const TeamsbotSettingsView: React.FC = () => {
|
|||
// Form state
|
||||
const [formData, setFormData] = useState<ConfigUpdateRequest>({});
|
||||
|
||||
// Dynamic voice data from Google TTS API
|
||||
const [languages, setLanguages] = useState<string[]>([]);
|
||||
// Voice catalog (single source of truth) + dynamic voices for the selected language
|
||||
const [languages, setLanguages] = useState<VoiceLanguage[]>([]);
|
||||
const [voices, setVoices] = useState<VoiceOption[]>([]);
|
||||
const [loadingVoices, setLoadingVoices] = useState(false);
|
||||
|
||||
|
|
@ -247,19 +248,13 @@ export const TeamsbotSettingsView: React.FC = () => {
|
|||
value={formData.language || 'de-DE'}
|
||||
onChange={(e) => _handleLanguageChange(e.target.value)}
|
||||
>
|
||||
{languages.length > 0 ? (
|
||||
languages.map((langCode, idx) => (
|
||||
<option key={`${langCode}-${idx}`} value={langCode}>{langCode}</option>
|
||||
))
|
||||
) : (
|
||||
<>
|
||||
<option value="de-DE">{t('Deutsch (Deutschland)')}</option>
|
||||
<option value="en-US">{t('Englisch (US)')}</option>
|
||||
<option value="fr-FR">Francais</option>
|
||||
</>
|
||||
)}
|
||||
{languages.map(lang => (
|
||||
<option key={lang.bcp47} value={lang.bcp47}>
|
||||
{lang.flag ? `${lang.flag} ` : ''}{lang.label} ({lang.bcp47})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<span className={styles.hint}>Sprache fuer Captions und Sprachausgabe ({languages.length} Sprachen verfuegbar)</span>
|
||||
<span className={styles.hint}>{t('Sprache für Captions und Sprachausgabe')} ({languages.length} {t('Sprachen verfügbar')})</span>
|
||||
</div>
|
||||
|
||||
<div className={styles.formGroup}>
|
||||
|
|
|
|||
|
|
@ -266,8 +266,8 @@ export const TrusteeDocumentsView: React.FC = () => {
|
|||
|
||||
{/* Create/Edit Modal */}
|
||||
{(editingDocument || isCreateMode) && (
|
||||
<div className={styles.modalOverlay} onClick={handleCloseModal}>
|
||||
<div className={styles.modal} onClick={e => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modal}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2 className={styles.modalTitle}>
|
||||
{isCreateMode ? t('Neues Dokument') : t('Dokument bearbeiten')}
|
||||
|
|
|
|||
|
|
@ -213,8 +213,8 @@ export const TrusteePositionDocumentsView: React.FC = () => {
|
|||
|
||||
{/* Create Modal */}
|
||||
{isCreateMode && (
|
||||
<div className={styles.modalOverlay} onClick={handleCloseModal}>
|
||||
<div className={styles.modal} onClick={e => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modal}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2 className={styles.modalTitle}>{t('Neue Verknüpfung erstellen')}</h2>
|
||||
<button
|
||||
|
|
@ -249,8 +249,8 @@ export const TrusteePositionDocumentsView: React.FC = () => {
|
|||
|
||||
{/* Edit Modal */}
|
||||
{editingLink && (
|
||||
<div className={styles.modalOverlay} onClick={() => setEditingLink(null)}>
|
||||
<div className={styles.modal} onClick={e => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modal}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2 className={styles.modalTitle}>{t('Verknüpfung bearbeiten')}</h2>
|
||||
<button
|
||||
|
|
|
|||
|
|
@ -484,8 +484,8 @@ export const TrusteePositionsView: React.FC = () => {
|
|||
|
||||
{/* Create/Edit Modal */}
|
||||
{(editingPosition || isCreateMode) && (
|
||||
<div className={styles.modalOverlay} onClick={handleCloseModal}>
|
||||
<div className={styles.modal} onClick={e => e.stopPropagation()}>
|
||||
<div className={styles.modalOverlay}>
|
||||
<div className={styles.modal}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2 className={styles.modalTitle}>
|
||||
{isCreateMode ? t('Neue Position') : t('Position bearbeiten')}
|
||||
|
|
|
|||
|
|
@ -11,21 +11,7 @@ import { useVoiceStream } from '../../../hooks/useSpeechAudioCapture';
|
|||
import type { WorkspaceFile, DataSource, FeatureDataSource } from './useWorkspace';
|
||||
|
||||
import { useLanguage } from '../../../providers/language/LanguageContext';
|
||||
|
||||
const _STT_LANGUAGES = [
|
||||
{ code: 'de-DE', label: 'Deutsch' },
|
||||
{ code: 'en-US', label: 'English (US)' },
|
||||
{ code: 'en-GB', label: 'English (UK)' },
|
||||
{ code: 'fr-FR', label: 'Francais' },
|
||||
{ code: 'it-IT', label: 'Italiano' },
|
||||
{ code: 'es-ES', label: 'Espanol' },
|
||||
{ code: 'pt-BR', label: 'Portugues' },
|
||||
{ code: 'nl-NL', label: 'Nederlands' },
|
||||
{ code: 'pl-PL', label: 'Polski' },
|
||||
{ code: 'ru-RU', label: 'Russkij' },
|
||||
{ code: 'ja-JP', label: 'Japanese' },
|
||||
{ code: 'zh-CN', label: 'Chinese' },
|
||||
];
|
||||
import { useVoiceCatalog } from '../../../contexts/VoiceCatalogContext';
|
||||
|
||||
interface PendingFile {
|
||||
fileId: string;
|
||||
|
|
@ -55,6 +41,10 @@ interface WorkspaceInputProps {
|
|||
onProviderSelectionChange?: (selection: ProviderSelection) => void;
|
||||
isMobile?: boolean;
|
||||
onTreeItemsDrop?: (items: TreeItemDrop[]) => void;
|
||||
onFeatureSourceDrop?: (params: { featureInstanceId: string; featureCode: string; tableName?: string; objectKey: string; label: string; fieldName?: string }) => void;
|
||||
onDataSourceDrop?: (params: { connectionId: string; sourceType: string; path: string; label: string; displayPath?: string }) => void;
|
||||
pendingAttachDsId?: string;
|
||||
onPendingAttachDsConsumed?: () => void;
|
||||
onPasteAsFile?: (file: File) => void;
|
||||
draftAppend?: string;
|
||||
onDraftAppendConsumed?: () => void;
|
||||
|
|
@ -75,11 +65,16 @@ export const WorkspaceInput: React.FC<WorkspaceInputProps> = ({ instanceId: _ins
|
|||
onProviderSelectionChange,
|
||||
isMobile = false,
|
||||
onTreeItemsDrop,
|
||||
onFeatureSourceDrop,
|
||||
onDataSourceDrop,
|
||||
pendingAttachDsId,
|
||||
onPendingAttachDsConsumed,
|
||||
onPasteAsFile,
|
||||
draftAppend,
|
||||
onDraftAppendConsumed,
|
||||
}) => {
|
||||
const { t } = useLanguage();
|
||||
const { languages: voiceCatalogLanguages } = useVoiceCatalog();
|
||||
const [prompt, setPrompt] = useState('');
|
||||
const [showAutocomplete, setShowAutocomplete] = useState(false);
|
||||
const [autocompleteFilter, setAutocompleteFilter] = useState('');
|
||||
|
|
@ -101,6 +96,15 @@ export const WorkspaceInput: React.FC<WorkspaceInputProps> = ({ instanceId: _ins
|
|||
}
|
||||
}, [draftAppend, onDraftAppendConsumed]);
|
||||
|
||||
useEffect(() => {
|
||||
if (pendingAttachDsId) {
|
||||
setAttachedDataSourceIds(prev =>
|
||||
prev.includes(pendingAttachDsId) ? prev : [...prev, pendingAttachDsId],
|
||||
);
|
||||
onPendingAttachDsConsumed?.();
|
||||
}
|
||||
}, [pendingAttachDsId, onPendingAttachDsConsumed]);
|
||||
|
||||
const promptBeforeVoiceRef = useRef('');
|
||||
const finalizedTextRef = useRef('');
|
||||
const currentInterimRef = useRef('');
|
||||
|
|
@ -142,7 +146,6 @@ export const WorkspaceInput: React.FC<WorkspaceInputProps> = ({ instanceId: _ins
|
|||
onSend(trimmed, allFileIds, attachedDataSourceIds, attachedFeatureDataSourceIds, options);
|
||||
setPrompt('');
|
||||
setShowAutocomplete(false);
|
||||
setShowSourcePicker(false);
|
||||
setAttachedFileIds([]);
|
||||
}, [prompt, isProcessing, _extractFileRefs, attachedFileIds, attachedDataSourceIds, attachedFeatureDataSourceIds, neutralizeActive, onSend]);
|
||||
|
||||
|
|
@ -197,14 +200,6 @@ export const WorkspaceInput: React.FC<WorkspaceInputProps> = ({ instanceId: _ins
|
|||
setAttachedDataSourceIds(prev => prev.filter(id => id !== dsId));
|
||||
}, []);
|
||||
|
||||
const [showSourcePicker, setShowSourcePicker] = useState(false);
|
||||
|
||||
const _toggleDataSource = useCallback((dsId: string) => {
|
||||
setAttachedDataSourceIds(prev =>
|
||||
prev.includes(dsId) ? prev.filter(id => id !== dsId) : [...prev, dsId],
|
||||
);
|
||||
}, []);
|
||||
|
||||
const _toggleFeatureDataSource = useCallback((fdsId: string) => {
|
||||
setAttachedFeatureDataSourceIds(prev =>
|
||||
prev.includes(fdsId) ? prev.filter(id => id !== fdsId) : [...prev, fdsId],
|
||||
|
|
@ -288,7 +283,9 @@ export const WorkspaceInput: React.FC<WorkspaceInputProps> = ({ instanceId: _ins
|
|||
const _handlePromptDragOver = useCallback((e: React.DragEvent) => {
|
||||
if (
|
||||
e.dataTransfer.types.includes('application/tree-items') ||
|
||||
e.dataTransfer.types.includes('application/chat-id')
|
||||
e.dataTransfer.types.includes('application/chat-id') ||
|
||||
e.dataTransfer.types.includes('application/feature-source') ||
|
||||
e.dataTransfer.types.includes('application/datasource')
|
||||
) {
|
||||
e.preventDefault();
|
||||
e.dataTransfer.dropEffect = 'copy';
|
||||
|
|
@ -311,6 +308,24 @@ export const WorkspaceInput: React.FC<WorkspaceInputProps> = ({ instanceId: _ins
|
|||
return;
|
||||
}
|
||||
|
||||
const featureSourceJson = e.dataTransfer.getData('application/feature-source');
|
||||
if (featureSourceJson && onFeatureSourceDrop) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const params = JSON.parse(featureSourceJson);
|
||||
onFeatureSourceDrop(params);
|
||||
return;
|
||||
}
|
||||
|
||||
const dataSourceJson = e.dataTransfer.getData('application/datasource');
|
||||
if (dataSourceJson && onDataSourceDrop) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const params = JSON.parse(dataSourceJson);
|
||||
onDataSourceDrop(params);
|
||||
return;
|
||||
}
|
||||
|
||||
const treeItemsJson = e.dataTransfer.getData('application/tree-items');
|
||||
if (treeItemsJson && onTreeItemsDrop) {
|
||||
e.preventDefault();
|
||||
|
|
@ -318,7 +333,7 @@ export const WorkspaceInput: React.FC<WorkspaceInputProps> = ({ instanceId: _ins
|
|||
const items: TreeItemDrop[] = JSON.parse(treeItemsJson);
|
||||
onTreeItemsDrop(items);
|
||||
}
|
||||
}, [onTreeItemsDrop]);
|
||||
}, [onTreeItemsDrop, onFeatureSourceDrop, onDataSourceDrop]);
|
||||
|
||||
return (
|
||||
<div
|
||||
|
|
@ -545,116 +560,7 @@ export const WorkspaceInput: React.FC<WorkspaceInputProps> = ({ instanceId: _ins
|
|||
{uploading ? '...' : '+'}
|
||||
</button>
|
||||
|
||||
{(dataSources.length > 0 || featureDataSources.length > 0) && (
|
||||
<div style={{ position: 'relative' }}>
|
||||
<button
|
||||
onClick={() => setShowSourcePicker(prev => !prev)}
|
||||
disabled={isProcessing}
|
||||
title={t('Datenquellen anhängen')}
|
||||
style={{
|
||||
width: _controlSize, height: _controlSize, borderRadius: 8, border: '1px solid var(--border-color, #ddd)',
|
||||
background: (attachedDataSourceIds.length + attachedFeatureDataSourceIds.length) > 0 ? '#e8f5e9' : 'var(--secondary-bg, #f5f5f5)',
|
||||
color: (attachedDataSourceIds.length + attachedFeatureDataSourceIds.length) > 0 ? '#2e7d32' : '#666',
|
||||
cursor: isProcessing ? 'not-allowed' : 'pointer',
|
||||
fontSize: 16, display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
opacity: isProcessing ? 0.5 : 1,
|
||||
position: 'relative',
|
||||
}}
|
||||
>
|
||||
🔗
|
||||
{(attachedDataSourceIds.length + attachedFeatureDataSourceIds.length) > 0 && (
|
||||
<span style={{
|
||||
position: 'absolute', top: -4, right: -4,
|
||||
background: '#2e7d32', color: '#fff', fontSize: 9, fontWeight: 700,
|
||||
borderRadius: '50%', width: 16, height: 16,
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
}}>
|
||||
{attachedDataSourceIds.length + attachedFeatureDataSourceIds.length}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
{showSourcePicker && (
|
||||
<div style={{
|
||||
position: 'absolute', bottom: '100%', left: 0, marginBottom: 4,
|
||||
background: '#fff', border: '1px solid var(--border-color, #e0e0e0)',
|
||||
borderRadius: 8, boxShadow: '0 -2px 8px rgba(0,0,0,0.1)', zIndex: 20,
|
||||
minWidth: 240, maxHeight: 260, overflowY: 'auto',
|
||||
}}>
|
||||
<div style={{ padding: '8px 12px', fontSize: 11, color: '#999', fontWeight: 600, borderBottom: '1px solid #f0f0f0' }}>
|
||||
Active Sources auswählen
|
||||
</div>
|
||||
{dataSources.map(ds => {
|
||||
const isSelected = attachedDataSourceIds.includes(ds.id);
|
||||
return (
|
||||
<div
|
||||
key={ds.id}
|
||||
onClick={() => _toggleDataSource(ds.id)}
|
||||
style={{
|
||||
padding: '8px 12px', cursor: 'pointer', fontSize: 13,
|
||||
display: 'flex', alignItems: 'center', gap: 8,
|
||||
background: isSelected ? '#e8f5e9' : 'transparent',
|
||||
}}
|
||||
onMouseEnter={e => { if (!isSelected) e.currentTarget.style.background = '#f5f5f5'; }}
|
||||
onMouseLeave={e => { if (!isSelected) e.currentTarget.style.background = ''; }}
|
||||
>
|
||||
<span style={{
|
||||
width: 16, height: 16, borderRadius: 3,
|
||||
border: isSelected ? '2px solid #2e7d32' : '2px solid #ccc',
|
||||
background: isSelected ? '#2e7d32' : 'transparent',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
color: '#fff', fontSize: 10, fontWeight: 700, flexShrink: 0,
|
||||
}}>
|
||||
{isSelected ? '✓' : ''}
|
||||
</span>
|
||||
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{ds.label || ds.path || ds.id}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{featureDataSources.length > 0 && (
|
||||
<>
|
||||
<div style={{ padding: '8px 12px', fontSize: 11, color: '#999', fontWeight: 600, borderTop: '1px solid #f0f0f0', borderBottom: '1px solid #f0f0f0' }}>
|
||||
Feature Data Sources
|
||||
</div>
|
||||
{featureDataSources.map(fds => {
|
||||
const isSelected = attachedFeatureDataSourceIds.includes(fds.id);
|
||||
return (
|
||||
<div
|
||||
key={fds.id}
|
||||
onClick={() => _toggleFeatureDataSource(fds.id)}
|
||||
style={{
|
||||
padding: '8px 12px', cursor: 'pointer', fontSize: 13,
|
||||
display: 'flex', alignItems: 'center', gap: 8,
|
||||
background: isSelected ? '#f3e5f5' : 'transparent',
|
||||
}}
|
||||
onMouseEnter={e => { if (!isSelected) e.currentTarget.style.background = '#f5f5f5'; }}
|
||||
onMouseLeave={e => { if (!isSelected) e.currentTarget.style.background = ''; }}
|
||||
>
|
||||
<span style={{
|
||||
width: 16, height: 16, borderRadius: 3,
|
||||
border: isSelected ? '2px solid #7b1fa2' : '2px solid #ccc',
|
||||
background: isSelected ? '#7b1fa2' : 'transparent',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
color: '#fff', fontSize: 10, fontWeight: 700, flexShrink: 0,
|
||||
}}>
|
||||
{isSelected ? '✓' : ''}
|
||||
</span>
|
||||
<span style={{ display: 'flex', alignItems: 'center', fontSize: 13, color: '#7b1fa2', flexShrink: 0 }}>
|
||||
{getPageIcon(`feature.${fds.featureCode}`) || '\uD83D\uDDC3\uFE0F'}
|
||||
</span>
|
||||
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{fds.label || fds.featureCode} – {fds.tableName}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{/* Source picker removed — data sources are now attached directly from the UDB Sources/Files tabs via "send to chat" buttons */}
|
||||
|
||||
{onProviderSelectionChange && providerSelection && (
|
||||
<ProviderMultiSelect
|
||||
|
|
@ -698,23 +604,23 @@ export const WorkspaceInput: React.FC<WorkspaceInputProps> = ({ instanceId: _ins
|
|||
borderRadius: 8, boxShadow: '0 -2px 8px rgba(0,0,0,0.1)', zIndex: 20,
|
||||
maxHeight: 240, overflowY: 'auto', minWidth: 160,
|
||||
}}>
|
||||
{_STT_LANGUAGES.map(lang => (
|
||||
{voiceCatalogLanguages.map(lang => (
|
||||
<div
|
||||
key={lang.code}
|
||||
key={lang.bcp47}
|
||||
onClick={() => {
|
||||
setVoiceLanguage(lang.code);
|
||||
setVoiceLanguage(lang.bcp47);
|
||||
setShowLangPicker(false);
|
||||
fetch('/api/voice/preferences', { method: 'PUT', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sttLanguage: lang.code }) }).catch(() => {});
|
||||
fetch('/api/voice/preferences', { method: 'PUT', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sttLanguage: lang.bcp47 }) }).catch(() => {});
|
||||
}}
|
||||
style={{
|
||||
padding: '8px 12px', cursor: 'pointer', fontSize: 13,
|
||||
background: lang.code === voiceLanguage ? 'var(--primary-color, #F25843)' : 'transparent',
|
||||
color: lang.code === voiceLanguage ? '#fff' : 'var(--text-primary, #333)',
|
||||
background: lang.bcp47 === voiceLanguage ? 'var(--primary-color, #F25843)' : 'transparent',
|
||||
color: lang.bcp47 === voiceLanguage ? '#fff' : 'var(--text-primary, #333)',
|
||||
}}
|
||||
onMouseEnter={e => { if (lang.code !== voiceLanguage) e.currentTarget.style.background = 'var(--bg-secondary, #f5f5f5)'; }}
|
||||
onMouseLeave={e => { if (lang.code !== voiceLanguage) e.currentTarget.style.background = ''; }}
|
||||
onMouseEnter={e => { if (lang.bcp47 !== voiceLanguage) e.currentTarget.style.background = 'var(--bg-secondary, #f5f5f5)'; }}
|
||||
onMouseLeave={e => { if (lang.bcp47 !== voiceLanguage) e.currentTarget.style.background = ''; }}
|
||||
>
|
||||
{lang.label} ({lang.code})
|
||||
{lang.flag ? `${lang.flag} ` : ''}{lang.label} ({lang.bcp47})
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ import { WorkspaceInput } from './WorkspaceInput';
|
|||
import { FilePreview } from './FilePreview';
|
||||
import { ToolActivityLog } from './ToolActivityLog';
|
||||
import { UnifiedDataBar } from '../../../components/UnifiedDataBar';
|
||||
import type { UdbContext, UdbTab } from '../../../components/UnifiedDataBar';
|
||||
import type { UdbContext, UdbTab, AddToChat_FileItem, AddToChat_FeatureSource } from '../../../components/UnifiedDataBar';
|
||||
import api from '../../../api';
|
||||
import { _defaultProviderSelection, _toBackendProviders } from '../../../components/ProviderSelector';
|
||||
import type { ProviderSelection } from '../../../components/ProviderSelector';
|
||||
|
|
@ -279,6 +279,59 @@ export const WorkspacePage: React.FC<WorkspacePageProps> = ({ persistentInstance
|
|||
workspace.refreshFeatureDataSources();
|
||||
}, [workspace]);
|
||||
|
||||
const _handleSendToChat_Files = useCallback((items: AddToChat_FileItem[]) => {
|
||||
setPendingFiles(prev => {
|
||||
const existing = new Set(prev.map(f => f.fileId));
|
||||
const toAdd: PendingFile[] = [];
|
||||
for (const item of items) {
|
||||
if (!existing.has(item.id)) {
|
||||
toAdd.push({ fileId: item.id, fileName: item.name, itemType: item.type });
|
||||
existing.add(item.id);
|
||||
}
|
||||
}
|
||||
return [...prev, ...toAdd];
|
||||
});
|
||||
}, []);
|
||||
|
||||
const _handleSendToChat_FeatureSource = useCallback(async (params: AddToChat_FeatureSource) => {
|
||||
try {
|
||||
await api.post(`/api/workspace/${instanceId}/feature-datasources`, {
|
||||
featureInstanceId: params.featureInstanceId,
|
||||
featureCode: params.featureCode,
|
||||
tableName: params.tableName || '',
|
||||
objectKey: params.objectKey,
|
||||
label: params.label,
|
||||
});
|
||||
workspace.refreshFeatureDataSources();
|
||||
} catch (err) {
|
||||
console.error('Failed to add feature source to chat:', err);
|
||||
}
|
||||
}, [instanceId, workspace]);
|
||||
|
||||
const [pendingAttachDsId, setPendingAttachDsId] = useState<string>('');
|
||||
const _handleAttachDataSource = useCallback((dsId: string) => {
|
||||
setPendingAttachDsId(dsId);
|
||||
}, []);
|
||||
|
||||
const _handleDataSourceDrop = useCallback(async (params: { connectionId: string; sourceType: string; path: string; label: string; displayPath?: string }) => {
|
||||
try {
|
||||
const res = await api.post(`/api/workspace/${instanceId}/datasources`, {
|
||||
connectionId: params.connectionId,
|
||||
sourceType: params.sourceType,
|
||||
path: params.path,
|
||||
label: params.label,
|
||||
displayPath: params.displayPath || params.label,
|
||||
});
|
||||
const newId = res.data?.id || res.data?.dataSource?.id;
|
||||
if (newId) {
|
||||
setPendingAttachDsId(newId);
|
||||
workspace.refreshDataSources();
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to drop data source to chat:', err);
|
||||
}
|
||||
}, [instanceId, workspace]);
|
||||
|
||||
const _leftPanelBody = (
|
||||
<UnifiedDataBar
|
||||
context={_udbContext}
|
||||
|
|
@ -291,6 +344,9 @@ export const WorkspacePage: React.FC<WorkspacePageProps> = ({ persistentInstance
|
|||
onDeleteChat={_handleDeleteChat}
|
||||
onFileSelect={_handleFileSelect}
|
||||
onSourcesChanged={_handleSourcesChanged}
|
||||
onSendToChat_Files={_handleSendToChat_Files}
|
||||
onSendToChat_FeatureSource={_handleSendToChat_FeatureSource}
|
||||
onAttachDataSource={_handleAttachDataSource}
|
||||
/>
|
||||
);
|
||||
|
||||
|
|
@ -461,6 +517,10 @@ export const WorkspacePage: React.FC<WorkspacePageProps> = ({ persistentInstance
|
|||
onProviderSelectionChange={setProviderSelection}
|
||||
isMobile={isMobile}
|
||||
onTreeItemsDrop={_handleTreeItemsDrop}
|
||||
onFeatureSourceDrop={_handleSendToChat_FeatureSource}
|
||||
onDataSourceDrop={_handleDataSourceDrop}
|
||||
pendingAttachDsId={pendingAttachDsId}
|
||||
onPendingAttachDsConsumed={() => setPendingAttachDsId('')}
|
||||
onPasteAsFile={_uploadAndAttach}
|
||||
draftAppend={draftAppend}
|
||||
onDraftAppendConsumed={() => setDraftAppend('')}
|
||||
|
|
|
|||
|
|
@ -19,6 +19,26 @@ interface LanguageContextType {
|
|||
|
||||
const LanguageContext = createContext<LanguageContextType | undefined>(undefined);
|
||||
|
||||
const _LANGUAGE_STORAGE_KEY = 'poweron.preLoginLanguage';
|
||||
|
||||
function _readStoredLanguage(): Language | null {
|
||||
try {
|
||||
const raw = window.localStorage.getItem(_LANGUAGE_STORAGE_KEY);
|
||||
if (raw && raw.trim()) return raw.trim() as Language;
|
||||
} catch {
|
||||
// localStorage may be disabled (private mode etc.) — ignore.
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function _writeStoredLanguage(language: Language): void {
|
||||
try {
|
||||
window.localStorage.setItem(_LANGUAGE_STORAGE_KEY, language);
|
||||
} catch {
|
||||
// ignore write failures
|
||||
}
|
||||
}
|
||||
|
||||
interface LanguageProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
|
@ -45,14 +65,25 @@ export const LanguageProvider: React.FC<LanguageProviderProps> = ({ children })
|
|||
useEffect(() => {
|
||||
const initializeLanguage = async () => {
|
||||
let initialLanguage: Language = 'de';
|
||||
|
||||
|
||||
// Priority order:
|
||||
// 1. Logged-in user preference (server truth)
|
||||
// 2. Pre-login choice persisted in localStorage (LanguageSelector on login/register/reset pages)
|
||||
// 3. Browser language (if available)
|
||||
// 4. Hard default 'de'
|
||||
const userData = getUserDataCache();
|
||||
if (userData?.language && String(userData.language).trim()) {
|
||||
initialLanguage = String(userData.language).trim() as Language;
|
||||
await loadAndSetLanguage(initialLanguage);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
const stored = _readStoredLanguage();
|
||||
if (stored) {
|
||||
await loadAndSetLanguage(stored);
|
||||
return;
|
||||
}
|
||||
|
||||
const browserLang = navigator.language.split('-')[0] as Language;
|
||||
try {
|
||||
const codes = await fetchAvailableLanguageCodes();
|
||||
|
|
@ -63,7 +94,7 @@ export const LanguageProvider: React.FC<LanguageProviderProps> = ({ children })
|
|||
} catch {
|
||||
// keep default
|
||||
}
|
||||
|
||||
|
||||
await loadAndSetLanguage(initialLanguage);
|
||||
};
|
||||
|
||||
|
|
@ -93,6 +124,7 @@ export const LanguageProvider: React.FC<LanguageProviderProps> = ({ children })
|
|||
}, []);
|
||||
|
||||
const setLanguage = async (language: Language) => {
|
||||
_writeStoredLanguage(language);
|
||||
await loadAndSetLanguage(language);
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -52,7 +52,11 @@
|
|||
--bg-primary: #ffffff;
|
||||
--bg-secondary: #F7FAFC;
|
||||
--bg-dark: #EDF2F7;
|
||||
|
||||
/* Canvas surface for the GraphicalEditor flow editor (slightly off-white). */
|
||||
--canvas-bg: #FAFAFA;
|
||||
/* Dot color of the infinite background grid on the editor canvas. */
|
||||
--canvas-grid: #D9DEE5;
|
||||
|
||||
/* Surface colors */
|
||||
--surface-color: #F7FAFC;
|
||||
--surface-dark: #EDF2F7;
|
||||
|
|
@ -126,7 +130,13 @@
|
|||
--bg-primary: #1A202C;
|
||||
--bg-secondary: #2D3748;
|
||||
--bg-dark: #171923;
|
||||
|
||||
/* Canvas surface for the GraphicalEditor flow editor — slightly darker than
|
||||
--bg-primary so nodes and connection lines stay legible against it. */
|
||||
--canvas-bg: #131820;
|
||||
/* Dot color of the infinite background grid — bright enough to read on
|
||||
--canvas-bg, but still discreet (no visual noise). */
|
||||
--canvas-grid: rgba(226, 232, 240, 0.18);
|
||||
|
||||
/* Surface colors */
|
||||
--surface-color: #2D3748;
|
||||
--surface-dark: #1A202C;
|
||||
|
|
|
|||
|
|
@ -102,12 +102,21 @@ export interface MandateFeature {
|
|||
|
||||
/**
|
||||
* Ein Mandant (oberste Ebene)
|
||||
* Enthält mehrere Features mit deren Instanzen
|
||||
* Enthält mehrere Features mit deren Instanzen.
|
||||
*
|
||||
* Felder:
|
||||
* - `id` — UUID des Mandanten.
|
||||
* - `name` — Kurzzeichen / Slug (UNIQUE, audit-stable). Nur lowercase
|
||||
* `a–z0–9` und `-`, Länge 2–32. Wird vom System aus `label`
|
||||
* generiert und kann nur durch einen PlatformAdmin geändert
|
||||
* werden (siehe `wiki/b-reference/platform/rbac.md`).
|
||||
* - `label` — Voller Name (Pflichtfeld), wird im UI gerendert. Frei
|
||||
* änderbar durch Mandate-Admin.
|
||||
*/
|
||||
export interface Mandate {
|
||||
id: string; // mandateId
|
||||
name: string; // Technischer Identifier
|
||||
label?: string; // Anzeige-Label (fuer FK-Referenzen und UI)
|
||||
name: string; // Kurzzeichen (Slug, audit-stable)
|
||||
label: string; // Voller Name — Anzeige im UI (mandatory)
|
||||
code?: string; // Optionaler Code
|
||||
features: MandateFeature[];
|
||||
}
|
||||
|
|
@ -140,8 +149,9 @@ export interface User {
|
|||
language: string;
|
||||
enabled: boolean;
|
||||
authenticationAuthority: string;
|
||||
isSysAdmin: boolean;
|
||||
roleLabels?: string[]; // System-weite Rollen (z.B. ["sysadmin"])
|
||||
isSysAdmin: boolean; // Infrastructure/System Operator (RBAC bypass)
|
||||
isPlatformAdmin: boolean; // Cross-Mandate Governance (no RBAC bypass)
|
||||
roleLabels?: string[]; // Mandanten-scoped role labels
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ export type AttributeType =
|
|||
| 'file'
|
||||
| 'string'
|
||||
| 'enum'
|
||||
| 'slug'
|
||||
| 'readonly';
|
||||
|
||||
export type InputComponentType =
|
||||
|
|
@ -66,6 +67,7 @@ export function attributeTypeToInputType(attributeType: AttributeType): InputCom
|
|||
switch (attributeType) {
|
||||
case 'text':
|
||||
case 'string':
|
||||
case 'slug':
|
||||
return 'text';
|
||||
|
||||
case 'textarea':
|
||||
|
|
|
|||
42
src/utils/mandateDisplayUtils.ts
Normal file
42
src/utils/mandateDisplayUtils.ts
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
/**
|
||||
* UI display helpers for Mandate `label` (Voller Name) vs `name` (Kurzzeichen / Slug).
|
||||
* Mirrors semantics in `wiki/c-work/1-plan/2026-04-mandate-name-label-logic.md`.
|
||||
*/
|
||||
|
||||
function _trimOrEmpty(value: unknown): string {
|
||||
if (value === null || value === undefined) return '';
|
||||
if (typeof value === 'string') return value.trim();
|
||||
return String(value).trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Primary string for lists, dropdowns, breadcrumbs: Voller Name, then Kurzzeichen,
|
||||
* then id (defensive).
|
||||
*/
|
||||
export function mandateDisplayLabel(m: {
|
||||
label?: string | null;
|
||||
name?: string | null;
|
||||
id?: string;
|
||||
}): string {
|
||||
const lab = _trimOrEmpty(m.label);
|
||||
if (lab) return lab;
|
||||
const slug = _trimOrEmpty(m.name);
|
||||
if (slug) return slug;
|
||||
return typeof m.id === 'string' ? m.id : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* One line: `"Voller Name (kurzzeichen)"` when both differ; otherwise the single value.
|
||||
* Use where users should see the human name first and the technical slug second.
|
||||
*/
|
||||
export function mandateDisplayLineLabelThenSlug(m: {
|
||||
label?: string | null;
|
||||
name?: string | null;
|
||||
}): string {
|
||||
const lab = _trimOrEmpty(m.label);
|
||||
const slug = _trimOrEmpty(m.name);
|
||||
if (lab && slug && lab !== slug) {
|
||||
return `${lab} (${slug})`;
|
||||
}
|
||||
return lab || slug;
|
||||
}
|
||||
77
src/utils/mandateNameUtils.ts
Normal file
77
src/utils/mandateNameUtils.ts
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
/**
|
||||
* Mandate slug helpers — domain-specific wrapper around the generic
|
||||
* `slugUtils.ts`. Keeps mandate-localized error strings & the historical
|
||||
* "mn" fallback while delegating all formatting logic to the generic layer.
|
||||
*
|
||||
* The rules MUST stay in sync with the gateway counterpart at
|
||||
* `gateway/modules/shared/mandateNameUtils.py`.
|
||||
*
|
||||
* Format: lowercase [a-z0-9], hyphen-separated segments, length 2–32.
|
||||
* German umlauts are transliterated (ä→ae, ö→oe, ü→ue, ß→ss) before slugging.
|
||||
*/
|
||||
|
||||
import {
|
||||
DEFAULT_SLUG_MIN_LEN,
|
||||
DEFAULT_SLUG_MAX_LEN,
|
||||
SLUG_PATTERN,
|
||||
SLUG_HINT,
|
||||
allocateUniqueSlug,
|
||||
isValidSlug,
|
||||
maskSlugInput,
|
||||
slugify,
|
||||
transliterateGerman as _transliterateGermanGeneric,
|
||||
} from './slugUtils';
|
||||
|
||||
export const MANDATE_NAME_MIN_LEN = DEFAULT_SLUG_MIN_LEN;
|
||||
export const MANDATE_NAME_MAX_LEN = DEFAULT_SLUG_MAX_LEN;
|
||||
export const MANDATE_NAME_PATTERN = SLUG_PATTERN;
|
||||
export const MANDATE_NAME_HINT = SLUG_HINT;
|
||||
|
||||
const _MANDATE_OPTS = {
|
||||
minLen: MANDATE_NAME_MIN_LEN,
|
||||
maxLen: MANDATE_NAME_MAX_LEN,
|
||||
};
|
||||
|
||||
export function transliterateGerman(text: string): string {
|
||||
return _transliterateGermanGeneric(text);
|
||||
}
|
||||
|
||||
/** Build a slug from a label. Falls back to "mn" if no valid slug can be derived. */
|
||||
export function slugifyMandateName(label: string | null | undefined): string {
|
||||
const trimmed = (label ?? '').toString().trim();
|
||||
if (!trimmed) return 'mn';
|
||||
const result = slugify(trimmed, _MANDATE_OPTS);
|
||||
return isValidMandateName(result) ? result : 'mn';
|
||||
}
|
||||
|
||||
export function maskMandateNameInput(raw: string | null | undefined): string {
|
||||
return maskSlugInput(raw, _MANDATE_OPTS);
|
||||
}
|
||||
|
||||
export function isValidMandateName(name: unknown): name is string {
|
||||
return isValidSlug(name, _MANDATE_OPTS);
|
||||
}
|
||||
|
||||
/** Returns a localized (mandate-flavored) error message, or null when valid. */
|
||||
export function validateMandateName(name: unknown): string | null {
|
||||
if (typeof name !== 'string' || name.length === 0) {
|
||||
return 'Kurzzeichen ist erforderlich.';
|
||||
}
|
||||
if (name.length < MANDATE_NAME_MIN_LEN) {
|
||||
return `Kurzzeichen muss mindestens ${MANDATE_NAME_MIN_LEN} Zeichen lang sein.`;
|
||||
}
|
||||
if (name.length > MANDATE_NAME_MAX_LEN) {
|
||||
return `Kurzzeichen darf maximal ${MANDATE_NAME_MAX_LEN} Zeichen lang sein.`;
|
||||
}
|
||||
if (!MANDATE_NAME_PATTERN.test(name)) {
|
||||
return MANDATE_NAME_HINT;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function allocateUniqueMandateSlug(
|
||||
base: string,
|
||||
taken: Iterable<string>,
|
||||
): string {
|
||||
return allocateUniqueSlug(base, taken, _MANDATE_OPTS);
|
||||
}
|
||||
152
src/utils/slugUtils.ts
Normal file
152
src/utils/slugUtils.ts
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
/**
|
||||
* Generic slug helpers for FormGenerator inputs of type `slug`.
|
||||
*
|
||||
* Format: lowercase ASCII (`[a-z0-9]`), single-hyphen segments, configurable
|
||||
* length range (defaults 2–32). German umlauts are transliterated
|
||||
* (ä→ae, ö→oe, ü→ue, ß→ss) before slugging.
|
||||
*
|
||||
* Domain-specific helpers (e.g. `mandateNameUtils.ts`) MUST delegate here so
|
||||
* that all slug inputs stay in sync.
|
||||
*/
|
||||
|
||||
export const DEFAULT_SLUG_MIN_LEN = 2;
|
||||
export const DEFAULT_SLUG_MAX_LEN = 32;
|
||||
export const SLUG_PATTERN = /^[a-z0-9]+(-[a-z0-9]+)*$/;
|
||||
export const SLUG_HINT =
|
||||
'Nur Kleinbuchstaben (a–z), Ziffern (0–9) und Bindestriche. Ohne führende oder folgende Bindestriche.';
|
||||
|
||||
export interface SlugOptions {
|
||||
minLen?: number;
|
||||
maxLen?: number;
|
||||
}
|
||||
|
||||
const _GERMAN_MAP: Record<string, string> = {
|
||||
ä: 'ae', Ä: 'ae',
|
||||
ö: 'oe', Ö: 'oe',
|
||||
ü: 'ue', Ü: 'ue',
|
||||
ß: 'ss',
|
||||
};
|
||||
|
||||
function _transliterateGerman(text: string): string {
|
||||
if (!text) return '';
|
||||
let out = '';
|
||||
for (const ch of text) {
|
||||
out += _GERMAN_MAP[ch] ?? ch;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function _collapseHyphensAndTrim(raw: string): string {
|
||||
const lowered = raw.toLowerCase();
|
||||
const replaced = lowered.replace(/[^a-z0-9]+/g, '-');
|
||||
return replaced.replace(/-+/g, '-').replace(/^-+|-+$/g, '');
|
||||
}
|
||||
|
||||
function _ensureMinSlugLength(slug: string, minLen: number): string {
|
||||
if (slug.length >= minLen) return slug;
|
||||
if (slug.length === 1) return slug + slug;
|
||||
return slug + 'x'.repeat(minLen - slug.length);
|
||||
}
|
||||
|
||||
function _truncateSlugToMaxLen(slug: string, minLen: number, maxLen: number): string {
|
||||
if (slug.length <= maxLen) return slug;
|
||||
let cut = slug.slice(0, maxLen).replace(/-+$/g, '');
|
||||
const lastHyphen = cut.lastIndexOf('-');
|
||||
if (lastHyphen > 0) {
|
||||
cut = cut.slice(0, lastHyphen);
|
||||
}
|
||||
cut = cut.replace(/^-+|-+$/g, '');
|
||||
if (cut.length < minLen) {
|
||||
return cut + 'x'.repeat(minLen - cut.length);
|
||||
}
|
||||
return cut;
|
||||
}
|
||||
|
||||
export function transliterateGerman(text: string): string {
|
||||
return _transliterateGerman(text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a slug from a free-text source. Falls back to "x".repeat(minLen)
|
||||
* when no valid slug can be derived (callers can override the fallback).
|
||||
*/
|
||||
export function slugify(source: string | null | undefined, opts: SlugOptions = {}): string {
|
||||
const minLen = opts.minLen ?? DEFAULT_SLUG_MIN_LEN;
|
||||
const maxLen = opts.maxLen ?? DEFAULT_SLUG_MAX_LEN;
|
||||
const fallback = 'x'.repeat(Math.max(minLen, 2));
|
||||
|
||||
const src = (source ?? '').toString().trim();
|
||||
if (!src) return fallback;
|
||||
const step1 = _transliterateGerman(src);
|
||||
const step2 = _collapseHyphensAndTrim(step1);
|
||||
if (!step2) return fallback;
|
||||
const ensured = _ensureMinSlugLength(step2, minLen);
|
||||
const truncated = _truncateSlugToMaxLen(ensured, minLen, maxLen);
|
||||
return isValidSlug(truncated, opts) ? truncated : fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Live-mask user input for a slug field. Does NOT enforce min length so users
|
||||
* can keep typing; the format check happens on submit.
|
||||
*/
|
||||
export function maskSlugInput(raw: string | null | undefined, opts: SlugOptions = {}): string {
|
||||
if (!raw) return '';
|
||||
const maxLen = opts.maxLen ?? DEFAULT_SLUG_MAX_LEN;
|
||||
const transliterated = _transliterateGerman(String(raw)).toLowerCase();
|
||||
const cleaned = transliterated.replace(/[^a-z0-9-]+/g, '-').replace(/-+/g, '-');
|
||||
return cleaned.slice(0, maxLen);
|
||||
}
|
||||
|
||||
export function isValidSlug(value: unknown, opts: SlugOptions = {}): value is string {
|
||||
const minLen = opts.minLen ?? DEFAULT_SLUG_MIN_LEN;
|
||||
const maxLen = opts.maxLen ?? DEFAULT_SLUG_MAX_LEN;
|
||||
if (typeof value !== 'string') return false;
|
||||
if (value.length < minLen || value.length > maxLen) return false;
|
||||
return SLUG_PATTERN.test(value);
|
||||
}
|
||||
|
||||
/** Returns a localized error message for an invalid slug, or null when valid. */
|
||||
export function validateSlug(value: unknown, opts: SlugOptions = {}): string | null {
|
||||
const minLen = opts.minLen ?? DEFAULT_SLUG_MIN_LEN;
|
||||
const maxLen = opts.maxLen ?? DEFAULT_SLUG_MAX_LEN;
|
||||
if (typeof value !== 'string' || value.length === 0) {
|
||||
return 'Wert ist erforderlich.';
|
||||
}
|
||||
if (value.length < minLen) {
|
||||
return `Wert muss mindestens ${minLen} Zeichen lang sein.`;
|
||||
}
|
||||
if (value.length > maxLen) {
|
||||
return `Wert darf maximal ${maxLen} Zeichen lang sein.`;
|
||||
}
|
||||
if (!SLUG_PATTERN.test(value)) {
|
||||
return SLUG_HINT;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Allocate a slug not already present in *taken*, by appending -2, -3, ...
|
||||
* Mirrors `allocateUniqueMandateSlug` in the gateway.
|
||||
*/
|
||||
export function allocateUniqueSlug(
|
||||
base: string,
|
||||
taken: Iterable<string>,
|
||||
opts: SlugOptions = {},
|
||||
): string {
|
||||
const minLen = opts.minLen ?? DEFAULT_SLUG_MIN_LEN;
|
||||
const maxLen = opts.maxLen ?? DEFAULT_SLUG_MAX_LEN;
|
||||
const used = new Set<string>();
|
||||
for (const x of taken) {
|
||||
if (x) used.add(x);
|
||||
}
|
||||
if (!used.has(base)) return base;
|
||||
for (let n = 2; n <= 100000; n += 1) {
|
||||
const suffix = `-${n}`;
|
||||
const room = Math.max(maxLen - suffix.length, minLen);
|
||||
let root = base.slice(0, room).replace(/-+$/g, '');
|
||||
if (root.length < minLen) root = 'x'.repeat(minLen);
|
||||
const cand = (root + suffix).slice(0, maxLen).replace(/-+$/g, '');
|
||||
if (isValidSlug(cand, opts) && !used.has(cand)) return cand;
|
||||
}
|
||||
throw new Error('allocateUniqueSlug: could not allocate a unique slug');
|
||||
}
|
||||
|
|
@ -21,7 +21,8 @@ export interface CachedUserData {
|
|||
roleLabels?: string[]; // Array of role labels from backend (e.g., ["user"])
|
||||
// mandateId entfernt - User gehört keinem Mandanten direkt an
|
||||
// Stattdessen hat er Zugriff auf Feature-Instanzen (siehe featureStore)
|
||||
isSysAdmin?: boolean; // System-Administrator Flag
|
||||
isSysAdmin?: boolean; // Infrastructure/System Operator (RBAC bypass)
|
||||
isPlatformAdmin?: boolean; // Cross-Mandate Governance (no RBAC bypass)
|
||||
language: string;
|
||||
enabled: boolean;
|
||||
authenticationAuthority: string;
|
||||
|
|
|
|||
Loading…
Reference in a new issue