Dev #1
No files matched your search
@@ -1,5 +1,5 @@
|
|||||||
# 🧠 BRAIN.md — MindSift Internal Dev Cheat Sheet & Architecture Log
|
# 🧠 BRAIN.md — MindSift Internal Dev Cheat Sheet & Architecture Log
|
||||||
> **Zweck:** Zentrales, technisch präzises Nachschlagewerk für Entwicklung, Design-System, Datenbank-Architektur, State-Machines und aktuellen Umsetzungsstand. Wird bei jeder Änderung aktuell gehalten.
|
> **Zweck:** Zentrales, technisch präzises Nachschlagewerk für Entwicklung, Design-System, Datenbank-Architektur, State-Machines, Backend-APIs und aktuellen Umsetzungsstand. Wird bei jeder Änderung aktuell gehalten.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -18,11 +18,29 @@
|
|||||||
- **Quick Dump (Standard):** Text oben eingeben + `Enter` wirft den Gedanken sofort als Quick Dump (`status: 'inbox'`) ins Triage-Deck.
|
- **Quick Dump (Standard):** Text oben eingeben + `Enter` wirft den Gedanken sofort als Quick Dump (`status: 'inbox'`) ins Triage-Deck.
|
||||||
- **Direkt-Zuordnung bei der Eingabe:** Über das Auswahl-Menü (`Quick Dump ▾`) in der Eingabeleiste kann ein Eintrag alternativ direkt als **Aufgabe** (`target: 'task'`), direkt auf eine **Geteilte Liste** (`target: 'list_item'`) oder direkt als **Workspace-Notiz** (`target: 'document'`) gespeichert werden.
|
- **Direkt-Zuordnung bei der Eingabe:** Über das Auswahl-Menü (`Quick Dump ▾`) in der Eingabeleiste kann ein Eintrag alternativ direkt als **Aufgabe** (`target: 'task'`), direkt auf eine **Geteilte Liste** (`target: 'list_item'`) oder direkt als **Workspace-Notiz** (`target: 'document'`) gespeichert werden.
|
||||||
- **Triage-Entscheidung & Warteschlange:** Im Triage-Deck per Swipe/Klick **Wegwerfen** (`←` / `H`), **Später** (`Leertaste` – ans Ende schieben), **Auf Liste**, **Als Notiz** (`D`), **Mit Termin** (`T`) oder **Als Aufgabe** (`→` / `L`). Inklusive Inline-Textbearbeitung und Warteschlangen-Liste unter der aktiven Karte.
|
- **Triage-Entscheidung & Warteschlange:** Im Triage-Deck per Swipe/Klick **Wegwerfen** (`←` / `H`), **Später** (`Leertaste` – ans Ende schieben), **Auf Liste**, **Als Notiz** (`D`), **Mit Termin** (`T`) oder **Als Aufgabe** (`→` / `L`). Inklusive Inline-Textbearbeitung und Warteschlangen-Liste unter der aktiven Karte.
|
||||||
- [x] **Root-Cause Fixes für Browser-Hänger & Cross-Browser-Kompatibilität (Chrome & Firefox):**
|
- [x] **Mehrere Aufgabenlisten & Kanban-Board (`TasksView.tsx`, `models.go`, `sqlite.go`):**
|
||||||
- **SQLite Connection-Pool Deadlock behoben (`internal/storage/sqlite.go`):** Vorher war `db.SetMaxOpenConns(1)` aktiv, während `GetAllListsForUser`, `GetListsForSpace` und `GetSpacesForUser` innerhalb von `for rows.Next()` (bei offenem Cursor!) Unterabfragen (`s.GetListItems`, `s.GetSpaceMembers`) aufriefen. Sobald eine Liste existierte, blockierte die einzige DB-Verbindung dauerhaft und alle nachfolgenden Requests (`POST /api/v1/inbox` etc.) hingen bis zum 15-Minuten-TCP-Timeout. Jetzt werden alle `rows` strikt vor jeder Unterabfrage geschlossen (`rows.Close()`), WAL-Pragmas + `busy_timeout(10000)` per DSN übergeben und `MaxOpenConns(8)` gesetzt.
|
- Beliebig viele Aufgabenlisten (z.B. Privat, Arbeit, Homelab) mit eigenem Farb- und Icon-Code.
|
||||||
- **Stale JWT User-Auflösung (`internal/api/server.go`):** Wenn nach einem Container-Neustart eine neue SQLite-DB initialisiert wird, löst `authMiddleware` alte Browser-Tokens automatisch auf `EnsureDefaultUser()` (mit `sync.Mutex` gegen Race-Conditions) auf.
|
- Teilen von Aufgabenlisten mit Teams/Spaces.
|
||||||
- **Service-Worker & Cache-Busting (`frontend/public/sw.js`, `frontend/index.html`, `internal/api/server.go`):** Kein Caching veralteter Bundles in Firefox/Chrome; `Cache-Control: no-store` auf allen `/api/*`-Routen und `index.html`.
|
- Umschalter zwischen kompakter Listenansicht und 3-Spalten-Kanban-Board (`Zu erledigen`, `In Arbeit`, `Erledigt`) mit 1-Klick-Statuswechsel, Fälligkeitsdaten und Notizfeldern.
|
||||||
- **Optimistisches Input-Clearing & Request-Timeout (`frontend/src/lib/api.ts`, `InstantCaptureBar.tsx`):** Eingabefeld leert sich sofort (<10ms) bei `Enter`, alle Fetch-Calls haben einen 8-Sekunden-`AbortController`-Timeout.
|
- [x] **Benutzer- & Rollensteuerung + Admin-Panel (`SettingsModal.tsx`, `server.go`, `sqlite.go`):**
|
||||||
|
- Benutzerrollen: `admin` und `member`.
|
||||||
|
- Admin-Verwaltungsbereich zur Erstellung von Accounts, Rollenwechsel, Deaktivierung und Passwort-Reset.
|
||||||
|
- Server-weite Sharing-Isolations-Modi: `open` (alle finden sich), `teams_only` (nur innerhalb von Teams/Organisationen sichtbar) und `strict_private` (kein Teilen).
|
||||||
|
- Organisationen & Teams zur Strukturierung von Benutzergruppen.
|
||||||
|
- [x] **Workspace Markdown-Wiki mit Notion-/Word-Toolbar & Disk-Sync (`WorkspaceView.tsx`, `sqlite.go`):**
|
||||||
|
- Word-/Notion-artige Formatierungsleiste oben (Fett, Kursiv, Durchgestrichen, Code, Links, Überschriften H1-H3, Checklisten, Aufzählungen, Callouts, Markdown-Tabellen, Fortschrittsbalken).
|
||||||
|
- Interne Wiki-Links (`[[Dokumenttitel]]`) mit Klick-Navigation und Auto-Erkennung.
|
||||||
|
- Physische Speicherung auf Festplatte unter `/data/workspace/<user_id>/...` als Standard-`.md`-Dateien zur einfachen Daten-Extraktion, synchronisiert mit SQLite.
|
||||||
|
- [x] **Webhooks, Alarm-Scheduler & Discord-Integration (`SettingsModal.tsx`, `server.go`):**
|
||||||
|
- "Webhooks & Export" aus dem Header in das Benutzereinstellungen-Modal verlagert.
|
||||||
|
- Eigene API-Tokens mit curl-Beispielen für Skripte und externe Alarme.
|
||||||
|
- Hintergrund-Goroutine im Backend prüft fällige Aufgaben und sendet rechtzeitig (z.B. 15, 30 oder 60 Min. vor Fälligkeit) formatierte Discord-Embeds via Webhook.
|
||||||
|
- Vollständiger JSON-DB-Export auf Knopfdruck.
|
||||||
|
- [x] **Cross-Browser & Performance Fixes (Chrome & Firefox):**
|
||||||
|
- SQLite Connection-Pool Deadlock durch striktes Schließen von `sql.Rows` vor Unterabfragen behoben.
|
||||||
|
- Stale Token Auto-Resolution via `EnsureDefaultUser()`.
|
||||||
|
- `Cache-Control: no-store` auf allen API-Routen und `index.html`.
|
||||||
|
- Optimistisches Leeren des Capture-Inputs und 8-Sekunden-Fetch-Timeout.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -66,7 +84,58 @@ Alle Farben, Abstände und Radien werden zentral in [`frontend/src/index.css`](f
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## ⚙️ 2. State-Machine: Quick Dump, Direkt-Zuordnung & Triage
|
## 🗄️ 2. Datenbank-Architektur (SQLite Schema & Tabellen)
|
||||||
|
|
||||||
|
MindSift speichert alle Daten lokal und hochperformant in SQLite (`/data/mindsift.db`).
|
||||||
|
|
||||||
|
### Tabellen-Übersicht
|
||||||
|
|
||||||
|
1. **`users`**
|
||||||
|
- `id TEXT PRIMARY KEY`, `email TEXT UNIQUE`, `password_hash TEXT`, `display_name TEXT`
|
||||||
|
- `role TEXT DEFAULT 'member'` (`'admin'` | `'member'`)
|
||||||
|
- `is_active INTEGER DEFAULT 1`
|
||||||
|
- `discord_webhook_url TEXT DEFAULT ''`
|
||||||
|
- `notify_before_minutes INTEGER DEFAULT 15`
|
||||||
|
- `created_at DATETIME`, `updated_at DATETIME`
|
||||||
|
|
||||||
|
2. **`thoughts` (Quick Dumps, Triage & Aufgaben)**
|
||||||
|
- `id TEXT PRIMARY KEY`, `user_id TEXT`, `content TEXT`, `source TEXT`, `priority TEXT`
|
||||||
|
- `status TEXT` (`'inbox'` | `'converted'` | `'discarded'`)
|
||||||
|
- `converted_type TEXT` (`'task'` | `'document'` | `'list_item'`)
|
||||||
|
- `converted_ref_id TEXT` (Referenz auf Document oder ListItem)
|
||||||
|
- `task_list_id TEXT` (FK auf `task_lists.id`)
|
||||||
|
- `kanban_status TEXT DEFAULT 'todo'` (`'todo'` | `'in_progress'` | `'done'`)
|
||||||
|
- `notes TEXT DEFAULT ''` (zusätzliche Aufgabenbeschreibung/Notizen)
|
||||||
|
- `due_date DATETIME` (Fälligkeitsdatum)
|
||||||
|
- `alarm_sent INTEGER DEFAULT 0` (Flag für Discord-Benachrichtigung)
|
||||||
|
- `created_at DATETIME`, `updated_at DATETIME`
|
||||||
|
|
||||||
|
3. **`task_lists` (Mehrere Aufgabenlisten)**
|
||||||
|
- `id TEXT PRIMARY KEY`, `user_id TEXT`, `space_id TEXT` (optional für Team-Sharing)
|
||||||
|
- `name TEXT NOT NULL`, `color TEXT DEFAULT '#2563eb'`, `icon TEXT DEFAULT 'list'`
|
||||||
|
- `is_default INTEGER DEFAULT 0`, `created_at DATETIME`, `updated_at DATETIME`
|
||||||
|
|
||||||
|
4. **`organizations` & `teams` & `team_members`**
|
||||||
|
- `organizations`: `id TEXT PRIMARY KEY`, `name TEXT`, `owner_id TEXT`, `created_at DATETIME`, `updated_at DATETIME`
|
||||||
|
- `teams`: `id TEXT PRIMARY KEY`, `organization_id TEXT`, `name TEXT`, `created_at DATETIME`
|
||||||
|
- `team_members`: `team_id TEXT`, `user_id TEXT`, `role TEXT DEFAULT 'member'`, `joined_at DATETIME`, `PRIMARY KEY (team_id, user_id)`
|
||||||
|
|
||||||
|
5. **`system_settings` (Admin-Konfiguration)**
|
||||||
|
- `key TEXT PRIMARY KEY`, `value TEXT`, `updated_at DATETIME`
|
||||||
|
- Wichtige Schlüssel:
|
||||||
|
- `sharing_isolation_mode`: `'open'` | `'teams_only'` | `'strict_private'`
|
||||||
|
- `allow_public_registration`: `'true'` | `'false'`
|
||||||
|
|
||||||
|
6. **`documents` & `document_blocks` (Workspace & Disk Sync)**
|
||||||
|
- `documents`: `id TEXT PRIMARY KEY`, `user_id TEXT`, `space_id TEXT`, `title TEXT`, `folder_path TEXT DEFAULT '/'`, `is_archived INTEGER`, `created_at DATETIME`, `updated_at DATETIME`
|
||||||
|
- `document_blocks`: `id TEXT PRIMARY KEY`, `document_id TEXT`, `block_type TEXT` (`paragraph`, `heading1`, `heading2`, `heading3`, `todo`, `bullet`, `callout`, `code`, `table`, `progress`), `content TEXT`, `order_index INTEGER`, `metadata TEXT`, `updated_at DATETIME`
|
||||||
|
|
||||||
|
7. **`spaces`, `space_members`, `shared_lists`, `list_items`, `api_keys`**
|
||||||
|
- Verwaltung geteilter Einkaufs-/Checklisten und privater Ingestion-Keys.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ⚙️ 3. State-Machine: Quick Dump, Direkt-Zuordnung & Triage
|
||||||
|
|
||||||
```
|
```
|
||||||
[ HEADER QUICK-CAPTURE BAR ]
|
[ HEADER QUICK-CAPTURE BAR ]
|
||||||
@@ -87,19 +156,66 @@ Alle Farben, Abstände und Radien werden zentral in [`frontend/src/index.css`](f
|
|||||||
```
|
```
|
||||||
|
|
||||||
### API-Endpunkt für Capture (`POST /api/v1/inbox`)
|
### API-Endpunkt für Capture (`POST /api/v1/inbox`)
|
||||||
Akzeptiert neben `content`, `priority`, `source`, `dueDate` auch direkt:
|
Akzeptiert:
|
||||||
- `target`: `'inbox'` (Standard Quick Dump) | `'task'` | `'list_item'` | `'document'`
|
- `content`: Fließtext des Gedankens
|
||||||
|
- `priority`: `'low'` | `'medium'` | `'high'`
|
||||||
|
- `target`: `'inbox'` (Standard) | `'task'` | `'list_item'` | `'document'`
|
||||||
|
- `taskListId`: ID der Aufgabenliste (wenn `target === 'task'`)
|
||||||
- `targetListId`: ID der Zielliste (wenn `target === 'list_item'`)
|
- `targetListId`: ID der Zielliste (wenn `target === 'list_item'`)
|
||||||
|
- `dueDate`: Optionales ISO-Datum
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🛡️ 3. Kritische Backend-Regeln (SQLite & HTTP)
|
## 🔔 4. Discord-Alarm-Scheduler & Webhook-Architektur
|
||||||
|
|
||||||
|
1. **Hintergrund-Ticker im Go-Backend (`internal/api/server.go`):**
|
||||||
|
- Ein Hintergrund-Goroutine-Ticker läuft alle 60 Sekunden.
|
||||||
|
- Fragt `GetDueTasksForAlarm()` ab: Sucht nach offenen Aufgaben (`status = 'converted'`, `converted_type = 'task'`, `kanban_status != 'done'`), deren `due_date` in der Vorwarnzeit liegt (`due_date <= now + notifyBeforeMinutes`) und bei denen `alarm_sent == 0` ist.
|
||||||
|
- Sendet ein JSON-Embed an die in den Benutzer-Einstellungen hinterlegte `discord_webhook_url`:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"username": "MindSift Reminder",
|
||||||
|
"embeds": [{
|
||||||
|
"title": "⏰ Aufgabe fällig: <Titel>",
|
||||||
|
"description": "<Notizen>",
|
||||||
|
"color": 2450411,
|
||||||
|
"fields": [
|
||||||
|
{"name": "Fällig am", "value": "<Datum>", "inline": true},
|
||||||
|
{"name": "Priorität", "value": "<Prio>", "inline": true}
|
||||||
|
]
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
- Markiert den Gedanken in SQLite mit `MarkTaskAlarmSent(taskID)` als benachrichtigt.
|
||||||
|
|
||||||
|
2. **Eingehende Webhooks / Private API-Tokens:**
|
||||||
|
- Erreichbar unter `POST /api/v1/inbox` mit Header `X-API-Key: ms_...`.
|
||||||
|
- Ermöglicht direkte Einbindung in Shell-Skripte, Crons oder Drittsysteme via `curl`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📝 5. Workspace: Word/Notion-Toolbar, Wiki-Links & Disk-Sync
|
||||||
|
|
||||||
|
1. **Formatierungs-Werkzeuge:**
|
||||||
|
- Markdown-Syntax wird in Echtzeit formatiert und visuell aufbereitet.
|
||||||
|
- Buttons für H1, H2, H3, Fett (`**`), Kursiv (`*`), Durchgestrichen (`~~`), Code-Blöcke (```` ``` ````), Aufzählungen (`- `), Todos (`- [ ] `), Callouts (`> `), Markdown-Tabellen (`| Spalte 1 | Spalte 2 |`) und Fortschrittsbalken (`[progress:65%]`).
|
||||||
|
2. **Wiki-Links (`[[Dokumenttitel]]`):**
|
||||||
|
- Interne Querverweise werden als interaktive Links gerendert.
|
||||||
|
- Ein Klick auf `[[Dokumenttitel]]` durchsucht die Workspace-Dokumente und öffnet das verlinkte Dokument direkt im Editor.
|
||||||
|
3. **Physische Speicherung auf Festplatte:**
|
||||||
|
- Jede Notiz wird zusätzlich zur SQLite-Tabelle als reine `.md`-Datei unter `/data/workspace/<user_id>/<folder_path>/<slug>.md` gespeichert.
|
||||||
|
- Ermöglicht jederzeitige manuelle Datensicherung, Git-Versionierung oder Backup-Extraktion ohne Datenbank-Abhängigkeit.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🛡️ 6. Kritische Backend-Regeln (SQLite & HTTP)
|
||||||
|
|
||||||
1. **NIEMALS verschachtelte Queries bei offenem `sql.Rows`-Cursor ausführen:**
|
1. **NIEMALS verschachtelte Queries bei offenem `sql.Rows`-Cursor ausführen:**
|
||||||
- In [`internal/storage/sqlite.go`](file:///home/sandro/Dokumente/git/MindSift/internal/storage/sqlite.go) muss jede Schleife `for rows.Next()` zuerst alle Zeilen in ein Slice einlesen und sofort `_ = rows.Close()` aufrufen, **bevor** Folgeabfragen (`GetListItems`, `GetSpaceMembers`, `QueryRow` etc.) ausgeführt werden.
|
- In [`internal/storage/sqlite.go`](file:///home/sandro/Dokumente/git/MindSift/internal/storage/sqlite.go) muss jede Schleife `for rows.Next()` zuerst alle Zeilen in ein Slice einlesen und sofort `_ = rows.Close()` aufrufen, **bevor** Folgeabfragen (`GetListItems`, `GetSpaceMembers`, `QueryRow` etc.) ausgeführt werden.
|
||||||
2. **SQLite DSN-Pragmas:**
|
2. **SQLite DSN-Pragmas:**
|
||||||
- Jede Verbindung im `sql.DB`-Pool erhält über den DSN automatisch:
|
- Jede Verbindung im `sql.DB`-Pool erhält über den DSN automatisch:
|
||||||
`?_pragma=busy_timeout(10000)&_pragma=journal_mode(WAL)&_pragma=synchronous(NORMAL)&_pragma=foreign_keys(1)`
|
`?_pragma=busy_timeout(10000)&_pragma=journal_mode(WAL)&_pragma=synchronous(NORMAL)&_pragma=foreign_keys(1)`
|
||||||
|
- `MaxOpenConns(8)` und `MaxIdleConns(4)` konfiguriert.
|
||||||
3. **Thread-Safe Default User (`EnsureDefaultUser`):**
|
3. **Thread-Safe Default User (`EnsureDefaultUser`):**
|
||||||
- Durch `s.initMu.Lock()` abgesichert, damit parallele Browser-Requests beim ersten Laden niemals in einen `UNIQUE constraint`-Konflikt laufen.
|
- Durch `s.initMu.Lock()` abgesichert, damit parallele Browser-Requests beim ersten Laden niemals in einen `UNIQUE constraint`-Konflikt laufen.
|
||||||
4. **Kein Browser-Caching auf API & `index.html`:**
|
4. **Kein Browser-Caching auf API & `index.html`:**
|
||||||
@@ -107,7 +223,7 @@ Akzeptiert neben `content`, `priority`, `source`, `dueDate` auch direkt:
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 📡 4. WebSocket Realtime Protocol (Geteilte Listen)
|
## 📡 7. WebSocket Realtime Protocol (Geteilte Listen)
|
||||||
|
|
||||||
Verbindungs-URL: `ws(s)://<host>/api/v1/ws/spaces/:spaceId?token=<jwt>`
|
Verbindungs-URL: `ws(s)://<host>/api/v1/ws/spaces/:spaceId?token=<jwt>`
|
||||||
|
|
||||||
@@ -120,7 +236,7 @@ Verbindungs-URL: `ws(s)://<host>/api/v1/ws/spaces/:spaceId?token=<jwt>`
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## ⌨️ 5. Tastatur-Shortcuts (Desktop)
|
## ⌨️ 8. Tastatur-Shortcuts (Desktop)
|
||||||
|
|
||||||
| Taste | Kontext | Aktion |
|
| Taste | Kontext | Aktion |
|
||||||
| :--- | :--- | :--- |
|
| :--- | :--- | :--- |
|
||||||
@@ -135,7 +251,7 @@ Verbindungs-URL: `ws(s)://<host>/api/v1/ws/spaces/:spaceId?token=<jwt>`
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🚀 6. Gitea CI/CD & Docker Workflow
|
## 🚀 9. Gitea CI/CD & Docker Workflow
|
||||||
|
|
||||||
- **Arbeits-Branch:** `dev` (`origin/dev`)
|
- **Arbeits-Branch:** `dev` (`origin/dev`)
|
||||||
- **Ziel-Image:** `git.dsit.me/sandrodach/mindsift:dev`
|
- **Ziel-Image:** `git.dsit.me/sandrodach/mindsift:dev`
|
||||||
|
|||||||
+12
-173
@@ -4,14 +4,7 @@ import {
|
|||||||
CheckSquare,
|
CheckSquare,
|
||||||
FileText,
|
FileText,
|
||||||
ShoppingCart,
|
ShoppingCart,
|
||||||
Webhook,
|
|
||||||
Brain,
|
Brain,
|
||||||
LogOut,
|
|
||||||
User as UserIcon,
|
|
||||||
Bell,
|
|
||||||
Shield,
|
|
||||||
ChevronRight,
|
|
||||||
Sparkles,
|
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import { DashboardStats, SharedList, Thought, User } from './lib/types';
|
import { DashboardStats, SharedList, Thought, User } from './lib/types';
|
||||||
import { api, clearToken, getToken, triggerHaptic } from './lib/api';
|
import { api, clearToken, getToken, triggerHaptic } from './lib/api';
|
||||||
@@ -20,9 +13,9 @@ import { TriageDeck } from './features/triage/TriageDeck';
|
|||||||
import { TasksView } from './features/triage/TasksView';
|
import { TasksView } from './features/triage/TasksView';
|
||||||
import { WorkspaceView } from './features/workspace/WorkspaceView';
|
import { WorkspaceView } from './features/workspace/WorkspaceView';
|
||||||
import { SharedListsView } from './features/lists/SharedListsView';
|
import { SharedListsView } from './features/lists/SharedListsView';
|
||||||
import { EcosystemView } from './features/settings/EcosystemView';
|
import { SettingsModal } from './features/settings/SettingsModal';
|
||||||
|
|
||||||
type ActiveTab = 'triage' | 'tasks' | 'workspace' | 'lists' | 'ecosystem';
|
type ActiveTab = 'triage' | 'tasks' | 'workspace' | 'lists';
|
||||||
|
|
||||||
export const App: React.FC = () => {
|
export const App: React.FC = () => {
|
||||||
const [user, setUser] = useState<User | null>(null);
|
const [user, setUser] = useState<User | null>(null);
|
||||||
@@ -41,14 +34,7 @@ export const App: React.FC = () => {
|
|||||||
const [captureFocusCount, setCaptureFocusCount] = useState(0);
|
const [captureFocusCount, setCaptureFocusCount] = useState(0);
|
||||||
const [refreshRevision, setRefreshRevision] = useState(0);
|
const [refreshRevision, setRefreshRevision] = useState(0);
|
||||||
|
|
||||||
// Profile & Auth Modal State (aligned with Template Screen 2)
|
|
||||||
const [showProfileModal, setShowProfileModal] = useState(false);
|
const [showProfileModal, setShowProfileModal] = useState(false);
|
||||||
const [authMode, setAuthMode] = useState<'login' | 'register'>('login');
|
|
||||||
const [email, setEmail] = useState('');
|
|
||||||
const [password, setPassword] = useState('');
|
|
||||||
const [displayName, setDisplayName] = useState('');
|
|
||||||
const [authError, setAuthError] = useState('');
|
|
||||||
const [notificationsEnabled, setNotificationsEnabled] = useState(true);
|
|
||||||
|
|
||||||
const refreshAll = async () => {
|
const refreshAll = async () => {
|
||||||
try {
|
try {
|
||||||
@@ -129,26 +115,6 @@ export const App: React.FC = () => {
|
|||||||
setCaptureFocusCount((c) => c + 1);
|
setCaptureFocusCount((c) => c + 1);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleAuthSubmit = async (e: React.FormEvent) => {
|
|
||||||
e.preventDefault();
|
|
||||||
setAuthError('');
|
|
||||||
triggerHaptic(15);
|
|
||||||
try {
|
|
||||||
if (authMode === 'login') {
|
|
||||||
await api.login(email, password);
|
|
||||||
} else {
|
|
||||||
await api.register(email, password, displayName);
|
|
||||||
}
|
|
||||||
setShowProfileModal(false);
|
|
||||||
setEmail('');
|
|
||||||
setPassword('');
|
|
||||||
setDisplayName('');
|
|
||||||
await refreshAll();
|
|
||||||
} catch (err: any) {
|
|
||||||
setAuthError(err.message || 'Authentifizierung fehlgeschlagen');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleLogout = async () => {
|
const handleLogout = async () => {
|
||||||
triggerHaptic(20);
|
triggerHaptic(20);
|
||||||
clearToken();
|
clearToken();
|
||||||
@@ -270,16 +236,6 @@ export const App: React.FC = () => {
|
|||||||
<span>Geteilte Listen</span>
|
<span>Geteilte Listen</span>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<button
|
|
||||||
onClick={() => {
|
|
||||||
triggerHaptic(10);
|
|
||||||
setActiveTab('ecosystem');
|
|
||||||
}}
|
|
||||||
className={`tab-btn ${activeTab === 'ecosystem' ? 'tab-btn-active' : ''}`}
|
|
||||||
>
|
|
||||||
<Webhook className="w-4 h-4" />
|
|
||||||
<span>Webhooks & Export</span>
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
</nav>
|
</nav>
|
||||||
</header>
|
</header>
|
||||||
@@ -316,137 +272,20 @@ export const App: React.FC = () => {
|
|||||||
{activeTab === 'lists' && (
|
{activeTab === 'lists' && (
|
||||||
<SharedListsView onRefreshGlobal={refreshAll} />
|
<SharedListsView onRefreshGlobal={refreshAll} />
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{activeTab === 'ecosystem' && (
|
|
||||||
<EcosystemView onIngested={refreshAll} />
|
|
||||||
)}
|
|
||||||
</section>
|
</section>
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
{/* Profile & Settings Modal styled identically to Template Screen 2 */}
|
{/* Profile, Settings, Discord Alarms, Webhooks, Teams & Admin Modal */}
|
||||||
{showProfileModal && (
|
{showProfileModal && (
|
||||||
<div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-center justify-center p-4">
|
<SettingsModal
|
||||||
<div className="w-full max-w-sm bg-[#222428] border border-white/[0.08] shadow-2xl p-4 overflow-hidden">
|
currentUser={user}
|
||||||
{/* Screen 2: Top Profile Card */}
|
onClose={() => setShowProfileModal(false)}
|
||||||
<div className="flex flex-col items-center text-center mb-4">
|
onUserUpdated={(u) => {
|
||||||
<div className="w-20 h-20 rounded-full bg-[#1d8cf8] text-white text-2xl font-bold flex items-center justify-center shadow-lg mb-3 ring-4 ring-white/[0.05]">
|
setUser(u);
|
||||||
{user?.displayName ? user.displayName.slice(0, 1).toUpperCase() : 'U'}
|
refreshAll();
|
||||||
</div>
|
}}
|
||||||
<h2 className="text-xl font-bold text-white tracking-tight">
|
onLoggedOut={handleLogout}
|
||||||
{user?.displayName || 'Standard Benutzer'}
|
/>
|
||||||
</h2>
|
|
||||||
<p className="text-xs text-zinc-400 mt-0.5">
|
|
||||||
{user?.email || 'lokal@mindsift.local'}
|
|
||||||
</p>
|
|
||||||
|
|
||||||
{/* Template Screen 2: Blue Pill Edit Button */}
|
|
||||||
<button
|
|
||||||
onClick={() => setAuthMode(authMode === 'login' ? 'register' : 'login')}
|
|
||||||
className="mt-3 px-5 py-1.5 rounded-full bg-[#1d8cf8] hover:bg-[#167ad6] text-white text-xs font-semibold shadow-sm transition-all"
|
|
||||||
>
|
|
||||||
{authMode === 'login' ? 'Konto wechseln' : 'Neues Konto anlegen'}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Settings Sections */}
|
|
||||||
<div className="space-y-2 mb-3">
|
|
||||||
{/* Notification toggle */}
|
|
||||||
<div className="p-2.5 bg-[#16171a] border border-white/[0.06] flex items-center justify-between">
|
|
||||||
<div className="flex items-center gap-2.5">
|
|
||||||
<div className="w-7 h-7 bg-[#1d8cf8]/20 text-[#1d8cf8] flex items-center justify-center">
|
|
||||||
<Bell className="w-3.5 h-3.5" />
|
|
||||||
</div>
|
|
||||||
<span className="text-xs font-medium text-white">Benachrichtigungen</span>
|
|
||||||
</div>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setNotificationsEnabled(!notificationsEnabled)}
|
|
||||||
className={`w-10 h-5 rounded-full transition-colors relative p-0.5 ${
|
|
||||||
notificationsEnabled ? 'bg-[#1d8cf8]' : 'bg-zinc-600'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
className={`w-4 h-4 rounded-full bg-white transition-transform ${
|
|
||||||
notificationsEnabled ? 'translate-x-5' : 'translate-x-0'
|
|
||||||
}`}
|
|
||||||
/>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Security info */}
|
|
||||||
<div className="p-2.5 bg-[#16171a] border border-white/[0.06] flex items-center justify-between">
|
|
||||||
<div className="flex items-center gap-2.5">
|
|
||||||
<div className="w-7 h-7 bg-[#1d8cf8]/20 text-[#1d8cf8] flex items-center justify-center">
|
|
||||||
<Shield className="w-3.5 h-3.5" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<span className="text-xs font-medium text-white block">Sicherheit</span>
|
|
||||||
<span className="text-[10px] text-zinc-400">Lokale SQLite Verschlüsselung</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<ChevronRight className="w-4 h-4 text-zinc-500" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Auth Switcher Form if switching accounts */}
|
|
||||||
<form onSubmit={handleAuthSubmit} className="space-y-2 mb-3">
|
|
||||||
{authMode === 'register' && (
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
value={displayName}
|
|
||||||
onChange={(e) => setDisplayName(e.target.value)}
|
|
||||||
placeholder="Anzeigename"
|
|
||||||
className="w-full h-8 px-2.5 bg-[#16171a] text-xs text-white placeholder-zinc-500 border border-white/[0.08] focus:border-[#1d8cf8] focus:outline-none"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
<input
|
|
||||||
type="email"
|
|
||||||
value={email}
|
|
||||||
onChange={(e) => setEmail(e.target.value)}
|
|
||||||
placeholder="E-Mail"
|
|
||||||
className="w-full h-8 px-2.5 bg-[#16171a] text-xs text-white placeholder-zinc-500 border border-white/[0.08] focus:border-[#1d8cf8] focus:outline-none"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
<input
|
|
||||||
type="password"
|
|
||||||
value={password}
|
|
||||||
onChange={(e) => setPassword(e.target.value)}
|
|
||||||
placeholder="Passwort"
|
|
||||||
className="w-full h-8 px-2.5 bg-[#16171a] text-xs text-white placeholder-zinc-500 border border-white/[0.08] focus:border-[#1d8cf8] focus:outline-none"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
|
|
||||||
{authError && <p className="text-xs text-red-400 px-1">{authError}</p>}
|
|
||||||
|
|
||||||
<button
|
|
||||||
type="submit"
|
|
||||||
className="w-full h-8 rounded-full bg-[#1d8cf8] hover:bg-[#167ad6] text-white font-medium text-xs transition-colors shadow-sm"
|
|
||||||
>
|
|
||||||
{authMode === 'login' ? 'Anmelden' : 'Registrieren'}
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
|
|
||||||
{/* Log Out Row matching Template Screen 2 */}
|
|
||||||
<div className="pt-2 border-t border-white/[0.06] flex items-center justify-between">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={handleLogout}
|
|
||||||
className="text-xs text-[#ef4444] hover:underline flex items-center gap-1.5 font-medium py-1"
|
|
||||||
>
|
|
||||||
<LogOut className="w-3.5 h-3.5" />
|
|
||||||
<span>Abmelden</span>
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setShowProfileModal(false)}
|
|
||||||
className="px-4 py-1.5 rounded-full bg-[#282a2f] hover:bg-[#32353a] text-xs text-zinc-300 font-medium transition-colors"
|
|
||||||
>
|
|
||||||
Fertig
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,953 @@
|
|||||||
|
import React, { useEffect, useState } from 'react';
|
||||||
|
import {
|
||||||
|
X,
|
||||||
|
User as UserIcon,
|
||||||
|
Shield,
|
||||||
|
Bell,
|
||||||
|
Key,
|
||||||
|
Users,
|
||||||
|
Settings as SettingsIcon,
|
||||||
|
Plus,
|
||||||
|
Trash2,
|
||||||
|
Check,
|
||||||
|
Copy,
|
||||||
|
RefreshCw,
|
||||||
|
LogOut,
|
||||||
|
Terminal,
|
||||||
|
Download,
|
||||||
|
AlertTriangle,
|
||||||
|
Lock,
|
||||||
|
Share2,
|
||||||
|
} from 'lucide-react';
|
||||||
|
import { APIKey, Organization, SystemSettings, Team, User } from '../../lib/types';
|
||||||
|
import { api, clearToken, getToken, triggerHaptic } from '../../lib/api';
|
||||||
|
|
||||||
|
interface SettingsModalProps {
|
||||||
|
currentUser: User | null;
|
||||||
|
onClose: () => void;
|
||||||
|
onUserUpdated: (u: User) => void;
|
||||||
|
onLoggedOut: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
type SettingsTab = 'profile' | 'alarms' | 'webhooks' | 'teams' | 'admin';
|
||||||
|
|
||||||
|
export const SettingsModal: React.FC<SettingsModalProps> = ({
|
||||||
|
currentUser,
|
||||||
|
onClose,
|
||||||
|
onUserUpdated,
|
||||||
|
onLoggedOut,
|
||||||
|
}) => {
|
||||||
|
const [activeTab, setActiveTab] = useState<SettingsTab>('profile');
|
||||||
|
|
||||||
|
// --- Profile State ---
|
||||||
|
const [displayName, setDisplayName] = useState(currentUser?.displayName || '');
|
||||||
|
const [email, setEmail] = useState(currentUser?.email || '');
|
||||||
|
const [newPassword, setNewPassword] = useState('');
|
||||||
|
const [profileMsg, setProfileMsg] = useState<{ type: 'ok' | 'err'; text: string } | null>(null);
|
||||||
|
|
||||||
|
// --- Alarms / Discord State ---
|
||||||
|
const [discordWebhookUrl, setDiscordWebhookUrl] = useState(currentUser?.discordWebhookUrl || '');
|
||||||
|
const [notifyBeforeMinutes, setNotifyBeforeMinutes] = useState(currentUser?.notifyBeforeMinutes || 30);
|
||||||
|
const [alarmMsg, setAlarmMsg] = useState<{ type: 'ok' | 'err'; text: string } | null>(null);
|
||||||
|
const [testingDiscord, setTestingDiscord] = useState(false);
|
||||||
|
|
||||||
|
// --- Webhooks / API Keys State ---
|
||||||
|
const [apiKeys, setApiKeys] = useState<APIKey[]>([]);
|
||||||
|
const [newKeyName, setNewKeyName] = useState('');
|
||||||
|
const [newlyCreatedKey, setNewlyCreatedKey] = useState<string | null>(null);
|
||||||
|
const [copiedKey, setCopiedKey] = useState(false);
|
||||||
|
|
||||||
|
// --- Organizations & Teams State ---
|
||||||
|
const [orgs, setOrgs] = useState<Organization[]>([]);
|
||||||
|
const [teams, setTeams] = useState<Team[]>([]);
|
||||||
|
const [newOrgName, setNewOrgName] = useState('');
|
||||||
|
const [selectedOrgId, setSelectedOrgId] = useState('');
|
||||||
|
const [newTeamName, setNewTeamName] = useState('');
|
||||||
|
const [newTeamDesc, setNewTeamDesc] = useState('');
|
||||||
|
|
||||||
|
// --- Admin State ---
|
||||||
|
const [adminUsers, setAdminUsers] = useState<User[]>([]);
|
||||||
|
const [systemSettings, setSystemSettings] = useState<SystemSettings>({
|
||||||
|
sharingMode: 'teams_only',
|
||||||
|
allowRegistration: true,
|
||||||
|
instanceName: 'MindSift',
|
||||||
|
});
|
||||||
|
const [newAdminUserEmail, setNewAdminUserEmail] = useState('');
|
||||||
|
const [newAdminUserPassword, setNewAdminUserPassword] = useState('');
|
||||||
|
const [newAdminUserDisplayName, setNewAdminUserDisplayName] = useState('');
|
||||||
|
const [newAdminUserRole, setNewAdminUserRole] = useState<'member' | 'admin'>('member');
|
||||||
|
const [resetPwdUserId, setResetPwdUserId] = useState<string | null>(null);
|
||||||
|
const [resetPwdVal, setResetPwdVal] = useState('');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
loadKeys();
|
||||||
|
loadOrgsAndTeams();
|
||||||
|
if (currentUser?.role === 'admin') {
|
||||||
|
loadAdminData();
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const loadKeys = async () => {
|
||||||
|
try {
|
||||||
|
const keys = await api.getAPIKeys();
|
||||||
|
setApiKeys(keys);
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const loadOrgsAndTeams = async () => {
|
||||||
|
try {
|
||||||
|
const [o, t] = await Promise.all([api.getOrganizations(), api.getUserTeams()]);
|
||||||
|
setOrgs(o);
|
||||||
|
setTeams(t);
|
||||||
|
if (o.length > 0 && !selectedOrgId) {
|
||||||
|
setSelectedOrgId(o[0].id);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const loadAdminData = async () => {
|
||||||
|
try {
|
||||||
|
const [u, s] = await Promise.all([api.adminGetUsers(), api.adminGetSettings()]);
|
||||||
|
setAdminUsers(u);
|
||||||
|
setSystemSettings(s);
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- Profile Handlers ---
|
||||||
|
const handleSaveProfile = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setProfileMsg(null);
|
||||||
|
try {
|
||||||
|
const patch: any = { displayName, email };
|
||||||
|
if (newPassword.trim()) {
|
||||||
|
patch.password = newPassword.trim();
|
||||||
|
}
|
||||||
|
const updated = await api.updateSettings(patch);
|
||||||
|
onUserUpdated(updated);
|
||||||
|
setNewPassword('');
|
||||||
|
setProfileMsg({ type: 'ok', text: 'Profil erfolgreich gespeichert.' });
|
||||||
|
} catch (err: any) {
|
||||||
|
setProfileMsg({ type: 'err', text: err.message || 'Fehler beim Speichern' });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- Alarms Handlers ---
|
||||||
|
const handleSaveAlarms = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setAlarmMsg(null);
|
||||||
|
try {
|
||||||
|
const updated = await api.updateSettings({
|
||||||
|
discordWebhookUrl: discordWebhookUrl.trim(),
|
||||||
|
notifyBeforeMinutes: Number(notifyBeforeMinutes),
|
||||||
|
});
|
||||||
|
onUserUpdated(updated);
|
||||||
|
setAlarmMsg({ type: 'ok', text: 'Discord Alarm-Einstellungen gespeichert.' });
|
||||||
|
} catch (err: any) {
|
||||||
|
setAlarmMsg({ type: 'err', text: err.message || 'Fehler beim Speichern' });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleTestDiscordWebhook = async () => {
|
||||||
|
if (!discordWebhookUrl.trim()) {
|
||||||
|
setAlarmMsg({ type: 'err', text: 'Bitte zuerst eine Discord Webhook URL eingeben.' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setTestingDiscord(true);
|
||||||
|
setAlarmMsg(null);
|
||||||
|
try {
|
||||||
|
const res = await fetch(discordWebhookUrl.trim(), {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
content: '🔔 **MindSift Test-Alarm**: Verbindung zu Discord erfolgreich hergestellt!',
|
||||||
|
embeds: [
|
||||||
|
{
|
||||||
|
title: 'MindSift Aufgaben-Alarm eingerichtet',
|
||||||
|
description: 'Du erhältst hier Benachrichtigungen, wenn Aufgaben fällig werden.',
|
||||||
|
color: 3066993,
|
||||||
|
footer: { text: 'MindSift System Test' },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(`Discord antwortete mit Status ${res.status}`);
|
||||||
|
}
|
||||||
|
setAlarmMsg({ type: 'ok', text: '✅ Test-Nachricht erfolgreich an Discord gesendet!' });
|
||||||
|
} catch (err: any) {
|
||||||
|
setAlarmMsg({ type: 'err', text: `Fehler: ${err.message}` });
|
||||||
|
} finally {
|
||||||
|
setTestingDiscord(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- Webhook / Key Handlers ---
|
||||||
|
const handleCreateAPIKey = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
triggerHaptic(15);
|
||||||
|
try {
|
||||||
|
const created = await api.createAPIKey(newKeyName.trim() || 'Home Assistant / Script');
|
||||||
|
if (created.rawKey) {
|
||||||
|
setNewlyCreatedKey(created.rawKey);
|
||||||
|
}
|
||||||
|
setNewKeyName('');
|
||||||
|
loadKeys();
|
||||||
|
} catch (err: any) {
|
||||||
|
alert(err.message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDeleteAPIKey = async (id: string) => {
|
||||||
|
if (!window.confirm('Schlüssel widerrufen?')) return;
|
||||||
|
await api.deleteAPIKey(id);
|
||||||
|
loadKeys();
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCopy = (text: string) => {
|
||||||
|
navigator.clipboard.writeText(text);
|
||||||
|
setCopiedKey(true);
|
||||||
|
setTimeout(() => setCopiedKey(false), 2000);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleExportData = async () => {
|
||||||
|
const data = await api.exportAll();
|
||||||
|
const blob = new Blob([JSON.stringify(data, null, 2)], {
|
||||||
|
type: 'application/json;charset=utf-8',
|
||||||
|
});
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const a = document.createElement('a');
|
||||||
|
a.href = url;
|
||||||
|
a.download = `mindsift-backup-${new Date().toISOString().slice(0, 10)}.json`;
|
||||||
|
a.click();
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- Orgs & Teams Handlers ---
|
||||||
|
const handleCreateOrg = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!newOrgName.trim()) return;
|
||||||
|
try {
|
||||||
|
const created = await api.createOrganization(newOrgName.trim());
|
||||||
|
setOrgs((prev) => [...prev, created]);
|
||||||
|
setSelectedOrgId(created.id);
|
||||||
|
setNewOrgName('');
|
||||||
|
} catch (err: any) {
|
||||||
|
alert(err.message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCreateTeam = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!selectedOrgId || !newTeamName.trim()) return;
|
||||||
|
try {
|
||||||
|
const created = await api.createOrgTeam(selectedOrgId, newTeamName.trim(), newTeamDesc.trim());
|
||||||
|
setTeams((prev) => [...prev, created]);
|
||||||
|
setNewTeamName('');
|
||||||
|
setNewTeamDesc('');
|
||||||
|
} catch (err: any) {
|
||||||
|
alert(err.message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- Admin Handlers ---
|
||||||
|
const handleUpdateSystemSettings = async (patch: Partial<SystemSettings>) => {
|
||||||
|
const next = { ...systemSettings, ...patch };
|
||||||
|
setSystemSettings(next);
|
||||||
|
try {
|
||||||
|
await api.adminUpdateSettings(next);
|
||||||
|
} catch (err: any) {
|
||||||
|
alert(err.message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleAdminCreateUser = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
try {
|
||||||
|
const created = await api.adminCreateUser({
|
||||||
|
email: newAdminUserEmail,
|
||||||
|
password: newAdminUserPassword,
|
||||||
|
displayName: newAdminUserDisplayName || newAdminUserEmail.split('@')[0],
|
||||||
|
role: newAdminUserRole,
|
||||||
|
});
|
||||||
|
setAdminUsers((prev) => [...prev, created]);
|
||||||
|
setNewAdminUserEmail('');
|
||||||
|
setNewAdminUserPassword('');
|
||||||
|
setNewAdminUserDisplayName('');
|
||||||
|
} catch (err: any) {
|
||||||
|
alert(err.message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleToggleUserActive = async (u: User) => {
|
||||||
|
try {
|
||||||
|
const updated = await api.adminUpdateUser(u.id, { isActive: !u.isActive });
|
||||||
|
setAdminUsers((prev) => prev.map((item) => (item.id === u.id ? updated : item)));
|
||||||
|
} catch (err: any) {
|
||||||
|
alert(err.message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleToggleUserRole = async (u: User) => {
|
||||||
|
const nextRole = u.role === 'admin' ? 'member' : 'admin';
|
||||||
|
try {
|
||||||
|
const updated = await api.adminUpdateUser(u.id, { role: nextRole });
|
||||||
|
setAdminUsers((prev) => prev.map((item) => (item.id === u.id ? updated : item)));
|
||||||
|
} catch (err: any) {
|
||||||
|
alert(err.message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleConfirmResetPassword = async (userId: string) => {
|
||||||
|
if (!resetPwdVal.trim()) return;
|
||||||
|
try {
|
||||||
|
await api.adminResetPassword(userId, resetPwdVal.trim());
|
||||||
|
alert('Passwort erfolgreich zurückgesetzt.');
|
||||||
|
setResetPwdUserId(null);
|
||||||
|
setResetPwdVal('');
|
||||||
|
} catch (err: any) {
|
||||||
|
alert(err.message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleAdminDeleteUser = async (userId: string) => {
|
||||||
|
if (!window.confirm('Benutzer unwiderruflich löschen? Alle Daten dieses Nutzers werden gelöscht.')) return;
|
||||||
|
try {
|
||||||
|
await api.adminDeleteUser(userId);
|
||||||
|
setAdminUsers((prev) => prev.filter((u) => u.id !== userId));
|
||||||
|
} catch (err: any) {
|
||||||
|
alert(err.message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const baseUrl = window.location.origin;
|
||||||
|
const curlExample = `curl -X POST ${baseUrl}/api/v1/inbox \\
|
||||||
|
-H "Authorization: Bearer ${newlyCreatedKey || apiKeys[0]?.keyPrefix || 'DEIN_API_KEY'}" \\
|
||||||
|
-H "Content-Type: application/json" \\
|
||||||
|
-d '{"content": "Server-Backup abgeschlossen #homelab #backup", "priority": "high", "target": "task"}'`;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 z-50 bg-black/75 backdrop-blur-sm flex items-center justify-center p-2 sm:p-4">
|
||||||
|
<div className="w-full max-w-3xl bg-panel border border-border shadow-2xl flex flex-col max-h-[90vh] overflow-hidden">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="p-3 bg-canvas border-b border-border flex items-center justify-between">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<SettingsIcon className="w-4 h-4 text-accent" />
|
||||||
|
<h2 className="text-sm font-bold text-white tracking-tight">
|
||||||
|
Konto-Einstellungen & Administration
|
||||||
|
</h2>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={onClose}
|
||||||
|
className="p-1 text-zinc-400 hover:text-white transition-colors"
|
||||||
|
>
|
||||||
|
<X className="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Modal Navigation Tabs */}
|
||||||
|
<div className="flex items-stretch border-b border-border bg-canvas overflow-x-auto no-scrollbar text-xs">
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab('profile')}
|
||||||
|
className={`h-9 px-3.5 flex items-center gap-1.5 font-medium border-r border-border transition-colors ${
|
||||||
|
activeTab === 'profile' ? 'bg-panel text-white border-b-2 border-b-accent' : 'text-zinc-400 hover:text-white'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<UserIcon className="w-3.5 h-3.5" />
|
||||||
|
<span>Profil & Sicherheit</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab('alarms')}
|
||||||
|
className={`h-9 px-3.5 flex items-center gap-1.5 font-medium border-r border-border transition-colors ${
|
||||||
|
activeTab === 'alarms' ? 'bg-panel text-white border-b-2 border-b-accent' : 'text-zinc-400 hover:text-white'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<Bell className="w-3.5 h-3.5" />
|
||||||
|
<span>Alarme & Discord</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab('webhooks')}
|
||||||
|
className={`h-9 px-3.5 flex items-center gap-1.5 font-medium border-r border-border transition-colors ${
|
||||||
|
activeTab === 'webhooks' ? 'bg-panel text-white border-b-2 border-b-accent' : 'text-zinc-400 hover:text-white'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<Key className="w-3.5 h-3.5" />
|
||||||
|
<span>Webhooks & Export</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab('teams')}
|
||||||
|
className={`h-9 px-3.5 flex items-center gap-1.5 font-medium border-r border-border transition-colors ${
|
||||||
|
activeTab === 'teams' ? 'bg-panel text-white border-b-2 border-b-accent' : 'text-zinc-400 hover:text-white'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<Users className="w-3.5 h-3.5" />
|
||||||
|
<span>Organisationen & Teams</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{currentUser?.role === 'admin' && (
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab('admin')}
|
||||||
|
className={`h-9 px-3.5 flex items-center gap-1.5 font-medium border-r border-border transition-colors ${
|
||||||
|
activeTab === 'admin' ? 'bg-panel text-accent font-semibold border-b-2 border-b-accent' : 'text-zinc-400 hover:text-white'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<Shield className="w-3.5 h-3.5 text-accent" />
|
||||||
|
<span>Administration</span>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Modal Body */}
|
||||||
|
<div className="p-4 overflow-y-auto flex-1 space-y-4 text-xs">
|
||||||
|
{/* TAB 1: PROFIL & SICHERHEIT */}
|
||||||
|
{activeTab === 'profile' && (
|
||||||
|
<div className="space-y-4 max-w-lg">
|
||||||
|
<div>
|
||||||
|
<h3 className="text-sm font-semibold text-white mb-1">Benutzerprofil bearbeiten</h3>
|
||||||
|
<p className="text-zinc-400 text-xs">
|
||||||
|
Passe deinen Anzeigenamen und dein Anmeldekennwort an.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{profileMsg && (
|
||||||
|
<div
|
||||||
|
className={`p-2 border text-xs ${
|
||||||
|
profileMsg.type === 'ok'
|
||||||
|
? 'bg-blue-900/20 border-accent text-blue-200'
|
||||||
|
: 'bg-red-900/20 border-red-500 text-red-200'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{profileMsg.text}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<form onSubmit={handleSaveProfile} className="space-y-3">
|
||||||
|
<div>
|
||||||
|
<label className="block text-zinc-400 mb-1">Anzeigename</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={displayName}
|
||||||
|
onChange={(e) => setDisplayName(e.target.value)}
|
||||||
|
required
|
||||||
|
className="w-full h-8 px-2.5 input-field text-white"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-zinc-400 mb-1">E-Mail-Adresse</label>
|
||||||
|
<input
|
||||||
|
type="email"
|
||||||
|
value={email}
|
||||||
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
|
required
|
||||||
|
className="w-full h-8 px-2.5 input-field text-white"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-zinc-400 mb-1">Neues Passwort (leer lassen für keine Änderung)</label>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={newPassword}
|
||||||
|
onChange={(e) => setNewPassword(e.target.value)}
|
||||||
|
placeholder="Mindestens 4 Zeichen"
|
||||||
|
className="w-full h-8 px-2.5 input-field text-white"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between pt-2 border-t border-border">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onLoggedOut}
|
||||||
|
className="text-red-400 hover:underline flex items-center gap-1.5 py-1"
|
||||||
|
>
|
||||||
|
<LogOut className="w-3.5 h-3.5" />
|
||||||
|
<span>Abmelden</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button type="submit" className="btn-primary h-8 px-4 text-xs">
|
||||||
|
Änderungen speichern
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* TAB 2: ALARME & DISCORD */}
|
||||||
|
{activeTab === 'alarms' && (
|
||||||
|
<div className="space-y-4 max-w-lg">
|
||||||
|
<div>
|
||||||
|
<h3 className="text-sm font-semibold text-white mb-1">Aufgaben-Alarme & Discord Benachrichtigungen</h3>
|
||||||
|
<p className="text-zinc-400 text-xs leading-relaxed">
|
||||||
|
Trage deine Discord Webhook URL ein, damit der MindSift Server dich automatisch erinnert, sobald Aufgaben fällig werden.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{alarmMsg && (
|
||||||
|
<div
|
||||||
|
className={`p-2 border text-xs ${
|
||||||
|
alarmMsg.type === 'ok'
|
||||||
|
? 'bg-blue-900/20 border-accent text-blue-200'
|
||||||
|
: 'bg-red-900/20 border-red-500 text-red-200'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{alarmMsg.text}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<form onSubmit={handleSaveAlarms} className="space-y-3">
|
||||||
|
<div>
|
||||||
|
<label className="block text-zinc-400 mb-1">Discord Webhook URL</label>
|
||||||
|
<input
|
||||||
|
type="url"
|
||||||
|
value={discordWebhookUrl}
|
||||||
|
onChange={(e) => setDiscordWebhookUrl(e.target.value)}
|
||||||
|
placeholder="https://discord.com/api/webhooks/123456789/token..."
|
||||||
|
className="w-full h-8 px-2.5 input-field text-white font-mono text-xs"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-zinc-400 mb-1">Vorwarnzeit vor Fälligkeit</label>
|
||||||
|
<select
|
||||||
|
value={notifyBeforeMinutes}
|
||||||
|
onChange={(e) => setNotifyBeforeMinutes(Number(e.target.value))}
|
||||||
|
className="w-full h-8 px-2 input-field text-white bg-canvas"
|
||||||
|
>
|
||||||
|
<option value={0}>Direkt bei Fälligkeit</option>
|
||||||
|
<option value={15}>15 Minuten vorher</option>
|
||||||
|
<option value={30}>30 Minuten vorher</option>
|
||||||
|
<option value={60}>1 Stunde vorher</option>
|
||||||
|
<option value={1440}>1 Tag vorher</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between pt-2 border-t border-border">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handleTestDiscordWebhook}
|
||||||
|
disabled={testingDiscord || !discordWebhookUrl.trim()}
|
||||||
|
className="btn-action h-8 px-3 text-xs disabled:opacity-40"
|
||||||
|
>
|
||||||
|
<span>{testingDiscord ? 'Sende Test…' : 'Webhook testen'}</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button type="submit" className="btn-primary h-8 px-4 text-xs">
|
||||||
|
Alarm-Einstellungen sichern
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* TAB 3: WEBHOOKS & EXPORT */}
|
||||||
|
{activeTab === 'webhooks' && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<h3 className="text-sm font-semibold text-white mb-1">Private Webhook Keys & Daten-Export</h3>
|
||||||
|
<p className="text-zinc-400 text-xs">
|
||||||
|
Erstelle API-Keys für eigene Bash-Skripte, Home Assistant oder Cronjobs, um Gedanken direkt per Curl zu erfassen.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* API Key Creator */}
|
||||||
|
<form onSubmit={handleCreateAPIKey} className="flex gap-2">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={newKeyName}
|
||||||
|
onChange={(e) => setNewKeyName(e.target.value)}
|
||||||
|
placeholder="Key Bezeichnung (z.B. Smart Home, Backup Skript)…"
|
||||||
|
className="flex-1 h-8 px-2.5 input-field text-xs text-white"
|
||||||
|
/>
|
||||||
|
<button type="submit" className="btn-primary h-8 px-3 text-xs flex items-center gap-1">
|
||||||
|
<Plus className="w-3.5 h-3.5" />
|
||||||
|
<span>Key erstellen</span>
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
{newlyCreatedKey && (
|
||||||
|
<div className="p-2.5 bg-accent/15 border border-accent/40 flex items-center justify-between gap-2">
|
||||||
|
<div className="min-w-0">
|
||||||
|
<p className="text-[10px] text-accent font-semibold">Neuer Key (jetzt kopieren):</p>
|
||||||
|
<code className="text-xs font-mono text-white break-all">{newlyCreatedKey}</code>
|
||||||
|
</div>
|
||||||
|
<button onClick={() => handleCopy(newlyCreatedKey)} className="btn-primary h-7 px-2.5 text-xs">
|
||||||
|
{copiedKey ? 'Kopiert!' : 'Kopieren'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Keys list */}
|
||||||
|
<div className="border border-border divide-y divide-border bg-canvas">
|
||||||
|
{apiKeys.length === 0 ? (
|
||||||
|
<div className="p-3 text-center text-zinc-500 text-xs">Noch keine API-Schlüssel angelegt.</div>
|
||||||
|
) : (
|
||||||
|
apiKeys.map((k) => (
|
||||||
|
<div key={k.id} className="p-2 flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<p className="font-semibold text-white">{k.name}</p>
|
||||||
|
<p className="text-[10px] text-zinc-500 font-mono">Präfix: {k.keyPrefix}••••••••</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => handleDeleteAPIKey(k.id)}
|
||||||
|
className="btn-icon btn-icon-danger"
|
||||||
|
title="Key löschen"
|
||||||
|
>
|
||||||
|
<Trash2 className="w-3.5 h-3.5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Interactive Curl Example */}
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center justify-between mb-1">
|
||||||
|
<span className="font-semibold text-zinc-300 flex items-center gap-1">
|
||||||
|
<Terminal className="w-3 h-3 text-accent" /> Curl Schnellbefehl für eigene Skripte:
|
||||||
|
</span>
|
||||||
|
<button onClick={() => handleCopy(curlExample)} className="text-zinc-400 hover:text-white text-[10px]">
|
||||||
|
{copiedKey ? 'Kopiert!' : 'Kopieren'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<pre className="p-2.5 bg-black/60 border border-border text-[11px] font-mono text-zinc-300 overflow-x-auto whitespace-pre">
|
||||||
|
{curlExample}
|
||||||
|
</pre>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Data Export Button */}
|
||||||
|
<div className="pt-2 border-t border-border flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<h4 className="font-semibold text-white">Vollständiger Daten-Export</h4>
|
||||||
|
<p className="text-zinc-500 text-[11px]">Sichere alle Notizen, Aufgaben, Listen und Metadaten als JSON.</p>
|
||||||
|
</div>
|
||||||
|
<button onClick={handleExportData} className="btn-action h-8 px-3 text-xs flex items-center gap-1.5">
|
||||||
|
<Download className="w-3.5 h-3.5 text-accent" />
|
||||||
|
<span>Backup herunterladen</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* TAB 4: ORGANISATIONEN & TEAMS */}
|
||||||
|
{activeTab === 'teams' && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<h3 className="text-sm font-semibold text-white mb-1">Organisationen & Teams gründen</h3>
|
||||||
|
<p className="text-zinc-400 text-xs">
|
||||||
|
Erstelle Organisationen und unterteile sie in Teams, um Aufgabenlisten und Workspace-Dokumente gemeinsam zu bearbeiten.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Org Creator */}
|
||||||
|
<div className="p-3 bg-canvas border border-border space-y-2">
|
||||||
|
<h4 className="font-semibold text-white">Neue Organisation</h4>
|
||||||
|
<form onSubmit={handleCreateOrg} className="flex gap-2">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={newOrgName}
|
||||||
|
onChange={(e) => setNewOrgName(e.target.value)}
|
||||||
|
placeholder="Name der Organisation (z.B. Familie, Startup, Homelab Crew)…"
|
||||||
|
className="flex-1 h-8 px-2.5 input-field text-xs text-white"
|
||||||
|
/>
|
||||||
|
<button type="submit" className="btn-primary h-8 px-3 text-xs">
|
||||||
|
Organisation anlegen
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Team Creator inside Org */}
|
||||||
|
{orgs.length > 0 && (
|
||||||
|
<div className="p-3 bg-canvas border border-border space-y-2">
|
||||||
|
<h4 className="font-semibold text-white">Neues Team in Organisation</h4>
|
||||||
|
<form onSubmit={handleCreateTeam} className="space-y-2">
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<select
|
||||||
|
value={selectedOrgId}
|
||||||
|
onChange={(e) => setSelectedOrgId(e.target.value)}
|
||||||
|
className="h-8 px-2 input-field text-white bg-panel"
|
||||||
|
>
|
||||||
|
{orgs.map((o) => (
|
||||||
|
<option key={o.id} value={o.id}>
|
||||||
|
{o.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={newTeamName}
|
||||||
|
onChange={(e) => setNewTeamName(e.target.value)}
|
||||||
|
placeholder="Team Name (z.B. DevOps, Einkauf)…"
|
||||||
|
required
|
||||||
|
className="flex-1 h-8 px-2.5 input-field text-xs text-white"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={newTeamDesc}
|
||||||
|
onChange={(e) => setNewTeamDesc(e.target.value)}
|
||||||
|
placeholder="Optionale Teambeschreibung…"
|
||||||
|
className="flex-1 h-8 px-2.5 input-field text-xs text-white"
|
||||||
|
/>
|
||||||
|
<button type="submit" className="btn-primary h-8 px-3 text-xs">
|
||||||
|
Team erstellen
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Active Teams List */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<h4 className="font-semibold text-zinc-300">Deine Teams ({teams.length}):</h4>
|
||||||
|
<div className="border border-border divide-y divide-border bg-canvas">
|
||||||
|
{teams.length === 0 ? (
|
||||||
|
<div className="p-3 text-center text-zinc-500">Du bist noch keinem Team beigetreten.</div>
|
||||||
|
) : (
|
||||||
|
teams.map((t) => (
|
||||||
|
<div key={t.id} className="p-2.5 flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<p className="font-bold text-white flex items-center gap-1.5">
|
||||||
|
<Users className="w-3.5 h-3.5 text-accent" />
|
||||||
|
<span>{t.name}</span>
|
||||||
|
</p>
|
||||||
|
{t.description && <p className="text-zinc-400 text-[11px]">{t.description}</p>}
|
||||||
|
</div>
|
||||||
|
<span className="text-[10px] text-zinc-500 font-mono">ID: {t.id}</span>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* TAB 5: ADMIN BEREICH */}
|
||||||
|
{activeTab === 'admin' && currentUser?.role === 'admin' && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<h3 className="text-sm font-semibold text-white mb-1">Server-Administration & Benutzersteuerung</h3>
|
||||||
|
<p className="text-zinc-400 text-xs">
|
||||||
|
Steuere die Instanz-Einstellungen, das Sharing-Verhalten und verwalte registrierte Benutzer.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Server Sharing Isolation Setting */}
|
||||||
|
<div className="p-3 bg-canvas border border-border space-y-3">
|
||||||
|
<h4 className="font-semibold text-white flex items-center gap-1.5">
|
||||||
|
<Share2 className="w-3.5 h-3.5 text-accent" />
|
||||||
|
<span>Sharing-Isolationsmodus</span>
|
||||||
|
</h4>
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => handleUpdateSystemSettings({ sharingMode: 'open' })}
|
||||||
|
className={`p-2.5 text-left border transition-colors ${
|
||||||
|
systemSettings.sharingMode === 'open'
|
||||||
|
? 'bg-panel border-accent text-white'
|
||||||
|
: 'border-border text-zinc-400 hover:text-white'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<p className="font-bold text-xs">Offen (Open)</p>
|
||||||
|
<p className="text-[10px] text-zinc-400 mt-0.5">Alle Benutzer können Spaces finden und beitreten.</p>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => handleUpdateSystemSettings({ sharingMode: 'teams_only' })}
|
||||||
|
className={`p-2.5 text-left border transition-colors ${
|
||||||
|
systemSettings.sharingMode === 'teams_only'
|
||||||
|
? 'bg-panel border-accent text-white'
|
||||||
|
: 'border-border text-zinc-400 hover:text-white'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<p className="font-bold text-xs">Teams isoliert</p>
|
||||||
|
<p className="text-[10px] text-zinc-400 mt-0.5">Sharing ausschließlich innerhalb zugewiesener Teams.</p>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => handleUpdateSystemSettings({ sharingMode: 'strict_private' })}
|
||||||
|
className={`p-2.5 text-left border transition-colors ${
|
||||||
|
systemSettings.sharingMode === 'strict_private'
|
||||||
|
? 'bg-panel border-accent text-white'
|
||||||
|
: 'border-border text-zinc-400 hover:text-white'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<p className="font-bold text-xs">Strikt Privat</p>
|
||||||
|
<p className="text-[10px] text-zinc-400 mt-0.5">Vollständige Benutzer-Isolation; kein Teilen möglich.</p>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between pt-2 border-t border-border">
|
||||||
|
<span className="text-zinc-300">Öffentliche Registrierung erlauben:</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() =>
|
||||||
|
handleUpdateSystemSettings({ allowRegistration: !systemSettings.allowRegistration })
|
||||||
|
}
|
||||||
|
className={`px-3 py-1 text-xs border ${
|
||||||
|
systemSettings.allowRegistration
|
||||||
|
? 'bg-accent/20 border-accent text-accent'
|
||||||
|
: 'bg-zinc-800 border-zinc-700 text-zinc-400'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{systemSettings.allowRegistration ? 'Aktiviert' : 'Deaktiviert'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* User Creation by Admin */}
|
||||||
|
<div className="p-3 bg-canvas border border-border space-y-2">
|
||||||
|
<h4 className="font-semibold text-white">Neuen Benutzer anlegen</h4>
|
||||||
|
<form onSubmit={handleAdminCreateUser} className="space-y-2">
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
|
||||||
|
<input
|
||||||
|
type="email"
|
||||||
|
value={newAdminUserEmail}
|
||||||
|
onChange={(e) => setNewAdminUserEmail(e.target.value)}
|
||||||
|
placeholder="E-Mail"
|
||||||
|
required
|
||||||
|
className="h-8 px-2.5 input-field text-white"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={newAdminUserPassword}
|
||||||
|
onChange={(e) => setNewAdminUserPassword(e.target.value)}
|
||||||
|
placeholder="Initial-Passwort"
|
||||||
|
required
|
||||||
|
className="h-8 px-2.5 input-field text-white"
|
||||||
|
/>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={newAdminUserDisplayName}
|
||||||
|
onChange={(e) => setNewAdminUserDisplayName(e.target.value)}
|
||||||
|
placeholder="Anzeigename"
|
||||||
|
className="flex-1 h-8 px-2.5 input-field text-white"
|
||||||
|
/>
|
||||||
|
<select
|
||||||
|
value={newAdminUserRole}
|
||||||
|
onChange={(e) => setNewAdminUserRole(e.target.value as any)}
|
||||||
|
className="h-8 px-2 input-field text-white bg-panel"
|
||||||
|
>
|
||||||
|
<option value="member">Member</option>
|
||||||
|
<option value="admin">Admin</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-end">
|
||||||
|
<button type="submit" className="btn-primary h-7 px-3 text-xs">
|
||||||
|
Benutzer erstellen
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Users Table */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<h4 className="font-semibold text-zinc-300">Registrierte Benutzer ({adminUsers.length}):</h4>
|
||||||
|
<div className="border border-border divide-y divide-border bg-canvas overflow-x-auto">
|
||||||
|
{adminUsers.map((u) => (
|
||||||
|
<div key={u.id} className="p-2.5 flex items-center justify-between gap-3 text-xs">
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="font-bold text-white">{u.displayName}</span>
|
||||||
|
<span
|
||||||
|
className={`px-1.5 py-0.2 text-[10px] uppercase font-bold border ${
|
||||||
|
u.role === 'admin'
|
||||||
|
? 'bg-accent/20 border-accent/40 text-accent'
|
||||||
|
: 'bg-zinc-800 border-zinc-700 text-zinc-400'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{u.role}
|
||||||
|
</span>
|
||||||
|
{!u.isActive && (
|
||||||
|
<span className="px-1.5 py-0.2 text-[10px] bg-red-900/30 border border-red-500/40 text-red-300">
|
||||||
|
Deaktiviert
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<p className="text-zinc-500 text-[11px] font-mono">{u.email}</p>
|
||||||
|
|
||||||
|
{/* Reset password inline form */}
|
||||||
|
{resetPwdUserId === u.id && (
|
||||||
|
<div className="mt-2 flex items-center gap-1.5 bg-panel p-1.5 border border-border">
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={resetPwdVal}
|
||||||
|
onChange={(e) => setResetPwdVal(e.target.value)}
|
||||||
|
placeholder="Neues Passwort…"
|
||||||
|
className="h-6 px-2 input-field text-xs text-white"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
onClick={() => handleConfirmResetPassword(u.id)}
|
||||||
|
className="btn-primary h-6 px-2 text-[10px]"
|
||||||
|
>
|
||||||
|
Speichern
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setResetPwdUserId(null)}
|
||||||
|
className="btn-action h-6 px-1.5 text-[10px]"
|
||||||
|
>
|
||||||
|
Abbrechen
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-1.5 flex-shrink-0">
|
||||||
|
<button
|
||||||
|
onClick={() => handleToggleUserActive(u)}
|
||||||
|
className="btn-action h-7 px-2 text-[11px]"
|
||||||
|
title="Aktiv / Deaktivieren"
|
||||||
|
>
|
||||||
|
{u.isActive ? 'Deaktivieren' : 'Aktivieren'}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => handleToggleUserRole(u)}
|
||||||
|
className="btn-action h-7 px-2 text-[11px]"
|
||||||
|
title="Rolle wechseln"
|
||||||
|
>
|
||||||
|
{u.role === 'admin' ? 'Zu Member' : 'Zu Admin'}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
setResetPwdUserId(u.id);
|
||||||
|
setResetPwdVal('');
|
||||||
|
}}
|
||||||
|
className="btn-action h-7 px-2 text-[11px]"
|
||||||
|
title="Passwort zurücksetzen"
|
||||||
|
>
|
||||||
|
<Lock className="w-3 h-3 text-zinc-400" />
|
||||||
|
</button>
|
||||||
|
{u.id !== currentUser.id && (
|
||||||
|
<button
|
||||||
|
onClick={() => handleAdminDeleteUser(u.id)}
|
||||||
|
className="btn-icon btn-icon-danger"
|
||||||
|
title="Benutzer löschen"
|
||||||
|
>
|
||||||
|
<Trash2 className="w-3.5 h-3.5" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,4 @@
|
|||||||
import React, { useEffect, useState, useMemo } from 'react';
|
import React, { useEffect, useState, useMemo, useRef } from 'react';
|
||||||
import {
|
import {
|
||||||
FilePlus,
|
FilePlus,
|
||||||
FolderPlus,
|
FolderPlus,
|
||||||
@@ -14,6 +14,7 @@ import {
|
|||||||
CheckSquare,
|
CheckSquare,
|
||||||
Heading1,
|
Heading1,
|
||||||
Heading2,
|
Heading2,
|
||||||
|
Heading3,
|
||||||
List,
|
List,
|
||||||
Code,
|
Code,
|
||||||
Sparkles,
|
Sparkles,
|
||||||
@@ -22,6 +23,14 @@ import {
|
|||||||
X,
|
X,
|
||||||
ArrowUp,
|
ArrowUp,
|
||||||
ArrowDown,
|
ArrowDown,
|
||||||
|
Bold,
|
||||||
|
Italic,
|
||||||
|
Strikethrough,
|
||||||
|
Link,
|
||||||
|
Table as TableIcon,
|
||||||
|
Percent,
|
||||||
|
Minus,
|
||||||
|
ExternalLink,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import { BlockType, Document, DocumentBlock } from '../../lib/types';
|
import { BlockType, Document, DocumentBlock } from '../../lib/types';
|
||||||
import { api, triggerHaptic } from '../../lib/api';
|
import { api, triggerHaptic } from '../../lib/api';
|
||||||
@@ -31,7 +40,7 @@ interface WorkspaceViewProps {
|
|||||||
onStatsChange: () => void;
|
onStatsChange: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const ICONS = ['🚀', '💡', '📄', '🏡', '⚡', '🎯', '🍕', '🛠️', '🧠', '🔥', '🏔️', '📦'];
|
const ICONS = ['🚀', '💡', '📄', '🏡', '⚡', '🎯', '🍕', '🛠️', '🧠', '🔥', '🏔️', '📦', '📑', '⚙️', '📊'];
|
||||||
|
|
||||||
interface FolderTreeItem {
|
interface FolderTreeItem {
|
||||||
path: string;
|
path: string;
|
||||||
@@ -50,6 +59,7 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
|
|||||||
const [searchQuery, setSearchQuery] = useState('');
|
const [searchQuery, setSearchQuery] = useState('');
|
||||||
const [saveState, setSaveState] = useState<'saved' | 'saving'>('saved');
|
const [saveState, setSaveState] = useState<'saved' | 'saving'>('saved');
|
||||||
const [showIconPicker, setShowIconPicker] = useState(false);
|
const [showIconPicker, setShowIconPicker] = useState(false);
|
||||||
|
const [showWikiLinkMenu, setShowWikiLinkMenu] = useState(false);
|
||||||
|
|
||||||
// Folder state
|
// Folder state
|
||||||
const [customFolders, setCustomFolders] = useState<string[]>(() => {
|
const [customFolders, setCustomFolders] = useState<string[]>(() => {
|
||||||
@@ -65,6 +75,9 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
|
|||||||
const [newFolderParent, setNewFolderParent] = useState<string | null>(null);
|
const [newFolderParent, setNewFolderParent] = useState<string | null>(null);
|
||||||
const [newFolderName, setNewFolderName] = useState('');
|
const [newFolderName, setNewFolderName] = useState('');
|
||||||
|
|
||||||
|
// Active focused block ref
|
||||||
|
const [lastFocusedBlockId, setLastFocusedBlockId] = useState<string | null>(null);
|
||||||
|
|
||||||
const loadDocs = async (selectId?: string | null) => {
|
const loadDocs = async (selectId?: string | null) => {
|
||||||
const list = await api.getDocuments();
|
const list = await api.getDocuments();
|
||||||
setDocs(list);
|
setDocs(list);
|
||||||
@@ -95,6 +108,7 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
|
|||||||
await api.updateDocument(updatedDoc.id, {
|
await api.updateDocument(updatedDoc.id, {
|
||||||
title: updatedDoc.title,
|
title: updatedDoc.title,
|
||||||
icon: updatedDoc.icon,
|
icon: updatedDoc.icon,
|
||||||
|
folderPath: updatedDoc.folderPath,
|
||||||
blocks: updatedDoc.blocks,
|
blocks: updatedDoc.blocks,
|
||||||
tags: updatedDoc.tags,
|
tags: updatedDoc.tags,
|
||||||
isPinned: updatedDoc.isPinned,
|
isPinned: updatedDoc.isPinned,
|
||||||
@@ -105,6 +119,7 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
|
|||||||
};
|
};
|
||||||
|
|
||||||
const getDocFolder = (doc: Document): string => {
|
const getDocFolder = (doc: Document): string => {
|
||||||
|
if (doc.folderPath) return doc.folderPath;
|
||||||
const tag = doc.tags?.find((t) => t.startsWith('folder:'));
|
const tag = doc.tags?.find((t) => t.startsWith('folder:'));
|
||||||
return tag ? tag.replace('folder:', '') : '';
|
return tag ? tag.replace('folder:', '') : '';
|
||||||
};
|
};
|
||||||
@@ -138,12 +153,14 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
|
|||||||
const handleCreateDoc = async (folderPath?: string | null) => {
|
const handleCreateDoc = async (folderPath?: string | null) => {
|
||||||
triggerHaptic(15);
|
triggerHaptic(15);
|
||||||
const tags = ['projekt'];
|
const tags = ['projekt'];
|
||||||
if (folderPath) {
|
const path = folderPath || '';
|
||||||
tags.push(`folder:${folderPath}`);
|
if (path) {
|
||||||
|
tags.push(`folder:${path}`);
|
||||||
}
|
}
|
||||||
const created = await api.createDocument({
|
const created = await api.createDocument({
|
||||||
title: 'Neues Projekt / Notiz',
|
title: 'Neues Projekt / Notiz',
|
||||||
icon: '💡',
|
icon: '💡',
|
||||||
|
folderPath: path,
|
||||||
blocks: [
|
blocks: [
|
||||||
{
|
{
|
||||||
id: `blk_${Date.now()}_1`,
|
id: `blk_${Date.now()}_1`,
|
||||||
@@ -158,100 +175,74 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
|
|||||||
{
|
{
|
||||||
id: `blk_${Date.now()}_3`,
|
id: `blk_${Date.now()}_3`,
|
||||||
type: 'todo',
|
type: 'todo',
|
||||||
content: 'Ersten Punkt abhaken',
|
content: 'Ersten Meilenstein definieren',
|
||||||
checked: false,
|
checked: false,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
tags,
|
tags,
|
||||||
|
isPinned: false,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (folderPath) {
|
|
||||||
setExpandedFolders((prev) => {
|
|
||||||
const next = new Set(prev);
|
|
||||||
next.add(folderPath);
|
|
||||||
return next;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
await loadDocs(created.id);
|
await loadDocs(created.id);
|
||||||
onStatsChange();
|
onStatsChange();
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDeleteDoc = async (docId: string) => {
|
const handleDeleteDoc = async (id: string) => {
|
||||||
|
if (!window.confirm('Dokument wirklich löschen?')) return;
|
||||||
triggerHaptic(20);
|
triggerHaptic(20);
|
||||||
await api.deleteDocument(docId);
|
await api.deleteDocument(id);
|
||||||
const remaining = docs.filter((d) => d.id !== docId);
|
const remaining = docs.filter((d) => d.id !== id);
|
||||||
setDocs(remaining);
|
setDocs(remaining);
|
||||||
setSelectedDoc(remaining[0] || null);
|
setSelectedDoc(remaining[0] || null);
|
||||||
onStatsChange();
|
onStatsChange();
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleChangeDocFolder = (targetFolder: string) => {
|
const handleChangeDocFolder = async (folderPath: string) => {
|
||||||
if (!selectedDoc) return;
|
if (!selectedDoc) return;
|
||||||
const cleanTags = (selectedDoc.tags || []).filter((t) => !t.startsWith('folder:'));
|
const cleanPath = folderPath.trim();
|
||||||
if (targetFolder) {
|
const updatedTags = (selectedDoc.tags || []).filter((t) => !t.startsWith('folder:'));
|
||||||
cleanTags.push(`folder:${targetFolder}`);
|
if (cleanPath) {
|
||||||
|
updatedTags.push(`folder:${cleanPath}`);
|
||||||
}
|
}
|
||||||
persistDocument({ ...selectedDoc, tags: cleanTags });
|
const updatedDoc = {
|
||||||
|
...selectedDoc,
|
||||||
|
folderPath: cleanPath,
|
||||||
|
tags: updatedTags,
|
||||||
|
};
|
||||||
|
await persistDocument(updatedDoc);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleStartCreateFolder = (parentPath: string | null = null) => {
|
const handleStartCreateFolder = (parentPath?: string | null) => {
|
||||||
triggerHaptic(10);
|
setNewFolderParent(parentPath || null);
|
||||||
setNewFolderParent(parentPath);
|
|
||||||
setNewFolderName('');
|
setNewFolderName('');
|
||||||
setIsCreatingFolder(true);
|
setIsCreatingFolder(true);
|
||||||
|
if (parentPath) {
|
||||||
|
setExpandedFolders((prev) => new Set([...prev, parentPath]));
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleConfirmCreateFolder = () => {
|
const handleConfirmCreateFolder = () => {
|
||||||
const trimmed = newFolderName.trim().replace(/^\/+|\/+$/g, '');
|
const trimmed = newFolderName.trim();
|
||||||
if (!trimmed) {
|
if (!trimmed) {
|
||||||
setIsCreatingFolder(false);
|
setIsCreatingFolder(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const fullPath = newFolderParent ? `${newFolderParent}/${trimmed}` : trimmed;
|
const fullPath = newFolderParent ? `${newFolderParent}/${trimmed}` : trimmed;
|
||||||
if (!customFolders.includes(fullPath)) {
|
if (!customFolders.includes(fullPath)) {
|
||||||
const updated = [...customFolders, fullPath];
|
const next = [...customFolders, fullPath].sort((a, b) => a.localeCompare(b));
|
||||||
setCustomFolders(updated);
|
setCustomFolders(next);
|
||||||
try {
|
try {
|
||||||
localStorage.setItem('mindsift_workspace_folders', JSON.stringify(updated));
|
localStorage.setItem('mindsift_workspace_folders', JSON.stringify(next));
|
||||||
} catch {
|
} catch {
|
||||||
// fallback
|
// ignore
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
setExpandedFolders((prev) => {
|
setExpandedFolders((prev) => new Set([...prev, fullPath]));
|
||||||
const next = new Set(prev);
|
|
||||||
next.add(fullPath);
|
|
||||||
if (newFolderParent) next.add(newFolderParent);
|
|
||||||
return next;
|
|
||||||
});
|
|
||||||
setIsCreatingFolder(false);
|
setIsCreatingFolder(false);
|
||||||
setNewFolderName('');
|
setNewFolderName('');
|
||||||
setNewFolderParent(null);
|
setNewFolderParent(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDeleteFolder = (folderPath: string, e: React.MouseEvent) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
triggerHaptic(15);
|
|
||||||
const updated = customFolders.filter(
|
|
||||||
(p) => p !== folderPath && !p.startsWith(folderPath + '/')
|
|
||||||
);
|
|
||||||
setCustomFolders(updated);
|
|
||||||
try {
|
|
||||||
localStorage.setItem('mindsift_workspace_folders', JSON.stringify(updated));
|
|
||||||
} catch {
|
|
||||||
// fallback
|
|
||||||
}
|
|
||||||
|
|
||||||
// Keep docs safe: drop folder prefix so they fall back to root
|
|
||||||
docs.forEach((d) => {
|
|
||||||
const f = getDocFolder(d);
|
|
||||||
if (f === folderPath || f.startsWith(folderPath + '/')) {
|
|
||||||
const nextTags = (d.tags || []).filter((t) => !t.startsWith('folder:'));
|
|
||||||
persistDocument({ ...d, tags: nextTags });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const toggleFolder = (folderPath: string) => {
|
const toggleFolder = (folderPath: string) => {
|
||||||
setExpandedFolders((prev) => {
|
setExpandedFolders((prev) => {
|
||||||
const next = new Set(prev);
|
const next = new Set(prev);
|
||||||
@@ -264,12 +255,12 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const addBlock = (type: BlockType, afterIndex?: number) => {
|
const addBlock = (type: BlockType, afterIndex?: number, defaultContent = '') => {
|
||||||
if (!selectedDoc) return;
|
if (!selectedDoc) return;
|
||||||
const newBlock: DocumentBlock = {
|
const newBlock: DocumentBlock = {
|
||||||
id: `blk_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`,
|
id: `blk_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`,
|
||||||
type,
|
type,
|
||||||
content: '',
|
content: defaultContent,
|
||||||
checked: false,
|
checked: false,
|
||||||
lang: type === 'code' ? 'bash' : undefined,
|
lang: type === 'code' ? 'bash' : undefined,
|
||||||
};
|
};
|
||||||
@@ -282,6 +273,7 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
|
|||||||
}
|
}
|
||||||
|
|
||||||
persistDocument({ ...selectedDoc, blocks: nextBlocks });
|
persistDocument({ ...selectedDoc, blocks: nextBlocks });
|
||||||
|
setLastFocusedBlockId(newBlock.id);
|
||||||
};
|
};
|
||||||
|
|
||||||
const updateBlock = (blockId: string, patch: Partial<DocumentBlock>) => {
|
const updateBlock = (blockId: string, patch: Partial<DocumentBlock>) => {
|
||||||
@@ -308,6 +300,32 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
|
|||||||
persistDocument({ ...selectedDoc, blocks: nextBlocks });
|
persistDocument({ ...selectedDoc, blocks: nextBlocks });
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// --- TOP TOOLBAR FORMATTING HELPERS ---
|
||||||
|
const applyInlineFormat = (prefix: string, suffix = prefix) => {
|
||||||
|
if (!selectedDoc) return;
|
||||||
|
const targetBlockId = lastFocusedBlockId || selectedDoc.blocks[selectedDoc.blocks.length - 1]?.id;
|
||||||
|
if (!targetBlockId) return;
|
||||||
|
|
||||||
|
const block = selectedDoc.blocks.find((b) => b.id === targetBlockId);
|
||||||
|
if (!block) return;
|
||||||
|
|
||||||
|
const newContent = `${block.content} ${prefix}Text${suffix}`;
|
||||||
|
updateBlock(targetBlockId, { content: newContent });
|
||||||
|
};
|
||||||
|
|
||||||
|
const insertWikiLink = (targetDocTitle: string) => {
|
||||||
|
if (!selectedDoc) return;
|
||||||
|
const targetBlockId = lastFocusedBlockId || selectedDoc.blocks[selectedDoc.blocks.length - 1]?.id;
|
||||||
|
if (!targetBlockId) return;
|
||||||
|
|
||||||
|
const block = selectedDoc.blocks.find((b) => b.id === targetBlockId);
|
||||||
|
if (!block) return;
|
||||||
|
|
||||||
|
const newContent = `${block.content} [[${targetDocTitle}]]`;
|
||||||
|
updateBlock(targetBlockId, { content: newContent });
|
||||||
|
setShowWikiLinkMenu(false);
|
||||||
|
};
|
||||||
|
|
||||||
const handleExportMarkdown = () => {
|
const handleExportMarkdown = () => {
|
||||||
if (!selectedDoc) return;
|
if (!selectedDoc) return;
|
||||||
const lines: string[] = [`# ${selectedDoc.icon} ${selectedDoc.title}`, ''];
|
const lines: string[] = [`# ${selectedDoc.icon} ${selectedDoc.title}`, ''];
|
||||||
@@ -334,6 +352,15 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
|
|||||||
case 'code':
|
case 'code':
|
||||||
lines.push('```' + (b.lang || ''), b.content, '```', '');
|
lines.push('```' + (b.lang || ''), b.content, '```', '');
|
||||||
break;
|
break;
|
||||||
|
case 'table':
|
||||||
|
lines.push(b.content, '');
|
||||||
|
break;
|
||||||
|
case 'progress':
|
||||||
|
lines.push(`<!-- progress: ${b.content} -->`, '');
|
||||||
|
break;
|
||||||
|
case 'divider':
|
||||||
|
lines.push('---', '');
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
lines.push(b.content, '');
|
lines.push(b.content, '');
|
||||||
}
|
}
|
||||||
@@ -348,75 +375,118 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
|
|||||||
URL.revokeObjectURL(url);
|
URL.revokeObjectURL(url);
|
||||||
};
|
};
|
||||||
|
|
||||||
const filteredDocs = docs.filter(
|
// Helper to render text with clickable Wiki-Links
|
||||||
(d) =>
|
const renderTextWithWikiLinks = (text: string) => {
|
||||||
d.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
const parts = text.split(/(\[\[.*?\]\])/g);
|
||||||
(d.content && d.content.toLowerCase().includes(searchQuery.toLowerCase()))
|
return parts.map((part, i) => {
|
||||||
);
|
if (part.startsWith('[[') && part.endsWith(']]')) {
|
||||||
|
const linkTitle = part.slice(2, -2).trim();
|
||||||
// Build recursive folder tree
|
const target = docs.find((d) => d.title.toLowerCase() === linkTitle.toLowerCase());
|
||||||
const buildTree = (parentPath: string = '', depth: number = 0): FolderTreeItem[] => {
|
return (
|
||||||
const directChildren = allFolderPaths.filter((p) => {
|
<span
|
||||||
if (parentPath === '') {
|
key={i}
|
||||||
return !p.includes('/');
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
if (target) setSelectedDoc(target);
|
||||||
|
}}
|
||||||
|
className={`inline-flex items-center gap-1 px-1.5 py-0.2 mx-0.5 border text-xs font-medium cursor-pointer transition-colors ${
|
||||||
|
target
|
||||||
|
? 'bg-accent/20 border-accent/40 text-accent hover:bg-accent/30'
|
||||||
|
: 'bg-zinc-800 border-zinc-700 text-zinc-400 hover:text-white'
|
||||||
|
}`}
|
||||||
|
title={target ? `Öffne: ${target.title}` : `Dokument "${linkTitle}" existiert noch nicht`}
|
||||||
|
>
|
||||||
|
<span>📄</span>
|
||||||
|
<span>{linkTitle}</span>
|
||||||
|
<ExternalLink className="w-2.5 h-2.5 opacity-60" />
|
||||||
|
</span>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
return p.startsWith(parentPath + '/') && !p.slice(parentPath.length + 1).includes('/');
|
return <span key={i}>{part}</span>;
|
||||||
});
|
|
||||||
|
|
||||||
return directChildren.map((p) => {
|
|
||||||
const name = p.split('/').pop() || p;
|
|
||||||
const matchingDocs = filteredDocs.filter((d) => getDocFolder(d) === p);
|
|
||||||
return {
|
|
||||||
path: p,
|
|
||||||
name,
|
|
||||||
depth,
|
|
||||||
subfolders: buildTree(p, depth + 1),
|
|
||||||
docs: matchingDocs,
|
|
||||||
};
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const rootTree = useMemo(() => buildTree('', 0), [allFolderPaths, filteredDocs]);
|
// --- FOLDER TREE CALCULATION ---
|
||||||
const rootDocs = useMemo(
|
const filteredDocs = useMemo(() => {
|
||||||
() => filteredDocs.filter((d) => !getDocFolder(d)),
|
if (!searchQuery.trim()) return docs;
|
||||||
[filteredDocs]
|
const q = searchQuery.toLowerCase();
|
||||||
);
|
return docs.filter(
|
||||||
|
(d) => d.title.toLowerCase().includes(q) || d.content.toLowerCase().includes(q)
|
||||||
|
);
|
||||||
|
}, [docs, searchQuery]);
|
||||||
|
|
||||||
const renderDocItem = (doc: Document, depth: number = 0) => {
|
const { rootTree, rootDocs } = useMemo(() => {
|
||||||
const active = selectedDoc?.id === doc.id;
|
const folderMap = new Map<string, FolderTreeItem>();
|
||||||
|
|
||||||
|
allFolderPaths.forEach((path) => {
|
||||||
|
const parts = path.split('/');
|
||||||
|
const name = parts[parts.length - 1];
|
||||||
|
folderMap.set(path, {
|
||||||
|
path,
|
||||||
|
name,
|
||||||
|
depth: parts.length - 1,
|
||||||
|
subfolders: [],
|
||||||
|
docs: [],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
filteredDocs.forEach((doc) => {
|
||||||
|
const folder = getDocFolder(doc);
|
||||||
|
if (folder && folderMap.has(folder)) {
|
||||||
|
folderMap.get(folder)!.docs.push(doc);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const rootFolders: FolderTreeItem[] = [];
|
||||||
|
allFolderPaths.forEach((path) => {
|
||||||
|
const item = folderMap.get(path)!;
|
||||||
|
const lastSlash = path.lastIndexOf('/');
|
||||||
|
if (lastSlash === -1) {
|
||||||
|
rootFolders.push(item);
|
||||||
|
} else {
|
||||||
|
const parentPath = path.substring(0, lastSlash);
|
||||||
|
const parent = folderMap.get(parentPath);
|
||||||
|
if (parent) {
|
||||||
|
parent.subfolders.push(item);
|
||||||
|
} else {
|
||||||
|
rootFolders.push(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const rootOnlyDocs = filteredDocs.filter((d) => !getDocFolder(d));
|
||||||
|
return { rootTree: rootFolders, rootDocs: rootOnlyDocs };
|
||||||
|
}, [allFolderPaths, filteredDocs]);
|
||||||
|
|
||||||
|
const renderDocItem = (doc: Document, depth: number) => {
|
||||||
|
const isSelected = selectedDoc?.id === doc.id;
|
||||||
return (
|
return (
|
||||||
<button
|
<div
|
||||||
key={doc.id}
|
key={doc.id}
|
||||||
type="button"
|
|
||||||
onClick={() => setSelectedDoc(doc)}
|
onClick={() => setSelectedDoc(doc)}
|
||||||
style={{ paddingLeft: `${depth * 14 + 10}px` }}
|
style={{ paddingLeft: `${depth * 14 + 16}px` }}
|
||||||
className={`w-full text-left py-1.5 pr-2 transition-colors flex items-center justify-between gap-2 border-l-2 ${
|
className={`group flex items-center justify-between py-1.5 pr-2 border-l-2 transition-colors cursor-pointer text-xs ${
|
||||||
active
|
isSelected
|
||||||
? 'tree-node-active'
|
? 'bg-panel-elevated border-accent text-white font-medium'
|
||||||
: 'border-l-transparent text-zinc-300 hover:bg-panel-elevated hover:text-white'
|
: 'border-transparent text-zinc-400 hover:text-white hover:bg-white/[0.02]'
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
<div className="flex items-center gap-1.5 min-w-0">
|
<div className="flex items-center gap-2 min-w-0 flex-1">
|
||||||
<span className="text-xs leading-none flex-shrink-0">
|
<span className="text-sm flex-shrink-0">{doc.icon}</span>
|
||||||
{doc.icon ? doc.icon : <FileText className="w-3.5 h-3.5 text-zinc-400" />}
|
<span className="truncate">{doc.title || 'Unbenannt'}</span>
|
||||||
</span>
|
{doc.isPinned && <Pin className="w-2.5 h-2.5 text-accent flex-shrink-0" />}
|
||||||
<span className="text-xs truncate font-normal">{doc.title || 'Ohne Titel'}</span>
|
|
||||||
</div>
|
</div>
|
||||||
{doc.isPinned && <Pin className="w-3 h-3 text-accent flex-shrink-0" />}
|
</div>
|
||||||
</button>
|
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const renderFolder = (node: FolderTreeItem) => {
|
const renderFolder = (node: FolderTreeItem): React.ReactNode => {
|
||||||
const isExpanded = expandedFolders.has(node.path);
|
const isExpanded = expandedFolders.has(node.path);
|
||||||
const isCreatingSubfolder = isCreatingFolder && newFolderParent === node.path;
|
const isCreatingSubfolder = isCreatingFolder && newFolderParent === node.path;
|
||||||
const totalItems =
|
const totalItems = node.docs.length + node.subfolders.length;
|
||||||
node.docs.length +
|
|
||||||
node.subfolders.reduce((acc, s) => acc + s.docs.length, 0);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div key={node.path} className="select-none">
|
<div key={node.path} className="select-none">
|
||||||
{/* Folder Header Row */}
|
|
||||||
<div
|
<div
|
||||||
onClick={() => toggleFolder(node.path)}
|
onClick={() => toggleFolder(node.path)}
|
||||||
style={{ paddingLeft: `${node.depth * 14 + 8}px` }}
|
style={{ paddingLeft: `${node.depth * 14 + 8}px` }}
|
||||||
@@ -439,7 +509,6 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
|
|||||||
<span className="text-[10px] text-zinc-500 font-mono">({totalItems})</span>
|
<span className="text-[10px] text-zinc-500 font-mono">({totalItems})</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Folder Actions on Hover */}
|
|
||||||
<div className="opacity-0 group-hover:opacity-100 flex items-center gap-1 transition-opacity">
|
<div className="opacity-0 group-hover:opacity-100 flex items-center gap-1 transition-opacity">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -463,24 +532,15 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
|
|||||||
>
|
>
|
||||||
<FolderPlus className="w-3 h-3" />
|
<FolderPlus className="w-3 h-3" />
|
||||||
</button>
|
</button>
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={(e) => handleDeleteFolder(node.path, e)}
|
|
||||||
className="p-1 hover:bg-red-500/20 text-zinc-500 hover:text-red-400"
|
|
||||||
title="Ordner entfernen"
|
|
||||||
>
|
|
||||||
<Trash2 className="w-3 h-3" />
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Subfolder inline creation input */}
|
|
||||||
{isCreatingSubfolder && (
|
{isCreatingSubfolder && (
|
||||||
<div
|
<div
|
||||||
style={{ paddingLeft: `${(node.depth + 1) * 14 + 8}px` }}
|
style={{ paddingLeft: `${(node.depth + 1) * 14 + 8}px` }}
|
||||||
className="py-1 pr-2 flex items-center gap-1.5 bg-canvas"
|
className="py-1 pr-2 flex items-center gap-1 bg-canvas"
|
||||||
>
|
>
|
||||||
<Folder className="w-3.5 h-3.5 text-zinc-400 flex-shrink-0" />
|
<Folder className="w-3 h-3 text-zinc-400 flex-shrink-0" />
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
autoFocus
|
autoFocus
|
||||||
@@ -490,8 +550,8 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
|
|||||||
if (e.key === 'Enter') handleConfirmCreateFolder();
|
if (e.key === 'Enter') handleConfirmCreateFolder();
|
||||||
if (e.key === 'Escape') setIsCreatingFolder(false);
|
if (e.key === 'Escape') setIsCreatingFolder(false);
|
||||||
}}
|
}}
|
||||||
placeholder="Unterordnername…"
|
placeholder="Unterordner…"
|
||||||
className="flex-1 h-6 px-1.5 input-field"
|
className="flex-1 h-6 px-1.5 input-field text-xs"
|
||||||
/>
|
/>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -512,7 +572,6 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Expanded Folder Content */}
|
|
||||||
{isExpanded && (
|
{isExpanded && (
|
||||||
<div>
|
<div>
|
||||||
{node.subfolders.map(renderFolder)}
|
{node.subfolders.map(renderFolder)}
|
||||||
@@ -537,9 +596,7 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
|
|||||||
<div className="grid grid-cols-1 lg:grid-cols-12 gap-2">
|
<div className="grid grid-cols-1 lg:grid-cols-12 gap-2">
|
||||||
{/* Left Document & Folder Explorer Tree */}
|
{/* Left Document & Folder Explorer Tree */}
|
||||||
<div className="lg:col-span-4 panel-surface flex flex-col self-start">
|
<div className="lg:col-span-4 panel-surface flex flex-col self-start">
|
||||||
{/* Top Explorer Action Bar */}
|
|
||||||
<div className="p-2 panel-header space-y-2">
|
<div className="p-2 panel-header space-y-2">
|
||||||
{/* Quick Search */}
|
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<Search className="w-3.5 h-3.5 text-zinc-400 absolute left-2.5 top-1/2 -translate-y-1/2" />
|
<Search className="w-3.5 h-3.5 text-zinc-400 absolute left-2.5 top-1/2 -translate-y-1/2" />
|
||||||
<input
|
<input
|
||||||
@@ -551,7 +608,6 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Monochromatic Square Action Buttons */}
|
|
||||||
<div className="flex items-center gap-1.5">
|
<div className="flex items-center gap-1.5">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -575,7 +631,6 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Root Folder Creation Input */}
|
|
||||||
{isCreatingFolder && newFolderParent === null && (
|
{isCreatingFolder && newFolderParent === null && (
|
||||||
<div className="p-2 panel-header bg-canvas flex items-center gap-1.5">
|
<div className="p-2 panel-header bg-canvas flex items-center gap-1.5">
|
||||||
<Folder className="w-3.5 h-3.5 text-zinc-400 flex-shrink-0" />
|
<Folder className="w-3.5 h-3.5 text-zinc-400 flex-shrink-0" />
|
||||||
@@ -610,7 +665,6 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Empty State */}
|
|
||||||
{isEmpty ? (
|
{isEmpty ? (
|
||||||
<div className="p-6 my-3 mx-2 border border-dashed border-border bg-canvas/50 text-center">
|
<div className="p-6 my-3 mx-2 border border-dashed border-border bg-canvas/50 text-center">
|
||||||
<Folder className="w-7 h-7 text-zinc-600 mx-auto mb-2" />
|
<Folder className="w-7 h-7 text-zinc-600 mx-auto mb-2" />
|
||||||
@@ -638,7 +692,6 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
/* File Explorer Tree View */
|
|
||||||
<div className="py-1 max-h-[calc(100vh-240px)] overflow-y-auto">
|
<div className="py-1 max-h-[calc(100vh-240px)] overflow-y-auto">
|
||||||
{rootTree.map(renderFolder)}
|
{rootTree.map(renderFolder)}
|
||||||
{rootDocs.map((doc) => renderDocItem(doc, 0))}
|
{rootDocs.map((doc) => renderDocItem(doc, 0))}
|
||||||
@@ -651,25 +704,24 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Right Block Editor */}
|
{/* Right Word / Notion Formatted Editor */}
|
||||||
<div className="lg:col-span-8">
|
<div className="lg:col-span-8">
|
||||||
{selectedDoc ? (
|
{selectedDoc ? (
|
||||||
<div className="p-4 panel-surface">
|
<div className="p-4 panel-surface space-y-3">
|
||||||
{/* Document Top Action Bar */}
|
{/* Document Header & Metadata */}
|
||||||
<div className="flex flex-wrap items-center justify-between gap-3 pb-3 mb-3 panel-header">
|
<div className="flex flex-wrap items-center justify-between gap-3 pb-3 panel-header">
|
||||||
<div className="flex flex-wrap items-center gap-2 text-xs text-zinc-400">
|
<div className="flex flex-wrap items-center gap-2 text-xs text-zinc-400">
|
||||||
<span className="badge-accent">
|
<span className="badge-accent">
|
||||||
<Check className="w-3 h-3" />
|
<Check className="w-3 h-3" />
|
||||||
{saveState === 'saving' ? 'Speichert…' : 'Gespeichert'}
|
{saveState === 'saving' ? 'Speichert…' : 'Gespeichert'}
|
||||||
</span>
|
</span>
|
||||||
|
|
||||||
{/* Folder Breadcrumb Selector */}
|
|
||||||
<div className="flex items-center gap-1.5">
|
<div className="flex items-center gap-1.5">
|
||||||
<Folder className="w-3.5 h-3.5 text-zinc-500" />
|
<Folder className="w-3.5 h-3.5 text-zinc-500" />
|
||||||
<select
|
<select
|
||||||
value={getDocFolder(selectedDoc)}
|
value={getDocFolder(selectedDoc)}
|
||||||
onChange={(e) => handleChangeDocFolder(e.target.value)}
|
onChange={(e) => handleChangeDocFolder(e.target.value)}
|
||||||
className="input-field px-2 py-0.5"
|
className="input-field px-2 py-0.5 text-xs bg-canvas"
|
||||||
>
|
>
|
||||||
<option value="">(Kein Ordner / Root)</option>
|
<option value="">(Kein Ordner / Root)</option>
|
||||||
{allFolderPaths.map((fp) => (
|
{allFolderPaths.map((fp) => (
|
||||||
@@ -699,9 +751,10 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
|
|||||||
type="button"
|
type="button"
|
||||||
onClick={handleExportMarkdown}
|
onClick={handleExportMarkdown}
|
||||||
className="btn-action"
|
className="btn-action"
|
||||||
|
title="Als Markdown-Datei (.md) herunterladen"
|
||||||
>
|
>
|
||||||
<Download className="w-3.5 h-3.5 text-accent" />
|
<Download className="w-3.5 h-3.5 text-accent" />
|
||||||
<span>Markdown (.md)</span>
|
<span>Export (.md)</span>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
@@ -716,7 +769,7 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Document Icon & Title */}
|
{/* Document Icon & Title */}
|
||||||
<div className="flex items-center gap-3 mb-4 relative">
|
<div className="flex items-center gap-3 relative">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => setShowIconPicker((prev) => !prev)}
|
onClick={() => setShowIconPicker((prev) => !prev)}
|
||||||
@@ -727,7 +780,7 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
|
|||||||
</button>
|
</button>
|
||||||
|
|
||||||
{showIconPicker && (
|
{showIconPicker && (
|
||||||
<div className="absolute top-12 left-0 z-20 p-2.5 panel-surface flex flex-wrap gap-1 w-64 shadow-xl">
|
<div className="absolute top-12 left-0 z-20 p-2.5 panel-surface flex flex-wrap gap-1 w-64 shadow-xl border border-border">
|
||||||
{ICONS.map((ic) => (
|
{ICONS.map((ic) => (
|
||||||
<button
|
<button
|
||||||
key={ic}
|
key={ic}
|
||||||
@@ -753,12 +806,140 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Blocks Stack */}
|
{/* NOTION / WORD RICH FORMATTING TOOLBAR */}
|
||||||
<div className="space-y-3">
|
<div className="p-1.5 bg-canvas border border-border flex flex-wrap items-center gap-1 text-xs">
|
||||||
|
{/* Text styling buttons */}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => applyInlineFormat('**')}
|
||||||
|
className="p-1 hover:bg-panel text-zinc-300 hover:text-white"
|
||||||
|
title="Fett (**text**)"
|
||||||
|
>
|
||||||
|
<Bold className="w-3.5 h-3.5" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => applyInlineFormat('*')}
|
||||||
|
className="p-1 hover:bg-panel text-zinc-300 hover:text-white"
|
||||||
|
title="Kursiv (*text*)"
|
||||||
|
>
|
||||||
|
<Italic className="w-3.5 h-3.5" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => applyInlineFormat('~~')}
|
||||||
|
className="p-1 hover:bg-panel text-zinc-300 hover:text-white"
|
||||||
|
title="Durchgestrichen (~~text~~)"
|
||||||
|
>
|
||||||
|
<Strikethrough className="w-3.5 h-3.5" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => applyInlineFormat('`')}
|
||||||
|
className="p-1 hover:bg-panel text-zinc-300 hover:text-white"
|
||||||
|
title="Inline Code (`code`)"
|
||||||
|
>
|
||||||
|
<Code className="w-3.5 h-3.5" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => applyInlineFormat('[Link](', ')')}
|
||||||
|
className="p-1 hover:bg-panel text-zinc-300 hover:text-white"
|
||||||
|
title="Link einfügen"
|
||||||
|
>
|
||||||
|
<Link className="w-3.5 h-3.5" />
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<span className="w-px h-4 bg-border mx-1" />
|
||||||
|
|
||||||
|
{/* Wiki-Link Popover Button */}
|
||||||
|
<div className="relative">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setShowWikiLinkMenu((prev) => !prev)}
|
||||||
|
className="px-2 py-0.5 bg-panel border border-border text-[11px] text-accent flex items-center gap-1 hover:bg-panel-hover"
|
||||||
|
title="Auf anderes Dokument verlinken ([[Dokumentname]])"
|
||||||
|
>
|
||||||
|
<span>[[ Wiki-Link ]]</span>
|
||||||
|
</button>
|
||||||
|
{showWikiLinkMenu && (
|
||||||
|
<div className="absolute top-7 left-0 z-30 w-56 bg-panel border border-border p-1.5 shadow-2xl space-y-1">
|
||||||
|
<p className="text-[10px] text-zinc-400 px-1.5 pb-1 border-b border-border">
|
||||||
|
Dokument zum Verlinken wählen:
|
||||||
|
</p>
|
||||||
|
<div className="max-h-48 overflow-y-auto">
|
||||||
|
{docs
|
||||||
|
.filter((d) => d.id !== selectedDoc.id)
|
||||||
|
.map((d) => (
|
||||||
|
<button
|
||||||
|
key={d.id}
|
||||||
|
type="button"
|
||||||
|
onClick={() => insertWikiLink(d.title)}
|
||||||
|
className="w-full text-left px-2 py-1 text-xs text-zinc-300 hover:text-white hover:bg-panel-hover truncate flex items-center gap-1.5"
|
||||||
|
>
|
||||||
|
<span>{d.icon}</span>
|
||||||
|
<span className="truncate">{d.title}</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
{docs.length <= 1 && (
|
||||||
|
<div className="p-2 text-center text-[11px] text-zinc-500">
|
||||||
|
Keine weiteren Dokumente vorhanden
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<span className="w-px h-4 bg-border mx-1" />
|
||||||
|
|
||||||
|
{/* Custom Elements: Table & Progress */}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() =>
|
||||||
|
addBlock(
|
||||||
|
'table',
|
||||||
|
undefined,
|
||||||
|
'| Spalte 1 | Spalte 2 | Spalte 3 |\n|---|---|---|\n| Inhalt A | Inhalt B | Inhalt C |\n| Wert 1 | Wert 2 | Wert 3 |'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
className="px-2 py-0.5 bg-panel border border-border text-[11px] text-zinc-300 hover:text-white flex items-center gap-1"
|
||||||
|
title="Tabelle einfügen"
|
||||||
|
>
|
||||||
|
<TableIcon className="w-3 h-3 text-accent" />
|
||||||
|
<span>Tabelle</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => addBlock('progress', undefined, '50')}
|
||||||
|
className="px-2 py-0.5 bg-panel border border-border text-[11px] text-zinc-300 hover:text-white flex items-center gap-1"
|
||||||
|
title="Fortschrittsbalken einfügen"
|
||||||
|
>
|
||||||
|
<Percent className="w-3 h-3 text-accent" />
|
||||||
|
<span>Fortschritt</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => addBlock('divider')}
|
||||||
|
className="p-1 hover:bg-panel text-zinc-400 hover:text-white"
|
||||||
|
title="Trennlinie"
|
||||||
|
>
|
||||||
|
<Minus className="w-3.5 h-3.5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* BLOCKS STACK */}
|
||||||
|
<div className="space-y-3 pt-2">
|
||||||
{selectedDoc.blocks.map((block, idx) => (
|
{selectedDoc.blocks.map((block, idx) => (
|
||||||
<div key={block.id} className="group flex items-start gap-2">
|
<div
|
||||||
{/* Block Renderer */}
|
key={block.id}
|
||||||
|
onClick={() => setLastFocusedBlockId(block.id)}
|
||||||
|
className="group flex items-start gap-2"
|
||||||
|
>
|
||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0">
|
||||||
|
{/* H1 */}
|
||||||
{block.type === 'h1' && (
|
{block.type === 'h1' && (
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
@@ -769,6 +950,7 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* H2 */}
|
||||||
{block.type === 'h2' && (
|
{block.type === 'h2' && (
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
@@ -779,16 +961,36 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{block.type === 'paragraph' && (
|
{/* H3 */}
|
||||||
<textarea
|
{block.type === 'h3' && (
|
||||||
rows={Math.max(1, Math.ceil(block.content.length / 75))}
|
<input
|
||||||
|
type="text"
|
||||||
value={block.content}
|
value={block.content}
|
||||||
onChange={(e) => updateBlock(block.id, { content: e.target.value })}
|
onChange={(e) => updateBlock(block.id, { content: e.target.value })}
|
||||||
placeholder="Text schreiben…"
|
placeholder="Unterabschnitt…"
|
||||||
className="w-full bg-transparent text-xs sm:text-sm text-zinc-200 leading-relaxed focus:outline-none resize-none font-normal"
|
className="w-full bg-transparent text-sm font-semibold text-zinc-200 focus:outline-none pt-1"
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* PARAGRAPH with Wiki-Link support */}
|
||||||
|
{block.type === 'paragraph' && (
|
||||||
|
<div className="space-y-1">
|
||||||
|
<textarea
|
||||||
|
rows={Math.max(1, Math.ceil((block.content || '').length / 75))}
|
||||||
|
value={block.content}
|
||||||
|
onChange={(e) => updateBlock(block.id, { content: e.target.value })}
|
||||||
|
placeholder="Text schreiben… (nutze [[Dokument]] für Wiki-Links)"
|
||||||
|
className="w-full bg-transparent text-xs sm:text-sm text-zinc-200 leading-relaxed focus:outline-none resize-none font-normal"
|
||||||
|
/>
|
||||||
|
{block.content.includes('[[') && (
|
||||||
|
<div className="text-xs text-zinc-400 pt-0.5">
|
||||||
|
{renderTextWithWikiLinks(block.content)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* TODO */}
|
||||||
{block.type === 'todo' && (
|
{block.type === 'todo' && (
|
||||||
<div className="flex items-center gap-2.5 py-1">
|
<div className="flex items-center gap-2.5 py-1">
|
||||||
<input
|
<input
|
||||||
@@ -797,48 +999,72 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
|
|||||||
onChange={(e) => updateBlock(block.id, { checked: e.target.checked })}
|
onChange={(e) => updateBlock(block.id, { checked: e.target.checked })}
|
||||||
className="w-3.5 h-3.5 accent-accent cursor-pointer"
|
className="w-3.5 h-3.5 accent-accent cursor-pointer"
|
||||||
/>
|
/>
|
||||||
<input
|
<div className="flex-1">
|
||||||
type="text"
|
<input
|
||||||
value={block.content}
|
type="text"
|
||||||
onChange={(e) => updateBlock(block.id, { content: e.target.value })}
|
value={block.content}
|
||||||
placeholder="To-Do Punkt…"
|
onChange={(e) => updateBlock(block.id, { content: e.target.value })}
|
||||||
className={`w-full bg-transparent text-xs sm:text-sm focus:outline-none ${
|
placeholder="To-Do Punkt…"
|
||||||
block.checked ? 'line-through text-zinc-500' : 'text-white'
|
className={`w-full bg-transparent text-xs sm:text-sm focus:outline-none ${
|
||||||
}`}
|
block.checked ? 'line-through text-zinc-500' : 'text-white'
|
||||||
/>
|
}`}
|
||||||
|
/>
|
||||||
|
{block.content.includes('[[') && (
|
||||||
|
<div className="text-xs text-zinc-400">
|
||||||
|
{renderTextWithWikiLinks(block.content)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* BULLET */}
|
||||||
{block.type === 'bullet' && (
|
{block.type === 'bullet' && (
|
||||||
<div className="flex items-center gap-2.5 py-0.5">
|
<div className="flex items-center gap-2.5 py-0.5">
|
||||||
<span className="w-1.5 h-1.5 bg-accent flex-shrink-0" />
|
<span className="w-1.5 h-1.5 bg-accent flex-shrink-0" />
|
||||||
<input
|
<div className="flex-1">
|
||||||
type="text"
|
<input
|
||||||
value={block.content}
|
type="text"
|
||||||
onChange={(e) => updateBlock(block.id, { content: e.target.value })}
|
value={block.content}
|
||||||
placeholder="Listenpunkt…"
|
onChange={(e) => updateBlock(block.id, { content: e.target.value })}
|
||||||
className="w-full bg-transparent text-xs sm:text-sm text-zinc-200 focus:outline-none"
|
placeholder="Listenpunkt…"
|
||||||
/>
|
className="w-full bg-transparent text-xs sm:text-sm text-zinc-200 focus:outline-none"
|
||||||
|
/>
|
||||||
|
{block.content.includes('[[') && (
|
||||||
|
<div className="text-xs text-zinc-400">
|
||||||
|
{renderTextWithWikiLinks(block.content)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* CALLOUT */}
|
||||||
{block.type === 'callout' && (
|
{block.type === 'callout' && (
|
||||||
<div className="p-2.5 bg-canvas border border-accent/40 flex items-start gap-2">
|
<div className="p-2.5 bg-canvas border border-accent/40 flex items-start gap-2">
|
||||||
<Sparkles className="w-3.5 h-3.5 text-accent flex-shrink-0 mt-0.5" />
|
<Sparkles className="w-3.5 h-3.5 text-accent flex-shrink-0 mt-0.5" />
|
||||||
<textarea
|
<div className="flex-1 space-y-1">
|
||||||
rows={2}
|
<textarea
|
||||||
value={block.content}
|
rows={2}
|
||||||
onChange={(e) => updateBlock(block.id, { content: e.target.value })}
|
value={block.content}
|
||||||
placeholder="Wichtiger Hinweis oder Zusammenfassung…"
|
onChange={(e) => updateBlock(block.id, { content: e.target.value })}
|
||||||
className="w-full bg-transparent text-xs sm:text-sm text-zinc-200 focus:outline-none resize-none"
|
placeholder="Wichtiger Hinweis oder Zusammenfassung…"
|
||||||
/>
|
className="w-full bg-transparent text-xs sm:text-sm text-zinc-200 focus:outline-none resize-none"
|
||||||
|
/>
|
||||||
|
{block.content.includes('[[') && (
|
||||||
|
<div className="text-xs text-zinc-400">
|
||||||
|
{renderTextWithWikiLinks(block.content)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* CODE */}
|
||||||
{block.type === 'code' && (
|
{block.type === 'code' && (
|
||||||
<div className="p-2.5 bg-canvas border border-border font-mono text-xs text-zinc-200">
|
<div className="p-2.5 bg-canvas border border-border font-mono text-xs text-zinc-200">
|
||||||
<textarea
|
<textarea
|
||||||
rows={Math.max(2, block.content.split('\n').length)}
|
rows={Math.max(2, (block.content || '').split('\n').length)}
|
||||||
value={block.content}
|
value={block.content}
|
||||||
onChange={(e) => updateBlock(block.id, { content: e.target.value })}
|
onChange={(e) => updateBlock(block.id, { content: e.target.value })}
|
||||||
placeholder="// Code oder Shell-Kommando…"
|
placeholder="// Code oder Shell-Kommando…"
|
||||||
@@ -846,9 +1072,62 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* TABLE */}
|
||||||
|
{block.type === 'table' && (
|
||||||
|
<div className="p-2.5 bg-canvas border border-border space-y-2">
|
||||||
|
<div className="flex items-center justify-between text-[11px] text-zinc-400 border-b border-border pb-1">
|
||||||
|
<span className="flex items-center gap-1 font-semibold text-zinc-300">
|
||||||
|
<TableIcon className="w-3 h-3 text-accent" /> Markdown Tabelle
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<textarea
|
||||||
|
rows={Math.max(3, (block.content || '').split('\n').length)}
|
||||||
|
value={block.content}
|
||||||
|
onChange={(e) => updateBlock(block.id, { content: e.target.value })}
|
||||||
|
placeholder="| Spalte 1 | Spalte 2 |\n|---|---|\n| Inhalt | Wert |"
|
||||||
|
className="w-full bg-transparent font-mono text-xs text-zinc-200 focus:outline-none resize-none"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* PROGRESS BAR */}
|
||||||
|
{block.type === 'progress' && (
|
||||||
|
<div className="p-2.5 bg-canvas border border-border space-y-2">
|
||||||
|
<div className="flex items-center justify-between text-xs">
|
||||||
|
<span className="text-zinc-300 font-medium flex items-center gap-1">
|
||||||
|
<Percent className="w-3 h-3 text-accent" /> Fortschritt
|
||||||
|
</span>
|
||||||
|
<span className="font-mono text-accent font-semibold">
|
||||||
|
{parseInt(block.content) || 0}%
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="w-full bg-panel h-2.5 overflow-hidden border border-border">
|
||||||
|
<div
|
||||||
|
className="bg-accent h-full transition-all"
|
||||||
|
style={{ width: `${Math.min(100, Math.max(0, parseInt(block.content) || 0))}%` }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<input
|
||||||
|
type="range"
|
||||||
|
min="0"
|
||||||
|
max="100"
|
||||||
|
value={parseInt(block.content) || 0}
|
||||||
|
onChange={(e) => updateBlock(block.id, { content: e.target.value })}
|
||||||
|
className="w-full accent-accent cursor-pointer"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* DIVIDER */}
|
||||||
|
{block.type === 'divider' && (
|
||||||
|
<div className="py-2">
|
||||||
|
<hr className="border-border" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Block Reorder & Delete Controls */}
|
{/* Block Controls */}
|
||||||
<div className="opacity-0 group-hover:opacity-100 flex items-center gap-0.5 transition-opacity pt-1">
|
<div className="opacity-0 group-hover:opacity-100 flex items-center gap-0.5 transition-opacity pt-1">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -879,9 +1158,9 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Add Block Toolbar */}
|
{/* Bottom Add Block Toolbar */}
|
||||||
<div className="mt-4 pt-3 border-t border-border flex flex-wrap items-center gap-1.5">
|
<div className="mt-4 pt-3 border-t border-border flex flex-wrap items-center gap-1.5">
|
||||||
<span className="text-xs text-zinc-400 mr-1">+ Block:</span>
|
<span className="text-xs text-zinc-400 mr-1">+ Neuer Block:</span>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -933,10 +1212,32 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
|
|||||||
|
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => addBlock('h1')}
|
onClick={() =>
|
||||||
|
addBlock(
|
||||||
|
'table',
|
||||||
|
undefined,
|
||||||
|
'| Spalte 1 | Spalte 2 |\n|---|---|\n| Inhalt A | Inhalt B |'
|
||||||
|
)
|
||||||
|
}
|
||||||
className="btn-action h-6 px-2 text-xs"
|
className="btn-action h-6 px-2 text-xs"
|
||||||
>
|
>
|
||||||
<Heading1 className="w-3 h-3 text-accent" /> H1
|
<TableIcon className="w-3 h-3 text-accent" /> Tabelle
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => addBlock('progress', undefined, '50')}
|
||||||
|
className="btn-action h-6 px-2 text-xs"
|
||||||
|
>
|
||||||
|
<Percent className="w-3 h-3 text-accent" /> Fortschritt
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => addBlock('divider')}
|
||||||
|
className="btn-action h-6 px-2 text-xs"
|
||||||
|
>
|
||||||
|
<Minus className="w-3 h-3 text-accent" /> Trennlinie
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+157
-4
@@ -4,9 +4,14 @@ import {
|
|||||||
Document,
|
Document,
|
||||||
DocumentBlock,
|
DocumentBlock,
|
||||||
ListItem,
|
ListItem,
|
||||||
|
Organization,
|
||||||
PriorityLevel,
|
PriorityLevel,
|
||||||
SharedList,
|
SharedList,
|
||||||
Space,
|
Space,
|
||||||
|
SystemSettings,
|
||||||
|
Team,
|
||||||
|
TeamMember,
|
||||||
|
TaskList,
|
||||||
Thought,
|
Thought,
|
||||||
User,
|
User,
|
||||||
} from './types';
|
} from './types';
|
||||||
@@ -97,7 +102,7 @@ async function request<T>(path: string, options: RequestInit = {}, isRetry = fal
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const api = {
|
export const api = {
|
||||||
// --- AUTH ---
|
// --- AUTH & SETTINGS ---
|
||||||
async quickStart(): Promise<{ token: string; user: User }> {
|
async quickStart(): Promise<{ token: string; user: User }> {
|
||||||
const res = await request<{ token: string; user: User }>('/api/v1/auth/quickstart', {
|
const res = await request<{ token: string; user: User }>('/api/v1/auth/quickstart', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
@@ -128,6 +133,19 @@ export const api = {
|
|||||||
return request<{ user: User; stats: DashboardStats }>('/api/v1/auth/me');
|
return request<{ user: User; stats: DashboardStats }>('/api/v1/auth/me');
|
||||||
},
|
},
|
||||||
|
|
||||||
|
async updateSettings(patch: {
|
||||||
|
displayName?: string;
|
||||||
|
email?: string;
|
||||||
|
password?: string;
|
||||||
|
discordWebhookUrl?: string;
|
||||||
|
notifyBeforeMinutes?: number;
|
||||||
|
}): Promise<User> {
|
||||||
|
return request<User>('/api/v1/auth/settings', {
|
||||||
|
method: 'PATCH',
|
||||||
|
body: JSON.stringify(patch),
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
async getStats(): Promise<DashboardStats> {
|
async getStats(): Promise<DashboardStats> {
|
||||||
return request<DashboardStats>('/api/v1/stats');
|
return request<DashboardStats>('/api/v1/stats');
|
||||||
},
|
},
|
||||||
@@ -141,6 +159,7 @@ export const api = {
|
|||||||
options?: {
|
options?: {
|
||||||
target?: 'inbox' | 'task' | 'list_item' | 'document';
|
target?: 'inbox' | 'task' | 'list_item' | 'document';
|
||||||
targetListId?: string;
|
targetListId?: string;
|
||||||
|
taskListId?: string;
|
||||||
}
|
}
|
||||||
): Promise<Thought> {
|
): Promise<Thought> {
|
||||||
try {
|
try {
|
||||||
@@ -153,6 +172,7 @@ export const api = {
|
|||||||
dueDate,
|
dueDate,
|
||||||
target: options?.target || 'inbox',
|
target: options?.target || 'inbox',
|
||||||
targetListId: options?.targetListId || '',
|
targetListId: options?.targetListId || '',
|
||||||
|
taskListId: options?.taskListId || '',
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
return thought;
|
return thought;
|
||||||
@@ -169,6 +189,7 @@ export const api = {
|
|||||||
status: 'inbox',
|
status: 'inbox',
|
||||||
isCompleted: false,
|
isCompleted: false,
|
||||||
dueDate,
|
dueDate,
|
||||||
|
taskListId: options?.taskListId || '',
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
};
|
};
|
||||||
queue.push(offlineThought);
|
queue.push(offlineThought);
|
||||||
@@ -193,6 +214,7 @@ export const api = {
|
|||||||
priority: item.priority,
|
priority: item.priority,
|
||||||
source: item.source,
|
source: item.source,
|
||||||
dueDate: item.dueDate || '',
|
dueDate: item.dueDate || '',
|
||||||
|
taskListId: item.taskListId || '',
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
synced++;
|
synced++;
|
||||||
@@ -220,6 +242,7 @@ export const api = {
|
|||||||
options?: {
|
options?: {
|
||||||
convertTo?: 'task' | 'document' | 'list_item';
|
convertTo?: 'task' | 'document' | 'list_item';
|
||||||
targetListId?: string;
|
targetListId?: string;
|
||||||
|
taskListId?: string;
|
||||||
dueDate?: string;
|
dueDate?: string;
|
||||||
}
|
}
|
||||||
): Promise<Thought> {
|
): Promise<Thought> {
|
||||||
@@ -229,18 +252,28 @@ export const api = {
|
|||||||
action,
|
action,
|
||||||
convertTo: options?.convertTo || '',
|
convertTo: options?.convertTo || '',
|
||||||
targetListId: options?.targetListId || '',
|
targetListId: options?.targetListId || '',
|
||||||
|
taskListId: options?.taskListId || '',
|
||||||
dueDate: options?.dueDate || '',
|
dueDate: options?.dueDate || '',
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
async getTasks(): Promise<Thought[]> {
|
async getTasks(taskListId?: string): Promise<Thought[]> {
|
||||||
return request<Thought[]>('/api/v1/tasks');
|
const query = taskListId ? `?taskListId=${encodeURIComponent(taskListId)}` : '';
|
||||||
|
return request<Thought[]>(`/api/v1/tasks${query}`);
|
||||||
},
|
},
|
||||||
|
|
||||||
async updateThought(
|
async updateThought(
|
||||||
thoughtId: string,
|
thoughtId: string,
|
||||||
patch: { content?: string; isCompleted?: boolean; dueDate?: string; priority?: PriorityLevel }
|
patch: {
|
||||||
|
content?: string;
|
||||||
|
isCompleted?: boolean;
|
||||||
|
dueDate?: string;
|
||||||
|
priority?: PriorityLevel;
|
||||||
|
taskListId?: string;
|
||||||
|
kanbanStatus?: 'todo' | 'in_progress' | 'done';
|
||||||
|
notes?: string;
|
||||||
|
}
|
||||||
): Promise<Thought> {
|
): Promise<Thought> {
|
||||||
return request<Thought>(`/api/v1/thoughts/${thoughtId}`, {
|
return request<Thought>(`/api/v1/thoughts/${thoughtId}`, {
|
||||||
method: 'PATCH',
|
method: 'PATCH',
|
||||||
@@ -256,6 +289,42 @@ export const api = {
|
|||||||
return request<{ purged: number }>('/api/v1/thoughts/discarded/purge', { method: 'DELETE' });
|
return request<{ purged: number }>('/api/v1/thoughts/discarded/purge', { method: 'DELETE' });
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// --- TASK LISTS ---
|
||||||
|
async getTaskLists(): Promise<TaskList[]> {
|
||||||
|
return request<TaskList[]>('/api/v1/task-lists');
|
||||||
|
},
|
||||||
|
|
||||||
|
async createTaskList(payload: {
|
||||||
|
title: string;
|
||||||
|
icon?: string;
|
||||||
|
color?: string;
|
||||||
|
spaceId?: string;
|
||||||
|
}): Promise<TaskList> {
|
||||||
|
return request<TaskList>('/api/v1/task-lists', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
async updateTaskList(
|
||||||
|
id: string,
|
||||||
|
patch: {
|
||||||
|
title?: string;
|
||||||
|
icon?: string;
|
||||||
|
color?: string;
|
||||||
|
spaceId?: string;
|
||||||
|
}
|
||||||
|
): Promise<TaskList> {
|
||||||
|
return request<TaskList>(`/api/v1/task-lists/${id}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify(patch),
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
async deleteTaskList(id: string): Promise<void> {
|
||||||
|
await request(`/api/v1/task-lists/${id}`, { method: 'DELETE' });
|
||||||
|
},
|
||||||
|
|
||||||
// --- WORKSPACE DOCUMENTS ---
|
// --- WORKSPACE DOCUMENTS ---
|
||||||
async getDocuments(): Promise<Document[]> {
|
async getDocuments(): Promise<Document[]> {
|
||||||
return request<Document[]>('/api/v1/documents');
|
return request<Document[]>('/api/v1/documents');
|
||||||
@@ -268,6 +337,7 @@ export const api = {
|
|||||||
async createDocument(payload: {
|
async createDocument(payload: {
|
||||||
title: string;
|
title: string;
|
||||||
icon?: string;
|
icon?: string;
|
||||||
|
folderPath?: string;
|
||||||
blocks?: DocumentBlock[];
|
blocks?: DocumentBlock[];
|
||||||
tags?: string[];
|
tags?: string[];
|
||||||
isPinned?: boolean;
|
isPinned?: boolean;
|
||||||
@@ -283,6 +353,7 @@ export const api = {
|
|||||||
patch: {
|
patch: {
|
||||||
title?: string;
|
title?: string;
|
||||||
icon?: string;
|
icon?: string;
|
||||||
|
folderPath?: string;
|
||||||
blocks?: DocumentBlock[];
|
blocks?: DocumentBlock[];
|
||||||
tags?: string[];
|
tags?: string[];
|
||||||
isPinned?: boolean;
|
isPinned?: boolean;
|
||||||
@@ -360,6 +431,88 @@ export const api = {
|
|||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// --- ORGANIZATIONS & TEAMS ---
|
||||||
|
async getOrganizations(): Promise<Organization[]> {
|
||||||
|
return request<Organization[]>('/api/v1/organizations');
|
||||||
|
},
|
||||||
|
|
||||||
|
async createOrganization(name: string): Promise<Organization> {
|
||||||
|
return request<Organization>('/api/v1/organizations', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ name }),
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
async getOrgTeams(orgId: string): Promise<Team[]> {
|
||||||
|
return request<Team[]>(`/api/v1/organizations/${orgId}/teams`);
|
||||||
|
},
|
||||||
|
|
||||||
|
async createOrgTeam(orgId: string, name: string, description: string): Promise<Team> {
|
||||||
|
return request<Team>(`/api/v1/organizations/${orgId}/teams`, {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ name, description }),
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
async getUserTeams(): Promise<Team[]> {
|
||||||
|
return request<Team[]>('/api/v1/teams');
|
||||||
|
},
|
||||||
|
|
||||||
|
async addTeamMember(teamId: string, userId: string, role = 'editor'): Promise<void> {
|
||||||
|
await request(`/api/v1/teams/${teamId}/members`, {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ userId, role }),
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
async removeTeamMember(teamId: string, userId: string): Promise<void> {
|
||||||
|
await request(`/api/v1/teams/${teamId}/members/${userId}`, { method: 'DELETE' });
|
||||||
|
},
|
||||||
|
|
||||||
|
// --- ADMIN PANEL ---
|
||||||
|
async adminGetUsers(): Promise<User[]> {
|
||||||
|
return request<User[]>('/api/v1/admin/users');
|
||||||
|
},
|
||||||
|
|
||||||
|
async adminCreateUser(payload: { email: string; password: string; displayName: string; role: string }): Promise<User> {
|
||||||
|
return request<User>('/api/v1/admin/users', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
async adminUpdateUser(
|
||||||
|
id: string,
|
||||||
|
patch: { displayName?: string; email?: string; role?: string; isActive?: boolean; discordWebhookUrl?: string }
|
||||||
|
): Promise<User> {
|
||||||
|
return request<User>(`/api/v1/admin/users/${id}`, {
|
||||||
|
method: 'PATCH',
|
||||||
|
body: JSON.stringify(patch),
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
async adminResetPassword(id: string, password: string): Promise<void> {
|
||||||
|
await request(`/api/v1/admin/users/${id}/password`, {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify({ password }),
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
async adminDeleteUser(id: string): Promise<void> {
|
||||||
|
await request(`/api/v1/admin/users/${id}`, { method: 'DELETE' });
|
||||||
|
},
|
||||||
|
|
||||||
|
async adminGetSettings(): Promise<SystemSettings> {
|
||||||
|
return request<SystemSettings>('/api/v1/admin/settings');
|
||||||
|
},
|
||||||
|
|
||||||
|
async adminUpdateSettings(settings: SystemSettings): Promise<SystemSettings> {
|
||||||
|
return request<SystemSettings>('/api/v1/admin/settings', {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify(settings),
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
// --- API KEYS, WEBHOOKS & EXPORT ---
|
// --- API KEYS, WEBHOOKS & EXPORT ---
|
||||||
async getAPIKeys(): Promise<APIKey[]> {
|
async getAPIKeys(): Promise<APIKey[]> {
|
||||||
return request<APIKey[]>('/api/v1/keys');
|
return request<APIKey[]>('/api/v1/keys');
|
||||||
|
|||||||
@@ -5,6 +5,10 @@ export interface User {
|
|||||||
id: string;
|
id: string;
|
||||||
email: string;
|
email: string;
|
||||||
displayName: string;
|
displayName: string;
|
||||||
|
role: 'admin' | 'member';
|
||||||
|
isActive: boolean;
|
||||||
|
discordWebhookUrl?: string;
|
||||||
|
notifyBeforeMinutes?: number;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -20,11 +24,58 @@ export interface Thought {
|
|||||||
convertedType?: 'task' | 'document' | 'list_item';
|
convertedType?: 'task' | 'document' | 'list_item';
|
||||||
convertedRefId?: string;
|
convertedRefId?: string;
|
||||||
dueDate?: string;
|
dueDate?: string;
|
||||||
|
taskListId?: string;
|
||||||
|
kanbanStatus?: 'todo' | 'in_progress' | 'done';
|
||||||
|
notes?: string;
|
||||||
|
alarmSent?: boolean;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
triagedAt?: string;
|
triagedAt?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type BlockType = 'h1' | 'h2' | 'h3' | 'paragraph' | 'todo' | 'bullet' | 'code' | 'callout' | 'divider';
|
export interface TaskList {
|
||||||
|
id: string;
|
||||||
|
userId: string;
|
||||||
|
spaceId?: string;
|
||||||
|
title: string;
|
||||||
|
icon: string;
|
||||||
|
color: string;
|
||||||
|
tasksCount?: number;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Organization {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
ownerId: string;
|
||||||
|
createdAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Team {
|
||||||
|
id: string;
|
||||||
|
orgId: string;
|
||||||
|
name: string;
|
||||||
|
description: string;
|
||||||
|
members?: TeamMember[];
|
||||||
|
createdAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TeamMember {
|
||||||
|
teamId: string;
|
||||||
|
userId: string;
|
||||||
|
displayName: string;
|
||||||
|
email: string;
|
||||||
|
role: 'owner' | 'editor' | 'viewer';
|
||||||
|
joinedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SystemSettings {
|
||||||
|
sharingMode: 'open' | 'teams_only' | 'strict_private';
|
||||||
|
allowRegistration: boolean;
|
||||||
|
instanceName: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type BlockType = 'h1' | 'h2' | 'h3' | 'paragraph' | 'todo' | 'bullet' | 'code' | 'callout' | 'divider' | 'table' | 'progress';
|
||||||
|
|
||||||
export interface DocumentBlock {
|
export interface DocumentBlock {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -43,6 +94,7 @@ export interface Document {
|
|||||||
content: string;
|
content: string;
|
||||||
blocks: DocumentBlock[];
|
blocks: DocumentBlock[];
|
||||||
tags: string[];
|
tags: string[];
|
||||||
|
folderPath?: string;
|
||||||
isPinned: boolean;
|
isPinned: boolean;
|
||||||
isArchived: boolean;
|
isArchived: boolean;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
|
|||||||
+453
-27
@@ -1,11 +1,13 @@
|
|||||||
package api
|
package api
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io/fs"
|
"io/fs"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
"github.com/go-chi/chi/v5/middleware"
|
"github.com/go-chi/chi/v5/middleware"
|
||||||
@@ -25,12 +27,14 @@ type Server struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewServer(cfg *config.Config, store *storage.Store, wsHub *ws.Hub, staticFS fs.FS) *Server {
|
func NewServer(cfg *config.Config, store *storage.Store, wsHub *ws.Hub, staticFS fs.FS) *Server {
|
||||||
return &Server{
|
srv := &Server{
|
||||||
cfg: cfg,
|
cfg: cfg,
|
||||||
store: store,
|
store: store,
|
||||||
wsHub: wsHub,
|
wsHub: wsHub,
|
||||||
staticFS: staticFS,
|
staticFS: staticFS,
|
||||||
}
|
}
|
||||||
|
go srv.startDiscordAlarmTicker()
|
||||||
|
return srv
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) Router() http.Handler {
|
func (s *Server) Router() http.Handler {
|
||||||
@@ -60,6 +64,7 @@ func (s *Server) Router() http.Handler {
|
|||||||
r.Use(s.authMiddleware)
|
r.Use(s.authMiddleware)
|
||||||
|
|
||||||
r.Get("/api/v1/auth/me", s.handleMe)
|
r.Get("/api/v1/auth/me", s.handleMe)
|
||||||
|
r.Patch("/api/v1/auth/settings", s.handleUpdateUserSettings)
|
||||||
r.Get("/api/v1/stats", s.handleStats)
|
r.Get("/api/v1/stats", s.handleStats)
|
||||||
r.Get("/api/v1/search", s.handleSearch)
|
r.Get("/api/v1/search", s.handleSearch)
|
||||||
r.Get("/api/v1/export", s.handleExport)
|
r.Get("/api/v1/export", s.handleExport)
|
||||||
@@ -76,6 +81,12 @@ func (s *Server) Router() http.Handler {
|
|||||||
r.Patch("/api/v1/triage/{id}", s.handleTriageAction)
|
r.Patch("/api/v1/triage/{id}", s.handleTriageAction)
|
||||||
r.Get("/api/v1/tasks", s.handleGetTasks)
|
r.Get("/api/v1/tasks", s.handleGetTasks)
|
||||||
|
|
||||||
|
// Task Lists
|
||||||
|
r.Get("/api/v1/task-lists", s.handleGetTaskLists)
|
||||||
|
r.Post("/api/v1/task-lists", s.handleCreateTaskList)
|
||||||
|
r.Put("/api/v1/task-lists/{id}", s.handleUpdateTaskList)
|
||||||
|
r.Delete("/api/v1/task-lists/{id}", s.handleDeleteTaskList)
|
||||||
|
|
||||||
// Workspace Documents
|
// Workspace Documents
|
||||||
r.Get("/api/v1/documents", s.handleGetDocuments)
|
r.Get("/api/v1/documents", s.handleGetDocuments)
|
||||||
r.Post("/api/v1/documents", s.handleCreateDocument)
|
r.Post("/api/v1/documents", s.handleCreateDocument)
|
||||||
@@ -97,10 +108,31 @@ func (s *Server) Router() http.Handler {
|
|||||||
r.Delete("/api/v1/lists/{id}/items/{itemId}", s.handleDeleteListItem)
|
r.Delete("/api/v1/lists/{id}/items/{itemId}", s.handleDeleteListItem)
|
||||||
r.Post("/api/v1/lists/{id}/clear-completed", s.handleClearCompletedItems)
|
r.Post("/api/v1/lists/{id}/clear-completed", s.handleClearCompletedItems)
|
||||||
|
|
||||||
|
// Organizations & Teams
|
||||||
|
r.Get("/api/v1/organizations", s.handleGetOrganizations)
|
||||||
|
r.Post("/api/v1/organizations", s.handleCreateOrganization)
|
||||||
|
r.Get("/api/v1/organizations/{id}/teams", s.handleGetOrgTeams)
|
||||||
|
r.Post("/api/v1/organizations/{id}/teams", s.handleCreateOrgTeam)
|
||||||
|
r.Get("/api/v1/teams", s.handleGetUserTeams)
|
||||||
|
r.Post("/api/v1/teams/{id}/members", s.handleAddTeamMember)
|
||||||
|
r.Delete("/api/v1/teams/{id}/members/{userId}", s.handleRemoveTeamMember)
|
||||||
|
|
||||||
// API Keys Management
|
// API Keys Management
|
||||||
r.Get("/api/v1/keys", s.handleGetAPIKeys)
|
r.Get("/api/v1/keys", s.handleGetAPIKeys)
|
||||||
r.Post("/api/v1/keys", s.handleCreateAPIKey)
|
r.Post("/api/v1/keys", s.handleCreateAPIKey)
|
||||||
r.Delete("/api/v1/keys/{id}", s.handleDeleteAPIKey)
|
r.Delete("/api/v1/keys/{id}", s.handleDeleteAPIKey)
|
||||||
|
|
||||||
|
// Admin Panel Routes
|
||||||
|
r.Group(func(r chi.Router) {
|
||||||
|
r.Use(s.adminMiddleware)
|
||||||
|
r.Get("/api/v1/admin/users", s.handleAdminGetUsers)
|
||||||
|
r.Post("/api/v1/admin/users", s.handleAdminCreateUser)
|
||||||
|
r.Patch("/api/v1/admin/users/{id}", s.handleAdminUpdateUser)
|
||||||
|
r.Put("/api/v1/admin/users/{id}/password", s.handleAdminResetPassword)
|
||||||
|
r.Delete("/api/v1/admin/users/{id}", s.handleAdminDeleteUser)
|
||||||
|
r.Get("/api/v1/admin/settings", s.handleAdminGetSettings)
|
||||||
|
r.Put("/api/v1/admin/settings", s.handleAdminUpdateSettings)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
// Embedded Frontend SPA Handler
|
// Embedded Frontend SPA Handler
|
||||||
@@ -186,6 +218,22 @@ func (s *Server) authMiddleware(next http.Handler) http.Handler {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *Server) adminMiddleware(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
userID := auth.GetUserID(r.Context())
|
||||||
|
if userID == "" {
|
||||||
|
writeError(w, http.StatusUnauthorized, "Nicht autorisiert")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
user, err := s.store.GetUserByID(userID)
|
||||||
|
if err != nil || user == nil || user.Role != "admin" {
|
||||||
|
writeError(w, http.StatusForbidden, "Administrator-Rechte erforderlich")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
// --- HANDLERS ---
|
// --- HANDLERS ---
|
||||||
|
|
||||||
func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -197,7 +245,8 @@ func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) {
|
||||||
if !s.cfg.AllowRegistration {
|
sysSettings, _ := s.store.GetSystemSettings()
|
||||||
|
if !s.cfg.AllowRegistration || (sysSettings != nil && !sysSettings.AllowRegistration) {
|
||||||
count, _ := s.store.CountUsers()
|
count, _ := s.store.CountUsers()
|
||||||
if count > 0 {
|
if count > 0 {
|
||||||
writeError(w, http.StatusForbidden, "Registrierung ist auf dieser Instanz deaktiviert")
|
writeError(w, http.StatusForbidden, "Registrierung ist auf dieser Instanz deaktiviert")
|
||||||
@@ -228,7 +277,13 @@ func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
user, err := s.store.CreateUser(req.Email, hash, req.DisplayName)
|
count, _ := s.store.CountUsers()
|
||||||
|
role := "member"
|
||||||
|
if count == 0 {
|
||||||
|
role = "admin"
|
||||||
|
}
|
||||||
|
|
||||||
|
user, err := s.store.CreateUser(req.Email, hash, req.DisplayName, role)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeError(w, http.StatusConflict, "E-Mail-Adresse existiert bereits")
|
writeError(w, http.StatusConflict, "E-Mail-Adresse existiert bereits")
|
||||||
return
|
return
|
||||||
@@ -263,6 +318,10 @@ func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeError(w, http.StatusUnauthorized, "E-Mail oder Passwort ungültig")
|
writeError(w, http.StatusUnauthorized, "E-Mail oder Passwort ungültig")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if !user.IsActive {
|
||||||
|
writeError(w, http.StatusForbidden, "Dieses Benutzerkonto ist deaktiviert")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
token, err := auth.GenerateToken(s.cfg.JWTSecret, user.ID, user.Email, user.DisplayName)
|
token, err := auth.GenerateToken(s.cfg.JWTSecret, user.ID, user.Email, user.DisplayName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -326,10 +385,12 @@ func (s *Server) handleCaptureInbox(w http.ResponseWriter, r *http.Request) {
|
|||||||
Priority string `json:"priority"`
|
Priority string `json:"priority"`
|
||||||
Source string `json:"source"`
|
Source string `json:"source"`
|
||||||
DueDate string `json:"dueDate"`
|
DueDate string `json:"dueDate"`
|
||||||
DueDate2 string `json:"due_date"` // Compatibility with snake_case README example
|
DueDate2 string `json:"due_date"`
|
||||||
Target string `json:"target"` // inbox | task | list_item | document
|
Target string `json:"target"` // inbox | task | list_item | document
|
||||||
TargetListID string `json:"targetListId"`
|
TargetListID string `json:"targetListId"`
|
||||||
TargetList2 string `json:"target_list_id"`
|
TargetList2 string `json:"target_list_id"`
|
||||||
|
TaskListID string `json:"taskListId"`
|
||||||
|
TaskListID2 string `json:"task_list_id"`
|
||||||
}
|
}
|
||||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
writeError(w, http.StatusBadRequest, "Ungültiges JSON")
|
writeError(w, http.StatusBadRequest, "Ungültiges JSON")
|
||||||
@@ -343,8 +404,12 @@ func (s *Server) handleCaptureInbox(w http.ResponseWriter, r *http.Request) {
|
|||||||
if targetListID == "" {
|
if targetListID == "" {
|
||||||
targetListID = req.TargetList2
|
targetListID = req.TargetList2
|
||||||
}
|
}
|
||||||
|
taskListID := req.TaskListID
|
||||||
|
if taskListID == "" {
|
||||||
|
taskListID = req.TaskListID2
|
||||||
|
}
|
||||||
|
|
||||||
thought, err := s.store.CreateThought(userID, req.Content, req.Priority, req.Source, dueDate)
|
thought, err := s.store.CreateThoughtWithDetails(userID, req.Content, req.Priority, req.Source, dueDate, taskListID, "todo", "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeError(w, http.StatusBadRequest, err.Error())
|
writeError(w, http.StatusBadRequest, err.Error())
|
||||||
return
|
return
|
||||||
@@ -352,7 +417,7 @@ func (s *Server) handleCaptureInbox(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
target := strings.TrimSpace(req.Target)
|
target := strings.TrimSpace(req.Target)
|
||||||
if target == "task" || target == "document" || (target == "list_item" && targetListID != "") {
|
if target == "task" || target == "document" || (target == "list_item" && targetListID != "") {
|
||||||
if converted, convErr := s.store.UpdateThoughtTriage(userID, thought.ID, "keep", target, targetListID, dueDate); convErr == nil && converted != nil {
|
if converted, convErr := s.store.UpdateThoughtTriage(userID, thought.ID, "keep", target, targetListID, dueDate, taskListID); convErr == nil && converted != nil {
|
||||||
thought = converted
|
thought = converted
|
||||||
if target == "list_item" && targetListID != "" {
|
if target == "list_item" && targetListID != "" {
|
||||||
if lst, lErr := s.store.GetListByID(targetListID); lErr == nil && lst != nil {
|
if lst, lErr := s.store.GetListByID(targetListID); lErr == nil && lst != nil {
|
||||||
@@ -396,6 +461,8 @@ func (s *Server) handleTriageAction(w http.ResponseWriter, r *http.Request) {
|
|||||||
ConvertTo2 string `json:"convert_to"`
|
ConvertTo2 string `json:"convert_to"`
|
||||||
TargetListID string `json:"targetListId"`
|
TargetListID string `json:"targetListId"`
|
||||||
TargetList2 string `json:"target_list_id"`
|
TargetList2 string `json:"target_list_id"`
|
||||||
|
TaskListID string `json:"taskListId"`
|
||||||
|
TaskListID2 string `json:"task_list_id"`
|
||||||
DueDate string `json:"dueDate"`
|
DueDate string `json:"dueDate"`
|
||||||
DueDate2 string `json:"due_date"`
|
DueDate2 string `json:"due_date"`
|
||||||
}
|
}
|
||||||
@@ -412,12 +479,16 @@ func (s *Server) handleTriageAction(w http.ResponseWriter, r *http.Request) {
|
|||||||
if targetListID == "" {
|
if targetListID == "" {
|
||||||
targetListID = req.TargetList2
|
targetListID = req.TargetList2
|
||||||
}
|
}
|
||||||
|
taskListID := req.TaskListID
|
||||||
|
if taskListID == "" {
|
||||||
|
taskListID = req.TaskListID2
|
||||||
|
}
|
||||||
dueDate := req.DueDate
|
dueDate := req.DueDate
|
||||||
if dueDate == "" {
|
if dueDate == "" {
|
||||||
dueDate = req.DueDate2
|
dueDate = req.DueDate2
|
||||||
}
|
}
|
||||||
|
|
||||||
updated, err := s.store.UpdateThoughtTriage(userID, thoughtID, req.Action, convertTo, targetListID, dueDate)
|
updated, err := s.store.UpdateThoughtTriage(userID, thoughtID, req.Action, convertTo, targetListID, dueDate, taskListID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeError(w, http.StatusBadRequest, err.Error())
|
writeError(w, http.StatusBadRequest, err.Error())
|
||||||
return
|
return
|
||||||
@@ -435,7 +506,8 @@ func (s *Server) handleTriageAction(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
func (s *Server) handleGetTasks(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleGetTasks(w http.ResponseWriter, r *http.Request) {
|
||||||
userID := auth.GetUserID(r.Context())
|
userID := auth.GetUserID(r.Context())
|
||||||
tasks, err := s.store.GetTasks(userID)
|
taskListID := r.URL.Query().Get("taskListId")
|
||||||
|
tasks, err := s.store.GetTasks(userID, taskListID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeError(w, http.StatusInternalServerError, err.Error())
|
writeError(w, http.StatusInternalServerError, err.Error())
|
||||||
return
|
return
|
||||||
@@ -448,17 +520,20 @@ func (s *Server) handleUpdateThought(w http.ResponseWriter, r *http.Request) {
|
|||||||
thoughtID := chi.URLParam(r, "id")
|
thoughtID := chi.URLParam(r, "id")
|
||||||
|
|
||||||
var req struct {
|
var req struct {
|
||||||
Content *string `json:"content"`
|
Content *string `json:"content"`
|
||||||
IsCompleted *bool `json:"isCompleted"`
|
IsCompleted *bool `json:"isCompleted"`
|
||||||
DueDate *string `json:"dueDate"`
|
DueDate *string `json:"dueDate"`
|
||||||
Priority *string `json:"priority"`
|
Priority *string `json:"priority"`
|
||||||
|
TaskListID *string `json:"taskListId"`
|
||||||
|
KanbanStatus *string `json:"kanbanStatus"`
|
||||||
|
Notes *string `json:"notes"`
|
||||||
}
|
}
|
||||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
writeError(w, http.StatusBadRequest, "Ungültiges JSON")
|
writeError(w, http.StatusBadRequest, "Ungültiges JSON")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
updated, err := s.store.UpdateThoughtDetails(userID, thoughtID, req.Content, req.IsCompleted, req.DueDate, req.Priority)
|
updated, err := s.store.UpdateThoughtDetails(userID, thoughtID, req.Content, req.IsCompleted, req.DueDate, req.Priority, req.TaskListID, req.KanbanStatus, req.Notes)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeError(w, http.StatusBadRequest, err.Error())
|
writeError(w, http.StatusBadRequest, err.Error())
|
||||||
return
|
return
|
||||||
@@ -501,19 +576,20 @@ func (s *Server) handleGetDocuments(w http.ResponseWriter, r *http.Request) {
|
|||||||
func (s *Server) handleCreateDocument(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleCreateDocument(w http.ResponseWriter, r *http.Request) {
|
||||||
userID := auth.GetUserID(r.Context())
|
userID := auth.GetUserID(r.Context())
|
||||||
var req struct {
|
var req struct {
|
||||||
SpaceID string `json:"spaceId"`
|
SpaceID string `json:"spaceId"`
|
||||||
Title string `json:"title"`
|
Title string `json:"title"`
|
||||||
Icon string `json:"icon"`
|
Icon string `json:"icon"`
|
||||||
Blocks []domain.DocumentBlock `json:"blocks"`
|
FolderPath string `json:"folderPath"`
|
||||||
Tags []string `json:"tags"`
|
Blocks []domain.DocumentBlock `json:"blocks"`
|
||||||
IsPinned bool `json:"isPinned"`
|
Tags []string `json:"tags"`
|
||||||
|
IsPinned bool `json:"isPinned"`
|
||||||
}
|
}
|
||||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
writeError(w, http.StatusBadRequest, "Ungültiges JSON")
|
writeError(w, http.StatusBadRequest, "Ungültiges JSON")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
doc, err := s.store.CreateDocument(userID, req.SpaceID, req.Title, req.Icon, req.Blocks, req.Tags, req.IsPinned)
|
doc, err := s.store.CreateDocument(userID, req.SpaceID, req.Title, req.Icon, req.FolderPath, req.Blocks, req.Tags, req.IsPinned)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeError(w, http.StatusBadRequest, err.Error())
|
writeError(w, http.StatusBadRequest, err.Error())
|
||||||
return
|
return
|
||||||
@@ -536,18 +612,19 @@ func (s *Server) handleUpdateDocument(w http.ResponseWriter, r *http.Request) {
|
|||||||
userID := auth.GetUserID(r.Context())
|
userID := auth.GetUserID(r.Context())
|
||||||
docID := chi.URLParam(r, "id")
|
docID := chi.URLParam(r, "id")
|
||||||
var req struct {
|
var req struct {
|
||||||
Title *string `json:"title"`
|
Title *string `json:"title"`
|
||||||
Icon *string `json:"icon"`
|
Icon *string `json:"icon"`
|
||||||
Blocks *[]domain.DocumentBlock `json:"blocks"`
|
FolderPath *string `json:"folderPath"`
|
||||||
Tags *[]string `json:"tags"`
|
Blocks *[]domain.DocumentBlock `json:"blocks"`
|
||||||
IsPinned *bool `json:"isPinned"`
|
Tags *[]string `json:"tags"`
|
||||||
|
IsPinned *bool `json:"isPinned"`
|
||||||
}
|
}
|
||||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
writeError(w, http.StatusBadRequest, "Ungültiges JSON")
|
writeError(w, http.StatusBadRequest, "Ungültiges JSON")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
doc, err := s.store.UpdateDocument(userID, docID, req.Title, req.Icon, req.Blocks, req.Tags, req.IsPinned)
|
doc, err := s.store.UpdateDocument(userID, docID, req.Title, req.Icon, req.FolderPath, req.Blocks, req.Tags, req.IsPinned)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeError(w, http.StatusBadRequest, err.Error())
|
writeError(w, http.StatusBadRequest, err.Error())
|
||||||
return
|
return
|
||||||
@@ -906,3 +983,352 @@ func (s *Server) handleExport(w http.ResponseWriter, r *http.Request) {
|
|||||||
w.Header().Set("Content-Disposition", "attachment; filename=mindsift-export.json")
|
w.Header().Set("Content-Disposition", "attachment; filename=mindsift-export.json")
|
||||||
writeJSON(w, http.StatusOK, exportData)
|
writeJSON(w, http.StatusOK, exportData)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- USER SETTINGS ---
|
||||||
|
|
||||||
|
func (s *Server) handleUpdateUserSettings(w http.ResponseWriter, r *http.Request) {
|
||||||
|
userID := auth.GetUserID(r.Context())
|
||||||
|
var req struct {
|
||||||
|
DisplayName *string `json:"displayName"`
|
||||||
|
Email *string `json:"email"`
|
||||||
|
Password *string `json:"password"`
|
||||||
|
DiscordWebhookURL *string `json:"discordWebhookUrl"`
|
||||||
|
NotifyBeforeMinutes *int `json:"notifyBeforeMinutes"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "Ungültiges JSON")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if req.Password != nil && strings.TrimSpace(*req.Password) != "" {
|
||||||
|
hash, err := auth.HashPassword(*req.Password)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "Fehler beim Hashen des Passworts")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_ = s.store.UpdateUserPassword(userID, hash)
|
||||||
|
}
|
||||||
|
u, err := s.store.UpdateUser(userID, req.DisplayName, req.Email, nil, nil, req.DiscordWebhookURL, req.NotifyBeforeMinutes)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, u)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- TASK LISTS ---
|
||||||
|
|
||||||
|
func (s *Server) handleGetTaskLists(w http.ResponseWriter, r *http.Request) {
|
||||||
|
userID := auth.GetUserID(r.Context())
|
||||||
|
lists, err := s.store.GetTaskLists(userID)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, lists)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleCreateTaskList(w http.ResponseWriter, r *http.Request) {
|
||||||
|
userID := auth.GetUserID(r.Context())
|
||||||
|
var req struct {
|
||||||
|
SpaceID string `json:"spaceId"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Icon string `json:"icon"`
|
||||||
|
Color string `json:"color"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "Ungültiges JSON")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
tl, err := s.store.CreateTaskList(userID, req.SpaceID, req.Title, req.Icon, req.Color)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusCreated, tl)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleUpdateTaskList(w http.ResponseWriter, r *http.Request) {
|
||||||
|
userID := auth.GetUserID(r.Context())
|
||||||
|
listID := chi.URLParam(r, "id")
|
||||||
|
var req struct {
|
||||||
|
Title *string `json:"title"`
|
||||||
|
Icon *string `json:"icon"`
|
||||||
|
Color *string `json:"color"`
|
||||||
|
SpaceID *string `json:"spaceId"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "Ungültiges JSON")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
tl, err := s.store.UpdateTaskList(userID, listID, req.Title, req.Icon, req.Color, req.SpaceID)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, tl)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleDeleteTaskList(w http.ResponseWriter, r *http.Request) {
|
||||||
|
userID := auth.GetUserID(r.Context())
|
||||||
|
listID := chi.URLParam(r, "id")
|
||||||
|
if err := s.store.DeleteTaskList(userID, listID); err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, map[string]bool{"deleted": true})
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- ORGANIZATIONS & TEAMS ---
|
||||||
|
|
||||||
|
func (s *Server) handleGetOrganizations(w http.ResponseWriter, r *http.Request) {
|
||||||
|
userID := auth.GetUserID(r.Context())
|
||||||
|
orgs, err := s.store.GetOrganizationsForUser(userID)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, orgs)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleCreateOrganization(w http.ResponseWriter, r *http.Request) {
|
||||||
|
userID := auth.GetUserID(r.Context())
|
||||||
|
var req struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "Ungültiges JSON")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
org, err := s.store.CreateOrganization(userID, req.Name)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusCreated, org)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleGetOrgTeams(w http.ResponseWriter, r *http.Request) {
|
||||||
|
orgID := chi.URLParam(r, "id")
|
||||||
|
teams, err := s.store.GetTeamsForOrg(orgID)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, teams)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleCreateOrgTeam(w http.ResponseWriter, r *http.Request) {
|
||||||
|
orgID := chi.URLParam(r, "id")
|
||||||
|
var req struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Description string `json:"description"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "Ungültiges JSON")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
team, err := s.store.CreateTeam(orgID, req.Name, req.Description)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusCreated, team)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleGetUserTeams(w http.ResponseWriter, r *http.Request) {
|
||||||
|
userID := auth.GetUserID(r.Context())
|
||||||
|
teams, err := s.store.GetTeamsForUser(userID)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, teams)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleAddTeamMember(w http.ResponseWriter, r *http.Request) {
|
||||||
|
teamID := chi.URLParam(r, "id")
|
||||||
|
var req struct {
|
||||||
|
UserID string `json:"userId"`
|
||||||
|
Role string `json:"role"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "Ungültiges JSON")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := s.store.AddTeamMember(teamID, req.UserID, req.Role); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, map[string]bool{"added": true})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleRemoveTeamMember(w http.ResponseWriter, r *http.Request) {
|
||||||
|
teamID := chi.URLParam(r, "id")
|
||||||
|
memberUserID := chi.URLParam(r, "userId")
|
||||||
|
if err := s.store.RemoveTeamMember(teamID, memberUserID); err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, map[string]bool{"removed": true})
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- ADMIN PANEL ---
|
||||||
|
|
||||||
|
func (s *Server) handleAdminGetUsers(w http.ResponseWriter, r *http.Request) {
|
||||||
|
users, err := s.store.GetAllUsers()
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, users)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleAdminCreateUser(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req struct {
|
||||||
|
Email string `json:"email"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
DisplayName string `json:"displayName"`
|
||||||
|
Role string `json:"role"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "Ungültiges JSON")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if req.Email == "" || req.Password == "" {
|
||||||
|
writeError(w, http.StatusBadRequest, "E-Mail und Passwort erforderlich")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
hash, err := auth.HashPassword(req.Password)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "Passwort-Hash fehlgeschlagen")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
u, err := s.store.CreateUser(req.Email, hash, req.DisplayName, req.Role)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusCreated, u)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleAdminUpdateUser(w http.ResponseWriter, r *http.Request) {
|
||||||
|
targetUserID := chi.URLParam(r, "id")
|
||||||
|
var req struct {
|
||||||
|
DisplayName *string `json:"displayName"`
|
||||||
|
Email *string `json:"email"`
|
||||||
|
Role *string `json:"role"`
|
||||||
|
IsActive *bool `json:"isActive"`
|
||||||
|
DiscordWebhookURL *string `json:"discordWebhookUrl"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "Ungültiges JSON")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
u, err := s.store.UpdateUser(targetUserID, req.DisplayName, req.Email, req.Role, req.IsActive, req.DiscordWebhookURL, nil)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, u)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleAdminResetPassword(w http.ResponseWriter, r *http.Request) {
|
||||||
|
targetUserID := chi.URLParam(r, "id")
|
||||||
|
var req struct {
|
||||||
|
Password string `json:"password"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || strings.TrimSpace(req.Password) == "" {
|
||||||
|
writeError(w, http.StatusBadRequest, "Neues Passwort erforderlich")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
hash, err := auth.HashPassword(req.Password)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "Passwort-Hash fehlgeschlagen")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := s.store.UpdateUserPassword(targetUserID, hash); err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, map[string]bool{"success": true})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleAdminDeleteUser(w http.ResponseWriter, r *http.Request) {
|
||||||
|
targetUserID := chi.URLParam(r, "id")
|
||||||
|
currUserID := auth.GetUserID(r.Context())
|
||||||
|
if targetUserID == currUserID {
|
||||||
|
writeError(w, http.StatusBadRequest, "Sie können Ihren eigenen Benutzer nicht löschen")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := s.store.DeleteUser(targetUserID); err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, map[string]bool{"deleted": true})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleAdminGetSettings(w http.ResponseWriter, r *http.Request) {
|
||||||
|
settings, err := s.store.GetSystemSettings()
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, settings)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleAdminUpdateSettings(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var settings domain.SystemSettings
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&settings); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "Ungültiges JSON")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := s.store.UpdateSystemSettings(&settings); err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, settings)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- DISCORD ALARMS BACKGROUND SCHEDULER ---
|
||||||
|
|
||||||
|
func (s *Server) startDiscordAlarmTicker() {
|
||||||
|
ticker := time.NewTicker(60 * time.Second)
|
||||||
|
defer ticker.Stop()
|
||||||
|
|
||||||
|
httpClient := &http.Client{Timeout: 10 * time.Second}
|
||||||
|
|
||||||
|
for range ticker.C {
|
||||||
|
alarms, err := s.store.GetDueTasksForAlarm()
|
||||||
|
if err != nil || len(alarms) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
today := time.Now().Format("2006-01-02")
|
||||||
|
|
||||||
|
for _, a := range alarms {
|
||||||
|
if a.DueDate <= today && a.DiscordWebhookURL != "" {
|
||||||
|
payload := map[string]interface{}{
|
||||||
|
"content": fmt.Sprintf("⏰ **MindSift Aufgaben-Erinnerung**"),
|
||||||
|
"embeds": []map[string]interface{}{
|
||||||
|
{
|
||||||
|
"title": a.Title,
|
||||||
|
"description": fmt.Sprintf("Diese Aufgabe ist fällig am **%s** (Priorität: %s)", a.DueDate, a.Priority),
|
||||||
|
"color": 3066993,
|
||||||
|
"footer": map[string]string{
|
||||||
|
"text": "MindSift Reminder",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
body, mErr := json.Marshal(payload)
|
||||||
|
if mErr == nil {
|
||||||
|
resp, pErr := httpClient.Post(a.DiscordWebhookURL, "application/json", bytes.NewReader(body))
|
||||||
|
if pErr == nil {
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
_ = s.store.MarkTaskAlarmSent(a.TaskID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -184,3 +184,106 @@ func TestStaleTokenFallbackAndQuickDumpToTriageAndDirectTargets(t *testing.T) {
|
|||||||
t.Fatalf("expected 200 OK for triage action, got %d: %s", rec.Code, rec.Body.String())
|
t.Fatalf("expected 200 OK for triage action, got %d: %s", rec.Code, rec.Body.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestNewFullFeatures(t *testing.T) {
|
||||||
|
srv, _, token := setupTestServer(t)
|
||||||
|
router := srv.Router()
|
||||||
|
|
||||||
|
// 1. Test TaskLists: Create & Get
|
||||||
|
taskListPayload := map[string]string{
|
||||||
|
"title": "Homelab & Docker",
|
||||||
|
"icon": "🐳",
|
||||||
|
"color": "#3b82f6",
|
||||||
|
}
|
||||||
|
body, _ := json.Marshal(taskListPayload)
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/task-lists", bytes.NewReader(body))
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(rec, req)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("expected 201 Created for TaskList, got %d: %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
var createdTaskList domain.TaskList
|
||||||
|
_ = json.Unmarshal(rec.Body.Bytes(), &createdTaskList)
|
||||||
|
if createdTaskList.Title != "Homelab & Docker" {
|
||||||
|
t.Fatalf("expected task list title 'Homelab & Docker', got %q", createdTaskList.Title)
|
||||||
|
}
|
||||||
|
|
||||||
|
req = httptest.NewRequest(http.MethodGet, "/api/v1/task-lists", nil)
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
rec = httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(rec, req)
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected 200 OK for GET /api/v1/task-lists, got %d", rec.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Test User Settings: Update Discord Webhook & Profile
|
||||||
|
settingsPayload := map[string]interface{}{
|
||||||
|
"displayName": "Sandro D.",
|
||||||
|
"discordWebhookUrl": "https://discord.com/api/webhooks/test/123",
|
||||||
|
"notifyBeforeMinutes": 15,
|
||||||
|
}
|
||||||
|
body, _ = json.Marshal(settingsPayload)
|
||||||
|
req = httptest.NewRequest(http.MethodPatch, "/api/v1/auth/settings", bytes.NewReader(body))
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
rec = httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(rec, req)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected 200 OK for PATCH /api/v1/auth/settings, got %d: %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Test Admin routes (default user is admin)
|
||||||
|
req = httptest.NewRequest(http.MethodGet, "/api/v1/admin/users", nil)
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
rec = httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(rec, req)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected 200 OK for GET /api/v1/admin/users, got %d: %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
req = httptest.NewRequest(http.MethodGet, "/api/v1/admin/settings", nil)
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
rec = httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(rec, req)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected 200 OK for GET /api/v1/admin/settings, got %d: %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Test Kanban & Task details update
|
||||||
|
taskUpdatePayload := map[string]interface{}{
|
||||||
|
"kanbanStatus": "in_progress",
|
||||||
|
"notes": "Detailnotizen für die Aufgabe",
|
||||||
|
"taskListId": createdTaskList.ID,
|
||||||
|
}
|
||||||
|
body, _ = json.Marshal(taskUpdatePayload)
|
||||||
|
req = httptest.NewRequest(http.MethodPost, "/api/v1/inbox", bytes.NewReader([]byte(`{"content":"Kanban Task Test","target":"task"}`)))
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
rec = httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(rec, req)
|
||||||
|
|
||||||
|
var taskThought domain.Thought
|
||||||
|
_ = json.Unmarshal(rec.Body.Bytes(), &taskThought)
|
||||||
|
|
||||||
|
body, _ = json.Marshal(taskUpdatePayload)
|
||||||
|
req = httptest.NewRequest(http.MethodPatch, "/api/v1/thoughts/"+taskThought.ID, bytes.NewReader(body))
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
rec = httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(rec, req)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected 200 OK for PATCH /api/v1/thoughts/{id}, got %d: %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
var updatedThought domain.Thought
|
||||||
|
_ = json.Unmarshal(rec.Body.Bytes(), &updatedThought)
|
||||||
|
if updatedThought.KanbanStatus != "in_progress" || updatedThought.Notes != "Detailnotizen für die Aufgabe" {
|
||||||
|
t.Fatalf("expected updated kanbanStatus and notes, got %+v", updatedThought)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -41,11 +41,15 @@ func ExtractTags(content string) []string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type User struct {
|
type User struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
Email string `json:"email"`
|
Email string `json:"email"`
|
||||||
PasswordHash string `json:"-"`
|
PasswordHash string `json:"-"`
|
||||||
DisplayName string `json:"displayName"`
|
DisplayName string `json:"displayName"`
|
||||||
CreatedAt string `json:"createdAt"`
|
Role string `json:"role"` // admin | member
|
||||||
|
IsActive bool `json:"isActive"`
|
||||||
|
DiscordWebhookURL string `json:"discordWebhookUrl"`
|
||||||
|
NotifyBeforeMinutes int `json:"notifyBeforeMinutes"`
|
||||||
|
CreatedAt string `json:"createdAt"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ThoughtStatus string
|
type ThoughtStatus string
|
||||||
@@ -69,13 +73,60 @@ type Thought struct {
|
|||||||
ConvertedType string `json:"convertedType,omitempty"` // task | document | list_item
|
ConvertedType string `json:"convertedType,omitempty"` // task | document | list_item
|
||||||
ConvertedRefID string `json:"convertedRefId,omitempty"` // referenced entity ID
|
ConvertedRefID string `json:"convertedRefId,omitempty"` // referenced entity ID
|
||||||
DueDate string `json:"dueDate,omitempty"`
|
DueDate string `json:"dueDate,omitempty"`
|
||||||
|
TaskListID string `json:"taskListId,omitempty"`
|
||||||
|
KanbanStatus string `json:"kanbanStatus,omitempty"` // todo | in_progress | done
|
||||||
|
Notes string `json:"notes,omitempty"`
|
||||||
|
AlarmSent bool `json:"alarmSent,omitempty"`
|
||||||
CreatedAt string `json:"createdAt"`
|
CreatedAt string `json:"createdAt"`
|
||||||
TriagedAt string `json:"triagedAt,omitempty"`
|
TriagedAt string `json:"triagedAt,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type TaskList struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
UserID string `json:"userId"`
|
||||||
|
SpaceID string `json:"spaceId,omitempty"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Icon string `json:"icon"`
|
||||||
|
Color string `json:"color"`
|
||||||
|
TasksCount int `json:"tasksCount,omitempty"`
|
||||||
|
CreatedAt string `json:"createdAt"`
|
||||||
|
UpdatedAt string `json:"updatedAt"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Organization struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
OwnerID string `json:"ownerId"`
|
||||||
|
CreatedAt string `json:"createdAt"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Team struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
OrgID string `json:"orgId"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Description string `json:"description"`
|
||||||
|
Members []TeamMember `json:"members,omitempty"`
|
||||||
|
CreatedAt string `json:"createdAt"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type TeamMember struct {
|
||||||
|
TeamID string `json:"teamId"`
|
||||||
|
UserID string `json:"userId"`
|
||||||
|
DisplayName string `json:"displayName"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Role string `json:"role"` // owner | editor | viewer
|
||||||
|
JoinedAt string `json:"joinedAt"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type SystemSettings struct {
|
||||||
|
SharingMode string `json:"sharingMode"` // open | teams_only | strict_private
|
||||||
|
AllowRegistration bool `json:"allowRegistration"`
|
||||||
|
InstanceName string `json:"instanceName"`
|
||||||
|
}
|
||||||
|
|
||||||
type DocumentBlock struct {
|
type DocumentBlock struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
Type string `json:"type"` // h1 | h2 | h3 | paragraph | todo | bullet | code | callout | divider
|
Type string `json:"type"` // h1 | h2 | h3 | paragraph | todo | bullet | code | callout | divider | table | progress
|
||||||
Content string `json:"content"`
|
Content string `json:"content"`
|
||||||
Checked bool `json:"checked,omitempty"`
|
Checked bool `json:"checked,omitempty"`
|
||||||
Lang string `json:"lang,omitempty"`
|
Lang string `json:"lang,omitempty"`
|
||||||
@@ -90,6 +141,7 @@ type Document struct {
|
|||||||
Content string `json:"content"`
|
Content string `json:"content"`
|
||||||
Blocks []DocumentBlock `json:"blocks"`
|
Blocks []DocumentBlock `json:"blocks"`
|
||||||
Tags []string `json:"tags"`
|
Tags []string `json:"tags"`
|
||||||
|
FolderPath string `json:"folderPath,omitempty"`
|
||||||
IsPinned bool `json:"isPinned"`
|
IsPinned bool `json:"isPinned"`
|
||||||
IsArchived bool `json:"isArchived"`
|
IsArchived bool `json:"isArchived"`
|
||||||
CreatedAt string `json:"createdAt"`
|
CreatedAt string `json:"createdAt"`
|
||||||
@@ -180,4 +232,5 @@ type FullExport struct {
|
|||||||
Documents []Document `json:"documents"`
|
Documents []Document `json:"documents"`
|
||||||
Spaces []Space `json:"spaces"`
|
Spaces []Space `json:"spaces"`
|
||||||
Lists []SharedList `json:"lists"`
|
Lists []SharedList `json:"lists"`
|
||||||
|
TaskLists []TaskList `json:"taskLists,omitempty"`
|
||||||
}
|
}
|
||||||
+742
-94
File diff suppressed because it is too large.
Load diff
@@ -38,7 +38,7 @@ func TestStoreLifecycle(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 2. Test Tinder-Style Triage -> Convert to Document
|
// 2. Test Tinder-Style Triage -> Convert to Document
|
||||||
triaged, err := store.UpdateThoughtTriage(user.ID, thought.ID, "keep", "document", "", "")
|
triaged, err := store.UpdateThoughtTriage(user.ID, thought.ID, "keep", "document", "", "", "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("UpdateThoughtTriage failed: %v", err)
|
t.Fatalf("UpdateThoughtTriage failed: %v", err)
|
||||||
}
|
}
|
||||||
@@ -73,4 +73,39 @@ func TestStoreLifecycle(t *testing.T) {
|
|||||||
if err != nil || validatedUser.ID != user.ID {
|
if err != nil || validatedUser.ID != user.ID {
|
||||||
t.Fatalf("ValidateAPIKeyAndGetUser failed: %v", err)
|
t.Fatalf("ValidateAPIKeyAndGetUser failed: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 5. Test TaskLists CRUD
|
||||||
|
taskList, err := store.CreateTaskList(user.ID, sp.ID, "Haus & Garten", "🏡", "#10b981")
|
||||||
|
if err != nil || taskList.ID == "" {
|
||||||
|
t.Fatalf("CreateTaskList failed: %v", err)
|
||||||
|
}
|
||||||
|
taskLists, err := store.GetTaskLists(user.ID)
|
||||||
|
if err != nil || len(taskLists) == 0 {
|
||||||
|
t.Fatalf("GetTaskLists failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 6. Test Organizations & Teams
|
||||||
|
org, err := store.CreateOrganization(user.ID, "Mindsift Inc")
|
||||||
|
if err != nil || org.ID == "" {
|
||||||
|
t.Fatalf("CreateOrganization failed: %v", err)
|
||||||
|
}
|
||||||
|
team, err := store.CreateTeam(org.ID, "DevOps", "Infrastructure team")
|
||||||
|
if err != nil || team.ID == "" {
|
||||||
|
t.Fatalf("CreateTeam failed: %v", err)
|
||||||
|
}
|
||||||
|
err = store.AddTeamMember(team.ID, user.ID, "owner")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("AddTeamMember failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 7. Test System Settings
|
||||||
|
sysSettings, err := store.GetSystemSettings()
|
||||||
|
if err != nil || sysSettings.InstanceName == "" {
|
||||||
|
t.Fatalf("GetSystemSettings failed: %v", err)
|
||||||
|
}
|
||||||
|
sysSettings.SharingMode = "teams_only"
|
||||||
|
err = store.UpdateSystemSettings(sysSettings)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("UpdateSystemSettings failed: %v", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user