Compare commits

...

8 Commits

Author SHA1 Message Date
160124a184 fix for #68
Some checks failed
Build and Push Docker Images / build-backend (push) Failing after 1m28s
Build and Push Docker Images / build-frontend (push) Successful in 1m12s
2026-01-20 13:55:10 +01:00
26dad422ec added size column 2026-01-17 16:04:39 +01:00
e59cbade53 Webdav 2026-01-17 16:04:32 +01:00
6423886930 added webdav server 2026-01-17 15:15:34 +01:00
6adf09faa0 DB Change con string 2026-01-17 15:15:26 +01:00
d7f3920763 Cors Change 2026-01-17 15:15:06 +01:00
3af92ebf71 #16 Added Move Up 2026-01-17 12:55:39 +01:00
5ab90830a0 Redone Files Index, #16 Added Drag and Drop for Files 2026-01-17 12:36:28 +01:00
9 changed files with 497 additions and 260 deletions

View File

@@ -1,13 +1,26 @@
import { drizzle } from "drizzle-orm/node-postgres"
import { Pool } from "pg"
import {secrets} from "../src/utils/secrets";
import * as schema from "./schema"
// src/db/index.ts
import { drizzle } from "drizzle-orm/node-postgres";
import { Pool } from "pg";
import * as schema from "./schema";
console.log("[DB INIT] 1. Suche Connection String...");
// Checken woher die URL kommt
let connectionString = process.env.DATABASE_URL;
if (connectionString) {
console.log("[DB INIT] -> Gefunden in process.env.DATABASE_URL");
} else {
console.error("[DB INIT] ❌ KEIN CONNECTION STRING GEFUNDEN! .env nicht geladen?");
}
export const pool = new Pool({
connectionString: secrets.DATABASE_URL,
max: 10, // je nach Last
})
connectionString,
max: 10,
});
export const db = drizzle(pool , {schema})
// TEST: Ist die DB wirklich da?
pool.query('SELECT NOW()')
.then(res => console.log(`[DB INIT] ✅ VERBINDUNG ERFOLGREICH! Zeit auf DB: ${res.rows[0].now}`))
.catch(err => console.error(`[DB INIT] ❌ VERBINDUNGSFEHLER:`, err.message));
export const db = drizzle(pool, { schema });

View File

@@ -73,6 +73,7 @@ export const files = pgTable("files", {
createdBy: uuid("created_by").references(() => authUsers.id),
authProfile: uuid("auth_profile").references(() => authProfiles.id),
size: bigint("size", { mode: "number" }),
})
export type File = typeof files.$inferSelect

View File

