10 Commits

10 changed files with 631 additions and 47 deletions

View File

@@ -0,0 +1,53 @@
<script lang="ts">
import { fly, scale, fade } from 'svelte/transition';
import { cubicOut } from 'svelte/easing';
import { tick } from 'svelte';
let expanded = false;
let formContainer: HTMLDivElement;
async function toggle() {
expanded = !expanded;
if (expanded) {
// Wait for DOM to update
await tick();
// Scroll smoothly into view
formContainer?.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
}
</script>
<div data-testid="expand-container" class="flex flex-col items-center">
<!-- + / × button -->
<button
class="flex items-center justify-center w-12 h-12 rounded-full bg-blue-600 text-white text-2xl font-bold hover:bg-blue-700 transition"
on:click={toggle}
aria-expanded={expanded}
aria-label="Add item"
>
{#if expanded}
{:else}
+
{/if}
</button>
<!-- Expandable content below button -->
{#if expanded}
<div
bind:this={formContainer}
class="w-full mt-4 flex justify-center"
transition:fade
>
<div
in:fly={{ y: 10, duration: 200, easing: cubicOut }}
out:scale={{ duration: 150 }}
class="w-full max-w-2xl"
>
<slot />
</div>
</div>
{/if}
</div>

View File

@@ -1,6 +1,7 @@
import { fail } from '@sveltejs/kit';
import { BUCKET, client, CONFIGFILENAME, TOKENFILENAME } from '$lib/minio';
import { checkIfExactDirectoryExists, getContentOfTextObject } from './s3ClientService';
import { v4 as uuidv4 } from 'uuid';
import { db } from './dbService';
@@ -45,6 +46,31 @@ export const getVorgangByToken = (
return result;
};
/**
* Create Vorgang, using a vorgangName and vorgangPIN
* @param vorgangName
* @param vorgangPIN
* @returns {string || false} vorgangToken if successful
*/
export const createVorgang = (vorgangName: string, vorgangPIN: string): string | boolean => {
const vorgangExists = vorgangNameExists(vorgangName);
if (vorgangExists) {
return false;
}
const vorgangToken = uuidv4();
const insertSQLStatement = `INSERT INTO cases (token, name, pin) VALUES (?, ?, ?)`;
const statement = db.prepare(insertSQLStatement);
const info = statement.run(vorgangToken, vorgangName, vorgangPIN);
if (info.changes) {
return vorgangToken;
} else {
return false;
}
};
/**
* Get Vorgang
* @param vorgangName

View File

@@ -31,18 +31,6 @@
Verschaffe Dir einen Überblick über alle gespeicherten Tatorte.
</p>
</div>
<div class="group relative rounded-lg p-6 text-sm leading-6 hover:bg-gray-50 w-1/4">
<div
class="flex h-11 w-11 items-center justify-center rounded-lg bg-gray-50 group-hover:bg-white"
>
<AddProcess class=" group-hover:text-indigo-600" />
</div>
<a href="{ROUTE_NAMES.UPLOAD}" class="mt-6 block font-semibold text-gray-900">
Hinzufügen
<span class="absolute inset-0"></span>
</a>
<p class="mt-1 text-gray-600">Fügen Sie einem Tatort Bilder hinzu.</p>
</div>
<div class="group relative rounded-lg p-6 text-sm leading-6 hover:bg-gray-50 w-1/4">
<div
class="flex h-11 w-11 items-center justify-center rounded-lg bg-gray-50 group-hover:bg-white"

View File

@@ -1,6 +1,6 @@
import { getVorgaenge } from '$lib/server/vorgangService';
import { createVorgang, getVorgaenge } from '$lib/server/vorgangService';
import type { PageServerLoad } from '../../(token-based)/view/$types';
import { error } from '@sveltejs/kit';
import { error, fail } from '@sveltejs/kit';
export const load: PageServerLoad = async (event) => {
if (!event.locals.user) {
@@ -13,3 +13,23 @@ export const load: PageServerLoad = async (event) => {
vorgangList
};
};
export const actions = {
default: async ({ request }: { request: Request }) => {
const data = await request.formData();
const vorgangName: string | null = data.get('vorgang') as string;
const vorgangPIN: string | null = data.get('pin') as string;
const err = {};
const token = createVorgang(vorgangName, vorgangPIN);
if (!token) {
err.message = "Der Vorgang konnte nicht angelegt werden"
return fail(400, err)
} else {
// success
return { token }
}
}
};

View File

@@ -1,15 +1,66 @@
<script lang="ts">
import ExpandableForm from '$lib/components/ExpandableForm.svelte';
import Trash from '$lib/icons/Trash.svelte';
import Folder from '$lib/icons/Folder.svelte';
import EmptyList from '$lib/components/EmptyList.svelte';
import { API_ROUTES, ROUTE_NAMES } from '../../index.js';
let { data } = $props();
let { data, form } = $props();
let vorgangList = data.vorgangList;
let isEmptyList = vorgangList.length === 0;
let vorgangName = $state('');
let vorgangPIN = $state('');
let errorMsg = $state('');
// reset input fields when submission successful
$effect(() => {
if (form?.token) {
vorgangName = '';
vorgangPIN = '';
errorMsg = '';
}
});
async function submitVorgang(ev: Event) {
const isValid = inputValid(vorgangName, vorgangPIN);
if (!isValid) {
ev.preventDefault();
return;
}
// continue form action on server
}
/**
* Check for required fields
* @param vorgangName
* @param vorgangPIN
* @returns {boolean} Indicates whether input is valid
*/
function inputValid(vorgangName, vorgangPIN) {
if (!(vorgangName || vorgangPIN)) {
errorMsg = 'Bitte beide Felder ausfüllen.';
return false;
} else if (!vorgangName) {
errorMsg = 'Bitte einen Vorgangsnamen vergeben.';
return false;
} else if (!vorgangPIN) {
errorMsg = 'Bitte einen Vorgangs-PIN eingeben.';
return false;
}
const existing = vorgangList.some((vorg) => vorg.vorgangName === vorgangName);
if (existing) {
errorMsg = 'Der Name existiert bereits.';
return false;
}
return true;
}
async function delete_item(ev: Event) {
let delete_item = window.confirm('Bist du sicher?');
@@ -80,6 +131,68 @@
</div>
</div>
<ExpandableForm>
<form class="flex flex-col items-center" method="POST">
<div class="flex flex-col sm:flex-row sm:space-x-4 w-full max-w-lg">
<div class="flex-1">
<label for="vorgang" class="block text-sm font-medium leading-6 text-gray-900">
<span class="flex"> Vorgangsname </span>
</label>
<div class="mt-2">
<div
class="flex rounded-md shadow-sm ring-1 ring-inset ring-gray-300 focus-within:ring-2 focus-within:ring-inset focus-within:ring-indigo-600"
>
<input
required
bind:value={vorgangName}
type="text"
name="vorgang"
id="vorgang"
class="block flex-1 border-0 bg-transparent py-1.5 pl-1 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
/>
</div>
</div>
</div>
<div class="flex-1 mt-4 sm:mt-0">
<label for="pin" class="block text-sm font-medium leading-6 text-gray-900">
<span class="flex"> PIN </span>
</label>
<div class="mt-2">
<div
class="flex rounded-md shadow-sm ring-1 ring-inset ring-gray-300 focus-within:ring-2 focus-within:ring-inset focus-within:ring-indigo-600"
>
<input
required
type="password"
bind:value={vorgangPIN}
name="pin"
id="pin"
class="block flex-1 border-0 bg-transparent py-1.5 pl-1 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
/>
</div>
</div>
</div>
</div>
{#if errorMsg}
<p>{errorMsg}</p>
{/if}
{#if form?.message}
<p>{form.message}</p>
{/if}
<button
type="submit"
on:click={submitVorgang}
class="mt-4 bg-indigo-600 text-white px-6 py-2 rounded hover:bg-indigo-700 transition"
>
Neuen Vorgang hinzufügen
</button>
</form>
</ExpandableForm>
<style>
ul {
min-width: 24rem;

View File

@@ -20,26 +20,11 @@ export const actions = {
const vorgangName: string | null = data.get('vorgang') as string;
const crimeName: string | null = data.get('name') as string;
const type: string | null = data.get('type') as string;
const vorgangPIN: string | null = data.get('vorgangPIN') as string;
const fileName: string | null = data.get('fileName') as string;
const vorgangExists = vorgangNameExists(vorgangName);
let vorgangToken;
if (!vorgangExists) {
vorgangToken = uuidv4();
const insertSQLStatement = `INSERT INTO cases (token, name, pin) VALUES (?, ?, ?)`;
const statement = db.prepare(insertSQLStatement);
statement.run(vorgangToken, vorgangName, vorgangPIN);
} else {
const vorgang = getVorgangByName(vorgangName);
vorgangToken = vorgang.token;
if (vorgang && vorgang.pin != vorgangPIN) {
const updateSQLStmt = `UPDATE cases SET pin = ? WHERE token = ?`;
const statement = db.prepare(updateSQLStmt);
statement.run(vorgangPIN, vorgangToken);
}
}
let objectName = `${vorgangToken}/${crimeName}`;
switch (type) {
@@ -60,7 +45,6 @@ export const actions = {
const data = Object.fromEntries(requestData);
const vorgang = data.vorgang;
const name = data.name;
const vorgangPIN = data.vorgangPIN;
let success = true;
const err = {};
if (isRequiredFieldValid(vorgang)) {
@@ -77,13 +61,6 @@ export const actions = {
success = false;
}
if (isRequiredFieldValid(vorgangPIN)) {
err.vorgangPIN = null;
} else {
err.vorgangPIN = 'Das Feld Zugangspasswort darf nicht leer bleiben.';
success = false;
}
if (success) return { success };
return fail(400, err);

View File

@@ -1,7 +1,8 @@
<script lang="ts">
import shortenFileSize from '$lib/helper/shortenFileSize';
import timeElapsed from '$lib/helper/timeElapsed';
import { deserialize } from '$app/forms';
import ExpandableForm from '$lib/components/ExpandableForm.svelte';
import Alert from '$lib/components/Alert.svelte';
import Button from '$lib/components/Button.svelte';
import Modal from '$lib/components/Modal/Modal.svelte';
@@ -12,10 +13,12 @@
import { invalidateAll } from '$app/navigation';
import NameItemEditor from '$lib/components/NameItemEditor.svelte';
import EmptyList from '$lib/components/EmptyList.svelte';
import FileRect from '$lib/icons/File-rect.svelte';
import Exclamation from '$lib/icons/Exclamation.svelte';
import { API_ROUTES, ROUTE_NAMES } from '../../../index.js';
//Seite für die Tatort-Liste
let { data } = $props();
let { data, form } = $props();
interface ListItem {
//sollte Typ Vorgang sein, aber der einfachheit ist es noch ListItem, damit die Komponente NameItemEditor für Vorgang und Tatort eingesetzt werden kann
@@ -33,6 +36,126 @@
let vorgangToken: string = data.vorgang.vorgangToken;
let isEmptyList = $derived(crimesList.length === 0);
// File Upload Variablen
let name = $state('');
let formErrors: Record<string, any> | null = $state(null);
let etag: string | null = $state(null);
let files: FileList | null = $state(null);
// Model Variablen für Upload
let openUL = $state(false);
let inProgressUL = $state(form === null);
async function buttonClick(event: MouseEvent) {
if (!(await validateForm())) {
event.preventDefault();
return;
}
const url = await getUrl();
openUL = true;
inProgressUL = true;
fetch(url, { method: 'PUT', body: files[0] })
.then((response) => {
inProgressUL = false;
etag = '123';
})
.catch((err) => {
inProgressUL = false;
etag = null;
console.log('ERROR', err);
});
}
async function validateForm() {
let data = new FormData();
data.append('vorgang', vorgangName);
data.append('name', name);
const response = await fetch(ROUTE_NAMES.UPLOAD_VALIDATE, { method: 'POST', body: data });
const result = deserialize(await response.text());
let success = true;
if (result.type === 'success') {
formErrors = null;
} else {
if (result.type === 'failure' && result.data) formErrors = result.data;
success = false;
}
if (!files?.length) {
formErrors = { file: 'Sie haben keine Datei ausgewählt.', ...formErrors };
success = false;
}
if (!(await check_valid_glb_file())) {
formErrors = { file: 'Keine gültige .GLD-Datei', ...formErrors };
success = false;
}
return success;
}
async function uploadSuccessful() {
openUL = false;
name = '';
files = null;
await invalidateAll();
crimesList = data.crimesList;
}
// `val` is hex string
function swap_endian(val) {
// from https://www.geeksforgeeks.org/bit-manipulation-swap-endianness-of-a-number/
let leftmost_byte = (val & eval(0x000000ff)) >> 0;
let left_middle_byte = (val & eval(0x0000ff00)) >> 8;
let right_middle_byte = (val & eval(0x00ff0000)) >> 16;
let rightmost_byte = (val & eval(0xff000000)) >> 24;
leftmost_byte <<= 24;
left_middle_byte <<= 16;
right_middle_byte <<= 8;
rightmost_byte <<= 0;
let res = leftmost_byte | left_middle_byte | right_middle_byte | rightmost_byte;
return res;
}
async function check_valid_glb_file() {
// GLD Header, magic value 0x46546C67, identifies data as binary glTF, 4 bytes
// little endian!
const GLD_MAGIC = 0x46546c67;
// big endian!
let file = files[0];
let file_header = file.slice(0, 4);
console.log(file_header);
let header_bytes = await file_header.bytes();
let file_header_hex = '0x' + header_bytes.toHex().toString();
if (GLD_MAGIC == swap_endian(file_header_hex)) {
return true;
} else {
return false;
}
return true;
}
async function getUrl() {
let data = new FormData();
data.append('vorgang', vorgangName);
data.append('name', name);
if (files?.length === 1) {
data.append('type', files[0].type);
data.append('fileName', files[0].name);
}
const response = await fetch(ROUTE_NAMES.UPLOAD_URL, { method: 'POST', body: data });
const result = deserialize(await response.text());
if (result.type === 'success') return result.data?.url;
return null;
}
//Variablen für Modal
let open = $state(false);
let inProgress = $state(false);
@@ -190,6 +313,93 @@ Mit freundlichen Grüßen,
</ul>
</div>
{#if admin}
<div class="flex justify-center my-4">
<ExpandableForm>
<div class="mx-auto max-w-2xl">
<div class="flex flex-col items-center space-y-6">
<!-- Name Input -->
<div class="w-full max-w-md">
<label for="name" class="block text-sm font-medium leading-6 text-gray-900">
<span class="flex">
{#if formErrors?.name}
<span class="inline-block mr-1"><Exclamation /></span>
{/if} Modellname
</span>
</label>
<div class="mt-2">
<div
class="flex rounded-md shadow-sm ring-1 ring-inset ring-gray-300 focus-within:ring-2 focus-within:ring-inset focus-within:ring-indigo-600"
>
<input
bind:value={name}
type="text"
name="name"
id="name"
autocomplete={name}
class="block flex-1 border-0 bg-transparent py-1.5 pl-1 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
/>
</div>
</div>
{#if formErrors?.name}
<p class="block text-sm leading-6 text-red-900 mt-2">{formErrors.name}</p>
{/if}
</div>
<!-- File Upload -->
<div class="w-full max-w-md">
<label for="file" class="block text-sm font-medium leading-6 text-gray-900">
<span class="flex">
{#if formErrors?.file}
<span class="inline-block mr-1"><Exclamation /></span>
{/if} Datei
</span>
</label>
<div
class="mt-2 flex justify-center rounded-lg border border-dashed border-gray-900/25 px-6 py-10"
>
<div class="text-center">
<FileRect />
<div class="mt-4 flex text-sm leading-6 text-gray-600">
<label
for="file"
class="relative cursor-pointer rounded-md bg-white font-semibold text-indigo-600 focus-within:outline-none focus-within:ring-2 focus-within:ring-indigo-600 focus-within:ring-offset-2 hover:text-indigo-500"
>
<span>Wähle eine Datei aus</span>
<input id="file" bind:files name="file" type="file" class="sr-only" />
</label>
<p class="pl-1">oder ziehe sie ins Feld</p>
</div>
<p class="text-xs leading-5 text-gray-600">GLB Dateien bis zu 1GB</p>
{#if files?.length}
<div class="flex justify-center text-xs mt-2">
<p class="mx-2">Datei: <span class="font-bold">{files[0].name}</span></p>
<p class="mx-2">
Größe: <span class="font-bold">{shortenFileSize(files[0].size)}</span>
</p>
</div>
{/if}
</div>
</div>
{#if formErrors?.file}
<p class="block text-sm leading-6 text-red-900 mt-2">{formErrors.file}</p>
{/if}
</div>
<div class="mt-6 flex items-center justify-end gap-x-6">
<Button
on:click={buttonClick}
class="rounded-md bg-indigo-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
>
Hinzufügen
</Button>
</div>
</div>
</div>
</ExpandableForm>
</div>
{/if}
<Modal {open}
><ModalTitle>Umbenennen</ModalTitle><ModalContent>
{#if inProgress}
@@ -202,6 +412,21 @@ Mit freundlichen Grüßen,
</ModalContent>
<ModalFooter><Button disabled={inProgress} on:click={closeModal}>Ok</Button></ModalFooter>
</Modal>
<Modal open={openUL}
><ModalTitle>Upload</ModalTitle><ModalContent>
{#if inProgressUL}
<p class="py-2 mb-1">Upload läuft...</p>
{:else if etag}
<Alert class="w-full">Upload erfolgreich</Alert>
{:else}
<Alert class="w-full" type="error">Fehler beim Upload</Alert>
{/if}
</ModalContent>
<ModalFooter
><Button disabled={inProgressUL} on:click={uploadSuccessful}>Ok</Button></ModalFooter
>
</Modal>
</div>
{/if}

View File

@@ -13,9 +13,8 @@ describe('Home-Page View', () => {
expect(linkElement).toBeInTheDocument();
expect(linkElement).toHaveAttribute('href', ROUTE_NAMES.LIST);
linkElement = screen.getByText('Hinzufügen');
expect(linkElement).toBeInTheDocument();
expect(linkElement).toHaveAttribute('href', ROUTE_NAMES.UPLOAD);
linkElement = screen.queryByText('Hinzufügen');
expect(linkElement).not.toBeInTheDocument();
linkElement = screen.getByText('Benutzerverwaltung');
expect(linkElement).toBeInTheDocument();

View File

@@ -9,6 +9,21 @@ import { API_ROUTES } from '../../src/routes';
vi.spyOn(nav, 'invalidateAll').mockResolvedValue();
global.fetch = vi.fn().mockResolvedValue({ ok: true });
async function clickPlusButton() {
// mock animation features of the browser
window.HTMLElement.prototype.scrollIntoView = vi.fn();
window.HTMLElement.prototype.animate = vi.fn(() => ({
finished: Promise.resolve(),
cancel: vi.fn(),
}))
// button is visible
const button = screen.getByRole('button', { name: /add item/i })
expect(button).toBeInTheDocument();
await fireEvent.click(button)
}
describe('Seite: Vorgangsansicht', () => {
test.todo('Share Link disabled wenn Liste leer');
@@ -83,3 +98,42 @@ describe('Seite: Vorgangsansicht', () => {
});
});
});
describe('Hinzufügen Button', () => {
it('Unexpandierter Button', () => {
const testData = { ...baseData, vorgangList: [] };
const { getByTestId } = render(TatortListPage, { props: { data: testData } });
const container = getByTestId('expand-container')
expect(container).toBeInTheDocument();
// button is visible
const button = within(container).getByRole('button')
expect(button).toBeInTheDocument();
// input fields are not visible
let label = screen.queryByText('Modellname');
expect(label).not.toBeInTheDocument();
});
it('Expandierter Button nach Klick', async () => {
const testData = { ...baseData, vorgangList: [] };
render(TatortListPage, { props: { data: testData } });
await clickPlusButton();
// input fields are visible
let label = screen.queryByText('Modellname');
expect(label).toBeInTheDocument();
});
it.todo('Check Validation: missing name', async () => {
console.log(`test: input field validation`);
});
it.todo('Create Tatort successful', async () => {
console.log(`test: tatort upload`);
});
});

View File

@@ -1,8 +1,10 @@
import { render, screen, within } from '@testing-library/svelte';
import { describe, expect, it } from 'vitest';
import { render, fireEvent, screen, within } from '@testing-library/svelte';
import { describe, expect, it, vi } from 'vitest';
import VorgangListPage from '$root/routes/(angemeldet)/list/+page.svelte';
import { baseData } from '../fixtures';
import { ROUTE_NAMES } from '../../src/routes';
import { actions } from '../../src/routes/(angemeldet)/list/+page.server';
import { createVorgang } from '$lib/server/vorgangService';
describe('Vorgänge Liste Page EmptyList-Komponente View', () => {
it('zeigt EmptyList-Komponente an, wenn Liste leer ist', () => {
@@ -43,3 +45,130 @@ describe('Teste Links auf Korrektheit', () => {
expect(linkElement.getAttribute('href')?.toLowerCase()).not.toContain('pin');
});
});
async function clickPlusButton() {
// mock animation features of the browser
window.HTMLElement.prototype.scrollIntoView = vi.fn();
window.HTMLElement.prototype.animate = vi.fn(() => ({
finished: Promise.resolve(),
cancel: vi.fn(),
}))
// button is visible
const button = screen.getByRole('button')
expect(button).toBeInTheDocument();
await fireEvent.click(button)
}
async function inputVorgang() {
const input = document.getElementById("vorgang");
input.value = 'test-vorgang';
// firing the event manually for Svelte
await fireEvent.input(input)
expect(input).toHaveValue('test-vorgang');
}
async function inputVorgangPIN() {
const input = document.getElementById("pin");
input.value = 'test-pin';
// firing the event manually for Svelte
await fireEvent.input(input)
expect(input).toHaveValue('test-pin');
}
describe('Hinzufügen Buton', () => {
it('Unexpandierter Button', () => {
const testData = { ...baseData, vorgangList: [] };
const { getByTestId } = render(VorgangListPage, { props: { data: testData } });
const container = getByTestId('expand-container')
expect(container).toBeInTheDocument();
// button is visible
const button = within(container).getByRole('button')
expect(button).toBeInTheDocument();
// input fields are not visible
let label = screen.queryByText('Vorgangsname');
expect(label).not.toBeInTheDocument();
});
it('Expandierter Button nach Klick', async () => {
const testData = { ...baseData, vorgangList: [] };
render(VorgangListPage, { props: { data: testData } });
await clickPlusButton()
// input fields are visible
let label = screen.queryByText('Vorgangsname');
expect(label).toBeInTheDocument();
});
it('Check Validation: missing PIN', async () => {
const testData = { ...baseData, vorgangList: [] };
render(VorgangListPage, { props: { data: testData } });
await clickPlusButton()
// input
inputVorgang();
// submit
const button = screen.getByText('Neuen Vorgang hinzufügen')
expect(button).toBeInTheDocument()
await fireEvent.click(button);
const errorMsg = 'Bitte einen Vorgangs-PIN eingeben.';
let para = await screen.getByText(errorMsg);
expect(para).toBeInTheDocument();
});
it('Create Vorgang successful', async () => {
const testData = { ...baseData, vorgangList: [] };
render(VorgangListPage, { props: { data: testData } });
await clickPlusButton();
// input fields are visible
let label = screen.queryByText('Vorgangsname');
expect(label).toBeInTheDocument();
inputVorgang();
inputVorgangPIN();
// emulate button click
const button = screen.getByText('Neuen Vorgang hinzufügen');
expect(button).toBeInTheDocument();
await fireEvent.click(button);
// no error message
label = screen.queryByText('Bitte');
expect(label).not.toBeInTheDocument();
});
it('Test default action', async () => {
vi.mock('$lib/server/vorgangService', () => ({
createVorgang: vi.fn(),
}));
const formData = new FormData(); // no data as we are mocking createVorgang
const mockRequest = {
formData: vi.fn().mockResolvedValue(formData)
};
const event = {
request: mockRequest,
};
const testVorgangToken = 'c322f26f-8c5e-4cb9-94b3-b5433bf5109e'
vi.mocked(createVorgang).mockReturnValueOnce(testVorgangToken);
const result = await actions.default(event);
expect(result).toEqual({ token: testVorgangToken });
});
});