Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5c7a96912b | ||
|
|
195f270064 | ||
|
|
3d592c5c76 | ||
|
|
08104d32db | ||
|
|
cc7c024892 | ||
|
|
3eb452aeab | ||
|
|
f46a654184 | ||
|
|
863409aed9 | ||
|
|
052137a697 | ||
|
|
2f3583ccd0 | ||
|
|
9da72cc5bf | ||
|
|
c633627b7c | ||
|
|
5259c41b13 | ||
|
|
3d9e3814fe | ||
|
|
b44edb2b1d | ||
|
|
a72fabc0a0 | ||
|
|
1406f28f86 | ||
|
|
38d1091e9b | ||
|
|
f82efecb8c | ||
|
|
1f12bc8839 | ||
|
|
f19750f6f3 | ||
|
|
808b3fd5c4 | ||
|
|
0891598eb9 | ||
|
|
39ff02f2e7 | ||
|
|
cc67fb4f85 | ||
|
|
75ff4aadc1 | ||
|
|
6f998d07c1 | ||
|
|
f2bb326040 | ||
|
|
8c701db900 | ||
|
|
d1664338a6 | ||
|
|
1a2624cd9e | ||
|
|
a138190cc6 | ||
|
|
993e0cd74b | ||
|
|
dab004a7b6 | ||
|
|
d039336f39 | ||
|
|
4c781e9325 | ||
|
|
451e6b3646 |
@@ -1,14 +0,0 @@
|
|||||||
**/node_modules
|
|
||||||
**/dist
|
|
||||||
**/dist-ssr
|
|
||||||
.git
|
|
||||||
.idea
|
|
||||||
.vscode
|
|
||||||
**/.env
|
|
||||||
**/.env.*
|
|
||||||
**/.DS_Store
|
|
||||||
**/*.log
|
|
||||||
docs
|
|
||||||
pics
|
|
||||||
icon
|
|
||||||
no-as-a-service
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
DB_PASSWORD=
|
|
||||||
BACKEND_URL=
|
|
||||||
MAIL_HOST=
|
|
||||||
MAIL_PORT=
|
|
||||||
MAIL_USER=
|
|
||||||
MAIL_PASSWORD=
|
|
||||||
MAIL_SENDEES_CONTACT=
|
|
||||||
MAIL_SENDEES=
|
|
||||||
NAAS_URL=
|
|
||||||
SECRET_KEY=
|
|
||||||
@@ -11,8 +11,6 @@ dist/
|
|||||||
build/
|
build/
|
||||||
out/
|
out/
|
||||||
|
|
||||||
docker-compose.override.yml
|
|
||||||
|
|
||||||
# Environment variables
|
# Environment variables
|
||||||
.env
|
.env
|
||||||
.env.local
|
.env.local
|
||||||
@@ -121,6 +119,6 @@ ToDo.txt
|
|||||||
next-env.d.ts
|
next-env.d.ts
|
||||||
|
|
||||||
# psd files from footage
|
# psd files from footage
|
||||||
pics/*.psd
|
footage/*.psd
|
||||||
|
|
||||||
icon/
|
icon/
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
[submodule "no-as-a-service"]
|
|
||||||
path = no-as-a-service
|
|
||||||
url = https://github.com/hotheadhacker/no-as-a-service.git
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
{
|
|
||||||
"semi": true,
|
|
||||||
"singleQuote": false,
|
|
||||||
"trailingComma": "all",
|
|
||||||
"printWidth": 80,
|
|
||||||
"tabWidth": 2
|
|
||||||
}
|
|
||||||
@@ -1,78 +0,0 @@
|
|||||||
# Docker
|
|
||||||
|
|
||||||
## Prerequisites
|
|
||||||
|
|
||||||
You have created an empty `docker-compose.override.yml` file in the root directory of this repository.
|
|
||||||
|
|
||||||
## Docker Network
|
|
||||||
|
|
||||||
If you want to run the stack in a docker network, you need to change the `BACKEND_HOST` variable in the root `.env` file
|
|
||||||
to `stockhome-backend`. To add a docker network, create a `docker-compose.override.yml` file in the root directory of
|
|
||||||
this repository with the following content:
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
services:
|
|
||||||
admin-frontend:
|
|
||||||
networks:
|
|
||||||
- proxynet
|
|
||||||
|
|
||||||
backend:
|
|
||||||
networks:
|
|
||||||
- proxynet
|
|
||||||
|
|
||||||
usr-frontend:
|
|
||||||
networks:
|
|
||||||
- proxynet
|
|
||||||
|
|
||||||
no-as-a-service:
|
|
||||||
networks:
|
|
||||||
- proxynet
|
|
||||||
|
|
||||||
mysql:
|
|
||||||
networks:
|
|
||||||
- proxynet
|
|
||||||
|
|
||||||
networks:
|
|
||||||
proxynet:
|
|
||||||
external: true
|
|
||||||
```
|
|
||||||
|
|
||||||
To start off I recommend to set the `BACKEND_HOST` variable to `localhost` and start the stack without a docker network.
|
|
||||||
After you have started the stack and everything is working, you can add a docker network.
|
|
||||||
|
|
||||||
## Ports
|
|
||||||
|
|
||||||
### Change Exposed Ports
|
|
||||||
|
|
||||||
If you want to change the exposed ports, you can do this in the `docker-compose.yml` file like so:
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
services:
|
|
||||||
mysql:
|
|
||||||
ports:
|
|
||||||
- "3306:3306"
|
|
||||||
|
|
||||||
backend:
|
|
||||||
ports:
|
|
||||||
- "8004:8004"
|
|
||||||
|
|
||||||
usr-frontend:
|
|
||||||
ports:
|
|
||||||
- "80:80"
|
|
||||||
```
|
|
||||||
|
|
||||||
### Remove Exposed Ports
|
|
||||||
|
|
||||||
If you want to remove the exposed ports, you can do this in the `docker-compose.override.yml` file like so:
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
services:
|
|
||||||
mysql:
|
|
||||||
ports: !override [ ]
|
|
||||||
|
|
||||||
backend:
|
|
||||||
ports: !override [ ]
|
|
||||||
|
|
||||||
usr-frontend:
|
|
||||||
ports: !override [ ]
|
|
||||||
```
|
|
||||||
|
Before Width: | Height: | Size: 1.2 MiB After Width: | Height: | Size: 1.2 MiB |
|
Before Width: | Height: | Size: 1.8 MiB After Width: | Height: | Size: 1.8 MiB |
|
Before Width: | Height: | Size: 428 KiB After Width: | Height: | Size: 428 KiB |
|
Before Width: | Height: | Size: 416 KiB After Width: | Height: | Size: 416 KiB |
@@ -0,0 +1,19 @@
|
|||||||
|
FROM node:22-alpine AS builder
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY package.json package-lock.json ./
|
||||||
|
RUN npm ci
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
FROM nginx:alpine AS runner
|
||||||
|
|
||||||
|
WORKDIR /usr/share/nginx/html
|
||||||
|
COPY --from=builder /app/dist .
|
||||||
|
|
||||||
|
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
|
|
||||||
|
EXPOSE 80
|
||||||
|
CMD ["nginx", "-g", "daemon off;"]
|
||||||
@@ -14,7 +14,7 @@ server {
|
|||||||
}
|
}
|
||||||
|
|
||||||
location /backend/ {
|
location /backend/ {
|
||||||
proxy_pass http://borrow-system_backend:8004/;
|
proxy_pass http://borrow_system-backend_v2:8102/;
|
||||||
}
|
}
|
||||||
|
|
||||||
location ~* \.(?:js|mjs|css|png|jpg|jpeg|gif|ico|svg|woff2?)$ {
|
location ~* \.(?:js|mjs|css|png|jpg|jpeg|gif|ico|svg|woff2?)$ {
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "frontend",
|
"name": "admin",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "2.1.2-dev",
|
"version": "v2.1.2 (dev)",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
@@ -12,7 +12,6 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@chakra-ui/react": "^3.28.0",
|
"@chakra-ui/react": "^3.28.0",
|
||||||
"@emotion/react": "^11.14.0",
|
"@emotion/react": "^11.14.0",
|
||||||
"@lottiefiles/dotlottie-react": "^0.19.0",
|
|
||||||
"@tailwindcss/vite": "^4.1.11",
|
"@tailwindcss/vite": "^4.1.11",
|
||||||
"@tanstack/react-query": "^5.90.5",
|
"@tanstack/react-query": "^5.90.5",
|
||||||
"i18next": "^25.6.0",
|
"i18next": "^25.6.0",
|
||||||
@@ -45,7 +44,6 @@
|
|||||||
"eslint-plugin-react-hooks": "^5.2.0",
|
"eslint-plugin-react-hooks": "^5.2.0",
|
||||||
"eslint-plugin-react-refresh": "^0.4.20",
|
"eslint-plugin-react-refresh": "^0.4.20",
|
||||||
"globals": "^16.3.0",
|
"globals": "^16.3.0",
|
||||||
"prettier": "^3.9.10",
|
|
||||||
"typescript": "~5.8.3",
|
"typescript": "~5.8.3",
|
||||||
"typescript-eslint": "^8.39.0",
|
"typescript-eslint": "^8.39.0",
|
||||||
"vite": "^7.1.0",
|
"vite": "^7.1.0",
|
||||||
|
Before Width: | Height: | Size: 1.9 MiB After Width: | Height: | Size: 1.9 MiB |
|
Before Width: | Height: | Size: 1.7 MiB After Width: | Height: | Size: 1.7 MiB |
|
Before Width: | Height: | Size: 4.0 KiB After Width: | Height: | Size: 4.0 KiB |
@@ -1,7 +1,6 @@
|
|||||||
import {
|
import {
|
||||||
Button,
|
Button,
|
||||||
Flex,
|
Flex,
|
||||||
Image,
|
|
||||||
Heading,
|
Heading,
|
||||||
Stack,
|
Stack,
|
||||||
Text,
|
Text,
|
||||||
@@ -69,7 +68,6 @@ export const Header = () => {
|
|||||||
className="mb-6"
|
className="mb-6"
|
||||||
position="relative"
|
position="relative"
|
||||||
pr={{ base: 10, md: 0 }} // Platz für den Mobile-Button rechts
|
pr={{ base: 10, md: 0 }} // Platz für den Mobile-Button rechts
|
||||||
marginBottom={1}
|
|
||||||
>
|
>
|
||||||
{/* Mobile: Drei-Punkte-Button, vertikal zentriert im Header */}
|
{/* Mobile: Drei-Punkte-Button, vertikal zentriert im Header */}
|
||||||
<Box
|
<Box
|
||||||
@@ -192,13 +190,6 @@ export const Header = () => {
|
|||||||
<Stack gap={1}>
|
<Stack gap={1}>
|
||||||
{/* Titelzeile ohne Mobile-Menu (wurde nach oben verlegt) */}
|
{/* Titelzeile ohne Mobile-Menu (wurde nach oben verlegt) */}
|
||||||
<Flex align="center" justify="space-between" gap={2}>
|
<Flex align="center" justify="space-between" gap={2}>
|
||||||
<Image
|
|
||||||
src="/icon_borrow-system-frontend_dark.png"
|
|
||||||
alt="borrow-system logo"
|
|
||||||
boxSize="10"
|
|
||||||
objectFit="contain"
|
|
||||||
flexShrink={0}
|
|
||||||
/>
|
|
||||||
<Heading
|
<Heading
|
||||||
size="2xl"
|
size="2xl"
|
||||||
className="tracking-tight text-slate-900 dark:text-slate-100"
|
className="tracking-tight text-slate-900 dark:text-slate-100"
|
||||||
@@ -36,43 +36,12 @@ export const UserDialogue = (props: UserDialogueProps) => {
|
|||||||
const [msgTitle, setMsgTitle] = useState("");
|
const [msgTitle, setMsgTitle] = useState("");
|
||||||
const [msgDescription, setMsgDescription] = useState("");
|
const [msgDescription, setMsgDescription] = useState("");
|
||||||
|
|
||||||
const [isMsgNAAS, setIsMsgNAAS] = useState(false);
|
|
||||||
const [msgStatusNAAS, setMsgStatusNAAS] = useState<"error" | "success">(
|
|
||||||
"error",
|
|
||||||
);
|
|
||||||
const [msgTitleNAAS, setMsgTitleNAAS] = useState("");
|
|
||||||
const [msgDescriptionNAAS, setMsgDescriptionNAAS] = useState("");
|
|
||||||
|
|
||||||
const [oldPassword, setOldPassword] = useState("");
|
const [oldPassword, setOldPassword] = useState("");
|
||||||
const [newPassword, setNewPassword] = useState("");
|
const [newPassword, setNewPassword] = useState("");
|
||||||
const [confirmPassword, setConfirmPassword] = useState("");
|
const [confirmPassword, setConfirmPassword] = useState("");
|
||||||
|
|
||||||
// Dialog control
|
// Dialog control
|
||||||
const [isPwOpen, setPwOpen] = useState(false);
|
const [isPwOpen, setPwOpen] = useState(false);
|
||||||
const [naasDialog, setNaasDialog] = useState(false);
|
|
||||||
const [naas, setNaas] = useState("");
|
|
||||||
|
|
||||||
const openNAAS = async () => {
|
|
||||||
try {
|
|
||||||
const response = await fetch(`${API_BASE}/no`, {
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
Authorization: `Bearer ${Cookies.get("token")}`,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const data = await response.json();
|
|
||||||
setNaas(data.reason);
|
|
||||||
setNaasDialog(true);
|
|
||||||
} catch (error) {
|
|
||||||
setMsgStatusNAAS("error");
|
|
||||||
setMsgTitleNAAS(t("naas-error"));
|
|
||||||
setMsgDescriptionNAAS(t("naas-error-desc"));
|
|
||||||
setIsMsgNAAS(true);
|
|
||||||
|
|
||||||
console.log(msgStatusNAAS, msgTitleNAAS, msgDescriptionNAAS);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const changePassword = async () => {
|
const changePassword = async () => {
|
||||||
if (newPassword !== confirmPassword) {
|
if (newPassword !== confirmPassword) {
|
||||||
@@ -178,31 +147,14 @@ export const UserDialogue = (props: UserDialogueProps) => {
|
|||||||
</Button>
|
</Button>
|
||||||
</Stack>
|
</Stack>
|
||||||
</Card.Body>
|
</Card.Body>
|
||||||
<Card.Footer>
|
<Card.Footer justifyContent="flex-end">
|
||||||
<Stack w="100%" gap={3}>
|
<Button variant="outline" onClick={() => props.setUserDialog(false)}>
|
||||||
{isMsgNAAS && (
|
|
||||||
<MyAlert
|
|
||||||
status={msgStatusNAAS}
|
|
||||||
title={msgTitleNAAS}
|
|
||||||
description={msgDescriptionNAAS}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
<HStack justify="flex-end" gap={2} wrap="wrap">
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
onClick={() => props.setUserDialog(false)}
|
|
||||||
>
|
|
||||||
{t("cancel")}
|
{t("cancel")}
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="outline" onClick={() => openNAAS()}>
|
|
||||||
{t("try-naas")}
|
|
||||||
</Button>
|
|
||||||
</HStack>
|
|
||||||
</Stack>
|
|
||||||
</Card.Footer>
|
</Card.Footer>
|
||||||
</Card.Root>
|
</Card.Root>
|
||||||
|
|
||||||
{/* Passwort-Dialog */}
|
{/* Passwort-Dialog (kontrolliert) */}
|
||||||
<Dialog.Root open={isPwOpen} onOpenChange={(e: any) => setPwOpen(e.open)}>
|
<Dialog.Root open={isPwOpen} onOpenChange={(e: any) => setPwOpen(e.open)}>
|
||||||
<Portal>
|
<Portal>
|
||||||
<Dialog.Backdrop />
|
<Dialog.Backdrop />
|
||||||
@@ -263,31 +215,6 @@ export const UserDialogue = (props: UserDialogueProps) => {
|
|||||||
</Dialog.Positioner>
|
</Dialog.Positioner>
|
||||||
</Portal>
|
</Portal>
|
||||||
</Dialog.Root>
|
</Dialog.Root>
|
||||||
|
|
||||||
<HStack wrap="wrap" gap="4">
|
|
||||||
<Dialog.Root
|
|
||||||
placement={"center"}
|
|
||||||
open={naasDialog}
|
|
||||||
motionPreset="slide-in-bottom"
|
|
||||||
>
|
|
||||||
<Portal>
|
|
||||||
<Dialog.Backdrop />
|
|
||||||
<Dialog.Positioner>
|
|
||||||
<Dialog.Content>
|
|
||||||
<Dialog.Header>
|
|
||||||
<Dialog.Title>{t("naas-header")}</Dialog.Title>
|
|
||||||
</Dialog.Header>
|
|
||||||
<Dialog.Body>
|
|
||||||
<p>{naas}</p>
|
|
||||||
</Dialog.Body>
|
|
||||||
<Dialog.CloseTrigger asChild>
|
|
||||||
<CloseButton onClick={() => setNaasDialog(false)} size="sm" />
|
|
||||||
</Dialog.CloseTrigger>
|
|
||||||
</Dialog.Content>
|
|
||||||
</Dialog.Positioner>
|
|
||||||
</Portal>
|
|
||||||
</Dialog.Root>
|
|
||||||
</HStack>
|
|
||||||
</Flex>
|
</Flex>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { ChakraProvider, defaultSystem } from "@chakra-ui/react";
|
||||||
|
import * as React from "react";
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
import { ColorModeProvider as ThemeColorModeProvider } from "./color-mode";
|
||||||
|
|
||||||
|
export interface ColorModeProviderProps {
|
||||||
|
children: React.ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ColorModeProvider({ children }: ColorModeProviderProps) {
|
||||||
|
// Wrap children with the real color-mode provider
|
||||||
|
return <ThemeColorModeProvider>{children}</ThemeColorModeProvider>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Provider({ children }: { children: ReactNode }) {
|
||||||
|
return (
|
||||||
|
<ChakraProvider value={defaultSystem}>
|
||||||
|
<ColorModeProvider>{children}</ColorModeProvider>
|
||||||
|
</ChakraProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -14,5 +14,5 @@ createRoot(document.getElementById("root")!).render(
|
|||||||
<Provider>
|
<Provider>
|
||||||
<App />
|
<App />
|
||||||
</Provider>
|
</Provider>
|
||||||
</StrictMode>,
|
</StrictMode>
|
||||||
);
|
);
|
||||||
@@ -5,8 +5,6 @@ import {
|
|||||||
Alert,
|
Alert,
|
||||||
Container,
|
Container,
|
||||||
Text,
|
Text,
|
||||||
VStack,
|
|
||||||
Spinner,
|
|
||||||
} from "@chakra-ui/react";
|
} from "@chakra-ui/react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
@@ -23,21 +21,9 @@ interface Alert {
|
|||||||
export const ContactPage = () => {
|
export const ContactPage = () => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const [message, setMessage] = useState("");
|
const [message, setMessage] = useState("");
|
||||||
const [isSending, setIsSending] = useState(false);
|
|
||||||
const [alert, setAlert] = useState<Alert | null>(null);
|
const [alert, setAlert] = useState<Alert | null>(null);
|
||||||
|
|
||||||
const sendMessage = async () => {
|
const sendMessage = async () => {
|
||||||
setIsSending(true);
|
|
||||||
if (message.trim() === "") {
|
|
||||||
setAlert({
|
|
||||||
type: "error",
|
|
||||||
headline: t("contactPage_messageErrorHeadline"),
|
|
||||||
text: t("contactPage_messageErrorText2"),
|
|
||||||
});
|
|
||||||
setIsSending(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Logic to send the message
|
// Logic to send the message
|
||||||
const result = await fetch(`${API_BASE}/api/users/contact`, {
|
const result = await fetch(`${API_BASE}/api/users/contact`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
@@ -56,12 +42,6 @@ export const ContactPage = () => {
|
|||||||
text: t("contactPage_successText"),
|
text: t("contactPage_successText"),
|
||||||
});
|
});
|
||||||
setMessage("");
|
setMessage("");
|
||||||
} else if (result.status === 503) {
|
|
||||||
setAlert({
|
|
||||||
type: "error",
|
|
||||||
headline: t("serviceDeactivatedHeadline"),
|
|
||||||
text: t("contactPage_serviceDeactivatedText"),
|
|
||||||
});
|
|
||||||
} else {
|
} else {
|
||||||
setAlert({
|
setAlert({
|
||||||
type: "error",
|
type: "error",
|
||||||
@@ -69,7 +49,6 @@ export const ContactPage = () => {
|
|||||||
text: t("contactPage_errorText"),
|
text: t("contactPage_errorText"),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
setIsSending(false);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -99,12 +78,6 @@ export const ContactPage = () => {
|
|||||||
</Alert.Content>
|
</Alert.Content>
|
||||||
</Alert.Root>
|
</Alert.Root>
|
||||||
)}
|
)}
|
||||||
{isSending && (
|
|
||||||
<VStack colorPalette="teal">
|
|
||||||
<Spinner color="colorPalette.600" />
|
|
||||||
<Text color="colorPalette.600">{t("loading")}</Text>
|
|
||||||
</VStack>
|
|
||||||
)}
|
|
||||||
<Button onClick={sendMessage}>{t("contactPage_sendButton")}</Button>
|
<Button onClick={sendMessage}>{t("contactPage_sendButton")}</Button>
|
||||||
</Container>
|
</Container>
|
||||||
);
|
);
|
||||||
@@ -0,0 +1,200 @@
|
|||||||
|
import {
|
||||||
|
Container,
|
||||||
|
Stack,
|
||||||
|
Text,
|
||||||
|
Button,
|
||||||
|
Input,
|
||||||
|
Spinner,
|
||||||
|
VStack,
|
||||||
|
Table,
|
||||||
|
InputGroup,
|
||||||
|
Span,
|
||||||
|
} from "@chakra-ui/react";
|
||||||
|
import { useAtom } from "jotai";
|
||||||
|
import { getBorrowableItems } from "@/utils/Fetcher";
|
||||||
|
import { useState } from "react";
|
||||||
|
import MyAlert from "@/components/myChakra/MyAlert";
|
||||||
|
import { borrowAbleItemsAtom } from "@/states/Atoms";
|
||||||
|
import { createLoan } from "@/utils/Fetcher";
|
||||||
|
import { Header } from "@/components/Header";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
|
export interface User {
|
||||||
|
username: string;
|
||||||
|
role: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const HomePage = () => {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
|
||||||
|
const [borrowableItems, setBorrowableItems] = useAtom(borrowAbleItemsAtom);
|
||||||
|
const [startDate, setStartDate] = useState("");
|
||||||
|
const [endDate, setEndDate] = useState("");
|
||||||
|
const [isLoadingA, setIsLoadingA] = useState(false);
|
||||||
|
const [selectedItems, setSelectedItems] = useState<number[]>([]);
|
||||||
|
|
||||||
|
const MAX_CHARACTERS = 500;
|
||||||
|
const [note, setNote] = useState("");
|
||||||
|
|
||||||
|
// Error handling states
|
||||||
|
const [isMsg, setIsMsg] = useState(false);
|
||||||
|
const [msgStatus, setMsgStatus] = useState<"error" | "success">("error");
|
||||||
|
const [msgTitle, setMsgTitle] = useState("");
|
||||||
|
const [msgDescription, setMsgDescription] = useState("");
|
||||||
|
|
||||||
|
const handleCheckboxChange = (itemId: number) => {
|
||||||
|
setSelectedItems((prevSelected) =>
|
||||||
|
prevSelected.includes(itemId)
|
||||||
|
? prevSelected.filter((id) => id !== itemId)
|
||||||
|
: [...prevSelected, itemId]
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Container className="px-6 sm:px-8 pt-10">
|
||||||
|
<Header />
|
||||||
|
{isMsg && (
|
||||||
|
<MyAlert
|
||||||
|
status={msgStatus}
|
||||||
|
title={msgTitle}
|
||||||
|
description={msgDescription}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<Stack as="main">
|
||||||
|
<Text>{t("timezone-info")}</Text>
|
||||||
|
<label htmlFor="startDate">
|
||||||
|
<strong>
|
||||||
|
<Text>{t("start-date")}</Text>
|
||||||
|
</strong>
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
id="startDate"
|
||||||
|
placeholder={t("start-date")}
|
||||||
|
type="datetime-local"
|
||||||
|
value={startDate}
|
||||||
|
onChange={(e) => setStartDate(e.target.value)}
|
||||||
|
/>
|
||||||
|
<label htmlFor="endDate">
|
||||||
|
<strong>
|
||||||
|
<Text>{t("end-date")}</Text>
|
||||||
|
</strong>
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
id="endDate"
|
||||||
|
placeholder={t("end-date")}
|
||||||
|
type="datetime-local"
|
||||||
|
value={endDate}
|
||||||
|
onChange={(e) => setEndDate(e.target.value)}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
onClick={async () => {
|
||||||
|
setIsLoadingA(true);
|
||||||
|
if (!startDate || !endDate) {
|
||||||
|
setMsgStatus("error");
|
||||||
|
setMsgTitle(t("missing-fields"));
|
||||||
|
setMsgDescription(t("missing-fields-desc"));
|
||||||
|
setIsMsg(true);
|
||||||
|
setIsLoadingA(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await getBorrowableItems(startDate, endDate).then((response) => {
|
||||||
|
setIsLoadingA(false);
|
||||||
|
if (response && response.status === "error") {
|
||||||
|
setMsgStatus("error");
|
||||||
|
setMsgTitle(response.title || t("error"));
|
||||||
|
setMsgDescription(response.description || t("unknown-error"));
|
||||||
|
setIsMsg(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setBorrowableItems(response.data);
|
||||||
|
setIsMsg(false);
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t("get-borrowable-items")}
|
||||||
|
</Button>
|
||||||
|
{isLoadingA && (
|
||||||
|
<VStack colorPalette="teal">
|
||||||
|
<Spinner color="colorPalette.600" />
|
||||||
|
<Text color="colorPalette.600">{t("loading")}</Text>
|
||||||
|
</VStack>
|
||||||
|
)}
|
||||||
|
{borrowableItems.length > 0 && (
|
||||||
|
<Table.ScrollArea borderWidth="1px" rounded="md">
|
||||||
|
<Table.Root size="sm" stickyHeader>
|
||||||
|
<Table.Header>
|
||||||
|
<Table.Row bg="bg.subtle">
|
||||||
|
<Table.ColumnHeader></Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader>{t("item")}</Table.ColumnHeader>
|
||||||
|
</Table.Row>
|
||||||
|
</Table.Header>
|
||||||
|
|
||||||
|
<Table.Body>
|
||||||
|
{borrowableItems.map((item) => (
|
||||||
|
<Table.Row key={item.id}>
|
||||||
|
<Table.Cell>
|
||||||
|
<input
|
||||||
|
onChange={() => handleCheckboxChange(item.id)}
|
||||||
|
type="checkbox"
|
||||||
|
name={item.id}
|
||||||
|
id={item.id}
|
||||||
|
/>
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell>{item.item_name}</Table.Cell>
|
||||||
|
</Table.Row>
|
||||||
|
))}
|
||||||
|
<Table.Row>
|
||||||
|
<Table.Cell colSpan={2}>
|
||||||
|
<InputGroup
|
||||||
|
endElement={
|
||||||
|
<Span color="fg.muted" textStyle="xs">
|
||||||
|
{note.length} / {MAX_CHARACTERS}
|
||||||
|
</Span>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Input
|
||||||
|
placeholder={t("optional-note")}
|
||||||
|
value={note}
|
||||||
|
maxLength={MAX_CHARACTERS}
|
||||||
|
onChange={(e) => {
|
||||||
|
setNote(
|
||||||
|
e.currentTarget.value.slice(0, MAX_CHARACTERS)
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</InputGroup>
|
||||||
|
</Table.Cell>
|
||||||
|
</Table.Row>
|
||||||
|
</Table.Body>
|
||||||
|
</Table.Root>
|
||||||
|
</Table.ScrollArea>
|
||||||
|
)}
|
||||||
|
{selectedItems.length >= 1 && (
|
||||||
|
<Button
|
||||||
|
onClick={() =>
|
||||||
|
createLoan(selectedItems, startDate, endDate, note).then(
|
||||||
|
(response) => {
|
||||||
|
if (response.status === "error") {
|
||||||
|
setMsgStatus("error");
|
||||||
|
setMsgTitle(response.title || t("error"));
|
||||||
|
setMsgDescription(
|
||||||
|
response.description || t("unknown-error")
|
||||||
|
);
|
||||||
|
setIsMsg(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setMsgStatus("success");
|
||||||
|
setMsgTitle(t("success"));
|
||||||
|
setMsgDescription(t("loan-success"));
|
||||||
|
setIsMsg(true);
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{t("create-loan")}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
|
</Container>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -79,16 +79,6 @@ const Landingpage: React.FC = () => {
|
|||||||
Authorization: `Bearer ${Cookies.get("token")}`,
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
if (loanRes.status === 503) {
|
|
||||||
setError(
|
|
||||||
"error",
|
|
||||||
t("serviceDeactivatedHeadline"),
|
|
||||||
t("loan_page_serviceDeactivatedText"),
|
|
||||||
);
|
|
||||||
setIsLoading(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const loanData = await loanRes.json();
|
const loanData = await loanRes.json();
|
||||||
if (Array.isArray(loanData)) {
|
if (Array.isArray(loanData)) {
|
||||||
setLoans(loanData);
|
setLoans(loanData);
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import MyAlert from "../components/myChakra/MyAlert";
|
||||||
|
import { Button, Card, Field, Input, Stack } from "@chakra-ui/react";
|
||||||
|
import { setIsLoggedInAtom, triggerLogoutAtom } from "@/states/Atoms";
|
||||||
|
import { useAtom } from "jotai";
|
||||||
|
import Cookies from "js-cookie";
|
||||||
|
import { Navigate, useNavigate, useLocation } from "react-router-dom";
|
||||||
|
import { PasswordInput } from "@/components/ui/password-input";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { API_BASE } from "@/config/api.config";
|
||||||
|
|
||||||
|
export const LoginPage = () => {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
|
||||||
|
const [isLoggedIn, setIsLoggedIn] = useAtom(setIsLoggedInAtom);
|
||||||
|
const [triggerLogout, setTriggerLogout] = useAtom(triggerLogoutAtom);
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const location = useLocation();
|
||||||
|
const from = location.state?.from?.pathname || "/";
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (isLoggedIn) {
|
||||||
|
navigate(from, { replace: true });
|
||||||
|
window.location.reload(); // if deleted, the user context is not updated in time
|
||||||
|
}
|
||||||
|
}, [isLoggedIn, navigate, from]);
|
||||||
|
|
||||||
|
const loginFnc = async (username: string, password: string) => {
|
||||||
|
const response = await fetch(`${API_BASE}/api/users/login`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ username, password }),
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message: data.message ?? t("login-failed"),
|
||||||
|
description: data.description ?? "",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
Cookies.set("token", data.token);
|
||||||
|
setIsLoggedIn(true);
|
||||||
|
return { success: true };
|
||||||
|
};
|
||||||
|
|
||||||
|
const [username, setUsername] = useState("");
|
||||||
|
const [password, setPassword] = useState("");
|
||||||
|
const [isError, setIsError] = useState(false);
|
||||||
|
const [errorMsg, setErrorMsg] = useState("");
|
||||||
|
const [errorDsc, setErrorDsc] = useState("");
|
||||||
|
|
||||||
|
const handleLogin = async () => {
|
||||||
|
const result = await loginFnc(username, password);
|
||||||
|
if (!result.success) {
|
||||||
|
setErrorMsg(result.message);
|
||||||
|
setErrorDsc(result.description);
|
||||||
|
setIsError(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setTriggerLogout(false);
|
||||||
|
navigate(from, { replace: true });
|
||||||
|
};
|
||||||
|
|
||||||
|
if (isLoggedIn) {
|
||||||
|
return <Navigate to={from} replace />;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-1 items-center justify-center p-4">
|
||||||
|
<form onSubmit={(e) => e.preventDefault()}>
|
||||||
|
<Card.Root maxW="sm">
|
||||||
|
<Card.Header>
|
||||||
|
<Card.Title>{t("login")}</Card.Title>
|
||||||
|
<Card.Description>{t("enter-credentials")}</Card.Description>
|
||||||
|
</Card.Header>
|
||||||
|
<Card.Body>
|
||||||
|
<Stack gap="4" w="full">
|
||||||
|
<Field.Root>
|
||||||
|
<Field.Label>{t("username")}</Field.Label>
|
||||||
|
<Input
|
||||||
|
value={username}
|
||||||
|
onChange={(e) => setUsername(e.target.value)}
|
||||||
|
/>
|
||||||
|
</Field.Root>
|
||||||
|
<Field.Root>
|
||||||
|
<Field.Label>{t("password")}</Field.Label>
|
||||||
|
<PasswordInput
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
/>
|
||||||
|
</Field.Root>
|
||||||
|
</Stack>
|
||||||
|
</Card.Body>
|
||||||
|
<Card.Footer justifyContent="flex-end">
|
||||||
|
{isError && (
|
||||||
|
<MyAlert status="error" title={errorMsg} description={errorDsc} />
|
||||||
|
)}
|
||||||
|
<Button type="submit" onClick={() => handleLogin()} variant="solid">
|
||||||
|
Login
|
||||||
|
</Button>
|
||||||
|
</Card.Footer>
|
||||||
|
<Card.Footer justifyContent="flex-end">
|
||||||
|
{triggerLogout && (
|
||||||
|
<MyAlert
|
||||||
|
status="success"
|
||||||
|
title={t("logout-success")}
|
||||||
|
description={t("logout-success-desc")}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</Card.Footer>
|
||||||
|
</Card.Root>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -52,13 +52,6 @@ export const MyLoansPage = () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
if (res.status === 503) {
|
|
||||||
setMsgStatus("error");
|
|
||||||
setMsgTitle(t("serviceDeactivatedHeadline"));
|
|
||||||
setMsgDescription(t("loan_page_serviceDeactivatedText"));
|
|
||||||
setIsMsg(true);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setMsgStatus("error");
|
setMsgStatus("error");
|
||||||
setMsgTitle(t("error"));
|
setMsgTitle(t("error"));
|
||||||
setMsgDescription(t("error-fetching-loans"));
|
setMsgDescription(t("error-fetching-loans"));
|
||||||
@@ -91,14 +84,6 @@ export const MyLoansPage = () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
if (res.status === 507) {
|
|
||||||
setMsgStatus("error");
|
|
||||||
setMsgTitle(t("error"));
|
|
||||||
setMsgDescription(t("error-deleting-loan-507"));
|
|
||||||
setIsMsg(true);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setMsgStatus("error");
|
setMsgStatus("error");
|
||||||
setMsgTitle(t("error"));
|
setMsgTitle(t("error"));
|
||||||
setMsgDescription(t("error-deleting-loan"));
|
setMsgDescription(t("error-deleting-loan"));
|
||||||
@@ -121,28 +106,10 @@ export const MyLoansPage = () => {
|
|||||||
|
|
||||||
const formatDate = (iso: string | null) => {
|
const formatDate = (iso: string | null) => {
|
||||||
if (!iso) return "-";
|
if (!iso) return "-";
|
||||||
const date = new Date(iso);
|
const m = iso.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/);
|
||||||
if (isNaN(date.getTime())) return iso;
|
if (!m) return iso;
|
||||||
return date.toLocaleString("de-DE", {
|
const [, y, M, d, h, min] = m;
|
||||||
timeZone: "Europe/Berlin",
|
return `${d}.${M}.${y} ${h}:${min}`;
|
||||||
day: "2-digit",
|
|
||||||
month: "2-digit",
|
|
||||||
year: "numeric",
|
|
||||||
hour: "2-digit",
|
|
||||||
minute: "2-digit",
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const dateAndTime = (isISO: boolean) => {
|
|
||||||
const date = new Date();
|
|
||||||
|
|
||||||
if (isISO) {
|
|
||||||
return date.toISOString();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!isISO) {
|
|
||||||
return date;
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleTakeAction = async (loanCode: string) => {
|
const handleTakeAction = async (loanCode: string) => {
|
||||||
@@ -169,7 +136,7 @@ export const MyLoansPage = () => {
|
|||||||
setLoans((prev) =>
|
setLoans((prev) =>
|
||||||
prev.map((loan) =>
|
prev.map((loan) =>
|
||||||
loan.loan_code === loanCode
|
loan.loan_code === loanCode
|
||||||
? { ...loan, take_date: dateAndTime(true) }
|
? { ...loan, take_date: new Date().toISOString() }
|
||||||
: loan,
|
: loan,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -209,7 +176,7 @@ export const MyLoansPage = () => {
|
|||||||
setLoans((prev) =>
|
setLoans((prev) =>
|
||||||
prev.map((loan) =>
|
prev.map((loan) =>
|
||||||
loan.loan_code === loanCode
|
loan.loan_code === loanCode
|
||||||
? { ...loan, returned_date: dateAndTime(true) }
|
? { ...loan, returned_date: new Date().toISOString() }
|
||||||
: loan,
|
: loan,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -17,16 +17,6 @@ export const getBorrowableItems = async (
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
if (response.status === 503) {
|
|
||||||
return {
|
|
||||||
data: null,
|
|
||||||
status: "error",
|
|
||||||
title: "Service deactivated",
|
|
||||||
description:
|
|
||||||
"The loan service is currently deactivated. Please try again later.",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
data: null,
|
data: null,
|
||||||
status: "error",
|
status: "error",
|
||||||
@@ -70,16 +60,6 @@ export const createLoan = async (
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
if (response.status === 503) {
|
|
||||||
return {
|
|
||||||
data: null,
|
|
||||||
status: "error",
|
|
||||||
title: "Service deactivated",
|
|
||||||
description:
|
|
||||||
"The loan service is currently deactivated. Please try again later.",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
data: null,
|
data: null,
|
||||||
status: "error",
|
status: "error",
|
||||||
@@ -60,7 +60,7 @@
|
|||||||
"sure-delete-loan-2": "Für den Admin bleibt sie weiterhin sichtbar.",
|
"sure-delete-loan-2": "Für den Admin bleibt sie weiterhin sichtbar.",
|
||||||
"delete": "Löschen",
|
"delete": "Löschen",
|
||||||
"change-language": "Sprache ändern",
|
"change-language": "Sprache ändern",
|
||||||
"timezone-info": "Die angezeigten Daten und Uhrzeiten werden in deutscher Zeitzone dargestellt und müssen auch so eingegeben werden. Das gesamte System ist auf die deutsche Zeitzone eingestellt.",
|
"timezone-info": "Die angezeigten Daten und Uhrzeiten werden in deutscher Zeitzone dargestellt und müssen auch so eingegeben werden.",
|
||||||
"optional-note": "Optionale Notiz",
|
"optional-note": "Optionale Notiz",
|
||||||
"note": "Notiz",
|
"note": "Notiz",
|
||||||
"user-info-desc": "Hier können Sie Ihre persönlichen Informationen einsehen und das Passwort ändern. Falls Sie weitere Änderungen benötigen, wenden Sie sich bitte an einen Administrator.",
|
"user-info-desc": "Hier können Sie Ihre persönlichen Informationen einsehen und das Passwort ändern. Falls Sie weitere Änderungen benötigen, wenden Sie sich bitte an einen Administrator.",
|
||||||
@@ -88,18 +88,5 @@
|
|||||||
"take-loan-success": "Ausleihe erfolgreich abgeholt",
|
"take-loan-success": "Ausleihe erfolgreich abgeholt",
|
||||||
"return-loan-success": "Ausleihe erfolgreich zurückgegeben",
|
"return-loan-success": "Ausleihe erfolgreich zurückgegeben",
|
||||||
"network-error": "Netzwerkfehler. Kontaktieren Sie den Administrator.",
|
"network-error": "Netzwerkfehler. Kontaktieren Sie den Administrator.",
|
||||||
"contactPage_messageDescription": "Bitte geben Sie hier Ihre Nachricht ein. Der Systemadministrator (Theis Gaedigk) wird sich so schnell wie möglich bei Ihnen melden.",
|
"contactPage_messageDescription": "Bitte geben Sie hier Ihre Nachricht ein. Der Systemadministrator (Theis Gaedigk) wird sich so schnell wie möglich bei Ihnen melden."
|
||||||
"naas": "No-as-a-service",
|
|
||||||
"try-naas": "Klick mich",
|
|
||||||
"naas-error": "Fehler mit no-as-a-service",
|
|
||||||
"naas-error-desc": "Ein Fehler ist beim Kommunizieren mit no-as-a-service aufgetreten.",
|
|
||||||
"naas-header": "Eine gute Möglichkeit, nein zu sagen...",
|
|
||||||
"error-deleting-loan-507": "Die Ausleihe kann nicht gelöscht werden, da sie noch nicht zurückgegeben wurde.",
|
|
||||||
"serviceDeactivatedHeadline": "Service deaktiviert",
|
|
||||||
"contactPage_serviceDeactivatedText": "Der Kontaktservice ist derzeit deaktiviert. Bitte versuchen Sie es später erneut.",
|
|
||||||
"loan_page_serviceDeactivatedText": "Der Ausleihservice ist derzeit deaktiviert. Bitte versuchen Sie es später erneut.",
|
|
||||||
"is-deactivated": "ist deaktiviert.",
|
|
||||||
"deactivated-services": "Deaktivierte Services",
|
|
||||||
"contactPage_messageErrorHeadline": "Fehler bei der Nachrichteneingabe",
|
|
||||||
"contactPage_messageErrorText2": "Bitte geben Sie eine Nachricht ein, bevor Sie sie senden."
|
|
||||||
}
|
}
|
||||||
@@ -60,7 +60,7 @@
|
|||||||
"sure-delete-loan-2": "It will remain visible to the admin.",
|
"sure-delete-loan-2": "It will remain visible to the admin.",
|
||||||
"delete": "Delete",
|
"delete": "Delete",
|
||||||
"change-language": "Change language",
|
"change-language": "Change language",
|
||||||
"timezone-info": "The displayed dates and times are shown in Berlin timezone and must also be entered as such. The entire system is set to Berlin timezone.",
|
"timezone-info": "The displayed dates and times are shown in Berlin timezone and must also be entered as such.",
|
||||||
"optional-note": "Optional note",
|
"optional-note": "Optional note",
|
||||||
"note": "Note",
|
"note": "Note",
|
||||||
"user-info-desc": "Here you can view your personal information and change your password. If you need to make further changes, please contact an administrator.",
|
"user-info-desc": "Here you can view your personal information and change your password. If you need to make further changes, please contact an administrator.",
|
||||||
@@ -88,18 +88,5 @@
|
|||||||
"take-loan-success": "Loan taken successfully",
|
"take-loan-success": "Loan taken successfully",
|
||||||
"return-loan-success": "Loan returned successfully",
|
"return-loan-success": "Loan returned successfully",
|
||||||
"network-error": "Network error. Please contact the administrator.",
|
"network-error": "Network error. Please contact the administrator.",
|
||||||
"contactPage_messageDescription": "Please enter your message here. The system administrator (Theis Gaedigk) will get back to you as soon as possible.",
|
"contactPage_messageDescription": "Please enter your message here. The system administrator (Theis Gaedigk) will get back to you as soon as possible."
|
||||||
"naas": "No-as-a-service",
|
|
||||||
"try-naas": "Click me",
|
|
||||||
"naas-error": "Error with no-as-a-service",
|
|
||||||
"naas-error-desc": "An error occurred while communicating with no-as-a-service.",
|
|
||||||
"naas-header": "A good way to say no...",
|
|
||||||
"error-deleting-loan-507": "The loan cannot be deleted because it has not been returned yet.",
|
|
||||||
"serviceDeactivatedHeadline": "Service deactivated",
|
|
||||||
"contactPage_serviceDeactivatedText": "The contact service is currently deactivated. Please try again later.",
|
|
||||||
"loan_page_serviceDeactivatedText": "The loan service is currently deactivated. Please try again later.",
|
|
||||||
"is-deactivated": "is deactivated.",
|
|
||||||
"deactivated-services": "Deactivated services",
|
|
||||||
"contactPage_messageErrorHeadline": "Error submitting message",
|
|
||||||
"contactPage_messageErrorText2": "Please enter a message before sending it."
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import { defineConfig } from "vite";
|
||||||
|
import tailwindcss from "@tailwindcss/vite";
|
||||||
|
import path from "node:path";
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [tailwindcss()],
|
||||||
|
resolve: {
|
||||||
|
alias: {
|
||||||
|
"@": path.resolve(__dirname, "src"),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
server: {
|
||||||
|
host: "0.0.0.0",
|
||||||
|
allowedHosts: ["insta.the1s.de"],
|
||||||
|
port: 8101,
|
||||||
|
watch: { usePolling: true },
|
||||||
|
hmr: {
|
||||||
|
host: "insta.the1s.de",
|
||||||
|
port: 8101,
|
||||||
|
protocol: "wss",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -19,18 +19,14 @@ A small full‑stack system to log in, view available items, reserve them for a
|
|||||||
## Contents
|
## Contents
|
||||||
|
|
||||||
- Frontend: [frontend/](frontend)
|
- Frontend: [frontend/](frontend)
|
||||||
- Vite/Tailwind
|
- Vite/Tailwind config: [frontend/vite.config.ts](frontend/vite.config.ts), [frontend/tailwind.config.js](frontend/tailwind.config.js)
|
||||||
config: [frontend/vite.config.ts](frontend/vite.config.ts), [frontend/tailwind.config.js](frontend/tailwind.config.js)
|
|
||||||
- App entry: [frontend/src/main.tsx](frontend/src/main.tsx), [frontend/src/App.tsx](frontend/src/App.tsx)
|
- App entry: [frontend/src/main.tsx](frontend/src/main.tsx), [frontend/src/App.tsx](frontend/src/App.tsx)
|
||||||
-
|
- UI: [frontend/src/layout/Layout.tsx](frontend/src/layout/Layout.tsx), [frontend/src/components](frontend/src/components)
|
||||||
UI: [frontend/src/layout/Layout.tsx](frontend/src/layout/Layout.tsx), [frontend/src/components](frontend/src/components)
|
- Data/utilities: [frontend/src/utils/fetchData.ts](frontend/src/utils/fetchData.ts), [frontend/src/utils/userHandler.ts](frontend/src/utils/userHandler.ts), [frontend/src/utils/toastify.ts](frontend/src/utils/toastify.ts)
|
||||||
-
|
|
||||||
Data/utilities: [frontend/src/utils/fetchData.ts](frontend/src/utils/fetchData.ts), [frontend/src/utils/userHandler.ts](frontend/src/utils/userHandler.ts), [frontend/src/utils/toastify.ts](frontend/src/utils/toastify.ts)
|
|
||||||
- Backend: [backend/](backend)
|
- Backend: [backend/](backend)
|
||||||
- Server: [backend/server.js](backend/server.js)
|
- Server: [backend/server.js](backend/server.js)
|
||||||
- Routes: [backend/routes/api.js](backend/routes/api.js), [backend/routes/apiV2.js](backend/routes/apiV2.js)
|
- Routes: [backend/routes/api.js](backend/routes/api.js), [backend/routes/apiV2.js](backend/routes/apiV2.js)
|
||||||
- DB +
|
- DB + services: [backend/services/database.js](backend/services/database.js), [backend/services/tokenService.js](backend/services/tokenService.js)
|
||||||
services: [backend/services/database.js](backend/services/database.js), [backend/services/tokenService.js](backend/services/tokenService.js)
|
|
||||||
- Schema/seed: [backend/scheme.sql](backend/scheme.sql)
|
- Schema/seed: [backend/scheme.sql](backend/scheme.sql)
|
||||||
- Docs: [docs/](docs)
|
- Docs: [docs/](docs)
|
||||||
- API docs (see below): [docs/backend_API_docs/README.md](docs/backend_API_docs/README.md)
|
- API docs (see below): [docs/backend_API_docs/README.md](docs/backend_API_docs/README.md)
|
||||||
@@ -45,8 +41,7 @@ A small full‑stack system to log in, view available items, reserve them for a
|
|||||||
Key frontend utilities:
|
Key frontend utilities:
|
||||||
|
|
||||||
- [`utils.fetchData.fetchAllData`](frontend/src/utils/fetchData.ts): loads items, loans, and user loans after login.
|
- [`utils.fetchData.fetchAllData`](frontend/src/utils/fetchData.ts): loads items, loans, and user loans after login.
|
||||||
- [`utils.fetchData.getBorrowableItems`](frontend/src/utils/fetchData.ts): fetches borrowable items for the selected
|
- [`utils.fetchData.getBorrowableItems`](frontend/src/utils/fetchData.ts): fetches borrowable items for the selected time range.
|
||||||
time range.
|
|
||||||
- [`utils.userHandler.createLoan`](frontend/src/utils/userHandler.ts): creates a new loan for selected items.
|
- [`utils.userHandler.createLoan`](frontend/src/utils/userHandler.ts): creates a new loan for selected items.
|
||||||
- [`utils.userHandler.handleDeleteLoan`](frontend/src/utils/userHandler.ts): deletes a loan and syncs local state.
|
- [`utils.userHandler.handleDeleteLoan`](frontend/src/utils/userHandler.ts): deletes a loan and syncs local state.
|
||||||
- [`utils.toastify.myToast`](frontend/src/utils/toastify.ts): toast notifications.
|
- [`utils.toastify.myToast`](frontend/src/utils/toastify.ts): toast notifications.
|
||||||
@@ -59,18 +54,20 @@ UI flow (main screens):
|
|||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
- The NAAS (no-as-a-service) and the mysql database are running in a docker container
|
- Scripts: see [frontend/package.json](frontend/package.json) and [backend/package.json](backend/package.json)
|
||||||
- `frontend`, `backend` and `admin` are both in a vite dev server and can be started by `npm run dev` in the root
|
- Frontend: `npm run dev`, `npm run build`, `npm run preview`, `npm run lint`
|
||||||
directory.
|
- Backend: `npm start`
|
||||||
|
- Linting: ESLint configured via [frontend/eslint.config.js](frontend/eslint.config.js)
|
||||||
|
- TypeScript configs: [frontend/tsconfig.app.json](frontend/tsconfig.app.json), [frontend/tsconfig.node.json](frontend/tsconfig.node.json)
|
||||||
|
|
||||||
## Configuration notes
|
## Configuration notes
|
||||||
|
|
||||||
- Vite/Tailwind integration via [frontend/vite.config.ts](frontend/vite.config.ts) and `@tailwindcss/vite`; CSS entry
|
- Vite/Tailwind integration via [frontend/vite.config.ts](frontend/vite.config.ts) and `@tailwindcss/vite`; CSS entry uses `@import "tailwindcss"` in [frontend/src/index.css](frontend/src/index.css).
|
||||||
uses `@import "tailwindcss"` in [frontend/src/index.css](frontend/src/index.css).
|
|
||||||
- Toasts wired in [frontend/src/main.tsx](frontend/src/main.tsx) with `react-toastify`.
|
- Toasts wired in [frontend/src/main.tsx](frontend/src/main.tsx) with `react-toastify`.
|
||||||
- Local state is stored in `localStorage` keys: `allItems`, `allLoans`, `userLoans`, `borrowableItems`. Cross‑component
|
- Local state is stored in `localStorage` keys: `allItems`, `allLoans`, `userLoans`, `borrowableItems`. Cross‑component updates are signaled via window events from [`utils.fetchData`](frontend/src/utils/fetchData.ts).
|
||||||
updates are signaled via window events from [`utils.fetchData`](frontend/src/utils/fetchData.ts).
|
|
||||||
|
|
||||||
## API documentation
|
## API documentation
|
||||||
|
|
||||||
Refer to the dedicated [API-Docs](docs/backend_API_docs/README.md)
|
Refer to the dedicated API docs:
|
||||||
|
|
||||||
|
`docs/backend_API_docs/README.md`
|
||||||
|
|||||||
@@ -1,26 +1,19 @@
|
|||||||
# Build context is the repo root (npm workspaces share one root package-lock.json)
|
FROM node:18 as builder
|
||||||
FROM node:22-alpine AS builder
|
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
COPY package.json package-lock.json ./
|
COPY package.json package-lock.json ./
|
||||||
COPY frontend/package.json frontend/
|
RUN npm ci
|
||||||
COPY admin/package.json admin/
|
|
||||||
COPY backend/package.json backend/
|
|
||||||
RUN npm ci -w admin
|
|
||||||
|
|
||||||
ARG VITE_BACKEND_URL
|
COPY . .
|
||||||
ENV VITE_BACKEND_URL=$VITE_BACKEND_URL
|
RUN npm run build
|
||||||
|
|
||||||
COPY admin/ admin/
|
|
||||||
RUN npm run build -w admin
|
|
||||||
|
|
||||||
FROM nginx:alpine AS runner
|
FROM nginx:alpine AS runner
|
||||||
|
|
||||||
WORKDIR /usr/share/nginx/html
|
WORKDIR /usr/share/nginx/html
|
||||||
COPY --from=builder /app/admin/dist .
|
COPY --from=builder /app/dist .
|
||||||
|
|
||||||
COPY admin/nginx.conf /etc/nginx/conf.d/default.conf
|
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
|
|
||||||
EXPOSE 80
|
EXPOSE 80
|
||||||
CMD ["nginx", "-g", "daemon off;"]
|
CMD ["nginx", "-g", "daemon off;"]
|
||||||
@@ -14,7 +14,7 @@ server {
|
|||||||
}
|
}
|
||||||
|
|
||||||
location /backend/ {
|
location /backend/ {
|
||||||
proxy_pass http://borrow-system_backend:8004/;
|
proxy_pass http://borrow_system-backend_v2:8102/;
|
||||||
}
|
}
|
||||||
|
|
||||||
location ~* \.(?:js|mjs|css|png|jpg|jpeg|gif|ico|svg|woff2?)$ {
|
location ~* \.(?:js|mjs|css|png|jpg|jpeg|gif|ico|svg|woff2?)$ {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "admin",
|
"name": "admin",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "1.3.2-dev",
|
"version": "v1.3.2 (dev)",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import UserTable from "../components/UserTable";
|
|||||||
import ItemTable from "../components/ItemTable";
|
import ItemTable from "../components/ItemTable";
|
||||||
import LoanTable from "../components/LoanTable";
|
import LoanTable from "../components/LoanTable";
|
||||||
import APIKeyTable from "@/components/APIKeyTable";
|
import APIKeyTable from "@/components/APIKeyTable";
|
||||||
import ServerConfig from "@/components/ServerConfig";
|
|
||||||
import { MoveLeft } from "lucide-react";
|
import { MoveLeft } from "lucide-react";
|
||||||
|
|
||||||
type DashboardProps = {
|
type DashboardProps = {
|
||||||
@@ -45,9 +44,8 @@ const Dashboard: React.FC<DashboardProps> = ({ onLogout }) => {
|
|||||||
viewSchliessfaecher={() => setActiveView("Schließfächer")}
|
viewSchliessfaecher={() => setActiveView("Schließfächer")}
|
||||||
viewUser={() => setActiveView("User")}
|
viewUser={() => setActiveView("User")}
|
||||||
viewAPI={() => setActiveView("API")}
|
viewAPI={() => setActiveView("API")}
|
||||||
viewConfig={() => setActiveView("Server Konfiguration")}
|
|
||||||
/>
|
/>
|
||||||
<Box flex="1" display="flex" flexDirection="column" minH={0}>
|
<Box flex="1" display="flex" flexDirection="column">
|
||||||
<Flex
|
<Flex
|
||||||
as="header"
|
as="header"
|
||||||
align="center"
|
align="center"
|
||||||
@@ -68,7 +66,7 @@ const Dashboard: React.FC<DashboardProps> = ({ onLogout }) => {
|
|||||||
</Button>
|
</Button>
|
||||||
</Flex>
|
</Flex>
|
||||||
</Flex>
|
</Flex>
|
||||||
<Box as="main" flex="1" p={6} minH={0} overflow="hidden">
|
<Box as="main" flex="1" p={6}>
|
||||||
{activeView === "" && (
|
{activeView === "" && (
|
||||||
<Flex
|
<Flex
|
||||||
align="center"
|
align="center"
|
||||||
@@ -90,7 +88,6 @@ const Dashboard: React.FC<DashboardProps> = ({ onLogout }) => {
|
|||||||
{activeView === "Ausleihen" && <LoanTable />}
|
{activeView === "Ausleihen" && <LoanTable />}
|
||||||
{activeView === "Gegenstände" && <ItemTable />}
|
{activeView === "Gegenstände" && <ItemTable />}
|
||||||
{activeView === "API" && <APIKeyTable />}
|
{activeView === "API" && <APIKeyTable />}
|
||||||
{activeView === "Server Konfiguration" && <ServerConfig />}
|
|
||||||
</Box>
|
</Box>
|
||||||
</Box>
|
</Box>
|
||||||
</Flex>
|
</Flex>
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ type SidebarProps = {
|
|||||||
viewSchliessfaecher: () => void;
|
viewSchliessfaecher: () => void;
|
||||||
viewUser: () => void;
|
viewUser: () => void;
|
||||||
viewAPI: () => void;
|
viewAPI: () => void;
|
||||||
viewConfig: () => void;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const Sidebar: React.FC<SidebarProps> = ({
|
const Sidebar: React.FC<SidebarProps> = ({
|
||||||
@@ -17,7 +16,6 @@ const Sidebar: React.FC<SidebarProps> = ({
|
|||||||
viewGegenstaende,
|
viewGegenstaende,
|
||||||
viewUser,
|
viewUser,
|
||||||
viewAPI,
|
viewAPI,
|
||||||
viewConfig
|
|
||||||
}) => {
|
}) => {
|
||||||
const [info, setInfo] = useState<any>(null);
|
const [info, setInfo] = useState<any>(null);
|
||||||
|
|
||||||
@@ -85,15 +83,6 @@ const Sidebar: React.FC<SidebarProps> = ({
|
|||||||
>
|
>
|
||||||
API Keys
|
API Keys
|
||||||
</Link>
|
</Link>
|
||||||
<Link
|
|
||||||
px={3}
|
|
||||||
py={2}
|
|
||||||
rounded="md"
|
|
||||||
_hover={{ bg: "gray.700", textDecoration: "none" }}
|
|
||||||
onClick={viewConfig}
|
|
||||||
>
|
|
||||||
Server Konfiguration
|
|
||||||
</Link>
|
|
||||||
</VStack>
|
</VStack>
|
||||||
|
|
||||||
<Box mt="auto" pt={8} fontSize="xs" color="gray.500">
|
<Box mt="auto" pt={8} fontSize="xs" color="gray.500">
|
||||||
|
|||||||
@@ -57,32 +57,32 @@ const ItemTable: React.FC = () => {
|
|||||||
|
|
||||||
const handleItemNameChange = (id: number, value: string) => {
|
const handleItemNameChange = (id: number, value: string) => {
|
||||||
setItems((prev) =>
|
setItems((prev) =>
|
||||||
prev.map((it) => (it.id === id ? { ...it, item_name: value } : it)),
|
prev.map((it) => (it.id === id ? { ...it, item_name: value } : it))
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleCanBorrowRoleChange = (id: number, value: string) => {
|
const handleCanBorrowRoleChange = (id: number, value: string) => {
|
||||||
setItems((prev) =>
|
setItems((prev) =>
|
||||||
prev.map((it) => (it.id === id ? { ...it, can_borrow_role: value } : it)),
|
prev.map((it) => (it.id === id ? { ...it, can_borrow_role: value } : it))
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleLockerNumberChange = (id: number, value: string) => {
|
const handleLockerNumberChange = (id: number, value: string) => {
|
||||||
setItems((prev) =>
|
setItems((prev) =>
|
||||||
prev.map((it) => (it.id === id ? { ...it, safe_nr: value } : it)),
|
prev.map((it) => (it.id === id ? { ...it, safe_nr: value } : it))
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDoorKeyChange = (id: number, value: string) => {
|
const handleDoorKeyChange = (id: number, value: string) => {
|
||||||
setItems((prev) =>
|
setItems((prev) =>
|
||||||
prev.map((it) => (it.id === id ? { ...it, door_key: value } : it)),
|
prev.map((it) => (it.id === id ? { ...it, door_key: value } : it))
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const setError = (
|
const setError = (
|
||||||
status: "error" | "success",
|
status: "error" | "success",
|
||||||
message: string,
|
message: string,
|
||||||
description: string,
|
description: string
|
||||||
) => {
|
) => {
|
||||||
setIsError(false);
|
setIsError(false);
|
||||||
setErrorStatus(status);
|
setErrorStatus(status);
|
||||||
@@ -102,7 +102,7 @@ const ItemTable: React.FC = () => {
|
|||||||
headers: {
|
headers: {
|
||||||
Authorization: `Bearer ${Cookies.get("token")}`,
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
},
|
},
|
||||||
},
|
}
|
||||||
);
|
);
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
return data;
|
return data;
|
||||||
@@ -193,50 +193,11 @@ const ItemTable: React.FC = () => {
|
|||||||
|
|
||||||
{/* make table fill available width, like UserTable */}
|
{/* make table fill available width, like UserTable */}
|
||||||
{!isLoading && (
|
{!isLoading && (
|
||||||
<Table.ScrollArea flex="1" minH={0} rounded="md" mt={4}>
|
|
||||||
<Table.Root
|
<Table.Root
|
||||||
size="sm"
|
size="sm"
|
||||||
striped
|
striped
|
||||||
stickyHeader
|
w="100%"
|
||||||
css={{
|
style={{ tableLayout: "auto" }} // Spalten nach Content
|
||||||
"& [data-sticky]": {
|
|
||||||
position: "sticky",
|
|
||||||
zIndex: 1,
|
|
||||||
bg: "bg",
|
|
||||||
|
|
||||||
_after: {
|
|
||||||
content: '""',
|
|
||||||
position: "absolute",
|
|
||||||
pointerEvents: "none",
|
|
||||||
top: "0",
|
|
||||||
bottom: "-1px",
|
|
||||||
width: "32px",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
|
|
||||||
"& [data-sticky=end]": {
|
|
||||||
_after: {
|
|
||||||
insetInlineEnd: "0",
|
|
||||||
translate: "100% 0",
|
|
||||||
shadow: "inset 8px 0px 8px -8px rgba(0, 0, 0, 0.16)",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
|
|
||||||
"& [data-sticky=start]": {
|
|
||||||
_after: {
|
|
||||||
insetInlineStart: "0",
|
|
||||||
translate: "-100% 0",
|
|
||||||
shadow: "inset -8px 0px 8px -8px rgba(0, 0, 0, 0.16)",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
|
|
||||||
"& thead tr": {
|
|
||||||
shadow: "0 1px 0 0 {colors.border}",
|
|
||||||
"&:has(th[data-sticky])": {
|
|
||||||
zIndex: 2,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
<Table.Header>
|
<Table.Header>
|
||||||
<Table.Row>
|
<Table.Row>
|
||||||
@@ -354,12 +315,8 @@ const ItemTable: React.FC = () => {
|
|||||||
value={item.door_key}
|
value={item.door_key}
|
||||||
/>
|
/>
|
||||||
</Table.Cell>
|
</Table.Cell>
|
||||||
<Table.Cell>
|
<Table.Cell>{formatDateTime(item.entry_created_at)}</Table.Cell>
|
||||||
{formatDateTime(item.entry_created_at)}
|
<Table.Cell>{formatDateTime(item.entry_updated_at)}</Table.Cell>
|
||||||
</Table.Cell>
|
|
||||||
<Table.Cell>
|
|
||||||
{formatDateTime(item.entry_updated_at)}
|
|
||||||
</Table.Cell>
|
|
||||||
<Table.Cell>{item.last_borrowed_person}</Table.Cell>
|
<Table.Cell>{item.last_borrowed_person}</Table.Cell>
|
||||||
<Table.Cell>{item.currently_borrowing}</Table.Cell>
|
<Table.Cell>{item.currently_borrowing}</Table.Cell>
|
||||||
<Table.Cell whiteSpace="nowrap">
|
<Table.Cell whiteSpace="nowrap">
|
||||||
@@ -370,7 +327,7 @@ const ItemTable: React.FC = () => {
|
|||||||
item.item_name,
|
item.item_name,
|
||||||
item.safe_nr,
|
item.safe_nr,
|
||||||
item.door_key,
|
item.door_key,
|
||||||
item.can_borrow_role,
|
item.can_borrow_role
|
||||||
).then((response) => {
|
).then((response) => {
|
||||||
if (response.success) {
|
if (response.success) {
|
||||||
setError(
|
setError(
|
||||||
@@ -381,7 +338,7 @@ const ItemTable: React.FC = () => {
|
|||||||
item.item_name +
|
item.item_name +
|
||||||
'" mit ID ' +
|
'" mit ID ' +
|
||||||
item.id +
|
item.id +
|
||||||
" bearbeitet.",
|
" bearbeitet."
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -399,7 +356,7 @@ const ItemTable: React.FC = () => {
|
|||||||
setError(
|
setError(
|
||||||
"success",
|
"success",
|
||||||
"Gegenstand gelöscht",
|
"Gegenstand gelöscht",
|
||||||
"Der Gegenstand wurde erfolgreich gelöscht.",
|
"Der Gegenstand wurde erfolgreich gelöscht."
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -415,7 +372,6 @@ const ItemTable: React.FC = () => {
|
|||||||
))}
|
))}
|
||||||
</Table.Body>
|
</Table.Body>
|
||||||
</Table.Root>
|
</Table.Root>
|
||||||
</Table.ScrollArea>
|
|
||||||
)}
|
)}
|
||||||
<Text>* LaP = Letzte ausleihende Person</Text>
|
<Text>* LaP = Letzte ausleihende Person</Text>
|
||||||
<Text>** Dav = Derzeit ausgeliehen von</Text>
|
<Text>** Dav = Derzeit ausgeliehen von</Text>
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import React from "react";
|
import React from "react";
|
||||||
import {
|
import {
|
||||||
Box,
|
|
||||||
Table,
|
Table,
|
||||||
Spinner,
|
Spinner,
|
||||||
Text,
|
Text,
|
||||||
@@ -32,7 +31,7 @@ const LoanTable: React.FC = () => {
|
|||||||
const setError = (
|
const setError = (
|
||||||
status: "error" | "success",
|
status: "error" | "success",
|
||||||
message: string,
|
message: string,
|
||||||
description: string,
|
description: string
|
||||||
) => {
|
) => {
|
||||||
setIsError(false);
|
setIsError(false);
|
||||||
setErrorStatus(status);
|
setErrorStatus(status);
|
||||||
@@ -66,7 +65,7 @@ const LoanTable: React.FC = () => {
|
|||||||
headers: {
|
headers: {
|
||||||
Authorization: `Bearer ${Cookies.get("token")}`,
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
},
|
},
|
||||||
},
|
}
|
||||||
);
|
);
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
return data;
|
return data;
|
||||||
@@ -84,7 +83,7 @@ const LoanTable: React.FC = () => {
|
|||||||
}, [reload]);
|
}, [reload]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box h="full" display="flex" flexDirection="column" minH={0}>
|
<>
|
||||||
{/* Action toolbar */}
|
{/* Action toolbar */}
|
||||||
<HStack
|
<HStack
|
||||||
mb={4}
|
mb={4}
|
||||||
@@ -132,51 +131,7 @@ const LoanTable: React.FC = () => {
|
|||||||
</VStack>
|
</VStack>
|
||||||
)}
|
)}
|
||||||
{!isLoading && (
|
{!isLoading && (
|
||||||
<Table.ScrollArea flex="1" minH={0} rounded="md" mt={4}>
|
<Table.Root size="sm" striped>
|
||||||
<Table.Root
|
|
||||||
size="sm"
|
|
||||||
striped
|
|
||||||
stickyHeader
|
|
||||||
css={{
|
|
||||||
"& [data-sticky]": {
|
|
||||||
position: "sticky",
|
|
||||||
zIndex: 1,
|
|
||||||
bg: "bg",
|
|
||||||
|
|
||||||
_after: {
|
|
||||||
content: '""',
|
|
||||||
position: "absolute",
|
|
||||||
pointerEvents: "none",
|
|
||||||
top: "0",
|
|
||||||
bottom: "-1px",
|
|
||||||
width: "32px",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
|
|
||||||
"& [data-sticky=end]": {
|
|
||||||
_after: {
|
|
||||||
insetInlineEnd: "0",
|
|
||||||
translate: "100% 0",
|
|
||||||
shadow: "inset 8px 0px 8px -8px rgba(0, 0, 0, 0.16)",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
|
|
||||||
"& [data-sticky=start]": {
|
|
||||||
_after: {
|
|
||||||
insetInlineStart: "0",
|
|
||||||
translate: "-100% 0",
|
|
||||||
shadow: "inset -8px 0px 8px -8px rgba(0, 0, 0, 0.16)",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
|
|
||||||
"& thead tr": {
|
|
||||||
shadow: "0 1px 0 0 {colors.border}",
|
|
||||||
"&:has(th[data-sticky])": {
|
|
||||||
zIndex: 2,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Table.Header>
|
<Table.Header>
|
||||||
<Table.Row>
|
<Table.Row>
|
||||||
<Table.ColumnHeader>
|
<Table.ColumnHeader>
|
||||||
@@ -238,7 +193,7 @@ const LoanTable: React.FC = () => {
|
|||||||
setError(
|
setError(
|
||||||
"success",
|
"success",
|
||||||
"Loan deleted",
|
"Loan deleted",
|
||||||
"The loan has been successfully deleted.",
|
"The loan has been successfully deleted."
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -254,9 +209,8 @@ const LoanTable: React.FC = () => {
|
|||||||
))}
|
))}
|
||||||
</Table.Body>
|
</Table.Body>
|
||||||
</Table.Root>
|
</Table.Root>
|
||||||
</Table.ScrollArea>
|
|
||||||
)}
|
)}
|
||||||
</Box>
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,175 +0,0 @@
|
|||||||
import React from "react";
|
|
||||||
import {
|
|
||||||
Table,
|
|
||||||
Spinner,
|
|
||||||
Text,
|
|
||||||
VStack,
|
|
||||||
Heading,
|
|
||||||
Switch,
|
|
||||||
} from "@chakra-ui/react";
|
|
||||||
import MyAlert from "./myChakra/MyAlert";
|
|
||||||
import Cookies from "js-cookie";
|
|
||||||
import { useState, useEffect } from "react";
|
|
||||||
import { formatDateTime } from "@/utils/userFuncs";
|
|
||||||
import { API_BASE } from "@/config/api.config";
|
|
||||||
|
|
||||||
type Items = {
|
|
||||||
id: number;
|
|
||||||
function_name: string;
|
|
||||||
active: boolean;
|
|
||||||
entry_created_at: string;
|
|
||||||
updated_at: string | null;
|
|
||||||
};
|
|
||||||
|
|
||||||
const ServerConfig: React.FC = () => {
|
|
||||||
const [items, setItems] = useState<Items[]>([]);
|
|
||||||
const [errorStatus, setErrorStatus] = useState<"error" | "success">("error");
|
|
||||||
const [errorMessage, setErrorMessage] = useState("");
|
|
||||||
const [errorDsc, setErrorDsc] = useState("");
|
|
||||||
const [isError, setIsError] = useState(false);
|
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
|
||||||
const [reload, setReload] = useState(false);
|
|
||||||
|
|
||||||
const handleSwitchChange = async (id: number, newState: boolean) => {
|
|
||||||
try {
|
|
||||||
const response = await fetch(
|
|
||||||
`${API_BASE}/api/admin/server-config/update?functionName=${encodeURIComponent(
|
|
||||||
items.find((item) => item.id === id)?.function_name || "",
|
|
||||||
)}&active=${newState}`,
|
|
||||||
{
|
|
||||||
method: "POST",
|
|
||||||
headers: {
|
|
||||||
Authorization: `Bearer ${Cookies.get("token")}`,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
);
|
|
||||||
if (response.ok) {
|
|
||||||
setReload((prev) => !prev);
|
|
||||||
setError(
|
|
||||||
"success",
|
|
||||||
"Status updated",
|
|
||||||
"The function status was updated successfully.",
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
setError(
|
|
||||||
"error",
|
|
||||||
"Failed to update status",
|
|
||||||
"There is an error updating the function status.",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
setError(
|
|
||||||
"error",
|
|
||||||
"Failed to update status",
|
|
||||||
"There is an error updating the function status.",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const setError = (
|
|
||||||
status: "error" | "success",
|
|
||||||
message: string,
|
|
||||||
description: string,
|
|
||||||
) => {
|
|
||||||
setIsError(false);
|
|
||||||
setErrorStatus(status);
|
|
||||||
setErrorMessage(message);
|
|
||||||
setErrorDsc(description);
|
|
||||||
setIsError(true);
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const fetchData = async () => {
|
|
||||||
setIsLoading(true);
|
|
||||||
try {
|
|
||||||
const response = await fetch(
|
|
||||||
`${API_BASE}/api/admin/server-config/all`,
|
|
||||||
{
|
|
||||||
method: "GET",
|
|
||||||
headers: {
|
|
||||||
Authorization: `Bearer ${Cookies.get("token")}`,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
);
|
|
||||||
const data = await response.json();
|
|
||||||
return data.data;
|
|
||||||
} catch (error) {
|
|
||||||
setError("error", "Failed to fetch items", "There is an error");
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
fetchData().then((data) => {
|
|
||||||
if (Array.isArray(data)) {
|
|
||||||
setItems(data);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}, [reload]);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<Heading marginBottom={4} size="2xl">
|
|
||||||
Server Konfiguration
|
|
||||||
</Heading>
|
|
||||||
{isError && (
|
|
||||||
<MyAlert
|
|
||||||
status={errorStatus}
|
|
||||||
description={errorDsc}
|
|
||||||
title={errorMessage}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
{isLoading && (
|
|
||||||
<VStack colorPalette="teal">
|
|
||||||
<Spinner color="colorPalette.600" />
|
|
||||||
<Text color="colorPalette.600">Loading...</Text>
|
|
||||||
</VStack>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Table.Root size="sm" striped w="100%" style={{ tableLayout: "auto" }}>
|
|
||||||
<Table.Header>
|
|
||||||
<Table.Row>
|
|
||||||
<Table.ColumnHeader width="1%" whiteSpace="nowrap">
|
|
||||||
<strong>#</strong>
|
|
||||||
</Table.ColumnHeader>
|
|
||||||
<Table.ColumnHeader>
|
|
||||||
<strong>Service Name</strong>
|
|
||||||
</Table.ColumnHeader>
|
|
||||||
<Table.ColumnHeader>
|
|
||||||
<strong>Toggle</strong>
|
|
||||||
</Table.ColumnHeader>
|
|
||||||
<Table.ColumnHeader>
|
|
||||||
<strong>Eintrag erstellt am</strong>
|
|
||||||
</Table.ColumnHeader>
|
|
||||||
</Table.Row>
|
|
||||||
</Table.Header>
|
|
||||||
<Table.Body>
|
|
||||||
{items.map((item) => (
|
|
||||||
<Table.Row key={item.id}>
|
|
||||||
<Table.Cell whiteSpace="nowrap">{item.id}</Table.Cell>
|
|
||||||
<Table.Cell fontFamily="mono">{item.function_name}</Table.Cell>
|
|
||||||
<Table.Cell>
|
|
||||||
<Switch.Root
|
|
||||||
checked={item.active}
|
|
||||||
onCheckedChange={() =>
|
|
||||||
handleSwitchChange(item.id, !item.active)
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<Switch.HiddenInput />
|
|
||||||
<Switch.Control>
|
|
||||||
<Switch.Thumb />
|
|
||||||
</Switch.Control>
|
|
||||||
<Switch.Label />
|
|
||||||
</Switch.Root>
|
|
||||||
</Table.Cell>
|
|
||||||
<Table.Cell whiteSpace="nowrap">
|
|
||||||
{formatDateTime(item.entry_created_at)}
|
|
||||||
</Table.Cell>
|
|
||||||
</Table.Row>
|
|
||||||
))}
|
|
||||||
</Table.Body>
|
|
||||||
</Table.Root>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default ServerConfig;
|
|
||||||
@@ -8,9 +8,13 @@ export default defineConfig({
|
|||||||
plugins: [react(), svgr(), tailwindcss(), tsconfigPaths()],
|
plugins: [react(), svgr(), tailwindcss(), tsconfigPaths()],
|
||||||
server: {
|
server: {
|
||||||
host: "0.0.0.0",
|
host: "0.0.0.0",
|
||||||
port: 8003,
|
allowedHosts: ["admin.insta.the1s.de"],
|
||||||
watch: {
|
port: 8103,
|
||||||
usePolling: true,
|
watch: { usePolling: true },
|
||||||
|
hmr: {
|
||||||
|
host: "admin.insta.the1s.de",
|
||||||
|
port: 8103,
|
||||||
|
protocol: "wss",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,28 +0,0 @@
|
|||||||
# Build context is the repo root (npm workspaces share one root package-lock.json)
|
|
||||||
FROM node:20-alpine
|
|
||||||
|
|
||||||
ENV NODE_ENV=production
|
|
||||||
WORKDIR /app
|
|
||||||
|
|
||||||
COPY package.json package-lock.json ./
|
|
||||||
COPY frontend/package.json frontend/
|
|
||||||
COPY admin/package.json admin/
|
|
||||||
COPY backend/package.json backend/
|
|
||||||
RUN npm ci -w backend --omit=dev
|
|
||||||
|
|
||||||
COPY backend/ backend/
|
|
||||||
|
|
||||||
# Generate info.json from the workspace package.json versions, without the "-dev" suffix
|
|
||||||
RUN node -e ' \
|
|
||||||
const fs = require("fs"); \
|
|
||||||
const v = (p) => "v" + JSON.parse(fs.readFileSync(p + "/package.json")).version.replace(/-dev$/, ""); \
|
|
||||||
fs.writeFileSync("backend/info.json", JSON.stringify({ \
|
|
||||||
"backend-info": { version: v("backend") }, \
|
|
||||||
"frontend-info": { version: v("frontend") }, \
|
|
||||||
"admin-panel-info": { version: v("admin") } \
|
|
||||||
}, null, 4)); \
|
|
||||||
'
|
|
||||||
|
|
||||||
WORKDIR /app/backend
|
|
||||||
EXPOSE 8004
|
|
||||||
CMD ["npm", "start"]
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
{
|
|
||||||
"backend-info": {
|
|
||||||
"version": "v2.2 (dev)"
|
|
||||||
},
|
|
||||||
"frontend-info": {
|
|
||||||
"version": "v2.2 (dev)"
|
|
||||||
},
|
|
||||||
"admin-panel-info": {
|
|
||||||
"version": "v1.4 (dev)"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
import mysql from "mysql2";
|
|
||||||
import dotenv from "dotenv";
|
|
||||||
dotenv.config();
|
|
||||||
|
|
||||||
const pool = mysql
|
|
||||||
.createPool({
|
|
||||||
host: process.env.DB_HOST,
|
|
||||||
user: process.env.DB_USER,
|
|
||||||
password: process.env.DB_PASSWORD,
|
|
||||||
database: process.env.DB_NAME,
|
|
||||||
})
|
|
||||||
.promise();
|
|
||||||
|
|
||||||
export const getAllFunctions = async () => {
|
|
||||||
const [rows] = await pool.query("SELECT * FROM functions");
|
|
||||||
return { success: true, data: rows };
|
|
||||||
};
|
|
||||||
|
|
||||||
export const updateFunctionStatus = async (functionName, active) => {
|
|
||||||
const [result] = await pool.query(
|
|
||||||
"UPDATE functions SET active = ? WHERE function_name = ?",
|
|
||||||
[active, functionName],
|
|
||||||
);
|
|
||||||
if (result.affectedRows > 0) return { success: true };
|
|
||||||
return { success: false };
|
|
||||||
};
|
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
import express from "express";
|
|
||||||
import { authenticateAdmin } from "../../services/authentication.js";
|
|
||||||
const router = express.Router();
|
|
||||||
import dotenv from "dotenv";
|
|
||||||
dotenv.config();
|
|
||||||
|
|
||||||
// database funcs import
|
|
||||||
import {
|
|
||||||
getAllFunctions,
|
|
||||||
updateFunctionStatus,
|
|
||||||
} from "./database/serverConfMgmt.database.js";
|
|
||||||
|
|
||||||
// Route to get all functions and their statuses
|
|
||||||
router.get("/all", async (req, res) => {
|
|
||||||
try {
|
|
||||||
const result = await getAllFunctions();
|
|
||||||
if (result.success) {
|
|
||||||
res.status(200).json({ data: result.data });
|
|
||||||
} else {
|
|
||||||
res.status(500).json({ message: "Failed to fetch functions" });
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
res
|
|
||||||
.status(500)
|
|
||||||
.json({ message: "An error occurred", error: error.message });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Route to update the status of a function
|
|
||||||
router.post("/update", async (req, res) => {
|
|
||||||
const functionName = req.query.functionName;
|
|
||||||
let active = req.query.active;
|
|
||||||
|
|
||||||
if (active === "false") {
|
|
||||||
active = 0;
|
|
||||||
} else if (active === "true") {
|
|
||||||
active = 1;
|
|
||||||
} else {
|
|
||||||
res.status(406).json({ message: "Got unexpected format" });
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = await updateFunctionStatus(functionName, active);
|
|
||||||
if (result.success) {
|
|
||||||
res.status(200).json({ message: "Function status updated successfully" });
|
|
||||||
} else {
|
|
||||||
res.status(500).json({ message: "Failed to update function status" });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
export default router;
|
|
||||||
@@ -1,237 +0,0 @@
|
|||||||
import express from "express";
|
|
||||||
import { authenticate, generateToken } from "../../services/authentication.js";
|
|
||||||
import {
|
|
||||||
checkIfServiceIsActive,
|
|
||||||
checkIfServiceIsActive2,
|
|
||||||
} from "../../services/functions.js";
|
|
||||||
|
|
||||||
// mailer imports
|
|
||||||
import { sendMail } from "../../services/mailer/send.js";
|
|
||||||
import { loanMail } from "../../services/mailer/templates/loan_created.js";
|
|
||||||
|
|
||||||
import dotenv from "dotenv";
|
|
||||||
dotenv.config();
|
|
||||||
const router = express.Router();
|
|
||||||
|
|
||||||
const loan_service = "Loan Service";
|
|
||||||
const loan_mailer_service = "Loan Mailer";
|
|
||||||
|
|
||||||
// database funcs import
|
|
||||||
import {
|
|
||||||
createLoanInDatabase,
|
|
||||||
getLoanInfoWithID,
|
|
||||||
getLoansFromDatabase,
|
|
||||||
getBorrowableItemsFromDatabase,
|
|
||||||
getALLLoans,
|
|
||||||
getItems,
|
|
||||||
SETdeleteLoanFromDatabase,
|
|
||||||
setReturnDate,
|
|
||||||
setTakeDate,
|
|
||||||
} from "./database/loansMgmt.database.js";
|
|
||||||
|
|
||||||
router.post(
|
|
||||||
"/createLoan",
|
|
||||||
checkIfServiceIsActive(loan_service),
|
|
||||||
authenticate,
|
|
||||||
async (req, res) => {
|
|
||||||
try {
|
|
||||||
const { items, startDate, endDate, note } = req.body || {};
|
|
||||||
|
|
||||||
if (!Array.isArray(items) || items.length === 0) {
|
|
||||||
return res.status(400).json({ message: "Items array is required" });
|
|
||||||
}
|
|
||||||
|
|
||||||
// If dates are not provided, default to now .. +7 days
|
|
||||||
const start =
|
|
||||||
startDate ?? new Date().toISOString().slice(0, 19).replace("T", " ");
|
|
||||||
const end =
|
|
||||||
endDate ??
|
|
||||||
new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
|
|
||||||
.toISOString()
|
|
||||||
.slice(0, 19)
|
|
||||||
.replace("T", " ");
|
|
||||||
|
|
||||||
// Coerce item IDs to numbers and filter invalids
|
|
||||||
const itemIds = items
|
|
||||||
.map((v) => Number(v))
|
|
||||||
.filter((n) => Number.isFinite(n));
|
|
||||||
|
|
||||||
if (itemIds.length === 0) {
|
|
||||||
return res.status(400).json({ message: "No valid item IDs provided" });
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = await createLoanInDatabase(
|
|
||||||
req.user.username,
|
|
||||||
start,
|
|
||||||
end,
|
|
||||||
note,
|
|
||||||
itemIds,
|
|
||||||
);
|
|
||||||
if (result.success) {
|
|
||||||
if (await checkIfServiceIsActive2(loan_mailer_service)) {
|
|
||||||
const mailInfo = await getLoanInfoWithID(result.data.id);
|
|
||||||
console.log(mailInfo);
|
|
||||||
const { html, text } = loanMail(
|
|
||||||
req.user.first_name + " " + req.user.last_name,
|
|
||||||
mailInfo.data.loaned_items_name,
|
|
||||||
mailInfo.data.start_date,
|
|
||||||
mailInfo.data.end_date,
|
|
||||||
mailInfo.data.created_at,
|
|
||||||
mailInfo.data.note,
|
|
||||||
);
|
|
||||||
await sendMail({
|
|
||||||
to: process.env.MAIL_SENDEES,
|
|
||||||
subject: "Neue Ausleihe erstellt!",
|
|
||||||
html,
|
|
||||||
text,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return res.status(201).json({
|
|
||||||
message: "Loan created successfully",
|
|
||||||
loanId: result.data.id,
|
|
||||||
loanCode: result.data.loan_code,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (result.code === "CONFLICT") {
|
|
||||||
return res
|
|
||||||
.status(409)
|
|
||||||
.json({ message: "Items not available in the selected period" });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (result.code === "BAD_REQUEST") {
|
|
||||||
return res.status(400).json({ message: result.message });
|
|
||||||
}
|
|
||||||
|
|
||||||
return res.status(500).json({ message: "Failed to create loan" });
|
|
||||||
} catch (err) {
|
|
||||||
console.error("createLoan error:", err);
|
|
||||||
return res.status(500).json({ message: "Failed to create loan" });
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
router.get(
|
|
||||||
"/loans",
|
|
||||||
checkIfServiceIsActive(loan_service),
|
|
||||||
authenticate,
|
|
||||||
async (req, res) => {
|
|
||||||
const result = await getLoansFromDatabase(req.user.username);
|
|
||||||
if (result.success) {
|
|
||||||
res.status(200).json(result.data);
|
|
||||||
} else if (result.status) {
|
|
||||||
res.status(200).json([]);
|
|
||||||
} else {
|
|
||||||
res.status(500).json({ message: "Failed to fetch loans" });
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
router.post(
|
|
||||||
"/set-return-date/:loan_code",
|
|
||||||
checkIfServiceIsActive(loan_service),
|
|
||||||
authenticate,
|
|
||||||
async (req, res) => {
|
|
||||||
const loanCode = req.params.loan_code;
|
|
||||||
const result = await setReturnDate(loanCode);
|
|
||||||
if (result.success) {
|
|
||||||
res.status(200).json({ data: result.data });
|
|
||||||
} else {
|
|
||||||
res.status(500).json({ message: "Failed to set return date" });
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
router.post(
|
|
||||||
"/set-take-date/:loan_code",
|
|
||||||
checkIfServiceIsActive(loan_service),
|
|
||||||
authenticate,
|
|
||||||
async (req, res) => {
|
|
||||||
const loanCode = req.params.loan_code;
|
|
||||||
const result = await setTakeDate(loanCode);
|
|
||||||
if (result.success) {
|
|
||||||
res.status(200).json({ data: result.data });
|
|
||||||
} else {
|
|
||||||
res.status(500).json({ message: "Failed to set take date" });
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
router.get("/all-items", authenticate, async (req, res) => {
|
|
||||||
const result = await getItems();
|
|
||||||
if (result.success) {
|
|
||||||
res.status(200).json(result.data);
|
|
||||||
} else {
|
|
||||||
res.status(500).json({ message: "Failed to fetch items" });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
router.delete(
|
|
||||||
"/delete-loan/:id",
|
|
||||||
checkIfServiceIsActive(loan_service),
|
|
||||||
authenticate,
|
|
||||||
async (req, res) => {
|
|
||||||
const loanId = req.params.id;
|
|
||||||
const result = await SETdeleteLoanFromDatabase(loanId);
|
|
||||||
if (result.success) {
|
|
||||||
res.status(200).json({ message: "Loan deleted successfully" });
|
|
||||||
} else {
|
|
||||||
if (result.code === "LOAN_NOT_FOUND") {
|
|
||||||
res.status(404).json({ message: "Loan not found" });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (result.code === "LOAN_NOT_RETURNED") {
|
|
||||||
res.status(507).json({
|
|
||||||
message: "Cannot delete loan that has not been returned",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
res.status(500).json({ message: "Failed to delete loan" });
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
router.get(
|
|
||||||
"/all-loans",
|
|
||||||
checkIfServiceIsActive(loan_service),
|
|
||||||
authenticate,
|
|
||||||
async (req, res) => {
|
|
||||||
const result = await getALLLoans();
|
|
||||||
if (result.success) {
|
|
||||||
res.status(200).json(result.data);
|
|
||||||
} else {
|
|
||||||
res.status(500).json({ message: "Failed to fetch loans" });
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
router.post(
|
|
||||||
"/borrowable-items",
|
|
||||||
checkIfServiceIsActive(loan_service),
|
|
||||||
authenticate,
|
|
||||||
async (req, res) => {
|
|
||||||
const { startDate, endDate } = req.body || {};
|
|
||||||
if (!startDate || !endDate) {
|
|
||||||
return res
|
|
||||||
.status(400)
|
|
||||||
.json({ message: "startDate and endDate are required" });
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = await getBorrowableItemsFromDatabase(
|
|
||||||
startDate,
|
|
||||||
endDate,
|
|
||||||
req.user.role,
|
|
||||||
);
|
|
||||||
if (result.success) {
|
|
||||||
// return the array directly for consistency with /items
|
|
||||||
return res.status(200).json(result.data);
|
|
||||||
} else {
|
|
||||||
return res
|
|
||||||
.status(500)
|
|
||||||
.json({ message: "Failed to fetch borrowable items" });
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
export default router;
|
|
||||||
@@ -1,99 +0,0 @@
|
|||||||
import express from "express";
|
|
||||||
import { authenticate, generateToken } from "../../services/authentication.js";
|
|
||||||
import { checkIfServiceIsActive } from "../../services/functions.js";
|
|
||||||
const router = express.Router();
|
|
||||||
import dotenv from "dotenv";
|
|
||||||
dotenv.config();
|
|
||||||
|
|
||||||
const user_frontend_service = "User Frontend";
|
|
||||||
const contact_form_service = "Contact Form Service";
|
|
||||||
|
|
||||||
// database funcs import
|
|
||||||
import {
|
|
||||||
loginFunc,
|
|
||||||
changePassword,
|
|
||||||
getDeactivatedServices,
|
|
||||||
} from "./database/userMgmt.database.js";
|
|
||||||
|
|
||||||
// mailer imports
|
|
||||||
import { sendMail } from "../../services/mailer/send.js";
|
|
||||||
import { contactMail } from "../../services/mailer/templates/contact.js";
|
|
||||||
|
|
||||||
router.post(
|
|
||||||
"/login",
|
|
||||||
checkIfServiceIsActive(user_frontend_service),
|
|
||||||
async (req, res) => {
|
|
||||||
const result = await loginFunc(req.body.username, req.body.password);
|
|
||||||
if (result.success) {
|
|
||||||
const token = await generateToken({
|
|
||||||
username: result.data.username,
|
|
||||||
is_admin: result.data.is_admin,
|
|
||||||
first_name: result.data.first_name,
|
|
||||||
last_name: result.data.last_name,
|
|
||||||
role: result.data.role,
|
|
||||||
});
|
|
||||||
res.status(200).json({ message: "Login successful", token });
|
|
||||||
} else {
|
|
||||||
res.status(401).json({ message: "Invalid credentials" });
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
router.post(
|
|
||||||
"/change-password",
|
|
||||||
checkIfServiceIsActive(user_frontend_service),
|
|
||||||
authenticate,
|
|
||||||
async (req, res) => {
|
|
||||||
const oldPassword = req.body.oldPassword;
|
|
||||||
const newPassword = req.body.newPassword;
|
|
||||||
const username = req.user.username;
|
|
||||||
const result = await changePassword(username, oldPassword, newPassword);
|
|
||||||
if (result.success) {
|
|
||||||
res.status(200).json({ message: "Password changed successfully" });
|
|
||||||
} else {
|
|
||||||
res.status(500).json({ message: "Failed to change password" });
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
router.post(
|
|
||||||
"/contact",
|
|
||||||
checkIfServiceIsActive(contact_form_service),
|
|
||||||
authenticate,
|
|
||||||
async (req, res) => {
|
|
||||||
try {
|
|
||||||
const message = req.body?.message;
|
|
||||||
const username = req.user?.first_name + " " + req.user?.last_name;
|
|
||||||
|
|
||||||
if (!username || !message) {
|
|
||||||
return res
|
|
||||||
.status(400)
|
|
||||||
.json({ message: "Username and message are required" });
|
|
||||||
}
|
|
||||||
|
|
||||||
const { html, text } = contactMail({ username, message });
|
|
||||||
await sendMail({
|
|
||||||
to: process.env.MAIL_SENDEES_CONTACT,
|
|
||||||
subject: "Neue Nachricht!",
|
|
||||||
html,
|
|
||||||
text,
|
|
||||||
});
|
|
||||||
|
|
||||||
res.status(200).json({ message: "Contact message sent successfully" });
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Failed to send contact mail:", error);
|
|
||||||
res.status(500).json({ message: "Failed to send contact message" });
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
router.get("/deactivated-services", authenticate, async (req, res) => {
|
|
||||||
const result = await getDeactivatedServices();
|
|
||||||
if (result.success) {
|
|
||||||
res.status(200).json(result.data);
|
|
||||||
} else {
|
|
||||||
res.status(500).json({ message: "Failed to fetch deactivated services" });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
export default router;
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
import mysql from "mysql2";
|
|
||||||
import dotenv from "dotenv";
|
|
||||||
dotenv.config();
|
|
||||||
|
|
||||||
const pool = mysql
|
|
||||||
.createPool({
|
|
||||||
host: process.env.DB_HOST,
|
|
||||||
user: process.env.DB_USER,
|
|
||||||
password: process.env.DB_PASSWORD,
|
|
||||||
database: process.env.DB_NAME,
|
|
||||||
})
|
|
||||||
.promise();
|
|
||||||
|
|
||||||
export function checkIfServiceIsActive(service) {
|
|
||||||
return async (req, res, next) => {
|
|
||||||
const [result] = await pool.query(
|
|
||||||
"SELECT * FROM functions WHERE function_name = ? AND active = 1;",
|
|
||||||
[service],
|
|
||||||
);
|
|
||||||
|
|
||||||
if (result.length > 0) {
|
|
||||||
return next();
|
|
||||||
}
|
|
||||||
|
|
||||||
return res
|
|
||||||
.status(503)
|
|
||||||
.json({ message: `-${service}- is currently unavailable.` });
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function checkIfServiceIsActive2(service) {
|
|
||||||
const [result] = await pool.query(
|
|
||||||
"SELECT * FROM functions WHERE function_name = ? AND active = 1;",
|
|
||||||
[service],
|
|
||||||
);
|
|
||||||
|
|
||||||
if (result.length > 0) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
import { transporter } from "./transporter.js";
|
|
||||||
|
|
||||||
export async function sendMail({ to, subject, text, html }) {
|
|
||||||
const info = await transporter.sendMail({
|
|
||||||
from: '"Ausleihsystem" <noreply@mcs-medien.de>',
|
|
||||||
to,
|
|
||||||
subject,
|
|
||||||
text,
|
|
||||||
html,
|
|
||||||
});
|
|
||||||
console.log("Mail sent:", info.messageId);
|
|
||||||
return info;
|
|
||||||
}
|
|
||||||
@@ -1,76 +0,0 @@
|
|||||||
export function contactMail({ username, message }) {
|
|
||||||
const brand = process.env.MAIL_BRAND_COLOR || "#0ea5e9";
|
|
||||||
|
|
||||||
const html = `<!DOCTYPE html>
|
|
||||||
<html lang="de">
|
|
||||||
<head>
|
|
||||||
<meta charset="utf-8">
|
|
||||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
||||||
<meta name="color-scheme" content="light">
|
|
||||||
<title>Neue Nachricht</title>
|
|
||||||
</head>
|
|
||||||
<body style="margin:0;padding:0;background:#f2f4f7;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Arial,sans-serif;color:#111827;-webkit-text-size-adjust:100%;">
|
|
||||||
<div style="display:none;max-height:0;overflow:hidden;opacity:0;">Neue Kontaktanfrage im Ausleihsystem.</div>
|
|
||||||
<table role="presentation" cellpadding="0" cellspacing="0" width="100%" style="background:#f2f4f7;">
|
|
||||||
<tr>
|
|
||||||
<td align="center" style="padding:32px 16px;">
|
|
||||||
<table role="presentation" cellpadding="0" cellspacing="0" width="600" style="max-width:600px;width:100%;border-radius:14px;overflow:hidden;box-shadow:0 2px 8px rgba(0,0,0,0.06);">
|
|
||||||
|
|
||||||
<!-- Header -->
|
|
||||||
<tr>
|
|
||||||
<td style="background:${brand};padding:32px 30px 28px;">
|
|
||||||
<h1 style="margin:0;font-size:24px;color:#ffffff;font-weight:700;">Neue Nachricht</h1>
|
|
||||||
<p style="margin:8px 0 0;font-size:14px;color:rgba(255,255,255,0.85);">Eine neue Kontaktanfrage ist eingegangen.</p>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
|
|
||||||
<!-- Accent line -->
|
|
||||||
<tr>
|
|
||||||
<td style="height:3px;line-height:3px;font-size:1px;background:${brand};"> </td>
|
|
||||||
</tr>
|
|
||||||
|
|
||||||
<!-- Content -->
|
|
||||||
<tr>
|
|
||||||
<td style="background:#ffffff;padding:28px 30px;">
|
|
||||||
<table role="presentation" cellpadding="0" cellspacing="0" width="100%" style="background:#fafbfc;border:1px solid #f3f4f6;border-radius:10px;border-collapse:collapse;">
|
|
||||||
<tr>
|
|
||||||
<td style="padding:14px 16px;color:#6b7280;font-size:13px;white-space:nowrap;vertical-align:top;border-bottom:1px solid #f3f4f6;">
|
|
||||||
Benutzername
|
|
||||||
</td>
|
|
||||||
<td style="padding:14px 16px;font-weight:600;color:#111827;font-size:14px;vertical-align:top;border-bottom:1px solid #f3f4f6;">
|
|
||||||
${username || "N/A"}
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td style="padding:14px 16px;color:#6b7280;font-size:13px;white-space:nowrap;vertical-align:top;">
|
|
||||||
Nachricht
|
|
||||||
</td>
|
|
||||||
<td style="padding:14px 16px;font-weight:600;color:#111827;font-size:14px;vertical-align:top;white-space:pre-line;">
|
|
||||||
${message || "N/A"}
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
|
|
||||||
<!-- Footer -->
|
|
||||||
<tr>
|
|
||||||
<td style="background:#f9fafb;padding:20px 30px;border-top:1px solid #e5e7eb;">
|
|
||||||
<p style="margin:0;font-size:12px;color:#9ca3af;text-align:center;line-height:1.6;">
|
|
||||||
Diese E-Mail wurde automatisch vom Ausleihsystem gesendet.<br>
|
|
||||||
Bitte antworten Sie nicht auf diese Nachricht.
|
|
||||||
</p>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
|
|
||||||
</table>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
</body>
|
|
||||||
</html>`;
|
|
||||||
|
|
||||||
const text = `Neue Kontaktanfrage\n\nBenutzername: ${username}\nNachricht:\n${message}`;
|
|
||||||
|
|
||||||
return { html, text };
|
|
||||||
}
|
|
||||||
@@ -1,124 +0,0 @@
|
|||||||
const formatDateTime = (value) => {
|
|
||||||
if (value == null) return "N/A";
|
|
||||||
const d = value instanceof Date ? value : new Date(value);
|
|
||||||
if (isNaN(d.getTime())) return "N/A";
|
|
||||||
return (
|
|
||||||
d.toLocaleString("de-DE", {
|
|
||||||
day: "2-digit",
|
|
||||||
month: "2-digit",
|
|
||||||
year: "numeric",
|
|
||||||
hour: "2-digit",
|
|
||||||
minute: "2-digit",
|
|
||||||
}) + " Uhr"
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export function loanMail(user, items, startDate, endDate, createdDate, note) {
|
|
||||||
const brand = process.env.MAIL_BRAND_COLOR || "#0ea5e9";
|
|
||||||
|
|
||||||
const itemsHtml =
|
|
||||||
Array.isArray(items) && items.length
|
|
||||||
? items
|
|
||||||
.map(
|
|
||||||
(i) =>
|
|
||||||
`<span style="display:inline-block;background:#f0f9ff;color:#0369a1;padding:4px 12px;margin:2px 4px 2px 0;border-radius:20px;font-size:13px;font-weight:500;">${i}</span>`,
|
|
||||||
)
|
|
||||||
.join(" ")
|
|
||||||
: '<span style="color:#9ca3af;">Keine Gegenstände</span>';
|
|
||||||
|
|
||||||
const row = (label, value, isLast = false) => `
|
|
||||||
<tr>
|
|
||||||
<td style="padding:14px 16px;color:#6b7280;font-size:13px;white-space:nowrap;vertical-align:top;${isLast ? "" : "border-bottom:1px solid #f3f4f6;"}">
|
|
||||||
${label}
|
|
||||||
</td>
|
|
||||||
<td style="padding:14px 16px;font-weight:600;color:#111827;font-size:14px;vertical-align:top;${isLast ? "" : "border-bottom:1px solid #f3f4f6;"}">
|
|
||||||
${value}
|
|
||||||
</td>
|
|
||||||
</tr>`;
|
|
||||||
|
|
||||||
const html = `<!DOCTYPE html>
|
|
||||||
<html lang="de">
|
|
||||||
<head>
|
|
||||||
<meta charset="utf-8">
|
|
||||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
||||||
<meta name="color-scheme" content="light">
|
|
||||||
<title>Neue Ausleihe</title>
|
|
||||||
</head>
|
|
||||||
<body style="margin:0;padding:0;background:#f2f4f7;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Arial,sans-serif;color:#111827;-webkit-text-size-adjust:100%;">
|
|
||||||
<div style="display:none;max-height:0;overflow:hidden;opacity:0;">Neue Ausleihe erstellt – Details zur Buchung.</div>
|
|
||||||
<table role="presentation" cellpadding="0" cellspacing="0" width="100%" style="background:#f2f4f7;">
|
|
||||||
<tr>
|
|
||||||
<td align="center" style="padding:32px 16px;">
|
|
||||||
<table role="presentation" cellpadding="0" cellspacing="0" width="600" style="max-width:600px;width:100%;border-radius:14px;overflow:hidden;box-shadow:0 2px 8px rgba(0,0,0,0.06);">
|
|
||||||
|
|
||||||
<!-- Header -->
|
|
||||||
<tr>
|
|
||||||
<td style="background:${brand};padding:32px 30px 28px;">
|
|
||||||
<h1 style="margin:0;font-size:24px;color:#ffffff;font-weight:700;">Neue Ausleihe</h1>
|
|
||||||
<p style="margin:8px 0 0;font-size:14px;color:rgba(255,255,255,0.85);">Es wurde soeben eine neue Ausleihe im System angelegt.</p>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
|
|
||||||
<!-- Accent line -->
|
|
||||||
<tr>
|
|
||||||
<td style="background:#ffffff;padding:0;height:3px;line-height:3px;font-size:1px;background:${brand};"> </td>
|
|
||||||
</tr>
|
|
||||||
|
|
||||||
<!-- Details -->
|
|
||||||
<tr>
|
|
||||||
<td style="background:#ffffff;padding:28px 30px 10px;">
|
|
||||||
<p style="margin:0 0 14px;font-size:11px;font-weight:700;color:#9ca3af;letter-spacing:1.5px;text-transform:uppercase;">Details zur Ausleihe</p>
|
|
||||||
<table role="presentation" cellpadding="0" cellspacing="0" width="100%" style="background:#fafbfc;border:1px solid #f3f4f6;border-radius:10px;border-collapse:collapse;">
|
|
||||||
${row("Benutzer", user || "N/A")}
|
|
||||||
${row("Gegenstände", itemsHtml)}
|
|
||||||
${row("Startdatum", formatDateTime(startDate))}
|
|
||||||
${row("Enddatum", formatDateTime(endDate))}
|
|
||||||
${row("Erstellt am", formatDateTime(createdDate))}
|
|
||||||
${row("Notiz", note || '<span style="color:#9ca3af;">Keine Notiz</span>', true)}
|
|
||||||
</table>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
|
|
||||||
<!-- Button -->
|
|
||||||
<tr>
|
|
||||||
<td style="background:#ffffff;padding:20px 30px 32px;" align="center">
|
|
||||||
<a href="https://admin.insta.the1s.de/api" target="_blank" rel="noopener noreferrer"
|
|
||||||
style="display:inline-block;background:${brand};color:#ffffff;text-decoration:none;padding:13px 28px;border-radius:8px;font-weight:600;font-size:15px;">
|
|
||||||
Ausleihe ansehen →
|
|
||||||
</a>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
|
|
||||||
<!-- Footer -->
|
|
||||||
<tr>
|
|
||||||
<td style="background:#f9fafb;padding:20px 30px;border-top:1px solid #e5e7eb;">
|
|
||||||
<p style="margin:0;font-size:12px;color:#9ca3af;text-align:center;line-height:1.6;">
|
|
||||||
Diese E-Mail wurde automatisch vom Ausleihsystem gesendet.<br>
|
|
||||||
Bitte antworten Sie nicht auf diese Nachricht.
|
|
||||||
</p>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
|
|
||||||
</table>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
</body>
|
|
||||||
</html>`;
|
|
||||||
|
|
||||||
const itemsText = Array.isArray(items) ? items.join(", ") : "N/A";
|
|
||||||
const text = [
|
|
||||||
"Neue Ausleihe erstellt",
|
|
||||||
"-".repeat(30),
|
|
||||||
`Benutzer: ${user || "N/A"}`,
|
|
||||||
`Gegenstaende: ${itemsText}`,
|
|
||||||
`Start: ${formatDateTime(startDate)}`,
|
|
||||||
`Ende: ${formatDateTime(endDate)}`,
|
|
||||||
`Erstellt: ${formatDateTime(createdDate)}`,
|
|
||||||
`Notiz: ${note || "Keine Notiz"}`,
|
|
||||||
"",
|
|
||||||
"-> https://admin.insta.the1s.de/api",
|
|
||||||
].join("\n");
|
|
||||||
|
|
||||||
return { html, text };
|
|
||||||
}
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
import nodemailer from "nodemailer";
|
|
||||||
import dotenv from "dotenv";
|
|
||||||
dotenv.config();
|
|
||||||
|
|
||||||
export const transporter = nodemailer.createTransport({
|
|
||||||
host: process.env.MAIL_HOST,
|
|
||||||
port: process.env.MAIL_PORT,
|
|
||||||
secure: true,
|
|
||||||
auth: {
|
|
||||||
user: process.env.MAIL_USER,
|
|
||||||
pass: process.env.MAIL_PASSWORD,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
FROM node:20-alpine
|
||||||
|
|
||||||
|
ENV NODE_ENV=production
|
||||||
|
WORKDIR /backend
|
||||||
|
|
||||||
|
COPY package*.json ./
|
||||||
|
RUN npm ci --omit=dev
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
EXPOSE 8004
|
||||||
|
CMD ["npm", "start"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
"backend-info": {
|
||||||
|
"version": "v2.1.1"
|
||||||
|
},
|
||||||
|
"frontend-info": {
|
||||||
|
"version": "v2.1.2"
|
||||||
|
},
|
||||||
|
"admin-panel-info": {
|
||||||
|
"version": "v1.3.2"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,10 @@
|
|||||||
{
|
{
|
||||||
"name": "backend",
|
"name": "backendv2",
|
||||||
"version": "2.1.1-dev",
|
"version": "v2.1.1 (dev)",
|
||||||
"private": true,
|
|
||||||
"main": "server.js",
|
"main": "server.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "node --watch server.js",
|
"test": "echo \"Error: no test specified\" && exit 1",
|
||||||
"start": "NODE_ENV=production node server.js"
|
"start": "node server.js"
|
||||||
},
|
},
|
||||||
"keywords": [],
|
"keywords": [],
|
||||||
"author": "",
|
"author": "",
|
||||||
@@ -16,9 +15,8 @@
|
|||||||
"dotenv": "^17.2.1",
|
"dotenv": "^17.2.1",
|
||||||
"ejs": "^3.1.10",
|
"ejs": "^3.1.10",
|
||||||
"express": "^5.1.0",
|
"express": "^5.1.0",
|
||||||
"express-rate-limit": "^8.4.1",
|
|
||||||
"jose": "^6.0.12",
|
"jose": "^6.0.12",
|
||||||
"mysql2": "^3.14.3",
|
"mysql2": "^3.14.3",
|
||||||
"nodemailer": "^10.2.1"
|
"nodemailer": "^7.0.6"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -12,15 +12,12 @@ const pool = mysql
|
|||||||
.promise();
|
.promise();
|
||||||
|
|
||||||
export const getAllLoans = async () => {
|
export const getAllLoans = async () => {
|
||||||
const [rows] = await pool.query("SELECT * FROM loans WHERE deleted_admin = 0;");
|
const [rows] = await pool.query("SELECT * FROM loans");
|
||||||
return { success: true, data: rows };
|
return { success: true, data: rows };
|
||||||
};
|
};
|
||||||
|
|
||||||
export const deleteLoanById = async (loanId) => {
|
export const deleteLoanById = async (loanId) => {
|
||||||
const [result] = await pool.query(
|
const [result] = await pool.query("DELETE FROM loans WHERE id = ?", [loanId]);
|
||||||
"UPDATE loans SET deleted = true, deleted_admin = true WHERE id = ?",
|
|
||||||
[loanId],
|
|
||||||
);
|
|
||||||
if (result.affectedRows > 0) return { success: true };
|
if (result.affectedRows > 0) return { success: true };
|
||||||
return { success: false };
|
return { success: false };
|
||||||
};
|
};
|
||||||
@@ -119,6 +119,14 @@ export const setTakeDateV2 = async (loanCode) => {
|
|||||||
return { message: "Failed to set take date", success: false };
|
return { message: "Failed to set take date", success: false };
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const getAllLoansV2 = async () => {
|
||||||
|
const [result] = await pool.query("SELECT * FROM loans;");
|
||||||
|
if (result.length > 0) {
|
||||||
|
return { success: true, data: result };
|
||||||
|
}
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
|
|
||||||
export const openDoor = async (doorKey) => {
|
export const openDoor = async (doorKey) => {
|
||||||
const [result] = await pool.query(
|
const [result] = await pool.query(
|
||||||
"SELECT safe_nr, id FROM items WHERE door_key = ?;",
|
"SELECT safe_nr, id FROM items WHERE door_key = ?;",
|
||||||
@@ -1,12 +1,9 @@
|
|||||||
import express from "express";
|
import express from "express";
|
||||||
import { authenticate } from "../../services/authentication.js";
|
import { authenticate } from "../../services/authentication.js";
|
||||||
import { checkIfServiceIsActive } from "../../services/functions.js";
|
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
import dotenv from "dotenv";
|
import dotenv from "dotenv";
|
||||||
dotenv.config();
|
dotenv.config();
|
||||||
|
|
||||||
const loan_service = "Loan Service";
|
|
||||||
|
|
||||||
import {
|
import {
|
||||||
getItemsFromDatabaseV2,
|
getItemsFromDatabaseV2,
|
||||||
changeInSafeStateV2,
|
changeInSafeStateV2,
|
||||||
@@ -42,7 +39,6 @@ router.post("/change-state/:key/:itemId", authenticate, async (req, res) => {
|
|||||||
router.get(
|
router.get(
|
||||||
"/get-loan-by-code/:key/:loan_code",
|
"/get-loan-by-code/:key/:loan_code",
|
||||||
authenticate,
|
authenticate,
|
||||||
checkIfServiceIsActive(loan_service),
|
|
||||||
async (req, res) => {
|
async (req, res) => {
|
||||||
const loan_code = req.params.loan_code;
|
const loan_code = req.params.loan_code;
|
||||||
const result = await getLoanByCodeV2(loan_code);
|
const result = await getLoanByCodeV2(loan_code);
|
||||||
@@ -58,7 +54,6 @@ router.get(
|
|||||||
router.post(
|
router.post(
|
||||||
"/set-return-date/:key/:loan_code",
|
"/set-return-date/:key/:loan_code",
|
||||||
authenticate,
|
authenticate,
|
||||||
checkIfServiceIsActive(loan_service),
|
|
||||||
async (req, res) => {
|
async (req, res) => {
|
||||||
const loanCode = req.params.loan_code;
|
const loanCode = req.params.loan_code;
|
||||||
const result = await setReturnDateV2(loanCode);
|
const result = await setReturnDateV2(loanCode);
|
||||||
@@ -74,7 +69,6 @@ router.post(
|
|||||||
router.post(
|
router.post(
|
||||||
"/set-take-date/:key/:loan_code",
|
"/set-take-date/:key/:loan_code",
|
||||||
authenticate,
|
authenticate,
|
||||||
checkIfServiceIsActive(loan_service),
|
|
||||||
async (req, res) => {
|
async (req, res) => {
|
||||||
const loanCode = req.params.loan_code;
|
const loanCode = req.params.loan_code;
|
||||||
const result = await setTakeDateV2(loanCode);
|
const result = await setTakeDateV2(loanCode);
|
||||||
@@ -63,9 +63,11 @@ export const createLoanInDatabase = async (
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const itemNames = itemIds.map(
|
const itemNames = itemIds
|
||||||
(id) => itemsRows.find((r) => Number(r.id) === Number(id)).item_name,
|
.map(
|
||||||
);
|
(id) => itemsRows.find((r) => Number(r.id) === Number(id))?.item_name,
|
||||||
|
)
|
||||||
|
.filter(Boolean);
|
||||||
|
|
||||||
// Build lockers array (unique, only 2-digit numbers from safe_nr)
|
// Build lockers array (unique, only 2-digit numbers from safe_nr)
|
||||||
const lockers = [
|
const lockers = [
|
||||||
@@ -107,24 +109,27 @@ export const createLoanInDatabase = async (
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
let index = false;
|
// Generate unique loan_code (retry a few times)
|
||||||
let candidate;
|
let loanCode = null;
|
||||||
let loanCode;
|
for (let i = 0; i < 6; i++) {
|
||||||
|
const candidate = Math.floor(100000 + Math.random() * 899999); // 6 digits
|
||||||
// Generates 6-digit loan code
|
const [exists] = await conn.query(
|
||||||
do {
|
"SELECT 1 FROM loans WHERE loan_code = ? LIMIT 1",
|
||||||
candidate = Math.floor(100000 + Math.random() * 899999);
|
|
||||||
|
|
||||||
const [rows] = await conn.query(
|
|
||||||
"SELECT 1 FROM loans where loan_code = ? LIMIT 1",
|
|
||||||
[candidate],
|
[candidate],
|
||||||
);
|
);
|
||||||
|
if (exists.length === 0) {
|
||||||
if (rows.length == 0) {
|
|
||||||
index = true;
|
|
||||||
loanCode = candidate;
|
loanCode = candidate;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!loanCode) {
|
||||||
|
await conn.rollback();
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
code: "SERVER_ERROR",
|
||||||
|
message: "Failed to generate unique loan code",
|
||||||
|
};
|
||||||
}
|
}
|
||||||
} while (index === false);
|
|
||||||
|
|
||||||
// Insert loan (now includes lockers)
|
// Insert loan (now includes lockers)
|
||||||
const [insertRes] = await conn.query(
|
const [insertRes] = await conn.query(
|
||||||
@@ -229,23 +234,6 @@ export const getBorrowableItemsFromDatabase = async (
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const SETdeleteLoanFromDatabase = async (loanId) => {
|
export const SETdeleteLoanFromDatabase = async (loanId) => {
|
||||||
const [checkIfdatesReturned] = await pool.query(
|
|
||||||
"SELECT take_date, returned_date FROM loans WHERE id = ? AND deleted = 0",
|
|
||||||
[loanId],
|
|
||||||
);
|
|
||||||
|
|
||||||
if (checkIfdatesReturned.length === 0) {
|
|
||||||
return { success: false, code: "LOAN_NOT_FOUND" };
|
|
||||||
}
|
|
||||||
|
|
||||||
const { take_date, returned_date } = checkIfdatesReturned[0];
|
|
||||||
const bothNull = take_date === null && returned_date === null;
|
|
||||||
const bothSet = take_date !== null && returned_date !== null;
|
|
||||||
|
|
||||||
if (!(bothNull || bothSet)) {
|
|
||||||
return { success: false, code: "LOAN_NOT_RETURNED" };
|
|
||||||
}
|
|
||||||
|
|
||||||
const [result] = await pool.query(
|
const [result] = await pool.query(
|
||||||
"UPDATE loans SET deleted = 1 WHERE id = ?;",
|
"UPDATE loans SET deleted = 1 WHERE id = ?;",
|
||||||
[loanId],
|
[loanId],
|
||||||
@@ -14,7 +14,7 @@ const pool = mysql
|
|||||||
export const loginFunc = async (username, password) => {
|
export const loginFunc = async (username, password) => {
|
||||||
const [result] = await pool.query(
|
const [result] = await pool.query(
|
||||||
"SELECT * FROM users WHERE username = ? AND password = ?",
|
"SELECT * FROM users WHERE username = ? AND password = ?",
|
||||||
[username, password],
|
[username, password]
|
||||||
);
|
);
|
||||||
if (result.length > 0) return { success: true, data: result[0] };
|
if (result.length > 0) return { success: true, data: result[0] };
|
||||||
return { success: false };
|
return { success: false };
|
||||||
@@ -40,7 +40,7 @@ export const changePassword = async (username, oldPassword, newPassword) => {
|
|||||||
// get user current password
|
// get user current password
|
||||||
const [user] = await pool.query(
|
const [user] = await pool.query(
|
||||||
"SELECT * FROM users WHERE username = ? AND password = ?",
|
"SELECT * FROM users WHERE username = ? AND password = ?",
|
||||||
[username, oldPassword],
|
[username, oldPassword]
|
||||||
);
|
);
|
||||||
if (user.length === 0) return { success: false };
|
if (user.length === 0) return { success: false };
|
||||||
|
|
||||||
@@ -48,16 +48,8 @@ export const changePassword = async (username, oldPassword, newPassword) => {
|
|||||||
|
|
||||||
const [result] = await pool.query(
|
const [result] = await pool.query(
|
||||||
"UPDATE users SET password = ? WHERE username = ?",
|
"UPDATE users SET password = ? WHERE username = ?",
|
||||||
[newPassword, username],
|
[newPassword, username]
|
||||||
);
|
);
|
||||||
if (result.affectedRows > 0) return { success: true };
|
if (result.affectedRows > 0) return { success: true };
|
||||||
return { success: false };
|
return { success: false };
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getDeactivatedServices = async () => {
|
|
||||||
const [rows] = await pool.query("SELECT function_name FROM functions WHERE active = 0;");
|
|
||||||
if (rows.length > 0) {
|
|
||||||
return { success: true, data: rows };
|
|
||||||
}
|
|
||||||
return { success: false };
|
|
||||||
};
|
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
import express from "express";
|
||||||
|
import { authenticate, generateToken } from "../../services/authentication.js";
|
||||||
|
const router = express.Router();
|
||||||
|
import dotenv from "dotenv";
|
||||||
|
dotenv.config();
|
||||||
|
|
||||||
|
// database funcs import
|
||||||
|
import {
|
||||||
|
createLoanInDatabase,
|
||||||
|
getLoanInfoWithID,
|
||||||
|
getLoansFromDatabase,
|
||||||
|
getBorrowableItemsFromDatabase,
|
||||||
|
getALLLoans,
|
||||||
|
getItems,
|
||||||
|
SETdeleteLoanFromDatabase,
|
||||||
|
setReturnDate,
|
||||||
|
setTakeDate,
|
||||||
|
} from "./database/loansMgmt.database.js";
|
||||||
|
import { sendMailLoan } from "./services/mailer.js";
|
||||||
|
|
||||||
|
router.post("/createLoan", authenticate, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { items, startDate, endDate, note } = req.body || {};
|
||||||
|
|
||||||
|
if (!Array.isArray(items) || items.length === 0) {
|
||||||
|
return res.status(400).json({ message: "Items array is required" });
|
||||||
|
}
|
||||||
|
|
||||||
|
// If dates are not provided, default to now .. +7 days
|
||||||
|
const start =
|
||||||
|
startDate ?? new Date().toISOString().slice(0, 19).replace("T", " ");
|
||||||
|
const end =
|
||||||
|
endDate ??
|
||||||
|
new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
|
||||||
|
.toISOString()
|
||||||
|
.slice(0, 19)
|
||||||
|
.replace("T", " ");
|
||||||
|
|
||||||
|
// Coerce item IDs to numbers and filter invalids
|
||||||
|
const itemIds = items
|
||||||
|
.map((v) => Number(v))
|
||||||
|
.filter((n) => Number.isFinite(n));
|
||||||
|
|
||||||
|
if (itemIds.length === 0) {
|
||||||
|
return res.status(400).json({ message: "No valid item IDs provided" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await createLoanInDatabase(
|
||||||
|
req.user.username,
|
||||||
|
start,
|
||||||
|
end,
|
||||||
|
note,
|
||||||
|
itemIds,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (result.success) {
|
||||||
|
const mailInfo = await getLoanInfoWithID(result.data.id);
|
||||||
|
console.log(mailInfo);
|
||||||
|
sendMailLoan(
|
||||||
|
mailInfo.data.username,
|
||||||
|
mailInfo.data.loaned_items_name,
|
||||||
|
mailInfo.data.start_date,
|
||||||
|
mailInfo.data.end_date,
|
||||||
|
mailInfo.data.created_at,
|
||||||
|
mailInfo.data.note,
|
||||||
|
);
|
||||||
|
return res.status(201).json({
|
||||||
|
message: "Loan created successfully",
|
||||||
|
loanId: result.data.id,
|
||||||
|
loanCode: result.data.loan_code,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.code === "CONFLICT") {
|
||||||
|
return res
|
||||||
|
.status(409)
|
||||||
|
.json({ message: "Items not available in the selected period" });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.code === "BAD_REQUEST") {
|
||||||
|
return res.status(400).json({ message: result.message });
|
||||||
|
}
|
||||||
|
|
||||||
|
return res.status(500).json({ message: "Failed to create loan" });
|
||||||
|
} catch (err) {
|
||||||
|
console.error("createLoan error:", err);
|
||||||
|
return res.status(500).json({ message: "Failed to create loan" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.get("/loans", authenticate, async (req, res) => {
|
||||||
|
const result = await getLoansFromDatabase(req.user.username);
|
||||||
|
if (result.success) {
|
||||||
|
res.status(200).json(result.data);
|
||||||
|
} else if (result.status) {
|
||||||
|
res.status(200).json([]);
|
||||||
|
} else {
|
||||||
|
res.status(500).json({ message: "Failed to fetch loans" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post("/set-return-date/:loan_code", authenticate, async (req, res) => {
|
||||||
|
const loanCode = req.params.loan_code;
|
||||||
|
const result = await setReturnDate(loanCode);
|
||||||
|
if (result.success) {
|
||||||
|
res.status(200).json({ data: result.data });
|
||||||
|
} else {
|
||||||
|
res.status(500).json({ message: "Failed to set return date" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post("/set-take-date/:loan_code", authenticate, async (req, res) => {
|
||||||
|
const loanCode = req.params.loan_code;
|
||||||
|
const result = await setTakeDate(loanCode);
|
||||||
|
if (result.success) {
|
||||||
|
res.status(200).json({ data: result.data });
|
||||||
|
} else {
|
||||||
|
res.status(500).json({ message: "Failed to set take date" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.get("/all-items", authenticate, async (req, res) => {
|
||||||
|
const result = await getItems();
|
||||||
|
if (result.success) {
|
||||||
|
res.status(200).json(result.data);
|
||||||
|
} else {
|
||||||
|
res.status(500).json({ message: "Failed to fetch items" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.delete("/delete-loan/:id", authenticate, async (req, res) => {
|
||||||
|
const loanId = req.params.id;
|
||||||
|
const result = await SETdeleteLoanFromDatabase(loanId);
|
||||||
|
if (result.success) {
|
||||||
|
res.status(200).json({ message: "Loan deleted successfully" });
|
||||||
|
} else {
|
||||||
|
res.status(500).json({ message: "Failed to delete loan" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.get("/all-loans", authenticate, async (req, res) => {
|
||||||
|
const result = await getALLLoans();
|
||||||
|
if (result.success) {
|
||||||
|
res.status(200).json(result.data);
|
||||||
|
} else {
|
||||||
|
res.status(500).json({ message: "Failed to fetch loans" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post("/borrowable-items", authenticate, async (req, res) => {
|
||||||
|
const { startDate, endDate } = req.body || {};
|
||||||
|
if (!startDate || !endDate) {
|
||||||
|
return res
|
||||||
|
.status(400)
|
||||||
|
.json({ message: "startDate and endDate are required" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await getBorrowableItemsFromDatabase(
|
||||||
|
startDate,
|
||||||
|
endDate,
|
||||||
|
req.user.role,
|
||||||
|
);
|
||||||
|
if (result.success) {
|
||||||
|
// return the array directly for consistency with /items
|
||||||
|
return res.status(200).json(result.data);
|
||||||
|
} else {
|
||||||
|
return res
|
||||||
|
.status(500)
|
||||||
|
.json({ message: "Failed to fetch borrowable items" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export default router;
|
||||||
@@ -0,0 +1,215 @@
|
|||||||
|
import nodemailer from "nodemailer";
|
||||||
|
import dotenv from "dotenv";
|
||||||
|
dotenv.config();
|
||||||
|
|
||||||
|
const formatDateTime = (value) => {
|
||||||
|
if (value == null) return "N/A";
|
||||||
|
|
||||||
|
const toOut = (d) => {
|
||||||
|
if (!(d instanceof Date) || isNaN(d.getTime())) return "N/A";
|
||||||
|
const dd = String(d.getDate()).padStart(2, "0");
|
||||||
|
const mm = String(d.getMonth() + 1).padStart(2, "0");
|
||||||
|
const yyyy = d.getFullYear();
|
||||||
|
const hh = String(d.getHours()).padStart(2, "0");
|
||||||
|
const mi = String(d.getMinutes()).padStart(2, "0");
|
||||||
|
return `${dd}.${mm}.${yyyy} ${hh}:${mi} Uhr`;
|
||||||
|
};
|
||||||
|
|
||||||
|
if (value instanceof Date) return toOut(value);
|
||||||
|
if (typeof value === "number") return toOut(new Date(value));
|
||||||
|
|
||||||
|
const s = String(value).trim();
|
||||||
|
|
||||||
|
// Direct pattern: "YYYY-MM-DD[ T]HH:mm[:ss]"
|
||||||
|
const m = s.match(/^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::\d{2})?/);
|
||||||
|
if (m) {
|
||||||
|
const [, y, M, d, h, min] = m;
|
||||||
|
return `${d}.${M}.${y} ${h}:${min} Uhr`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ISO or other parseable formats
|
||||||
|
const dObj = new Date(s);
|
||||||
|
if (!isNaN(dObj.getTime())) return toOut(dObj);
|
||||||
|
|
||||||
|
return "N/A";
|
||||||
|
};
|
||||||
|
|
||||||
|
function buildLoanEmail({
|
||||||
|
user,
|
||||||
|
items,
|
||||||
|
startDate,
|
||||||
|
endDate,
|
||||||
|
createdDate,
|
||||||
|
note,
|
||||||
|
}) {
|
||||||
|
const brand = process.env.MAIL_BRAND_COLOR || "#0ea5e9";
|
||||||
|
const itemsList =
|
||||||
|
Array.isArray(items) && items.length
|
||||||
|
? `<ul style="margin:4px 0 0 18px; padding:0;">${items
|
||||||
|
.map(
|
||||||
|
(i) =>
|
||||||
|
`<li style="margin:2px 0; color:#111827; line-height:1.3;">${i}</li>`,
|
||||||
|
)
|
||||||
|
.join("")}</ul>`
|
||||||
|
: "<span style='color:#111827;'>N/A</span>";
|
||||||
|
|
||||||
|
return `<!doctype html>
|
||||||
|
<html lang="de">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="color-scheme" content="light">
|
||||||
|
<meta name="supported-color-schemes" content="light">
|
||||||
|
<meta name="x-apple-disable-message-reformatting">
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
|
<style>
|
||||||
|
:root { color-scheme: light; supported-color-schemes: light; }
|
||||||
|
body { margin:0; padding:0; }
|
||||||
|
/* Mobile stacking */
|
||||||
|
@media (max-width:480px) {
|
||||||
|
.outer { width:100% !important; }
|
||||||
|
.pad-sm { padding:16px !important; }
|
||||||
|
.w-label { width:120px !important; }
|
||||||
|
}
|
||||||
|
/* Dark-mode override safety */
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
body, table, td, p, a, h1, h2, h3 { background:#ffffff !important; color:#111827 !important; }
|
||||||
|
.brand-header { background:${brand} !important; color:#ffffff !important; }
|
||||||
|
a { color:${brand} !important; }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body bgcolor="#ffffff" style="background:#ffffff; font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Arial,sans-serif; color:#111827; -webkit-text-size-adjust:100%;">
|
||||||
|
<!-- Preheader (hidden) -->
|
||||||
|
<div style="display:none; max-height:0; overflow:hidden; opacity:0; mso-hide:all;">
|
||||||
|
Neue Ausleihe erstellt – Übersicht der Buchung.
|
||||||
|
</div>
|
||||||
|
<div role="article" aria-roledescription="email" lang="de" style="padding:24px; background:#f2f4f7;">
|
||||||
|
<table role="presentation" cellpadding="0" cellspacing="0" width="100%" class="outer" style="max-width:600px; margin:0 auto; background:#ffffff; border:1px solid #e5e7eb; border-radius:14px; overflow:hidden;">
|
||||||
|
<tr>
|
||||||
|
<td class="brand-header" style="padding:22px 26px; background:${brand}; color:#ffffff;">
|
||||||
|
<h1 style="margin:0; font-size:18px; line-height:1.35; font-weight:600;">Neue Ausleihe erstellt</h1>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td class="pad-sm" style="padding:24px 26px; color:#111827;">
|
||||||
|
<p style="margin:0 0 14px 0; line-height:1.4;">Es wurde eine neue Ausleihe angelegt. Hier sind die Details:</p>
|
||||||
|
<table role="presentation" cellpadding="0" cellspacing="0" width="100%" style="border-collapse:collapse; font-size:14px; line-height:1.3; background:#fcfcfd; border:1px solid #e5e7eb; border-radius:10px; overflow:hidden;">
|
||||||
|
<tbody>
|
||||||
|
<tr>
|
||||||
|
<td class="w-label" style="padding:10px 14px; color:#6b7280; width:170px; border-bottom:1px solid #ececec;">Benutzer</td>
|
||||||
|
<td style="padding:10px 14px; font-weight:600; border-bottom:1px solid #ececec; color:#111827;">${
|
||||||
|
user || "N/A"
|
||||||
|
}</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td style="padding:10px 14px; color:#6b7280; vertical-align:top; border-bottom:1px solid #ececec;">Ausgeliehene Gegenstände</td>
|
||||||
|
<td style="padding:10px 14px; font-weight:600; border-bottom:1px solid #ececec; color:#111827;">${itemsList}</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td style="padding:10px 14px; color:#6b7280; border-bottom:1px solid #ececec;">Startdatum</td>
|
||||||
|
<td style="padding:10px 14px; font-weight:600; border-bottom:1px solid #ececec; color:#111827;">${formatDateTime(
|
||||||
|
startDate,
|
||||||
|
)}</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td style="padding:10px 14px; color:#6b7280; border-bottom:1px solid #ececec;">Enddatum</td>
|
||||||
|
<td style="padding:10px 14px; font-weight:600; border-bottom:1px solid #ececec; color:#111827;">${formatDateTime(
|
||||||
|
endDate,
|
||||||
|
)}</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td style="padding:10px 14px; color:#6b7280;">Erstellt am</td>
|
||||||
|
<td style="padding:10px 14px; font-weight:600; color:#111827;">${formatDateTime(
|
||||||
|
createdDate,
|
||||||
|
)}</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td style="padding:10px 14px; color:#6b7280; vertical-align:top;">Notiz</td>
|
||||||
|
<td style="padding:10px 14px; font-weight:600; color:#111827;">${
|
||||||
|
note || "Keine Notiz"
|
||||||
|
}</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
<p style="margin:22px 0 0 0; font-size:14px;">
|
||||||
|
<a href="https://admin.insta.the1s.de/api" style="display:inline-block; background:${brand}; color:#ffffff; text-decoration:none; padding:10px 16px; border-radius:6px; font-weight:600; font-size:14px;" target="_blank" rel="noopener noreferrer">
|
||||||
|
Übersicht öffnen
|
||||||
|
</a>
|
||||||
|
</p>
|
||||||
|
<p style="margin:18px 0 0 0; font-size:12px; color:#6b7280; line-height:1.4;">
|
||||||
|
Diese E-Mail wurde automatisch vom Ausleihsystem gesendet. Bitte nicht antworten.
|
||||||
|
</p>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildLoanEmailText({
|
||||||
|
user,
|
||||||
|
items,
|
||||||
|
startDate,
|
||||||
|
endDate,
|
||||||
|
createdDate,
|
||||||
|
note,
|
||||||
|
}) {
|
||||||
|
const itemsText =
|
||||||
|
Array.isArray(items) && items.length ? items.join(", ") : "N/A";
|
||||||
|
return [
|
||||||
|
"Neue Ausleihe erstellt",
|
||||||
|
"",
|
||||||
|
`Benutzer: ${user || "N/A"}`,
|
||||||
|
`Gegenstände: ${itemsText}`,
|
||||||
|
`Start: ${formatDateTime(startDate)}`,
|
||||||
|
`Ende: ${formatDateTime(endDate)}`,
|
||||||
|
`Erstellt am: ${formatDateTime(createdDate)}`,
|
||||||
|
`Notiz: ${note || "Keine Notiz"}`,
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sendMailLoan(
|
||||||
|
user,
|
||||||
|
items,
|
||||||
|
startDate,
|
||||||
|
endDate,
|
||||||
|
createdDate,
|
||||||
|
note,
|
||||||
|
) {
|
||||||
|
const transporter = nodemailer.createTransport({
|
||||||
|
host: process.env.MAIL_HOST,
|
||||||
|
port: process.env.MAIL_PORT,
|
||||||
|
secure: true,
|
||||||
|
auth: {
|
||||||
|
user: process.env.MAIL_USER,
|
||||||
|
pass: process.env.MAIL_PASSWORD,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
const info = await transporter.sendMail({
|
||||||
|
from: '"Ausleihsystem" <noreply@mcs-medien.de>',
|
||||||
|
to: process.env.MAIL_SENDEES,
|
||||||
|
subject: "Eine neue Ausleihe wurde erstellt!",
|
||||||
|
text: buildLoanEmailText({
|
||||||
|
user,
|
||||||
|
items,
|
||||||
|
startDate,
|
||||||
|
endDate,
|
||||||
|
createdDate,
|
||||||
|
note,
|
||||||
|
}),
|
||||||
|
html: buildLoanEmail({
|
||||||
|
user,
|
||||||
|
items,
|
||||||
|
startDate,
|
||||||
|
endDate,
|
||||||
|
createdDate,
|
||||||
|
note,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log("Loan message sent:", info.messageId);
|
||||||
|
})();
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import nodemailer from "nodemailer";
|
||||||
|
import dotenv from "dotenv";
|
||||||
|
dotenv.config();
|
||||||
|
|
||||||
|
export function sendMail(username, message) {
|
||||||
|
const transporter = nodemailer.createTransport({
|
||||||
|
host: process.env.MAIL_HOST,
|
||||||
|
port: process.env.MAIL_PORT,
|
||||||
|
secure: true,
|
||||||
|
auth: {
|
||||||
|
user: process.env.MAIL_USER,
|
||||||
|
pass: process.env.MAIL_PASSWORD,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
const mailText = `Neue Kontaktanfrage im Ausleihsystem.\n\nBenutzername: ${username}\n\nNachricht:\n${message}`;
|
||||||
|
|
||||||
|
const mailHtml = `<!DOCTYPE html>
|
||||||
|
<html lang="de">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<title>Neue Nachricht im Ausleihsystem</title>
|
||||||
|
</head>
|
||||||
|
<body style="font-family: Arial, sans-serif; line-height: 1.5; color: #222;">
|
||||||
|
<h2>Neue Nachricht im Ausleihsystem</h2>
|
||||||
|
<p><strong>Benutzername:</strong> ${username}</p>
|
||||||
|
<p><strong>Nachricht:</strong></p>
|
||||||
|
<p style="white-space: pre-line;">${message}</p>
|
||||||
|
</body>
|
||||||
|
</html>`;
|
||||||
|
|
||||||
|
const info = await transporter.sendMail({
|
||||||
|
from: '"Ausleihsystem" <noreply@mcs-medien.de>',
|
||||||
|
to: process.env.MAIL_SENDEES_CONTACT,
|
||||||
|
subject: "Sie haben eine neue Nachricht!",
|
||||||
|
text: mailText,
|
||||||
|
html: mailHtml,
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log("Contact message sent: %s", info.messageId);
|
||||||
|
})();
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import express from "express";
|
||||||
|
import { authenticate, generateToken } from "../../services/authentication.js";
|
||||||
|
const router = express.Router();
|
||||||
|
import dotenv from "dotenv";
|
||||||
|
dotenv.config();
|
||||||
|
|
||||||
|
// database funcs import
|
||||||
|
import { loginFunc, changePassword } from "./database/userMgmt.database.js";
|
||||||
|
import { sendMail } from "./services/mailer_v2.js";
|
||||||
|
|
||||||
|
router.post("/login", async (req, res) => {
|
||||||
|
const result = await loginFunc(req.body.username, req.body.password);
|
||||||
|
if (result.success) {
|
||||||
|
const token = await generateToken({
|
||||||
|
username: result.data.username,
|
||||||
|
is_admin: result.data.is_admin,
|
||||||
|
first_name: result.data.first_name,
|
||||||
|
last_name: result.data.last_name,
|
||||||
|
role: result.data.role,
|
||||||
|
});
|
||||||
|
res.status(200).json({ message: "Login successful", token });
|
||||||
|
} else {
|
||||||
|
res.status(401).json({ message: "Invalid credentials" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post("/change-password", authenticate, async (req, res) => {
|
||||||
|
const oldPassword = req.body.oldPassword;
|
||||||
|
const newPassword = req.body.newPassword;
|
||||||
|
const username = req.user.username;
|
||||||
|
const result = await changePassword(username, oldPassword, newPassword);
|
||||||
|
if (result.success) {
|
||||||
|
res.status(200).json({ message: "Password changed successfully" });
|
||||||
|
} else {
|
||||||
|
res.status(500).json({ message: "Failed to change password" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post("/contact", authenticate, async (req, res) => {
|
||||||
|
const message = req.body.message;
|
||||||
|
const username = req.user.username;
|
||||||
|
|
||||||
|
sendMail(username, message);
|
||||||
|
|
||||||
|
res.status(200).json({ message: "Contact message sent successfully" });
|
||||||
|
});
|
||||||
|
|
||||||
|
export default router;
|
||||||
@@ -27,7 +27,6 @@ CREATE TABLE loans (
|
|||||||
loaned_items_id json NOT NULL DEFAULT ('[]'),
|
loaned_items_id json NOT NULL DEFAULT ('[]'),
|
||||||
loaned_items_name json NOT NULL DEFAULT ('[]'),
|
loaned_items_name json NOT NULL DEFAULT ('[]'),
|
||||||
deleted bool NOT NULL DEFAULT false,
|
deleted bool NOT NULL DEFAULT false,
|
||||||
deleted_admin bool NOT NULL DEFAULT false,
|
|
||||||
note varchar(500) DEFAULT NULL,
|
note varchar(500) DEFAULT NULL,
|
||||||
PRIMARY KEY (id),
|
PRIMARY KEY (id),
|
||||||
CHECK (loan_code REGEXP '^[0-9]{6}$')
|
CHECK (loan_code REGEXP '^[0-9]{6}$')
|
||||||
@@ -56,14 +55,3 @@ CREATE TABLE apiKeys (
|
|||||||
PRIMARY KEY (id),
|
PRIMARY KEY (id),
|
||||||
CHECK (api_key REGEXP '^[0-9]{8}$')
|
CHECK (api_key REGEXP '^[0-9]{8}$')
|
||||||
) ENGINE=InnoDB;
|
) ENGINE=InnoDB;
|
||||||
|
|
||||||
CREATE TABLE functions (
|
|
||||||
id INT NOT NULL AUTO_INCREMENT,
|
|
||||||
function_name VARCHAR(500) NOT NULL UNIQUE,
|
|
||||||
active BOOLEAN NOT NULL DEFAULT true,
|
|
||||||
entry_updated_at timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
|
||||||
entry_created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
|
|
||||||
PRIMARY KEY (id)
|
|
||||||
) ENGINE=InnoDB;
|
|
||||||
|
|
||||||
INSERT INTO functions (function_name) VALUES ("Loan Mailer"), ("Loan Service"), ("Contact Form Service"), ("User Frontend"), ("API")
|
|
||||||
@@ -1,25 +1,8 @@
|
|||||||
import express from "express";
|
import express from "express";
|
||||||
import cors from "cors";
|
import cors from "cors";
|
||||||
import dotenv from "dotenv";
|
import env from "dotenv";
|
||||||
import info from "./info.json" with { type: "json" };
|
import info from "./info.json" assert { type: "json" };
|
||||||
import { authenticate } from "./services/authentication.js";
|
import { authenticate } from "./services/authentication.js";
|
||||||
import { rateLimit } from "express-rate-limit";
|
|
||||||
|
|
||||||
dotenv.config();
|
|
||||||
const app = express();
|
|
||||||
const port = 8004;
|
|
||||||
const naasURL = process.env.NAAS_URL;
|
|
||||||
|
|
||||||
const limiter = rateLimit({
|
|
||||||
windowMs: 1 * 60 * 1000, // 1 minute
|
|
||||||
limit: 50, // Limit each IP to 50 requests per `window` (here, per 1 minute).
|
|
||||||
standardHeaders: "draft-8", // draft-6: `RateLimit-*` headers; draft-7 & draft-8: combined `RateLimit` header
|
|
||||||
legacyHeaders: false, // Disable the `X-RateLimit-*` headers.
|
|
||||||
ipv6Subnet: 56, // Set to 60 or 64 to be less aggressive, or 52 or 48 to be more aggressive
|
|
||||||
// store: ... , // Redis, Memcached, etc. See below.
|
|
||||||
});
|
|
||||||
|
|
||||||
app.use(limiter);
|
|
||||||
|
|
||||||
// frontend routes
|
// frontend routes
|
||||||
import loansMgmtRouter from "./routes/app/loanMgmt.route.js";
|
import loansMgmtRouter from "./routes/app/loanMgmt.route.js";
|
||||||
@@ -31,11 +14,14 @@ import loanDataMgmtRouter from "./routes/admin/loanDataMgmt.route.js";
|
|||||||
import itemDataMgmtRouter from "./routes/admin/itemDataMgmt.route.js";
|
import itemDataMgmtRouter from "./routes/admin/itemDataMgmt.route.js";
|
||||||
import apiDataMgmtRouter from "./routes/admin/apiDataMgmt.route.js";
|
import apiDataMgmtRouter from "./routes/admin/apiDataMgmt.route.js";
|
||||||
import userMgmtRouterADMIN from "./routes/admin/userMgmt.route.js";
|
import userMgmtRouterADMIN from "./routes/admin/userMgmt.route.js";
|
||||||
import serverConfMgmtRouter from "./routes/admin/serverConfMgmt.route.js";
|
|
||||||
|
|
||||||
// API routes
|
// API routes
|
||||||
import apiRouter from "./routes/api/api.route.js";
|
import apiRouter from "./routes/api/api.route.js";
|
||||||
|
|
||||||
|
env.config();
|
||||||
|
const app = express();
|
||||||
|
const port = 8102;
|
||||||
|
|
||||||
app.use(cors());
|
app.use(cors());
|
||||||
// Body-Parser VOR den Routen registrieren
|
// Body-Parser VOR den Routen registrieren
|
||||||
app.use(express.json({ limit: "10mb" }));
|
app.use(express.json({ limit: "10mb" }));
|
||||||
@@ -51,7 +37,6 @@ app.use("/api/admin/user-data", userDataMgmtRouter);
|
|||||||
app.use("/api/admin/item-data", itemDataMgmtRouter);
|
app.use("/api/admin/item-data", itemDataMgmtRouter);
|
||||||
app.use("/api/admin/api-data", apiDataMgmtRouter);
|
app.use("/api/admin/api-data", apiDataMgmtRouter);
|
||||||
app.use("/api/admin/user-mgmt", userMgmtRouterADMIN);
|
app.use("/api/admin/user-mgmt", userMgmtRouterADMIN);
|
||||||
app.use("/api/admin/server-config", serverConfMgmtRouter);
|
|
||||||
|
|
||||||
// API routes
|
// API routes
|
||||||
app.use("/api", apiRouter);
|
app.use("/api", apiRouter);
|
||||||
@@ -62,20 +47,6 @@ app.listen(port, () => {
|
|||||||
console.log(`Server is running on port: ${port}`);
|
console.log(`Server is running on port: ${port}`);
|
||||||
});
|
});
|
||||||
|
|
||||||
app.get("/no", async (req, res) => {
|
|
||||||
try {
|
|
||||||
const response = await fetch(naasURL);
|
|
||||||
if (!response.ok) {
|
|
||||||
res.status(500).send("Request to no-as-a-service went wrong.");
|
|
||||||
}
|
|
||||||
const data = await response.json();
|
|
||||||
res.json(data);
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error communicating with no-as-a-service:", error);
|
|
||||||
res.status(500).send("Error communicating with no-as-a-service.");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
app.get("/verify", authenticate, async (req, res) => {
|
app.get("/verify", authenticate, async (req, res) => {
|
||||||
res.status(200).json({ message: "Token is valid", user: req.user });
|
res.status(200).json({ message: "Token is valid", user: req.user });
|
||||||
});
|
});
|
||||||