@@ -14,7 +14,7 @@ export const hourrates = pgTable("hourrates", {
name: text("name").notNull(),
purchasePrice: doublePrecision("purchasePrice").notNull(),
purchase_price: doublePrecision("purchasePrice").notNull(),
sellingPrice: doublePrecision("sellingPrice").notNull(),
archived: boolean("archived").notNull().default(false),

View File

@@ -5,6 +5,8 @@
"main": "index.js",
"scripts": {
"dev": "tsx watch src/index.ts",
"fill": "ts-node src/webdav/fill-file-sizes.ts",
"dev:dav": "tsx watch src/webdav/server.ts",
"build": "tsc",
"start": "node dist/src/index.js",
"schema:index": "ts-node scripts/generate-schema-index.ts"
@@ -48,6 +50,7 @@
"pg": "^8.16.3",
"pngjs": "^7.0.0",
"sharp": "^0.34.5",
"webdav-server": "^2.6.2",
"xmlbuilder": "^15.1.1",
"zpl-image": "^0.2.0",
"zpl-renderer-js": "^2.0.2"

View File

@@ -52,6 +52,7 @@ import {loadSecrets, secrets} from "./utils/secrets";
import {initMailer} from "./utils/mailer"
import {initS3} from "./utils/s3";
//Services
import servicesPlugin from "./plugins/services";

View File

@@ -14,8 +14,9 @@ export default fp(async (server: FastifyInstance) => {
"https://app.fedeo.de", // dein Nuxt-Frontend
"capacitor://localhost", // dein Nuxt-Frontend
],
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allowedHeaders: ["Content-Type", "Authorization", "Context", "X-Public-Pin"],
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS",
"PROPFIND", "PROPPATCH", "MKCOL", "COPY", "MOVE", "LOCK", "UNLOCK"],
allowedHeaders: ["Content-Type", "Authorization", "Context", "X-Public-Pin","Depth", "Overwrite", "Destination", "Lock-Token", "If"],
exposedHeaders: ["Authorization", "Content-Disposition", "Content-Type", "Content-Length"], // optional, falls du ihn auch auslesen willst
credentials: true, // wichtig, falls du Cookies nutzt
});

View File

@@ -0,0 +1,74 @@
// scripts/fill-file-sizes.ts
import 'dotenv/config';
import { db } from '../../db';
import { files } from '../../db/schema';
import { eq, isNull } from 'drizzle-orm';
import { HeadObjectCommand } from "@aws-sdk/client-s3";
import { s3, initS3 } from '../utils/s3';
import { loadSecrets, secrets } from '../utils/secrets';
async function migrate() {
console.log("🚀 Starte Migration der Dateigrößen...");
// 1. Setup
await loadSecrets();
await initS3();
// 2. Alle Dateien holen, die noch keine Größe haben (oder alle, um sicherzugehen)
// Wir nehmen erstmal ALLE, um sicherzustellen, dass alles stimmt.
const allFiles = await db.select().from(files);
console.log(`📦 ${allFiles.length} Dateien in der Datenbank gefunden.`);
let successCount = 0;
let errorCount = 0;
// 3. Loop durch alle Dateien
for (const file of allFiles) {
if (!file.path) {
console.log(`⏭️ Überspringe Datei ${file.id} (Kein Pfad)`);
continue;
}
try {
// S3 fragen (HeadObject lädt nur Metadaten, nicht die ganze Datei -> Schnell)
const command = new HeadObjectCommand({
Bucket: secrets.S3_BUCKET, // Oder secrets.S3_BUCKET_NAME je nach deiner Config
Key: file.path
});
const response = await s3.send(command);
const size = response.ContentLength || 0;
// In DB speichern
await db.update(files)
.set({ size: size })
.where(eq(files.id, file.id));
process.stdout.write("."); // Fortschrittsanzeige
successCount++;
} catch (error: any) {
process.stdout.write("X");
// console.error(`\n❌ Fehler bei ${file.path}: ${error.name}`);
// Optional: Wenn Datei in S3 fehlt, könnten wir sie markieren oder loggen
if (error.name === 'NotFound') {
// console.error(` -> Datei existiert nicht im Bucket!`);
}
errorCount++;
}
}
console.log("\n\n------------------------------------------------");
console.log(`✅ Fertig!`);
console.log(`Updated: ${successCount}`);
console.log(`Fehler: ${errorCount} (Meistens Dateien, die im Bucket fehlen)`);
console.log("------------------------------------------------");
process.exit(0);
}
migrate().catch(err => {
console.error("Fataler Fehler:", err);
process.exit(1);
});

View File

@@ -0,0 +1,198 @@
import 'dotenv/config';
import { v2 as webdav } from 'webdav-server';
import { db } from '../../db';
import { tenants, files, folders } from '../../db/schema';
import { Readable } from 'stream';
import { GetObjectCommand, HeadObjectCommand } from "@aws-sdk/client-s3";
import { s3, initS3 } from '../utils/s3';
import { secrets, loadSecrets } from '../utils/secrets';
// ============================================================================
// 1. SETUP
// ============================================================================
const userManager = new webdav.SimpleUserManager();
const user = userManager.addUser('admin', 'admin', true);
const privilegeManager = new webdav.SimplePathPrivilegeManager();
privilegeManager.setRights(user, '/', [ 'all' ]);
const server = new webdav.WebDAVServer({
httpAuthentication: new webdav.HTTPDigestAuthentication(userManager, 'Default realm'),
privilegeManager: privilegeManager,
port: 3200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,POST,PUT,DELETE,OPTIONS,PROPFIND,PROPPATCH,MKCOL,COPY,MOVE,LOCK,UNLOCK',
'Access-Control-Allow-Headers': 'Authorization, Content-Type, Depth, User-Agent, X-Expected-Entity-Length, If-Modified-Since, Cache-Control, Range, Overwrite, Destination',
}
});
// ============================================================================
// 2. CACHE
// ============================================================================
const pathToS3KeyMap = new Map<string, string>();
const pathToSizeMap = new Map<string, number>();
// ============================================================================
// 3. LOGIC
// ============================================================================
async function startServer() {
console.log('------------------------------------------------');
console.log('[WebDAV] Starte Server (Filtered Mode)...');
try {
await loadSecrets();
await initS3();
console.log('[WebDAV] S3 Verbindung OK.');
console.log('[WebDAV] Lade Datenbank...');
const allTenants = await db.select().from(tenants);
const allFolders = await db.select().from(folders);
const allFiles = await db.select().from(files);
// Zähler für Statistik
let hiddenFilesCount = 0;
// --------------------------------------------------------------------
// BUILDER
// --------------------------------------------------------------------
const buildFolderContent = (tenantId: string, parentFolderId: string | null, currentWebDavPath: string) => {
const currentDir: any = {};
// 1. UNTERORDNER
const subFolders = allFolders.filter(f => f.tenant === tenantId && f.parent === parentFolderId);
subFolders.forEach(folder => {
const folderName = folder.name.replace(/\//g, '-');
const nextPath = `${currentWebDavPath}/${folderName}`;
currentDir[folderName] = buildFolderContent(tenantId, folder.id, nextPath);
});
// 2. DATEIEN
const dirFiles = allFiles.filter(f => f.tenant === tenantId && f.folder === parentFolderId);
dirFiles.forEach(file => {
// ============================================================
// ❌ FILTER: DATEIEN OHNE GRÖSSE AUSBLENDEN
// ============================================================
const fileSize = Number(file.size || 0);
if (fileSize <= 0) {
// Datei überspringen, wenn 0 Bytes oder null
hiddenFilesCount++;
return;
}
// ============================================================
// Name bestimmen
let fileName = 'Unbenannt';
if (file.path) fileName = file.path.split('/').pop() || 'Unbenannt';
else if (file.name) fileName = file.name;
// A) Eintrag im WebDAV
currentDir[fileName] = `Ref: ${file.id}`;
// B) Maps füllen
const webDavFullPath = `${currentWebDavPath}/${fileName}`;
if (file.path) {
pathToS3KeyMap.set(webDavFullPath, file.path);
}
// C) Größe setzen (wir wissen jetzt sicher, dass sie > 0 ist)
pathToSizeMap.set(webDavFullPath, fileSize);
});
return currentDir;
};
// --------------------------------------------------------------------
// BAUM ZUSAMMENSETZEN
// --------------------------------------------------------------------
const dbTree: any = {};
allTenants.forEach(tenant => {
const tName = tenant.name.replace(/\//g, '-');
const rootPath = `/${tName}`;
const content = buildFolderContent(tenant.id, null, rootPath);
// Leere Ordner Hinweis (optional)
if (Object.keys(content).length === 0) {
content['(Leer).txt'] = 'Keine gültigen Dateien vorhanden.';
}
dbTree[tName] = content;
});
if (Object.keys(dbTree).length === 0) {
dbTree['Status.txt'] = 'Datenbank leer.';
}
// --------------------------------------------------------------------
// REGISTRIEREN
// --------------------------------------------------------------------
const rootFS = server.rootFileSystem();
rootFS.addSubTree(server.createExternalContext(), dbTree);
// ====================================================================
// OVERRIDE 1: DOWNLOAD
// ====================================================================
(rootFS as any)._openReadStream = async (path: webdav.Path, ctx: any, callback: any) => {
const p = path.toString();
const s3Key = pathToS3KeyMap.get(p);
if (s3Key) {
try {
const command = new GetObjectCommand({ Bucket: secrets.S3_BUCKET, Key: s3Key });
const response = await s3.send(command);
if (response.Body) return callback(null, response.Body as Readable);
} catch (e: any) {
console.error(`[S3 ERROR] ${e.message}`);
return callback(null, Readable.from([`Error: ${e.message}`]));
}
}
return callback(null, Readable.from(['System File']));
};
// ====================================================================
// OVERRIDE 2: SIZE
// ====================================================================
(rootFS as any)._size = async (path: webdav.Path, ctx: any, callback: any) => {
const p = path.toString();
const cachedSize = pathToSizeMap.get(p);
if (cachedSize !== undefined) return callback(null, cachedSize);
// Fallback S3 Check (sollte durch Filter kaum noch vorkommen)
const s3Key = pathToS3KeyMap.get(p);
if (s3Key) {
try {
const command = new HeadObjectCommand({ Bucket: secrets.S3_BUCKET, Key: s3Key });
const response = await s3.send(command);
const realSize = response.ContentLength || 0;
pathToSizeMap.set(p, realSize);
return callback(null, realSize);
} catch (e) {
return callback(null, 0);
}
}
return callback(null, 0);
};
// --------------------------------------------------------------------
// START
// --------------------------------------------------------------------
server.start(() => {
console.log('[WebDAV] 🚀 READY auf http://localhost:3200');
console.log(`[WebDAV] Sichtbare Dateien: ${pathToS3KeyMap.size}`);
console.log(`[WebDAV] Ausgeblendet (0 Bytes): ${hiddenFilesCount}`);
});
} catch (error) {
console.error('[WebDAV] 💥 ERROR:', error);
}
}
startServer();

View File

@@ -1,37 +1,16 @@
<script setup>
import { ref, computed, watch } from 'vue';
import { ref, computed, watch, onMounted } from 'vue';
import DocumentDisplayModal from "~/components/DocumentDisplayModal.vue";
import DocumentUploadModal from "~/components/DocumentUploadModal.vue";
import dayjs from "dayjs";
import arraySort from "array-sort";
// --- Shortcuts ---
defineShortcuts({
'/': () => document.getElementById("searchinput").focus(),
'+': () => { uploadModalOpen.value = true },
'Enter': {
usingInput: true,
handler: () => {
const entry = renderedFileList.value[selectedFileIndex.value]
if (!entry) return
if (entry.type === "file") showFile(entry.id)
else if (entry.type === "folder") changeFolder(folders.value.find(i => i.id === entry.id))
}
},
'arrowdown': () => {
if (selectedFileIndex.value < renderedFileList.value.length - 1) selectedFileIndex.value++
},
'arrowup': () => {
if (selectedFileIndex.value > 0) selectedFileIndex.value--
}
})
// --- Services & Stores ---
const dataStore = useDataStore()
const tempStore = useTempStore()
const router = useRouter()
const route = useRoute()
const modal = useModal()
const auth = useAuthStore()
const toast = useToast()
const files = useFiles()
// --- State ---
@@ -49,8 +28,11 @@ const displayModes = [
const createFolderModalOpen = ref(false)
const createFolderData = ref({ name: '', standardFiletype: null, standardFiletypeIsOptional: true })
const selectedFiles = ref({})
const renameModalOpen = ref(false)
const renameData = ref({ id: null, name: '', type: '' })
const selectedFileIndex = ref(0)
const draggedItem = ref(null)
// --- Search & Debounce ---
const searchString = ref(tempStore.searchStrings["files"] || '')
@@ -65,43 +47,83 @@ watch(searchString, (val) => {
}, 300)
})
// --- Logic ---
// --- Data Fetching ---
const setupPage = async () => {
loadingDocs.value = true
const [fRes, dRes, tRes] = await Promise.all([
useEntities("folders").select(),
files.selectDocuments(),
useEntities("filetags").select()
])
folders.value = fRes
documents.value = dRes
filetags.value = tRes
try {
const [fRes, dRes, tRes] = await Promise.all([
useEntities("folders").select(),
files.selectDocuments(),
useEntities("filetags").select()
])
folders.value = fRes || []
documents.value = dRes || []
filetags.value = tRes || []
if (route.query?.folder) {
currentFolder.value = folders.value.find(i => i.id === route.query.folder) || null
if (route.query?.folder) {
currentFolder.value = folders.value.find(i => i.id === route.query.folder) || null
} else {
currentFolder.value = null
}
} finally {
loadingDocs.value = false
loaded.value = true
}
loadingDocs.value = false
loaded.value = true
}
onMounted(() => setupPage())
const currentFolders = computed(() => {
return folders.value
.filter(i => currentFolder.value ? i.parent === currentFolder.value.id : !i.parent)
.sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }))
})
// --- Navigation ---
const changeFolder = async (folder) => {
currentFolder.value = folder
await router.push(folder ? `/files?folder=${folder.id}` : `/files`)
}
const navigateUp = () => {
if (!currentFolder.value) return
const parent = folders.value.find(f => f.id === currentFolder.value.parent)
changeFolder(parent || null)
}
// --- Drag & Drop ---
const handleDragStart = (entry) => {
draggedItem.value = entry
}
const handleDrop = async (targetFolderId) => {
// targetFolderId kann null sein (Root)
if (!draggedItem.value) return
if (draggedItem.value.id === targetFolderId) return
loadingDocs.value = true
try {
if (draggedItem.value.type === 'file') {
await useEntities("files").update(draggedItem.value.id, { folder: targetFolderId })
} else {
await useEntities("folders").update(draggedItem.value.id, { parent: targetFolderId })
}
toast.add({ title: 'Erfolgreich verschoben', icon: 'i-heroicons-check-circle', color: 'green' })
await setupPage()
} catch (e) {
toast.add({ title: 'Fehler beim Verschieben', color: 'red' })
} finally {
draggedItem.value = null
loadingDocs.value = false
}
}
// --- Breadcrumbs ---
const breadcrumbLinks = computed(() => {
const links = [{ label: "Home", icon: "i-heroicons-home", click: () => changeFolder(null) }]
if (currentFolder.value) {
let path = []
const path = []
let curr = currentFolder.value
while (curr) {
const folderObj = curr
path.unshift({
label: curr.name,
label: folderObj.name,
icon: "i-heroicons-folder",
click: () => changeFolder(folders.value.find(f => f.id === curr.id))
click: () => changeFolder(folderObj)
})
curr = folders.value.find(f => f.id === curr.parent)
}
@@ -110,48 +132,74 @@ const breadcrumbLinks = computed(() => {
return links
})
// --- Data Mapping ---
const renderedFileList = computed(() => {
const folderList = currentFolders.value.map(i => ({
label: i.name,
id: i.id,
type: "folder",
createdAt: i.createdAt
}))
// 1. Aktuelle Ordner filtern
const folderList = folders.value
.filter(i => currentFolder.value ? i.parent === currentFolder.value.id : !i.parent)
.map(i => ({ ...i, label: i.name, type: "folder" }))
.sort((a, b) => a.label.localeCompare(b.label))
// 2. Aktuelle Dateien filtern
const fileList = documents.value
.filter(i => currentFolder.value ? i.folder === currentFolder.value.id : !i.folder)
.map(i => ({
label: i.path.split("/").pop(),
id: i.id,
type: "file",
createdAt: i.createdAt
}))
.sort((a, b) => a.label.localeCompare(b.label, undefined, { sensitivity: 'base' }))
.map(i => ({ ...i, label: i.path.split("/").pop(), type: "file" }))
.sort((a, b) => a.label.localeCompare(b.label))
let combined = [...folderList, ...fileList]
if (debouncedSearch.value) {
combined = useSearch(debouncedSearch.value, combined)
}
// 3. "Nach oben" (..) einfügen, wenn wir nicht im Root sind und nicht suchen
if (currentFolder.value && !debouncedSearch.value) {
combined.unshift({
id: 'go-up',
label: '..',
type: 'up',
parentId: currentFolder.value.parent || null
})
}
return combined
})
const changeFolder = async (folder) => {
currentFolder.value = folder
await router.push(folder ? `/files?folder=${folder.id}` : `/files`)
}
// --- Actions ---
const createFolder = async () => {
await useEntities("folders").create({
parent: currentFolder.value?.id,
name: createFolderData.value.name,
standardFiletype: createFolderData.value.standardFiletype,
standardFiletypeIsOptional: createFolderData.value.standardFiletypeIsOptional
name: createFolderData.value.name
})
createFolderModalOpen.value = false
createFolderData.value = { name: '', standardFiletype: null, standardFiletypeIsOptional: true }
createFolderData.value = { name: '' }
setupPage()
}
const openRenameModal = (entry) => {
renameData.value = { id: entry.id, name: entry.label, type: entry.type }
renameModalOpen.value = true
}
const updateName = async () => {
if (!renameData.value.name) return
loadingDocs.value = true
try {
if (renameData.value.type === 'folder') {
await useEntities("folders").update(renameData.value.id, { name: renameData.value.name })
} else {
const file = documents.value.find(d => d.id === renameData.value.id)
const pathParts = file.path.split('/')
pathParts[pathParts.length - 1] = renameData.value.name
await useEntities("files").update(renameData.value.id, { path: pathParts.join('/') })
}
toast.add({ title: 'Umbenannt', color: 'green' })
setupPage()
} finally {
renameModalOpen.value = false
loadingDocs.value = false
}
}
const showFile = (fileId) => {
modal.open(DocumentDisplayModal, {
documentData: documents.value.find(i => i.id === fileId),
@@ -159,234 +207,132 @@ const showFile = (fileId) => {
})
}
const downloadSelected = async () => {
const ids = Object.keys(selectedFiles.value).filter(k => selectedFiles.value[k])
await useFiles().downloadFile(undefined, ids)
}
const clearSearchString = () => {
searchString.value = ''
debouncedSearch.value = ''
tempStore.clearSearchString("files")
}
const selectAll = (event) => {
if (event.target.checked) {
const obj = {}
renderedFileList.value.filter(e => e.type === 'file').forEach(e => obj[e.id] = true)
selectedFiles.value = obj
} else {
selectedFiles.value = {}
}
}
defineShortcuts({
'/': () => document.getElementById("searchinput")?.focus(),
'Enter': {
usingInput: true,
handler: () => {
const entry = renderedFileList.value[selectedFileIndex.value]
if (!entry) return
if (entry.type === "file") showFile(entry.id)
else if (entry.type === "folder") changeFolder(entry)
else if (entry.type === "up") navigateUp()
}
},
'arrowdown': () => { if (selectedFileIndex.value < renderedFileList.value.length - 1) selectedFileIndex.value++ },
'arrowup': () => { if (selectedFileIndex.value > 0) selectedFileIndex.value-- }
})
</script>
<template>
<UDashboardNavbar title="Dateien">
<template #right>
<UInput
id="searchinput"
v-model="searchString"
icon="i-heroicons-magnifying-glass"
autocomplete="off"
placeholder="Suche..."
class="hidden lg:block w-64"
@keydown.esc="$event.target.blur()"
>
<template #trailing>
<div class="flex items-center gap-1">
<UKbd value="/" />
<UButton
v-if="searchString.length > 0"
icon="i-heroicons-x-mark"
variant="ghost"
color="gray"
size="xs"
@click="clearSearchString"
/>
</div>
</template>
</UInput>
<UInput id="searchinput" v-model="searchString" icon="i-heroicons-magnifying-glass" placeholder="Suche..." class="w-64" />
</template>
</UDashboardNavbar>
<UDashboardToolbar class="sticky top-0 z-10 bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-800">
<UDashboardToolbar class="sticky top-0 z-30 bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-800">
<template #left>
<UBreadcrumb :links="breadcrumbLinks" :ui="{ ol: 'gap-x-2', li: 'text-sm' }" />
<UBreadcrumb :links="breadcrumbLinks" />
</template>
<template #right>
<USelectMenu
v-model="displayMode"
:options="displayModes"
value-attribute="key"
class="w-32"
>
<USelectMenu v-model="displayMode" :options="displayModes" value-attribute="key" class="w-32" :ui-menu="{ zIndex: 'z-50' }">
<template #label>
<UIcon :name="displayModes.find(i => i.key === displayMode).icon" class="w-4 h-4" />
<span>{{ displayModes.find(i => i.key === displayMode).label }}</span>
</template>
</USelectMenu>
<UButtonGroup size="sm">
<UButton
icon="i-heroicons-document-plus"
color="primary"
@click="modal.open(DocumentUploadModal, {
fileData: {
folder: currentFolder?.id,
type: currentFolder?.standardFiletype,
typeEnabled: currentFolder?.standardFiletypeIsOptional
},
onUploadFinished: () => setupPage()
})"
>Datei</UButton>
<UButton
icon="i-heroicons-folder-plus"
color="white"
@click="createFolderModalOpen = true"
>Ordner</UButton>
<UButton icon="i-heroicons-document-plus" color="primary" @click="modal.open(DocumentUploadModal, { fileData: { folder: currentFolder?.id }, onUploadFinished: setupPage })">Datei</UButton>
<UButton icon="i-heroicons-folder-plus" color="white" @click="createFolderModalOpen = true">Ordner</UButton>
</UButtonGroup>
<UButton
v-if="Object.values(selectedFiles).some(Boolean)"
icon="i-heroicons-cloud-arrow-down"
color="gray"
variant="solid"
@click="downloadSelected"
>Download</UButton>
</template>
</UDashboardToolbar>
<div id="drop_zone" class="flex-1 overflow-hidden flex flex-col relative">
<div v-if="!loaded" class="p-10 flex justify-center">
<UProgress animation="carousel" class="w-1/2" />
</div>
<UDashboardPanelContent class="p-0 overflow-y-auto">
<div v-if="!loaded" class="p-10 flex justify-center"><UProgress animation="carousel" class="w-1/2" /></div>
<UDashboardPanelContent v-else class="p-0 overflow-y-auto">
<div v-if="displayMode === 'list'" class="min-w-full inline-block align-middle">
<table class="min-w-full divide-y divide-gray-300 dark:divide-gray-700">
<div v-else>
<div v-if="displayMode === 'list'">
<table class="min-w-full divide-y divide-gray-200 dark:divide-gray-800">
<thead class="bg-gray-50 dark:bg-gray-800 sticky top-0 z-20">
<tr>
<th scope="col" class="py-3.5 pl-4 pr-3 sm:pl-6 w-10">
<UCheckbox @change="selectAll" />
</th>
<th scope="col" class="py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 dark:text-white sm:pl-6">Name</th>
<th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900 dark:text-white">Erstellt am</th>
<th class="py-3.5 pl-4 pr-3 text-left text-sm font-semibold sm:pl-6">Name</th>
<th class="px-3 py-3.5 text-left text-sm font-semibold">Erstellt</th>
<th class="relative py-3.5 pl-3 pr-4 sm:pr-6"></th>
</tr>
</thead>
<tbody class="divide-y divide-gray-200 dark:divide-gray-800 bg-white dark:bg-gray-900">
<tr
v-for="(entry, index) in renderedFileList"
:key="entry.id"
v-for="(entry, index) in renderedFileList" :key="entry.id"
:draggable="entry.type !== 'up'"
@dragstart="handleDragStart(entry)"
@dragover.prevent
@drop="entry.type === 'folder' ? handleDrop(entry.id) : (entry.type === 'up' ? handleDrop(entry.parentId) : null)"
class="hover:bg-gray-50 dark:hover:bg-gray-800/50 cursor-pointer transition-colors"
:class="{'bg-primary-50 dark:bg-primary-900/10': index === selectedFileIndex}"
@click="entry.type === 'folder' ? changeFolder(entry) : showFile(entry.id)"
@click="entry.type === 'folder' ? changeFolder(entry) : (entry.type === 'up' ? navigateUp() : showFile(entry.id))"
>
<td class="relative w-12 px-6 sm:w-16 sm:px-8" @click.stop>
<UCheckbox v-if="entry.type === 'file'" v-model="selectedFiles[entry.id]" />
</td>
<td class="whitespace-nowrap py-4 pl-4 pr-3 text-sm sm:pl-6">
<div class="flex items-center">
<div class="flex items-center font-medium">
<UIcon
:name="entry.type === 'folder' ? 'i-heroicons-folder-solid' : 'i-heroicons-document-text'"
class="flex-shrink-0 h-5 w-5 mr-3"
:class="entry.type === 'folder' ? 'text-primary-500' : 'text-gray-400'"
:name="entry.type === 'up' ? 'i-heroicons-arrow-uturn-left' : (entry.type === 'folder' ? 'i-heroicons-folder-solid' : 'i-heroicons-document-text')"
class="h-5 w-5 mr-3"
:class="entry.type === 'up' ? 'text-orange-500' : (entry.type === 'folder' ? 'text-primary-500' : 'text-gray-400')"
/>
<span class="font-medium text-gray-900 dark:text-white truncate max-w-md">
{{ entry.label }}
</span>
{{ entry.label }}
</div>
</td>
<td class="whitespace-nowrap px-3 py-4 text-sm text-gray-500 dark:text-gray-400">
{{ dayjs(entry.createdAt).format("DD.MM.YY · HH:mm") }}
<td class="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
{{ entry.type !== 'up' ? dayjs(entry.createdAt).format("DD.MM.YY") : '-' }}
</td>
<td class="px-3 text-right" @click.stop>
<UDropdown v-if="entry.type !== 'up'" :items="[[{ label: 'Umbenennen', icon: 'i-heroicons-pencil-square', click: () => openRenameModal(entry) }]]">
<UButton color="gray" variant="ghost" icon="i-heroicons-ellipsis-horizontal" />
</UDropdown>
</td>
</tr>
</tbody>
</table>
</div>
<div v-else class="p-6">
<div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 xl:grid-cols-8 gap-4">
<div
v-for="folder in currentFolders"
:key="folder.id"
class="group relative bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-xl p-4 flex flex-col items-center hover:border-primary-500 transition-all cursor-pointer"
@click="changeFolder(folder)"
>
<UIcon name="i-heroicons-folder-solid" class="w-12 h-12 text-primary-500 mb-2 group-hover:scale-110 transition-transform" />
<span class="text-sm font-medium text-center truncate w-full">{{ folder.name }}</span>
</div>
<div
v-for="doc in renderedFileList.filter(e => e.type === 'file')"
:key="doc.id"
class="group relative bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-xl p-4 flex flex-col items-center hover:border-primary-500 transition-all cursor-pointer"
@click="showFile(doc.id)"
>
<UCheckbox v-model="selectedFiles[doc.id]" class="absolute top-2 left-2 opacity-0 group-hover:opacity-100 transition-opacity" @click.stop />
<UIcon name="i-heroicons-document-text" class="w-12 h-12 text-gray-400 mb-2 group-hover:scale-110 transition-transform" />
<span class="text-sm font-medium text-center truncate w-full">{{ doc.label }}</span>
</div>
<div v-else class="p-6 grid grid-cols-2 sm:grid-cols-4 md:grid-cols-6 lg:grid-cols-8 gap-4">
<div
v-for="entry in renderedFileList" :key="entry.id"
:draggable="entry.type !== 'up'"
@dragstart="handleDragStart(entry)"
@dragover.prevent
@drop="entry.type === 'folder' ? handleDrop(entry.id) : (entry.type === 'up' ? handleDrop(entry.parentId) : null)"
class="group relative bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-xl p-4 flex flex-col items-center hover:border-primary-500 transition-all cursor-pointer"
@click="entry.type === 'folder' ? changeFolder(entry) : (entry.type === 'up' ? navigateUp() : showFile(entry.id))"
>
<UDropdown v-if="entry.type !== 'up'" :items="[[{ label: 'Umbenennen', icon: 'i-heroicons-pencil-square', click: () => openRenameModal(entry) }]]" class="absolute top-1 right-1 opacity-0 group-hover:opacity-100" @click.stop>
<UButton color="gray" variant="ghost" icon="i-heroicons-ellipsis-vertical" size="xs" />
</UDropdown>
<UIcon
:name="entry.type === 'up' ? 'i-heroicons-arrow-uturn-left' : (entry.type === 'folder' ? 'i-heroicons-folder-solid' : 'i-heroicons-document-text')"
class="w-12 h-12 mb-2"
:class="entry.type === 'up' ? 'text-orange-500' : (entry.type === 'folder' ? 'text-primary-500' : 'text-gray-400')"
/>
<span class="text-xs font-medium text-center truncate w-full">{{ entry.label }}</span>
</div>
</div>
</UDashboardPanelContent>
</div>
</div>
</UDashboardPanelContent>
<UModal v-model="createFolderModalOpen">
<UCard>
<template #header>
<div class="flex items-center justify-between">
<h3 class="text-lg font-bold">Ordner erstellen</h3>
<UButton color="gray" variant="ghost" icon="i-heroicons-x-mark" @click="createFolderModalOpen = false" />
</div>
</template>
<div class="space-y-4">
<UFormGroup label="Name" required>
<UInput v-model="createFolderData.name" placeholder="Name eingeben..." autofocus @keyup.enter="createFolder" />
</UFormGroup>
<UFormGroup label="Standard-Dateityp">
<USelectMenu
v-model="createFolderData.standardFiletype"
:options="filetags"
option-attribute="name"
value-attribute="id"
placeholder="Kein Standard"
/>
</UFormGroup>
<UCheckbox
v-if="createFolderData.standardFiletype"
v-model="createFolderData.standardFiletypeIsOptional"
label="Typ ist optional"
/>
</div>
<template #footer>
<div class="flex justify-end gap-2">
<UButton color="gray" variant="soft" @click="createFolderModalOpen = false">Abbrechen</UButton>
<UButton color="primary" :disabled="!createFolderData.name" @click="createFolder">Erstellen</UButton>
</div>
</template>
<template #header><h3 class="font-bold">Ordner erstellen</h3></template>
<UFormGroup label="Name" required><UInput v-model="createFolderData.name" autofocus @keyup.enter="createFolder" /></UFormGroup>
<template #footer><div class="flex justify-end gap-2"><UButton color="gray" @click="createFolderModalOpen = false">Abbrechen</UButton><UButton color="primary" @click="createFolder">Erstellen</UButton></div></template>
</UCard>
</UModal>
</template>
<style scoped>
#drop_zone::after {
content: 'Datei hierher ziehen';
@apply absolute inset-0 flex items-center justify-center bg-primary-500/10 border-4 border-dashed border-primary-500 opacity-0 pointer-events-none transition-opacity z-50 rounded-xl m-4;
}
#drop_zone:hover::after {
/* In der setupPage Logik wird das Modal getriggert,
dieser Style dient nur der visuellen Hilfe */
}
/* Custom Table Shadows & Borders */
table {
border-collapse: separate;
border-spacing: 0;
}
</style>
<UModal v-model="renameModalOpen">
<UCard>
<template #header><h3 class="font-bold">Umbenennen</h3></template>
<UFormGroup label="Neuer Name"><UInput v-model="renameData.name" autofocus @keyup.enter="updateName" /></UFormGroup>
<template #footer><div class="flex justify-end gap-2"><UButton color="gray" @click="renameModalOpen = false">Abbrechen</UButton><UButton color="primary" @click="updateName">Speichern</UButton></div></template>
</UCard>
</UModal>
</template>