Compare commits

..

7 Commits

Author SHA1 Message Date
theis.gaedigk 8589971dc8 added scheme to demo branch 2026-02-09 15:55:27 +01:00
theis.gaedigk 6ec8e19737 Merge branch 'dev' into demoDev 2026-02-09 15:51:25 +01:00
theis.gaedigk 9f44a4796d Merge branch 'dev' into demoDev 2026-02-07 17:50:34 +01:00
theis.gaedigk dc0a68f7f1 fixed version info 2026-02-07 17:42:21 +01:00
theis.gaedigk fe3a06e5ce Merge branch 'dev' into demoDev 2026-02-07 17:41:57 +01:00
theis.gaedigk 179f5686d1 Merge branch 'dev' into demoDev 2026-02-04 13:47:33 +01:00
theis.gaedigk 28373e0231 changed version info 2026-02-01 15:47:51 +01:00
32 changed files with 905 additions and 995 deletions
-5
View File
@@ -117,8 +117,3 @@ ToDo.txt
# only in development branch # only in development branch
next-env.d.ts next-env.d.ts
# psd files from footage
footage/*.psd
icon/
+260 -71
View File
@@ -1,177 +1,366 @@
# Borrow System API Documentation # Borrow System API Documentation
## Overview **Frontend:** https://insta.the1s.de
**Backend base URL:** `https://insta.the1s.de/backend/api`
The Borrow System API provides endpoints for managing items, loans, and door access for a borrowing/locker system. All endpoints require authentication via an 8-digit API key passed as a URL parameter. ---
## Authentication ## Authentication
All requests must include a valid API key in the URL path as the `:key` parameter. API keys are 8-digit numeric strings. All API endpoints require **either**:
### 1. Bearer Token (JWT)
Send an `Authorization` header:
```http
Authorization: Bearer <JWT_TOKEN>
```
- Used for user-based access.
- Token must be valid and not expired.
### 2. API Key (for devices / machine-to-machine)
Include an API key in the route as `:key` parameter:
```text
/api/.../:key/...
```
Example:
```http
GET /api/items/12345678
```
Where `12345678` is your API key.
The API key is validated server-side.
---
## Common Response Codes
- `200 OK` Request was successful.
- `401 Unauthorized` Missing or malformed credentials.
- `403 Forbidden` Credentials invalid or not allowed to access this resource.
- `404 Not Found` Resource (e.g., loan) not found.
- `500 Internal Server Error` Unexpected server error.
---
## Endpoints ## Endpoints
The Base URL for all endpoints is: `https://insta.the1s.de/backend/api` ### 1. Get All Items
### Get All Items **GET** `/api/items/:key`
`GET /items/:key` Returns a list of all items.
Returns all items in the system. #### Path Parameters
**Response 200:** - `:key` API key (8-digit number)
#### Authentication
- Either:
- Valid `Authorization: Bearer <token>`
- Or valid `:key` path parameter
#### Request Example
```http
GET /api/items/12345678 HTTP/1.1
Host: backend.insta.the1s.de
Authorization: Bearer <JWT_TOKEN>
```
#### Successful Response (200)
```json ```json
{ {
"data": [ "data": [
{ {
"id": 1, "id": 1,
"item_name": "Laptop", "item_name": "DJI 1er Mikro",
"can_borrow_role": 1, "can_borrow_role": 4,
"in_safe": true, "inSafe": 1,
"safe_nr": 3, "safe_nr": 3,
"door_key": 101, "door_key": "123",
"last_borrowed_person": "jdoe", "entry_created_at": "2025-08-19T22:02:16.000Z",
"entry_updated_at": "2025-08-19T22:02:16.000Z",
"last_borrowed_person": "alice",
"currently_borrowing": null "currently_borrowing": null
} }
] ]
} }
``` ```
**Response 500:** #### Error Response (500)
```json ```json
{ "message": "Failed to fetch items" } {
"message": "Failed to fetch items"
}
``` ```
--- ---
### Change Item Safe State ### 2. Toggle Item Safe State
`POST /change-state/:key/:itemId` Toggles `in_safe` between `0` and `1` for a given item.
Toggles the `in_safe` boolean state of an item. **Keep in mind that when you return a loan by code, the item states are automatically updated.**
**URL Parameters:** **POST** `/api/change-state/:key/:itemId`
- **key** - API key #### Path Parameters
- **itemId** - The item's ID
**Response 200:** Returns on successful toggle. - `:key` API key (8-digit number)
- `:itemId` Item ID (integer)
**Response 500:** #### Authentication
- Either Bearer token or `:key` API key.
#### Request Example
```http
POST /api/change-state/12345678/42 HTTP/1.1
Host: backend.insta.the1s.de
```
#### Successful Response (200)
```json ```json
{ "message": "Failed to update item state" } {
"data": {}
}
```
_(Implementation currently only returns `{ success: true }`, so `data` may be empty.)_
#### Error Response (500)
```json
{
"message": "Failed to update item state"
}
``` ```
--- ---
### Get Loan by Code ### 3. Get Loan by Code
`GET /get-loan-by-code/:key/:loan_code` Fetch loan information by `loan_code`.
Retrieves loan details by its 6-digit loan code. **GET** `/api/get-loan-by-code/:key/:loan_code`
**URL Parameters:** #### Path Parameters
- **key** - API key - `:key` API key (8-digit number)
- **loan_code** - A 6-digit numeric loan code - `:loan_code` Loan code (string)
**Response 200:** #### Authentication
- Either Bearer token or `:key` API key.
#### Request Example
```http
GET /api/get-loan-by-code/12345678/12345 HTTP/1.1
Host: backend.insta.the1s.de
```
#### Successful Response (200)
```json ```json
{ {
"data": { "data": {
"username": "jdoe", "username": "john",
"returned_date": null, "returned_date": null,
"take_date": "2024-01-15T10:30:00.000Z", "take_date": "2025-01-01T10:00:00.000Z",
"lockers": [1, 3] "lockers": "[1, 2, 3]"
} }
} }
``` ```
**Response 404:** #### Error Response (404)
```json ```json
{ "message": "Loan not found" } {
"message": "Loan not found"
}
``` ```
--- ---
### Set Take Date ### 4. Set Loan Return Date
`POST /set-take-date/:key/:loan_code` Sets `returned_date = NOW()` on a loan and updates related items:
Records when items are physically taken by setting `take_date` to the current timestamp. Updates associated items to `in_safe = false` and sets `currently_borrowing` to the loan's username. - `in_safe = 1`
- `currently_borrowing = NULL`
- `last_borrowed_person = username`
**URL Parameters:** **POST** `/api/set-return-date/:key/:loan_code`
- **key** - API key #### Path Parameters
- **loan_code** - A 6-digit numeric loan code
**Response 200:** Empty JSON object on success. - `:key` API key (8-digit number)
- `:loan_code` Loan code (string)
**Response 500:** #### Authentication
```json - Either Bearer token or `:key` API key.
{ "message": "Loan not found or already taken" }
#### Request Example
```http
POST /api/set-return-date/12345678/12345 HTTP/1.1
Host: backend.insta.the1s.de
``` ```
> **Note:** This endpoint will fail if the loan has already been taken or does not exist. #### Successful Response (200)
```json
{
"data": {}
}
```
#### Error Response (500)
```json
{
"message": "Failed to set return date"
}
```
--- ---
### Set Return Date ### 5. Set Loan Take Date
`POST /set-return-date/:key/:loan_code` Sets `take_date = NOW()` on a loan and updates related items:
Marks a loan as returned by setting `returned_date` to the current timestamp. Also updates all associated items to `in_safe = true`, clears `currently_borrowing`, and sets `last_borrowed_person`. Therefore, keep in mind that you must not call other endpoints that will change the safe state of an item after or before calling this endpoint, otherwise the state of the items will be inconsistent. - `in_safe = 0`
- `currently_borrowing = username`
**URL Parameters:** **POST** `/api/set-take-date/:key/:loan_code`
- **key** - API key #### Path Parameters
- **loan_code** - A 6-digit numeric loan code
**Response 200:** Empty JSON object on success. - `:key` API key (8-digit number)
- `:loan_code` Loan code (string)
**Response 500:** #### Authentication
```json - Either Bearer token or `:key` API key.
{ "message": "Failed to set return date" }
#### Request Example
```http
POST /api/set-take-date/12345678/LOAN-12345 HTTP/1.1
Host: backend.insta.the1s.de
``` ```
> **Note:** This endpoint will fail if the loan has already been returned (i.e., `returned_date` is not `NULL`). #### Successful Response (200)
```json
{
"data": {}
}
```
#### Error Response (500)
```json
{
"message": "Failed to set take date"
}
```
--- ---
### Open Door ### 6. Open Door by Door Key
`GET /open-door/:key/:doorKey` Looks up an item by its `door_key`, toggles `in_safe`, and returns safe information.
Toggles the safe state of an item identified by its door key and returns the associated safe number. **GET** `/api/open-door/:key/:doorKey`
**URL Parameters:** #### Path Parameters
- **key** - API key - `:key` API key (8-digit number)
- **doorKey** - The door key identifier assigned to an item - `:doorKey` Door key/token (string) used by hardware to identify the locker.
**Response 200:** #### Authentication
- Either Bearer token or `:key` API key.
#### Request Example
```http
GET /api/open-door/12345678/123 HTTP/1.1
Host: backend.insta.the1s.de
```
#### Successful Response (200)
```json ```json
{ {
"data": { "data": {
"safe_nr": 3, "safe_nr": 5,
"id": 1 "id": 42
} }
} }
``` ```
**Response 500:** #### Error Response (500)
```json ```json
{ "message": "Failed to open door" } {
"message": "Failed to open door"
}
``` ```
## Error Handling ---
All endpoints return a `500` status code for server-side failures and a JSON body with a `message` field, except for **Get Loan by Code** which returns `404` when no matching loan is found. ## Authentication Error Messages
### Missing credentials
Status: `401`
```json
{
"message": "Unauthorized"
}
```
### Invalid JWT
Status: `403`
```json
{
"message": "Present token invalid"
}
```
### Invalid API Key
Status: `403`
```json
{
"message": "API Key invalid"
}
```
---
## Notes
- All responses are JSON.
- Time fields like `take_date` and `returned_date` are in the format returned by MySQL (usually ISO-like strings).
- `loaned_items_id` in the database is stored as a JSON array string (e.g. `"[1,2,3]"`) and is parsed internally; clients do not interact with this field directly via current endpoints.
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 MiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 MiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 428 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 416 KiB

+1 -5
View File
@@ -2,11 +2,7 @@
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<link <link rel="icon" type="image/svg+xml" href="/vite.svg" />
rel="icon"
type="image/png"
href="/icon_borrow-system-frontend_dark.png"
/>
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ausleihsystem</title> <title>Ausleihsystem</title>
</head> </head>
+257 -325
View File
File diff suppressed because it is too large Load Diff
+1 -2
View File
@@ -1,7 +1,7 @@
{ {
"name": "admin", "name": "admin",
"private": true, "private": true,
"version": "v2.1.2 (dev)", "version": "0.0.0",
"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",
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 MiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-shapes-icon lucide-shapes"><path d="M8.3 10a.7.7 0 0 1-.626-1.079L11.4 3a.7.7 0 0 1 1.198-.043L16.3 8.9a.7.7 0 0 1-.572 1.1Z"/><rect x="3" y="14" width="7" height="7" rx="1"/><circle cx="17.5" cy="17.5" r="3.5"/></svg>

After

Width:  |  Height:  |  Size: 420 B

+4 -4
View File
@@ -12,7 +12,7 @@ import { triggerLogoutAtom } from "@/states/Atoms";
import { MyLoansPage } from "./pages/MyLoansPage"; import { MyLoansPage } from "./pages/MyLoansPage";
import Landingpage from "./pages/Landingpage"; import Landingpage from "./pages/Landingpage";
import { changeLanguage } from "i18next"; import { changeLanguage } from "i18next";
import { Flex } from "@chakra-ui/react"; import { Box, Flex } from "@chakra-ui/react";
import { Footer } from "./components/footer/Footer"; import { Footer } from "./components/footer/Footer";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { API_BASE } from "@/config/api.config"; import { API_BASE } from "@/config/api.config";
@@ -72,8 +72,8 @@ function App() {
return ( return (
<QueryClientProvider client={queryClient}> <QueryClientProvider client={queryClient}>
<Flex direction="column" minH="100dvh"> <Flex direction="column" minH="100vh">
<Flex as="main" flex="1" direction="column"> <Box as="main" flex="1">
<UserContext.Provider value={user}> <UserContext.Provider value={user}>
<BrowserRouter> <BrowserRouter>
<Routes> <Routes>
@@ -88,7 +88,7 @@ function App() {
</Routes> </Routes>
</BrowserRouter> </BrowserRouter>
</UserContext.Provider> </UserContext.Provider>
</Flex> </Box>
<Footer /> <Footer />
</Flex> </Flex>
</QueryClientProvider> </QueryClientProvider>
+2 -2
View File
@@ -142,7 +142,7 @@ export const Header = () => {
value="help" value="help"
onSelect={() => onSelect={() =>
window.open( window.open(
"https://git.the1s.de/Matthias-Claudius-Schule/borrow-system/wiki/?action=_pages", "https://git.the1s.de/Matthias-Claudius-Schule/borrow-system/wiki",
"_blank", "_blank",
"noopener,noreferrer", "noopener,noreferrer",
) )
@@ -279,7 +279,7 @@ export const Header = () => {
</Button> </Button>
<a <a
href="https://git.the1s.de/Matthias-Claudius-Schule/borrow-system/wiki/?action=_pages" href="https://git.the1s.de/Matthias-Claudius-Schule/borrow-system/wiki"
target="_blank" target="_blank"
> >
<Button variant="ghost"> <Button variant="ghost">
-28
View File
@@ -1,28 +0,0 @@
import { DotLottieReact } from "@lottiefiles/dotlottie-react";
export const unlockAnimation = () => {
return (
<DotLottieReact
src="https://lottie.host/f839baa1-9c64-44c4-9386-f0e4c87ab208/2Iw1m4k86d.lottie"
autoplay
/>
);
};
export const approvalAnimation = () => {
return (
<DotLottieReact
src="https://lottie.host/b7257009-9e3f-43e2-8112-a176f4696e4c/iQxxqAVOGX.lottie"
autoplay
/>
);
};
export const logoutAnimation = () => {
return (
<DotLottieReact
src="https://lottie.host/4975758c-de38-4d15-9f74-927709751d32/v8FtKpnD1y.lottie"
autoplay
/>
);
};
+1 -8
View File
@@ -5,14 +5,7 @@ export const Footer = () => {
const { data: info } = useVersionInfoQuery(); const { data: info } = useVersionInfoQuery();
return ( return (
<Box <Box as="footer" py={4} textAlign="center" width="100%">
as="footer"
py={4}
textAlign="center"
width="100%"
flexShrink={0}
fontSize="sm"
>
Made with by Theis Gaedigk - Class of 2019 at MCS-Bochum Made with by Theis Gaedigk - Class of 2019 at MCS-Bochum
<br /> <br />
Frontend-Version: {info ? info["frontend-info"].version : "N/A"} | Frontend-Version: {info ? info["frontend-info"].version : "N/A"} |
+137 -157
View File
@@ -18,7 +18,6 @@ import { borrowAbleItemsAtom } from "@/states/Atoms";
import { createLoan } from "@/utils/Fetcher"; import { createLoan } from "@/utils/Fetcher";
import { Header } from "@/components/Header"; import { Header } from "@/components/Header";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { approvalAnimation } from "@/components/dotLottie";
export interface User { export interface User {
username: string; username: string;
@@ -28,8 +27,6 @@ export interface User {
export const HomePage = () => { export const HomePage = () => {
const { t } = useTranslation(); const { t } = useTranslation();
const [showAnimation, setShowAnimation] = useState(false);
const [borrowableItems, setBorrowableItems] = useAtom(borrowAbleItemsAtom); const [borrowableItems, setBorrowableItems] = useAtom(borrowAbleItemsAtom);
const [startDate, setStartDate] = useState(""); const [startDate, setStartDate] = useState("");
const [endDate, setEndDate] = useState(""); const [endDate, setEndDate] = useState("");
@@ -49,172 +46,155 @@ export const HomePage = () => {
setSelectedItems((prevSelected) => setSelectedItems((prevSelected) =>
prevSelected.includes(itemId) prevSelected.includes(itemId)
? prevSelected.filter((id) => id !== itemId) ? prevSelected.filter((id) => id !== itemId)
: [...prevSelected, itemId], : [...prevSelected, itemId]
); );
}; };
const showApprovalAnimation = (seconds: number) => {
const milliseconds = seconds * 1000;
setShowAnimation(true);
window.setTimeout(() => {
setShowAnimation(false);
}, milliseconds);
};
return ( return (
<> <Container className="px-6 sm:px-8 pt-10">
{showAnimation && ( <Header />
<div className="fixed inset-0 z-9999 flex items-center justify-center pointer-events-none"> {isMsg && (
<div>{approvalAnimation()}</div> <MyAlert
</div> status={msgStatus}
title={msgTitle}
description={msgDescription}
/>
)} )}
<Container className="px-6 sm:px-8 pt-10"> <Stack as="main">
<Header /> <Text>{t("timezone-info")}</Text>
{isMsg && ( <label htmlFor="startDate">
<MyAlert <strong>
status={msgStatus} <Text>{t("start-date")}</Text>
title={msgTitle} </strong>
description={msgDescription} </label>
/> <Input
)} id="startDate"
<Stack as="main"> placeholder={t("start-date")}
<Text>{t("timezone-info")}</Text> type="datetime-local"
<label htmlFor="startDate"> value={startDate}
<strong> onChange={(e) => setStartDate(e.target.value)}
<Text>{t("start-date")}</Text> />
</strong> <label htmlFor="endDate">
</label> <strong>
<Input <Text>{t("end-date")}</Text>
id="startDate" </strong>
placeholder={t("start-date")} </label>
type="datetime-local" <Input
value={startDate} id="endDate"
onChange={(e) => setStartDate(e.target.value)} placeholder={t("end-date")}
/> type="datetime-local"
<label htmlFor="endDate"> value={endDate}
<strong> onChange={(e) => setEndDate(e.target.value)}
<Text>{t("end-date")}</Text> />
</strong> <Button
</label> onClick={async () => {
<Input setIsLoadingA(true);
id="endDate" if (!startDate || !endDate) {
placeholder={t("end-date")} setMsgStatus("error");
type="datetime-local" setMsgTitle(t("missing-fields"));
value={endDate} setMsgDescription(t("missing-fields-desc"));
onChange={(e) => setEndDate(e.target.value)} setIsMsg(true);
/> setIsLoadingA(false);
<Button return;
onClick={async () => { }
setIsLoadingA(true); await getBorrowableItems(startDate, endDate).then((response) => {
if (!startDate || !endDate) { setIsLoadingA(false);
if (response && response.status === "error") {
setMsgStatus("error"); setMsgStatus("error");
setMsgTitle(t("missing-fields")); setMsgTitle(response.title || t("error"));
setMsgDescription(t("missing-fields-desc")); setMsgDescription(response.description || t("unknown-error"));
setIsMsg(true); setIsMsg(true);
setIsLoadingA(false);
return; return;
} }
await getBorrowableItems(startDate, endDate).then((response) => { setBorrowableItems(response.data);
setIsLoadingA(false); setIsMsg(false);
if (response && response.status === "error") { });
setMsgStatus("error"); }}
setMsgTitle(response.title || t("error")); >
setMsgDescription(response.description || t("unknown-error")); {t("get-borrowable-items")}
setIsMsg(true); </Button>
return; {isLoadingA && (
} <VStack colorPalette="teal">
setBorrowableItems(response.data); <Spinner color="colorPalette.600" />
setIsMsg(false); <Text color="colorPalette.600">{t("loading")}</Text>
}); </VStack>
}} )}
> {borrowableItems.length > 0 && (
{t("get-borrowable-items")} <Table.ScrollArea borderWidth="1px" rounded="md">
</Button> <Table.Root size="sm" stickyHeader>
{isLoadingA && ( <Table.Header>
<VStack colorPalette="teal"> <Table.Row bg="bg.subtle">
<Spinner color="colorPalette.600" /> <Table.ColumnHeader></Table.ColumnHeader>
<Text color="colorPalette.600">{t("loading")}</Text> <Table.ColumnHeader>{t("item")}</Table.ColumnHeader>
</VStack> </Table.Row>
)} </Table.Header>
{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> <Table.Body>
{borrowableItems.map((item) => ( {borrowableItems.map((item) => (
<Table.Row key={item.id}> <Table.Row key={item.id}>
<Table.Cell> <Table.Cell>
<input <input
onChange={() => handleCheckboxChange(item.id)} onChange={() => handleCheckboxChange(item.id)}
type="checkbox" type="checkbox"
name={item.id} name={item.id}
id={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.Cell>
<Table.Cell>{item.item_name}</Table.Cell>
</Table.Row> </Table.Row>
</Table.Body> ))}
</Table.Root> <Table.Row>
</Table.ScrollArea> <Table.Cell colSpan={2}>
)} <InputGroup
{selectedItems.length >= 1 && ( endElement={
<Button <Span color="fg.muted" textStyle="xs">
onClick={() => {note.length} / {MAX_CHARACTERS}
createLoan(selectedItems, startDate, endDate, note).then( </Span>
(response) => { }
if (response.status === "error") { >
setMsgStatus("error"); <Input
setMsgTitle(response.title || t("error")); placeholder={t("optional-note")}
setMsgDescription( value={note}
response.description || t("unknown-error"), maxLength={MAX_CHARACTERS}
); onChange={(e) => {
setIsMsg(true); setNote(
return; e.currentTarget.value.slice(0, MAX_CHARACTERS)
} );
showApprovalAnimation(3); }}
setMsgStatus("success"); />
setMsgTitle(t("success")); </InputGroup>
setMsgDescription(t("loan-success")); </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); setIsMsg(true);
}, return;
) }
} setMsgStatus("success");
> setMsgTitle(t("success"));
{t("create-loan")} setMsgDescription(t("loan-success"));
</Button> setIsMsg(true);
)} }
</Stack> )
</Container> }
</> >
{t("create-loan")}
</Button>
)}
</Stack>
</Container>
); );
}; };
+14 -13
View File
@@ -9,13 +9,12 @@ import {
Card, Card,
SimpleGrid, SimpleGrid,
Button, Button,
Container,
} from "@chakra-ui/react"; } from "@chakra-ui/react";
import MyAlert from "@/components/myChakra/MyAlert"; import MyAlert from "@/components/myChakra/MyAlert";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { API_BASE } from "@/config/api.config"; import { API_BASE } from "@/config/api.config";
import Cookies from "js-cookie"; import Cookies from "js-cookie";
import { Header } from "@/components/Header"; import { useNavigate } from "react-router-dom";
export const formatDateTime = (value: string | null | undefined) => { export const formatDateTime = (value: string | null | undefined) => {
if (!value) return "N/A"; if (!value) return "N/A";
@@ -33,7 +32,6 @@ type Loan = {
returned_date: string | null; returned_date: string | null;
take_date: string | null; take_date: string | null;
loaned_items_name: string[] | string; loaned_items_name: string[] | string;
note: string | null;
}; };
type Device = { type Device = {
@@ -48,6 +46,7 @@ type Device = {
const Landingpage: React.FC = () => { const Landingpage: React.FC = () => {
const { t } = useTranslation(); const { t } = useTranslation();
const navigate = useNavigate();
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [loans, setLoans] = useState<Loan[]>([]); const [loans, setLoans] = useState<Loan[]>([]);
@@ -60,7 +59,7 @@ const Landingpage: 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);
@@ -86,7 +85,7 @@ const Landingpage: React.FC = () => {
setError( setError(
"error", "error",
t("error-by-loading"), t("error-by-loading"),
t("unexpected-date-format_loan"), t("unexpected-date-format_loan")
); );
} }
@@ -103,7 +102,7 @@ const Landingpage: React.FC = () => {
setError( setError(
"error", "error",
t("error-by-loading"), t("error-by-loading"),
t("unexpected-date-format_device"), t("unexpected-date-format_device")
); );
} }
} catch (e) { } catch (e) {
@@ -116,8 +115,14 @@ const Landingpage: React.FC = () => {
}, []); }, []);
return ( return (
<Container className="px-6 sm:px-8 pt-10"> <>
<Header /> <Heading as="h1" size="lg" mb={2}>
Matthias-Claudius-Schule Technik
</Heading>
<Button onClick={() => navigate("/", { replace: true })}>
{t("back")}
</Button>
<Heading as="h2" size="md" mb={4}> <Heading as="h2" size="md" mb={4}>
{t("all-loans")} {t("all-loans")}
@@ -163,9 +168,6 @@ const Landingpage: React.FC = () => {
<Table.ColumnHeader> <Table.ColumnHeader>
<strong>{t("return-date")}</strong> <strong>{t("return-date")}</strong>
</Table.ColumnHeader> </Table.ColumnHeader>
<Table.ColumnHeader>
<strong>{t("note")}</strong>
</Table.ColumnHeader>
</Table.Row> </Table.Row>
</Table.Header> </Table.Header>
<Table.Body> <Table.Body>
@@ -182,7 +184,6 @@ const Landingpage: React.FC = () => {
</Table.Cell> </Table.Cell>
<Table.Cell>{formatDateTime(loan.take_date)}</Table.Cell> <Table.Cell>{formatDateTime(loan.take_date)}</Table.Cell>
<Table.Cell>{formatDateTime(loan.returned_date)}</Table.Cell> <Table.Cell>{formatDateTime(loan.returned_date)}</Table.Cell>
<Table.Cell>{loan.note}</Table.Cell>
</Table.Row> </Table.Row>
))} ))}
</Table.Body> </Table.Body>
@@ -259,7 +260,7 @@ const Landingpage: React.FC = () => {
</HStack> </HStack>
</Button> </Button>
</HStack> </HStack>
</Container> </>
); );
}; };
+54 -92
View File
@@ -4,47 +4,27 @@ import { Button, Card, Field, Input, Stack } from "@chakra-ui/react";
import { setIsLoggedInAtom, triggerLogoutAtom } from "@/states/Atoms"; import { setIsLoggedInAtom, triggerLogoutAtom } from "@/states/Atoms";
import { useAtom } from "jotai"; import { useAtom } from "jotai";
import Cookies from "js-cookie"; import Cookies from "js-cookie";
import { useNavigate, useLocation } from "react-router-dom"; import { Navigate, useNavigate, useLocation } from "react-router-dom";
import { PasswordInput } from "@/components/ui/password-input"; import { PasswordInput } from "@/components/ui/password-input";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Footer } from "@/components/footer/Footer";
import { API_BASE } from "@/config/api.config"; import { API_BASE } from "@/config/api.config";
import { unlockAnimation } from "@/components/dotLottie";
import { logoutAnimation } from "@/components/dotLottie";
export const LoginPage = () => { export const LoginPage = () => {
const { t } = useTranslation(); const { t } = useTranslation();
const [isLoggedIn, setIsLoggedIn] = useAtom(setIsLoggedInAtom); const [isLoggedIn, setIsLoggedIn] = useAtom(setIsLoggedInAtom);
const [triggerLogout, setTriggerLogout] = useAtom(triggerLogoutAtom); const [triggerLogout, setTriggerLogout] = useAtom(triggerLogoutAtom);
const [showAnimation, setShowAnimation] = useState(false);
const [showLogout, setShowLogout] = useState(false);
const navigate = useNavigate(); const navigate = useNavigate();
const location = useLocation(); const location = useLocation();
const from = location.state?.from?.pathname || "/"; const from = location.state?.from?.pathname || "/";
useEffect(() => { useEffect(() => {
if (triggerLogout) { if (isLoggedIn) {
setShowLogout(true);
window.setTimeout(() => {
setShowLogout(false);
}, 4500);
}
if (!isLoggedIn) return;
// Existing sessions should redirect immediately, fresh logins wait for animation.
if (!showAnimation) {
navigate(from, { replace: true }); navigate(from, { replace: true });
return; window.location.reload(); // if deleted, the user context is not updated in time
} }
}, [isLoggedIn, navigate, from]);
const timeoutId = window.setTimeout(() => {
navigate(from, { replace: true });
window.location.reload(); // keeps user context in sync after login
}, 3000);
return () => window.clearTimeout(timeoutId);
}, [isLoggedIn, showAnimation, navigate, from]);
const loginFnc = async (username: string, password: string) => { const loginFnc = async (username: string, password: string) => {
const response = await fetch(`${API_BASE}/api/users/login`, { const response = await fetch(`${API_BASE}/api/users/login`, {
@@ -63,8 +43,6 @@ export const LoginPage = () => {
}; };
} }
setShowAnimation(true);
Cookies.set("token", data.token); Cookies.set("token", data.token);
setIsLoggedIn(true); setIsLoggedIn(true);
return { success: true }; return { success: true };
@@ -85,75 +63,59 @@ export const LoginPage = () => {
return; return;
} }
setTriggerLogout(false); setTriggerLogout(false);
navigate(from, { replace: true });
}; };
if (isLoggedIn) {
return <Navigate to={from} replace />;
}
return ( return (
<> <div className="min-h-screen flex items-center justify-center p-4">
{showAnimation && ( <form onSubmit={(e) => e.preventDefault()}>
<div className="fixed inset-0 z-9999 flex items-center justify-center pointer-events-none"> <Card.Root maxW="sm">
<div>{unlockAnimation()}</div> <Card.Header>
</div> <Card.Title>{t("login")}</Card.Title>
)} <Card.Description>{t("enter-credentials")}</Card.Description>
</Card.Header>
{showLogout && ( <Card.Body>
<div className="fixed inset-0 z-9999 flex items-center justify-center pointer-events-none"> <Stack gap="4" w="full">
<div>{logoutAnimation()}</div> <Field.Root>
</div> <Field.Label>{t("username")}</Field.Label>
)} <Input
value={username}
<div className="flex flex-1 items-center justify-center p-4"> onChange={(e) => setUsername(e.target.value)}
<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}
/> />
)} </Field.Root>
<Button <Field.Root>
type="submit" <Field.Label>{t("password")}</Field.Label>
onClick={() => handleLogin()} <PasswordInput
variant="solid" value={password}
> onChange={(e) => setPassword(e.target.value)}
Login
</Button>
</Card.Footer>
<Card.Footer justifyContent="flex-end">
{triggerLogout && (
<MyAlert
status="success"
title={t("logout-success")}
description={t("logout-success-desc")}
/> />
)} </Field.Root>
</Card.Footer> </Stack>
</Card.Root> </Card.Body>
</form> <Card.Footer justifyContent="flex-end">
</div> {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>
<Footer />
</div>
); );
}; };
+4 -2
View File
@@ -1,10 +1,13 @@
import Cookies from "js-cookie"; import Cookies from "js-cookie";
import { API_BASE } from "@/config/api.config"; import { API_BASE } from "@/config/api.config";
import { useTranslation } from "react-i18next";
export const getBorrowableItems = async ( export const getBorrowableItems = async (
startDate: string, startDate: string,
endDate: string, endDate: string,
) => { ) => {
const { t } = useTranslation();
try { try {
const response = await fetch(`${API_BASE}/api/loans/borrowable-items`, { const response = await fetch(`${API_BASE}/api/loans/borrowable-items`, {
method: "POST", method: "POST",
@@ -21,8 +24,7 @@ export const getBorrowableItems = async (
data: null, data: null,
status: "error", status: "error",
title: "Server error", title: "Server error",
description: description: t("serverError"),
"An error occurred on the server. Sometimes reloading the page helps. Otherwise, please contact the administrator.",
}; };
} }
-6
View File
@@ -1,6 +0,0 @@
Copyright (c) 2026 Theis Gaedigk
All rights reserved.
This source code is not to be copied, modified, or distributed in any form
without explicit written permission from the author.
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "admin", "name": "admin",
"private": true, "private": true,
"version": "v1.3.2 (dev)", "version": "0.0.0",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
+2 -2
View File
@@ -3,7 +3,6 @@ import { useState } from "react";
import { loginFunc } from "@/utils/loginUser"; import { loginFunc } from "@/utils/loginUser";
import MyAlert from "../components/myChakra/MyAlert"; import MyAlert from "../components/myChakra/MyAlert";
import { Button, Card, Field, Input, Stack } from "@chakra-ui/react"; import { Button, Card, Field, Input, Stack } from "@chakra-ui/react";
import { PasswordInput } from "@/components/ui/password-input";
const Login: React.FC<{ onSuccess: () => void }> = ({ onSuccess }) => { const Login: React.FC<{ onSuccess: () => void }> = ({ onSuccess }) => {
const [username, setUsername] = useState(""); const [username, setUsername] = useState("");
@@ -44,7 +43,8 @@ const Login: React.FC<{ onSuccess: () => void }> = ({ onSuccess }) => {
</Field.Root> </Field.Root>
<Field.Root> <Field.Root>
<Field.Label>password</Field.Label> <Field.Label>password</Field.Label>
<PasswordInput <Input
type="password"
value={password} value={password}
onChange={(e) => setPassword(e.target.value)} onChange={(e) => setPassword(e.target.value)}
/> />
-159
View File
@@ -1,159 +0,0 @@
"use client"
import type {
ButtonProps,
GroupProps,
InputProps,
StackProps,
} from "@chakra-ui/react"
import {
Box,
HStack,
IconButton,
Input,
InputGroup,
Stack,
mergeRefs,
useControllableState,
} from "@chakra-ui/react"
import * as React from "react"
import { LuEye, LuEyeOff } from "react-icons/lu"
export interface PasswordVisibilityProps {
/**
* The default visibility state of the password input.
*/
defaultVisible?: boolean
/**
* The controlled visibility state of the password input.
*/
visible?: boolean
/**
* Callback invoked when the visibility state changes.
*/
onVisibleChange?: (visible: boolean) => void
/**
* Custom icons for the visibility toggle button.
*/
visibilityIcon?: { on: React.ReactNode; off: React.ReactNode }
}
export interface PasswordInputProps
extends InputProps,
PasswordVisibilityProps {
rootProps?: GroupProps
}
export const PasswordInput = React.forwardRef<
HTMLInputElement,
PasswordInputProps
>(function PasswordInput(props, ref) {
const {
rootProps,
defaultVisible,
visible: visibleProp,
onVisibleChange,
visibilityIcon = { on: <LuEye />, off: <LuEyeOff /> },
...rest
} = props
const [visible, setVisible] = useControllableState({
value: visibleProp,
defaultValue: defaultVisible || false,
onChange: onVisibleChange,
})
const inputRef = React.useRef<HTMLInputElement>(null)
return (
<InputGroup
endElement={
<VisibilityTrigger
disabled={rest.disabled}
onPointerDown={(e) => {
if (rest.disabled) return
if (e.button !== 0) return
e.preventDefault()
setVisible(!visible)
}}
>
{visible ? visibilityIcon.off : visibilityIcon.on}
</VisibilityTrigger>
}
{...rootProps}
>
<Input
{...rest}
ref={mergeRefs(ref, inputRef)}
type={visible ? "text" : "password"}
/>
</InputGroup>
)
})
const VisibilityTrigger = React.forwardRef<HTMLButtonElement, ButtonProps>(
function VisibilityTrigger(props, ref) {
return (
<IconButton
tabIndex={-1}
ref={ref}
me="-2"
aspectRatio="square"
size="sm"
variant="ghost"
height="calc(100% - {spacing.2})"
aria-label="Toggle password visibility"
{...props}
/>
)
},
)
interface PasswordStrengthMeterProps extends StackProps {
max?: number
value: number
}
export const PasswordStrengthMeter = React.forwardRef<
HTMLDivElement,
PasswordStrengthMeterProps
>(function PasswordStrengthMeter(props, ref) {
const { max = 4, value, ...rest } = props
const percent = (value / max) * 100
const { label, colorPalette } = getColorPalette(percent)
return (
<Stack align="flex-end" gap="1" ref={ref} {...rest}>
<HStack width="full" {...rest}>
{Array.from({ length: max }).map((_, index) => (
<Box
key={index}
height="1"
flex="1"
rounded="sm"
data-selected={index < value ? "" : undefined}
layerStyle="fill.subtle"
colorPalette="gray"
_selected={{
colorPalette,
layerStyle: "fill.solid",
}}
/>
))}
</HStack>
{label && <HStack textStyle="xs">{label}</HStack>}
</Stack>
)
})
function getColorPalette(percent: number) {
switch (true) {
case percent < 33:
return { label: "Low", colorPalette: "red" }
case percent < 66:
return { label: "Medium", colorPalette: "orange" }
default:
return { label: "High", colorPalette: "green" }
}
}
+6 -4
View File
@@ -1,11 +1,10 @@
{ {
"compilerOptions": { "compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo", "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022", "target": "ESNext",
"useDefineForClassFields": true, "useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"], "lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext", "module": "ESNext",
"types": ["vite/client"],
"skipLibCheck": true, "skipLibCheck": true,
/* Bundler mode */ /* Bundler mode */
@@ -24,10 +23,13 @@
"noFallthroughCasesInSwitch": true, "noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true, "noUncheckedSideEffectImports": true,
/* Path aliases */ /* Chakra / Pfad Aliases */
"baseUrl": ".",
"paths": { "paths": {
"@/*": ["./src/*"] "@/*": ["./src/*"]
} },
"forceConsistentCasingInFileNames": true
}, },
"include": ["src"] "include": ["src"]
} }
+3 -3
View File
@@ -1,11 +1,11 @@
{ {
"backend-info": { "backend-info": {
"version": "v2.1.1 (dev)" "version": "v2.1 (demo)"
}, },
"frontend-info": { "frontend-info": {
"version": "v2.1.2 (dev)" "version": "v2.1 (demo)"
}, },
"admin-panel-info": { "admin-panel-info": {
"version": "v1.3.2 (dev)" "version": "v1.3.2 (demo)"
} }
} }
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "backendv2", "name": "backendv2",
"version": "v2.1.1 (dev)", "version": "1.0.0",
"main": "server.js", "main": "server.js",
"scripts": { "scripts": {
"test": "echo \"Error: no test specified\" && exit 1", "test": "echo \"Error: no test specified\" && exit 1",
+44 -56
View File
@@ -22,7 +22,7 @@ export const getItemsFromDatabaseV2 = async () => {
export const getLoanByCodeV2 = async (loan_code) => { export const getLoanByCodeV2 = async (loan_code) => {
const [result] = await pool.query( const [result] = await pool.query(
"SELECT username, returned_date, take_date, lockers FROM loans WHERE loan_code = ?;", "SELECT username, returned_date, take_date, lockers FROM loans WHERE loan_code = ?;",
[loan_code], [loan_code]
); );
if (result.length > 0) { if (result.length > 0) {
return { success: true, data: result[0] }; return { success: true, data: result[0] };
@@ -33,7 +33,7 @@ export const getLoanByCodeV2 = async (loan_code) => {
export const changeInSafeStateV2 = async (itemId) => { export const changeInSafeStateV2 = async (itemId) => {
const [result] = await pool.query( const [result] = await pool.query(
"UPDATE items SET in_safe = NOT in_safe WHERE id = ?", "UPDATE items SET in_safe = NOT in_safe WHERE id = ?",
[itemId], [itemId]
); );
if (result.affectedRows > 0) { if (result.affectedRows > 0) {
return { success: true }; return { success: true };
@@ -42,62 +42,50 @@ export const changeInSafeStateV2 = async (itemId) => {
}; };
export const setReturnDateV2 = async (loanCode) => { export const setReturnDateV2 = async (loanCode) => {
try {
const [items] = await pool.query(
"SELECT loaned_items_id, username FROM loans WHERE loan_code = ?",
[loanCode],
);
if (items.length === 0)
return { success: false, message: "No items found for loan" };
const itemIds = Array.isArray(items[0].loaned_items_id)
? items[0].loaned_items_id
: JSON.parse(items[0].loaned_items_id || "[]");
const [result] = await pool.query(
"UPDATE loans SET returned_date = NOW() WHERE loan_code = ? AND returned_date IS NULL",
[loanCode],
);
if (result.affectedRows === 0) return { success: false };
if (itemIds.length > 0) {
await pool.query(
"UPDATE items SET in_safe = 1, currently_borrowing = NULL, last_borrowed_person = ? WHERE id IN (?)",
[items[0].username, itemIds],
);
}
return { success: true, data: { returned: true } };
} catch (error) {
console.error("setReturnDateV2 error:", error);
return { success: false, message: "Failed to set return date" };
}
};
export const setTakeDateV2 = async (loanCode) => {
const [isTaken] = await pool.query(
"SELECT take_date FROM loans WHERE loan_code = ?",
[loanCode],
);
if (isTaken.length === 0 || isTaken[0].take_date !== null) {
return { success: false, message: "Loan not found or already taken" };
}
const [items] = await pool.query( const [items] = await pool.query(
"SELECT loaned_items_id FROM loans WHERE loan_code = ?", "SELECT loaned_items_id FROM loans WHERE loan_code = ?",
[loanCode], [loanCode]
); );
const [owner] = await pool.query( const [owner] = await pool.query(
"SELECT username FROM loans WHERE loan_code = ?", "SELECT username FROM loans WHERE loan_code = ?",
[loanCode], [loanCode]
); );
if (items.length === 0) if (items.length === 0) return { success: false };
return { success: false, message: "No items found for loan" };
const itemIds = Array.isArray(items[0].loaned_items_id)
? items[0].loaned_items_id
: JSON.parse(items[0].loaned_items_id || "[]");
const [setItemStates] = await pool.query(
"UPDATE items SET in_safe = 1, currently_borrowing = NULL, last_borrowed_person = (?) WHERE id IN (?)",
[owner[0].username, itemIds]
);
const [result] = await pool.query(
"UPDATE loans SET returned_date = NOW() WHERE loan_code = ?",
[loanCode]
);
if (result.affectedRows > 0 && setItemStates.affectedRows > 0) {
return { success: true };
}
return { success: false };
};
export const setTakeDateV2 = async (loanCode) => {
const [items] = await pool.query(
"SELECT loaned_items_id FROM loans WHERE loan_code = ?",
[loanCode]
);
const [owner] = await pool.query(
"SELECT username FROM loans WHERE loan_code = ?",
[loanCode]
);
if (items.length === 0) return { success: false };
const itemIds = Array.isArray(items[0].loaned_items_id) const itemIds = Array.isArray(items[0].loaned_items_id)
? items[0].loaned_items_id ? items[0].loaned_items_id
@@ -105,18 +93,18 @@ export const setTakeDateV2 = async (loanCode) => {
const [setItemStates] = await pool.query( const [setItemStates] = await pool.query(
"UPDATE items SET in_safe = 0, currently_borrowing = (?) WHERE id IN (?)", "UPDATE items SET in_safe = 0, currently_borrowing = (?) WHERE id IN (?)",
[owner[0].username, itemIds], [owner[0].username, itemIds]
); );
const [result] = await pool.query( const [result] = await pool.query(
"UPDATE loans SET take_date = NOW() WHERE loan_code = ? AND take_date IS NULL", "UPDATE loans SET take_date = NOW() WHERE loan_code = ?",
[loanCode], [loanCode]
); );
if (result.affectedRows > 0 && setItemStates.affectedRows > 0) { if (result.affectedRows > 0 && setItemStates.affectedRows > 0) {
return { success: true }; return { success: true };
} }
return { message: "Failed to set take date", success: false }; return { success: false };
}; };
export const getAllLoansV2 = async () => { export const getAllLoansV2 = async () => {
@@ -130,12 +118,12 @@ export const getAllLoansV2 = async () => {
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 = ?;",
[doorKey], [doorKey]
); );
if (result.length > 0) { if (result.length > 0) {
const [changeItemSate] = await pool.query( const [changeItemSate] = await pool.query(
"UPDATE items SET in_safe = NOT in_safe WHERE id = ?", "UPDATE items SET in_safe = NOT in_safe WHERE id = ?",
[result[0].id], [result[0].id]
); );
if (changeItemSate.affectedRows > 0) { if (changeItemSate.affectedRows > 0) {
return { success: true, data: result[0] }; return { success: true, data: result[0] };
+6 -6
View File
@@ -47,7 +47,7 @@ router.get(
} else { } else {
res.status(404).json({ message: "Loan not found" }); res.status(404).json({ message: "Loan not found" });
} }
}, }
); );
// Route for API to set the return date by the loan code // Route for API to set the return date by the loan code
@@ -58,11 +58,11 @@ router.post(
const loanCode = req.params.loan_code; const loanCode = req.params.loan_code;
const result = await setReturnDateV2(loanCode); const result = await setReturnDateV2(loanCode);
if (result.success) { if (result.success) {
res.status(200).json({}); res.status(200).json({ data: result.data });
} else { } else {
res.status(500).json({ message: "Failed to set return date" }); res.status(500).json({ message: "Failed to set return date" });
} }
}, }
); );
// Route for API to set the take away date by the loan code // Route for API to set the take away date by the loan code
@@ -73,11 +73,11 @@ router.post(
const loanCode = req.params.loan_code; const loanCode = req.params.loan_code;
const result = await setTakeDateV2(loanCode); const result = await setTakeDateV2(loanCode);
if (result.success) { if (result.success) {
res.status(200).json({}); res.status(200).json({ data: result.data });
} else { } else {
res.status(500).json({ message: result.message }); res.status(500).json({ message: "Failed to set take date" });
} }
}, }
); );
// Route for API to open a door // Route for API to open a door
-1
View File
@@ -62,7 +62,6 @@ router.post("/createLoan", authenticate, async (req, res) => {
mailInfo.data.start_date, mailInfo.data.start_date,
mailInfo.data.end_date, mailInfo.data.end_date,
mailInfo.data.created_at, mailInfo.data.created_at,
mailInfo.data.note,
); );
return res.status(201).json({ return res.status(201).json({
message: "Loan created successfully", message: "Loan created successfully",
+4 -40
View File
@@ -34,14 +34,7 @@ const formatDateTime = (value) => {
return "N/A"; return "N/A";
}; };
function buildLoanEmail({ function buildLoanEmail({ user, items, startDate, endDate, createdDate }) {
user,
items,
startDate,
endDate,
createdDate,
note,
}) {
const brand = process.env.MAIL_BRAND_COLOR || "#0ea5e9"; const brand = process.env.MAIL_BRAND_COLOR || "#0ea5e9";
const itemsList = const itemsList =
Array.isArray(items) && items.length Array.isArray(items) && items.length
@@ -123,12 +116,6 @@ function buildLoanEmail({
createdDate, createdDate,
)}</td> )}</td>
</tr> </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> </tbody>
</table> </table>
<p style="margin:22px 0 0 0; font-size:14px;"> <p style="margin:22px 0 0 0; font-size:14px;">
@@ -147,14 +134,7 @@ function buildLoanEmail({
</html>`; </html>`;
} }
function buildLoanEmailText({ function buildLoanEmailText({ user, items, startDate, endDate, createdDate }) {
user,
items,
startDate,
endDate,
createdDate,
note,
}) {
const itemsText = const itemsText =
Array.isArray(items) && items.length ? items.join(", ") : "N/A"; Array.isArray(items) && items.length ? items.join(", ") : "N/A";
return [ return [
@@ -165,18 +145,10 @@ function buildLoanEmailText({
`Start: ${formatDateTime(startDate)}`, `Start: ${formatDateTime(startDate)}`,
`Ende: ${formatDateTime(endDate)}`, `Ende: ${formatDateTime(endDate)}`,
`Erstellt am: ${formatDateTime(createdDate)}`, `Erstellt am: ${formatDateTime(createdDate)}`,
`Notiz: ${note || "Keine Notiz"}`,
].join("\n"); ].join("\n");
} }
export function sendMailLoan( export function sendMailLoan(user, items, startDate, endDate, createdDate) {
user,
items,
startDate,
endDate,
createdDate,
note,
) {
const transporter = nodemailer.createTransport({ const transporter = nodemailer.createTransport({
host: process.env.MAIL_HOST, host: process.env.MAIL_HOST,
port: process.env.MAIL_PORT, port: process.env.MAIL_PORT,
@@ -198,16 +170,8 @@ export function sendMailLoan(
startDate, startDate,
endDate, endDate,
createdDate, createdDate,
note,
}),
html: buildLoanEmail({
user,
items,
startDate,
endDate,
createdDate,
note,
}), }),
html: buildLoanEmail({ user, items, startDate, endDate, createdDate }),
}); });
console.log("Loan message sent:", info.messageId); console.log("Loan message sent:", info.messageId);
+100
View File
@@ -0,0 +1,100 @@
USE borrow_system_new;
-- USERS
INSERT INTO users (username, password, email, first_name, last_name, role, is_admin)
VALUES
('user1', 'passwordhash1', 'user1@example.com', 'First1', 'Last1', 1, false),
('user2', 'passwordhash2', 'user2@example.com', 'First2', 'Last2', 1, false),
('user3', 'passwordhash3', 'user3@example.com', 'First3', 'Last3', 2, false),
('admin1', 'passwordhash4', 'admin1@example.com', 'Admin', 'One', 9, true),
('admin2', 'passwordhash5', 'admin2@example.com', 'Admin', 'Two', 9, true);
-- ITEMS
INSERT INTO items (item_name, can_borrow_role, in_safe, safe_nr, door_key, last_borrowed_person, currently_borrowing)
VALUES
('Item1', 1, true, 1, 101, NULL, NULL),
('Item2', 1, true, 2, 102, 'user1', 'user1'),
('Item3', 2, true, 3, 103, 'user2', NULL),
('Item4', 1, false, NULL, NULL, NULL, NULL),
('Item5', 2, false, NULL, NULL, 'user3', 'user3');
-- LOANS
INSERT INTO loans (
username,
lockers,
loan_code,
start_date,
end_date,
take_date,
returned_date,
created_at,
loaned_items_id,
loaned_items_name,
deleted,
note
)
VALUES
(
'user1',
JSON_ARRAY('Locker1', 'Locker2'),
'123456',
'2026-02-01 09:00:00',
'2026-02-10 17:00:00',
'2026-02-01 09:15:00',
NULL,
'2026-02-01 09:00:00',
JSON_ARRAY(1, 2),
JSON_ARRAY('Item1', 'Item2'),
false,
'Erste allgemeine Ausleihe'
),
(
'user2',
JSON_ARRAY('Locker3'),
'234567',
'2026-02-02 10:00:00',
'2026-02-05 16:00:00',
'2026-02-02 10:05:00',
'2026-02-05 15:30:00',
'2026-02-02 10:00:00',
JSON_ARRAY(3),
JSON_ARRAY('Item3'),
false,
'Zurückgegeben vor Enddatum'
),
(
'user3',
JSON_ARRAY(),
'345678',
'2026-02-03 08:30:00',
'2026-02-15 18:00:00',
NULL,
NULL,
'2026-02-03 08:30:00',
JSON_ARRAY(5),
JSON_ARRAY('Item5'),
false,
'Noch ausgeliehen'
),
(
'user1',
JSON_ARRAY('Locker4'),
'456789',
'2025-12-01 09:00:00',
'2025-12-03 17:00:00',
'2025-12-01 09:10:00',
'2025-12-03 16:45:00',
'2025-12-01 09:00:00',
JSON_ARRAY(1),
JSON_ARRAY('Item1'),
true,
'Alte, gelöschte Ausleihe'
);
-- API KEYS
INSERT INTO apiKeys (api_key, entry_name)
VALUES
('10000001', 'Entry1'),
('10000002', 'Entry2'),
('10000003', 'Entry3'),
('10000004', 'Entry4');