30 Commits

Author SHA1 Message Date
1b15cf96e8 changed url 2025-08-28 21:38:17 +02:00
bb7f66ecc7 changed urls 2025-08-28 21:15:37 +02:00
59de6d69d9 Merge branch 'dev_v1' into debian12_v1 2025-08-28 21:14:48 +02:00
478f03452d added take and return setter buttons 2025-08-28 21:12:58 +02:00
a932144e94 Update README.md 2025-08-21 19:02:13 +02:00
36ad60b782 Merge branch 'dev' into debian12 2025-08-21 18:55:50 +02:00
7faf95188d added source code button 2025-08-21 18:53:33 +02:00
79df00a17e added footer component 2025-08-21 18:53:18 +02:00
d1625d7e47 refactor help site 2025-08-21 13:00:01 +02:00
a8377e5ec3 added help section 2025-08-21 12:48:03 +02:00
8f1d401aa1 enhance sidebar item descriptions for clarity 2025-08-21 12:44:15 +02:00
226a267ccb updated example response in API documentation to include detailed item properties and entry creation timestamps 2025-08-21 00:38:28 +02:00
fd9496645a added detailed API documentation for retrieving loan details by loan code 2025-08-21 00:36:19 +02:00
33bb64f44b added ToDo.tsx to .gitignore 2025-08-20 18:14:15 +02:00
e4467dba32 Merge branch 'dev' into debian12 2025-08-20 18:10:27 +02:00
2cf82c8dcb fixed bug: error handeling 2025-08-20 18:09:33 +02:00
bcf3cc08bb added improved error handeling 2025-08-20 18:06:59 +02:00
cd2b0e8e42 deleted unused notes 2025-08-20 18:06:40 +02:00
410923af92 Merge branch 'dev' into debian12 2025-08-20 13:39:19 +02:00
24c405386b fixed url bug 2025-08-20 13:21:55 +02:00
d5296bd3fa Merge branch 'dev' into debian12 2025-08-20 13:18:01 +02:00
3ee2f6b670 Merge branch 'dev' into debian12 2025-08-20 01:08:15 +02:00
09af4c760c fix: update database connection settings in docker-compose and database service 2025-08-20 00:49:44 +02:00
3fd0fd9584 fix: add borrow_system-internal network to frontend, backend, and mysql services in docker-compose 2025-08-20 00:45:43 +02:00
27984ebac8 added 2025-08-20 00:42:56 +02:00
3d4aab74d5 changed back 2025-08-20 00:30:49 +02:00
4076630eec changed 2025-08-20 00:27:06 +02:00
6025212e93 refactor: remove redundant environment variable validation and connection check in database service
fix: update dependency reference for backend service in docker-compose
2025-08-20 00:25:35 +02:00
de554048eb added tester 2025-08-20 00:20:35 +02:00
e1d79d2c79 fix: update port numbers and API endpoints for consistency across backend and frontend 2025-08-19 23:55:13 +02:00
20 changed files with 487 additions and 136 deletions

2
.gitignore vendored
View File

@@ -112,3 +112,5 @@ backend/public/uploads/
config/ config/
secrets/ secrets/
keys/ keys/
ToDo.txt

11
Docs/HELP.md Normal file
View File

@@ -0,0 +1,11 @@
# Hilfe Seite
Hier finden Sie Informationen zur Verwendung des Systems.
## Unerwartete Probleme
Falls unerwartetet Probleme im Web oder im Safe auftreten sollten, können Sie den Support via Teams kontaktieren.
**Kontaktpersonen:**
- Theis Gaedigk (Web & Safe)
- Niklas Brunke (Safe)

View File

@@ -8,7 +8,7 @@ On this page you will learn how my API works.
When you look at my backend folder and file structure, you can see that I have two files called `API`. The first file called `api.js` is for my web frontend, because this file works together with my JWT token service. When you look at my backend folder and file structure, you can see that I have two files called `API`. The first file called `api.js` is for my web frontend, because this file works together with my JWT token service.
But I have built a second API. You can see the second API file in the same directory, the file is called `apiV2.js`. **\*But I have built a second API. You can see the second API file in the same directory, the file is called `apiV2.js`.**
This is the file that you can use to build an API. This is the file that you can use to build an API.
@@ -45,21 +45,114 @@ Returns a list of all items and their details.
#### Example Request #### Example Request
``` ```
GET /apiV2/items/your_admin_key GET https://backend.insta.the1s.de/apiV2/items/your_admin_key
``` ```
#### Example Response #### Example Response
``` ```
[ {
{ "data": [
"id": 1, {
"item_name": "DJI 1er Mikro", "id": 1,
"can_borrow_role": "4", "item_name": "DJI 1er Mikro",
"inSafe": 1 "can_borrow_role": 4,
}, "inSafe": 1,
... "entry_created_at": "2025-08-19T22:02:16.000Z"
] },
{
"id": 2,
"item_name": "DJI 2er Mikro 1",
"can_borrow_role": 4,
"inSafe": 1,
"entry_created_at": "2025-08-19T22:02:16.000Z"
},
{
"id": 3,
"item_name": "DJI 2er Mikro 2",
"can_borrow_role": 4,
"inSafe": 1,
"entry_created_at": "2025-08-19T22:02:16.000Z"
},
{
"id": 4,
"item_name": "Rode Richt Mikrofon",
"can_borrow_role": 2,
"inSafe": 1,
"entry_created_at": "2025-08-19T22:02:16.000Z"
},
{
"id": 5,
"item_name": "Kamera Stativ",
"can_borrow_role": 1,
"inSafe": 1,
"entry_created_at": "2025-08-19T22:02:16.000Z"
},
{
"id": 6,
"item_name": "SONY Kamera - inkl. Akkus und Objektiv",
"can_borrow_role": 1,
"inSafe": 1,
"entry_created_at": "2025-08-19T22:02:16.000Z"
},
{
"id": 7,
"item_name": "MacBook inkl. Adapter",
"can_borrow_role": 2,
"inSafe": 1,
"entry_created_at": "2025-08-19T22:02:16.000Z"
},
{
"id": 8,
"item_name": "SD Karten",
"can_borrow_role": 3,
"inSafe": 1,
"entry_created_at": "2025-08-19T22:02:16.000Z"
},
{
"id": 9,
"item_name": "Kameragimbal",
"can_borrow_role": 1,
"inSafe": 1,
"entry_created_at": "2025-08-19T22:02:16.000Z"
},
{
"id": 10,
"item_name": "ATEM MINI PRO",
"can_borrow_role": 1,
"inSafe": 1,
"entry_created_at": "2025-08-19T22:02:16.000Z"
},
{
"id": 11,
"item_name": "Handygimbal",
"can_borrow_role": 4,
"inSafe": 1,
"entry_created_at": "2025-08-19T22:02:16.000Z"
},
{
"id": 12,
"item_name": "Kameralfter",
"can_borrow_role": 1,
"inSafe": 1,
"entry_created_at": "2025-08-19T22:02:16.000Z"
},
{
"id": 13,
"item_name": "Kleine Kamera 1 - inkl. Objektiv",
"can_borrow_role": 2,
"inSafe": 1,
"entry_created_at": "2025-08-19T22:02:16.000Z"
},
{
"id": 14,
"item_name": "Kleine Kamera 2 - inkl. Objektiv",
"can_borrow_role": 2,
"inSafe": 1,
"entry_created_at": "2025-08-19T22:02:16.000Z"
}
]
}
``` ```
Each item has the following properties: Each item has the following properties:
@@ -69,6 +162,8 @@ Each item has the following properties:
- `can_borrow_role`: The role ID that is allowed to borrow the item. - `can_borrow_role`: The role ID that is allowed to borrow the item.
- `inSafe`: Indicates whether the item is currently in the locker (1) or not (0). This variable/state can change over time. - `inSafe`: Indicates whether the item is currently in the locker (1) or not (0). This variable/state can change over time.
_You also get an http 200 status code._
--- ---
### 2. Change Item Safe State ### 2. Change Item Safe State
@@ -82,7 +177,7 @@ Updates the `inSafe` state of an item (whether it is in the locker).
#### Example Request #### Example Request
``` ```
POST /apiV2/controlInSafe/your_admin_key/5/0 POST https://backend.insta.the1s.de/apiV2/controlInSafe/your_admin_key/item_id/new_item_state
``` ```
#### Example Response #### Example Response
@@ -93,7 +188,7 @@ POST /apiV2/controlInSafe/your_admin_key/5/0
_An empty object means, that the operation was successful and no further information is returned._ _An empty object means, that the operation was successful and no further information is returned._
_You also get an http 2xx status code._ _You also get an http 200 status code._
--- ---
@@ -108,7 +203,7 @@ Sets the `returned_date` of a loan to the current server time.
#### Example Request #### Example Request
``` ```
POST /apiV2/setReturnDate/your_admin_key/123456 POST https://backend.insta.the1s.de/apiV2/setReturnDate/your_admin_key/your_loan_code
``` ```
#### Example Response #### Example Response
@@ -119,7 +214,7 @@ POST /apiV2/setReturnDate/your_admin_key/123456
_An empty object means, that the operation was successful and no further information is returned._ _An empty object means, that the operation was successful and no further information is returned._
_You also get an http 2xx status code._ _You also get an http 200 status code._
--- ---
@@ -134,7 +229,7 @@ Sets the `take_date` of a loan to the current server time.
#### Example Request #### Example Request
``` ```
POST /apiV2/setTakeDate/your_admin_key/123456 POST https://backend.insta.the1s.de/apiV2/setTakeDate/your_admin_key/your_loan_code
``` ```
#### Example Response #### Example Response
@@ -149,6 +244,57 @@ _You also get an http 2xx status code._
--- ---
### 5. Get whole loan by loan code
**POST** `/getLoanByCode/:key/:loan_code`
Retrieves the details of a specific loan by its unique code.
- `loan_code`: The unique code of the loan.
#### Example Request
```
GET https://backend.insta.the1s.de/getLoanByCode/your_admin_key/your_loan_code
```
#### Example Response
```
{
"data": {
"id": 6,
"username": "theis",
"loan_code": 646473,
"start_date": "2025-08-25T13:23:00.000Z",
"end_date": "2025-08-26T13:23:00.000Z",
"take_date": null,
"returned_date": null,
"created_at": "2025-08-20T11:23:40.000Z",
"loaned_items_id": [
8,
9
],
"loaned_items_name": [
"SD Karten",
"Kameragimbal"
]
}
}
```
_You also get an http 200 status code._
If the loan id does not exist, you will receive a 404 status code and an error message.
```
{
"message": "Loan not found"
}
```
---
## Error Handling ## Error Handling
- `403 Forbidden`: Invalid or missing API key. - `403 Forbidden`: Invalid or missing API key.

View File

@@ -1,73 +1,7 @@
# Borrow System # Borrow System
![React](https://img.shields.io/badge/React-20232A?logo=react&logoColor=61DAFB) **You have reached the `debian12` branch.**
![TypeScript](https://img.shields.io/badge/TypeScript-3178C6?logo=typescript&logoColor=white)
![Vite](https://img.shields.io/badge/Vite-646CFF?logo=vite&logoColor=white)
![TailwindCSS](https://img.shields.io/badge/Tailwind_CSS-38B2AC?logo=tailwind-css&logoColor=white)
![Node.js](https://img.shields.io/badge/Node.js-339933?logo=node.js&logoColor=white)
![Express](https://img.shields.io/badge/Express-000000?logo=express&logoColor=white)
![MySQL](https://img.shields.io/badge/MySQL-4479A1?logo=mysql&logoColor=white)
![Docker](https://img.shields.io/badge/Docker-2496ED?logo=docker&logoColor=white)
![JWT](https://img.shields.io/badge/JWT-000000?logo=jsonwebtokens&logoColor=white)
A small fullstack system to log in, view available items, reserve them for a time window, and manage personal loans. Here you will find the source code of exactly the application that I have hosted.
- Frontend: React + TypeScript + Vite + Tailwind CSS The main branch or the branch that I am developing on, is the `dev` branch.
- Backend: Node.js + Express + MySQL + JWT (jose)
- Orchestration: Docker Compose (backend + MySQL)
## Contents
- Frontend: [frontend/](frontend)
- Vite/Tailwind 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)
- 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)
- Backend: [backend/](backend)
- Server: [backend/server.js](backend/server.js)
- Routes: [backend/routes/api.js](backend/routes/api.js), [backend/routes/apiV2.js](backend/routes/apiV2.js)
- DB + 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)
- Docs: [docs/](docs)
- API docs (see below): [docs/backend_API_docs/README.md](docs/backend_API_docs/README.md)
## Features (highlevel)
- Auth via JWT (login -> token cookie) using the backend route in [backend/routes/api.js](backend/routes/api.js).
- After login, the app loads items, loans, and user loans and keeps them in localStorage.
- Choose a date range to fetch borrowable items, select items, and create a loan.
- Manage personal loans list (and delete a loan).
Key frontend utilities:
- [`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 time range.
- [`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.toastify.myToast`](frontend/src/utils/toastify.ts): toast notifications.
UI flow (main screens):
- Period selection: [frontend/src/components/Form1.tsx](frontend/src/components/Form1.tsx)
- Borrowable items + selection: [frontend/src/components/Form2.tsx](frontend/src/components/Form2.tsx)
- User loans table: [frontend/src/components/Form4.tsx](frontend/src/components/Form4.tsx)
## Development
- Scripts: see [frontend/package.json](frontend/package.json) and [backend/package.json](backend/package.json)
- Frontend: `npm run dev`, `npm run build`, `npm run preview`, `npm run lint`
- 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
- 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).
- 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`. Crosscomponent updates are signaled via window events from [`utils.fetchData`](frontend/src/utils/fetchData.ts).
## API documentation
Refer to the dedicated API docs:
`docs/backend_API_docs/README.md`

View File

@@ -7,6 +7,6 @@ RUN npm install
COPY . . COPY . .
EXPOSE 8002 EXPOSE 8102
CMD ["npm", "start"] CMD ["npm", "start"]

View File

@@ -7,11 +7,12 @@ import {
deleteLoanFromDatabase, deleteLoanFromDatabase,
getBorrowableItemsFromDatabase, getBorrowableItemsFromDatabase,
createLoanInDatabase, createLoanInDatabase,
onTake,
onReturn,
} from "../services/database.js"; } from "../services/database.js";
import { authenticate, generateToken } from "../services/tokenService.js"; import { authenticate, generateToken } from "../services/tokenService.js";
const router = express.Router(); const router = express.Router();
// Example endpoint
router.post("/login", async (req, res) => { router.post("/login", async (req, res) => {
const result = await loginFunc(req.body.username, req.body.password); const result = await loginFunc(req.body.username, req.body.password);
if (result.success) { if (result.success) {
@@ -86,6 +87,26 @@ router.post("/borrowableItems", authenticate, async (req, res) => {
} }
}); });
router.post("/takeLoan/:id", authenticate, async (req, res) => {
const loanId = req.params.id;
const result = await onTake(loanId);
if (result.success) {
res.status(200).json({ message: "Loan taken successfully" });
} else {
res.status(500).json({ message: "Failed to take loan" });
}
});
router.post("/returnLoan/:id", authenticate, async (req, res) => {
const loanId = req.params.id;
const result = await onReturn(loanId);
if (result.success) {
res.status(200).json({ message: "Loan returned successfully" });
} else {
res.status(500).json({ message: "Failed to return loan" });
}
});
router.post("/createLoan", authenticate, async (req, res) => { router.post("/createLoan", authenticate, async (req, res) => {
try { try {
const { items, startDate, endDate } = req.body || {}; const { items, startDate, endDate } = req.body || {};

View File

@@ -5,7 +5,7 @@ import apiRouter from "./routes/api.js";
import apiRouterV2 from "./routes/apiV2.js"; import apiRouterV2 from "./routes/apiV2.js";
env.config(); env.config();
const app = express(); const app = express();
const port = 8002; const port = 8102;
app.use(cors()); app.use(cors());
// Increase body size limits to support large CSV JSON payloads // Increase body size limits to support large CSV JSON payloads

View File

@@ -8,6 +8,7 @@ const pool = mysql
user: process.env.DB_USER, user: process.env.DB_USER,
password: process.env.DB_PASSWORD, password: process.env.DB_PASSWORD,
database: process.env.DB_NAME, database: process.env.DB_NAME,
port: process.env.DB_PORT,
}) })
.promise(); .promise();
@@ -293,3 +294,29 @@ export const createLoanInDatabase = async (
conn.release(); conn.release();
} }
}; };
// These functions are only temporary, and will be deleted when the full bin is set up.
export const onTake = async (loanId) => {
const [result] = await pool.query(
"UPDATE loans SET take_date = NOW() WHERE id = ?",
[loanId]
);
if (result.affectedRows > 0) {
return { success: true };
}
return { success: false };
};
export const onReturn = async (loanId) => {
const [result] = await pool.query(
"UPDATE loans SET returned_date = NOW() WHERE id = ?",
[loanId]
);
if (result.affectedRows > 0) {
return { success: true };
}
return { success: false };
};

View File

@@ -1,23 +1,30 @@
services: services:
# borrow_system-frontend: borrow_system-frontend:
# container_name: borrow_system-frontend container_name: borrow_system-frontend
# build: ./frontend build: ./frontend
# ports: ports:
# - "8001:8001" - "8101:8101"
# environment: networks:
# - CHOKIDAR_USEPOLLING=true - proxynet
# volumes: - borrow_system-internal
# - ./frontend:/app environment:
# - /app/node_modules - CHOKIDAR_USEPOLLING=true
# restart: unless-stopped volumes:
- ./frontend:/app
- /app/node_modules
restart: unless-stopped
borrow_system-backend: borrow_system-backend:
container_name: borrow_system-backend container_name: borrow_system-backend
build: ./backend build: ./backend
ports: ports:
- "8002:8002" - "8102:8102"
networks:
- proxynet
- borrow_system-internal
environment: environment:
DB_HOST: mysql DB_HOST: mysql
DB_PORT: 3306
DB_USER: root DB_USER: root
DB_PASSWORD: ${DB_PASSWORD} DB_PASSWORD: ${DB_PASSWORD}
DB_NAME: borrow_system DB_NAME: borrow_system
@@ -38,6 +45,14 @@ services:
- mysql-data:/var/lib/mysql - mysql-data:/var/lib/mysql
ports: ports:
- "3309:3306" - "3309:3306"
networks:
- borrow_system-internal
volumes: volumes:
mysql-data: mysql-data:
networks:
proxynet:
external: true
borrow_system-internal:
external: false

View File

@@ -7,6 +7,6 @@ RUN npm install
COPY . . COPY . .
EXPOSE 8001 EXPOSE 8101
CMD ["npm", "run", "dev"] CMD ["npm", "run", "dev"]

View File

@@ -6,7 +6,11 @@ import Form2 from "./components/Form2";
import Form4 from "./components/Form4"; import Form4 from "./components/Form4";
import LoginForm from "./components/LoginForm"; import LoginForm from "./components/LoginForm";
import Cookies from "js-cookie"; import Cookies from "js-cookie";
import { fetchAllData, ALL_ITEMS_UPDATED_EVENT } from "./utils/fetchData"; import {
fetchAllData,
ALL_ITEMS_UPDATED_EVENT,
AUTH_LOGOUT_EVENT,
} from "./utils/fetchData";
import { myToast } from "./utils/toastify"; import { myToast } from "./utils/toastify";
function App() { function App() {
@@ -18,10 +22,17 @@ function App() {
setIsLoggedIn(true); setIsLoggedIn(true);
fetchAllData(token); fetchAllData(token);
} }
localStorage.setItem("borrowableItems", JSON.stringify([])); localStorage.setItem("borrowableItems", JSON.stringify([]));
}, []); }, []);
useEffect(() => {
const onAuthLogout = () => {
setIsLoggedIn(false);
};
window.addEventListener(AUTH_LOGOUT_EVENT, onAuthLogout);
return () => window.removeEventListener(AUTH_LOGOUT_EVENT, onAuthLogout);
}, []);
const handleLogout = () => { const handleLogout = () => {
Cookies.remove("token"); Cookies.remove("token");
localStorage.removeItem("allItems"); localStorage.removeItem("allItems");

View File

@@ -0,0 +1,12 @@
import React from "react";
const Footer: React.FC = () => {
return (
<footer className="fixed bottom-0 left-0 text-sm w-full bg-slate-100 text-center py-2 border-t border-slate-200 z-50">
<p>Made with by Theis Gaedigk - Jahrgang 2019</p>
<p>v1.1</p>
</footer>
);
};
export default Footer;

View File

@@ -4,6 +4,7 @@ import { handleDeleteLoan } from "../utils/userHandler";
import { useMutation, useQuery } from "@tanstack/react-query"; import { useMutation, useQuery } from "@tanstack/react-query";
import Cookies from "js-cookie"; import Cookies from "js-cookie";
import { queryClient } from "../utils/queryClient"; import { queryClient } from "../utils/queryClient";
import { onTake, onReturn } from "../utils/userHandler";
type Loan = { type Loan = {
id: number; id: number;
@@ -26,7 +27,7 @@ const formatDate = (iso: string | null) => {
}; };
async function fetchUserLoans(): Promise<Loan[]> { async function fetchUserLoans(): Promise<Loan[]> {
const res = await fetch("http://localhost:8002/api/userLoans", { const res = await fetch("https://backend.insta.the1s.de/api/userLoans", {
method: "GET", method: "GET",
headers: { Authorization: `Bearer ${Cookies.get("token") || ""}` }, headers: { Authorization: `Bearer ${Cookies.get("token") || ""}` },
}); });
@@ -49,6 +50,20 @@ const Form4: React.FC = () => {
}, },
}); });
const takeMutation = useMutation({
mutationFn: (loanID: number) => onTake(loanID),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["userLoans"] });
},
});
const returnMutation = useMutation({
mutationFn: (loanID: number) => onReturn(loanID),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["userLoans"] });
},
});
const onDelete = (loanID: number) => deleteMutation.mutate(loanID); const onDelete = (loanID: number) => deleteMutation.mutate(loanID);
if (isFetching) { if (isFetching) {
@@ -99,11 +114,32 @@ const Form4: React.FC = () => {
</div> </div>
<div> <div>
<span className="text-slate-500">Abgeholt:</span>{" "} <span className="text-slate-500">Abgeholt:</span>{" "}
{formatDate(loan.take_date)} {loan.take_date ? (
formatDate(loan.take_date)
) : (
<button
className="inline-flex items-center rounded-md border border-blue-200 bg-blue-50 px-2 py-0.5 text-[11px] font-medium text-blue-700 hover:bg-blue-100 focus:outline-none focus:ring-2 focus:ring-blue-500/40 disabled:opacity-50"
onClick={() => takeMutation.mutate(loan.id)}
disabled={takeMutation.isPending}
>
{takeMutation.isPending ? "..." : "Abholen"}
</button>
)}
</div> </div>
<div> <div>
<span className="text-slate-500">Zurück:</span>{" "} <span className="text-slate-500">Zurück:</span>{" "}
{formatDate(loan.returned_date)} {loan.returned_date ? (
formatDate(loan.returned_date)
) : (
<button
className="inline-flex items-center rounded-md border border-emerald-200 bg-emerald-50 px-2 py-0.5 text-[11px] font-medium text-emerald-700 hover:bg-emerald-100 focus:outline-none focus:ring-2 focus:ring-emerald-500/40 disabled:opacity-50"
onClick={() => returnMutation.mutate(loan.id)}
disabled={returnMutation.isPending || !loan.take_date}
title={!loan.take_date ? "Erst abholen" : ""}
>
{returnMutation.isPending ? "..." : "Zurückgeben"}
</button>
)}
</div> </div>
</div> </div>
<div className="mt-2 text-xs text-slate-700"> <div className="mt-2 text-xs text-slate-700">
@@ -170,10 +206,31 @@ const Form4: React.FC = () => {
{formatDate(loan.end_date)} {formatDate(loan.end_date)}
</td> </td>
<td className="px-4 py-3 whitespace-nowrap font-mono tabular-nums text-slate-900"> <td className="px-4 py-3 whitespace-nowrap font-mono tabular-nums text-slate-900">
{formatDate(loan.take_date)} {loan.take_date ? (
formatDate(loan.take_date)
) : (
<button
className="inline-flex items-center rounded-md border border-blue-200 bg-blue-50 px-2 py-1 text-xs font-medium text-blue-700 hover:bg-blue-100 focus:outline-none focus:ring-2 focus:ring-blue-500/40 disabled:opacity-50"
onClick={() => takeMutation.mutate(loan.id)}
disabled={takeMutation.isPending}
>
{takeMutation.isPending ? "..." : "Abholen"}
</button>
)}
</td> </td>
<td className="px-4 py-3 whitespace-nowrap font-mono tabular-nums text-slate-900"> <td className="px-4 py-3 whitespace-nowrap font-mono tabular-nums text-slate-900">
{formatDate(loan.returned_date)} {loan.returned_date ? (
formatDate(loan.returned_date)
) : (
<button
className="inline-flex items-center rounded-md border border-emerald-200 bg-emerald-50 px-2 py-1 text-xs font-medium text-emerald-700 hover:bg-emerald-100 focus:outline-none focus:ring-2 focus:ring-emerald-500/40 disabled:opacity-50"
onClick={() => returnMutation.mutate(loan.id)}
disabled={returnMutation.isPending || !loan.take_date}
title={!loan.take_date ? "Erst abholen" : ""}
>
{returnMutation.isPending ? "..." : "Zurückgeben"}
</button>
)}
</td> </td>
<td className="px-4 py-3 whitespace-nowrap font-mono tabular-nums text-slate-900"> <td className="px-4 py-3 whitespace-nowrap font-mono tabular-nums text-slate-900">
{formatDate(loan.created_at)} {formatDate(loan.created_at)}
@@ -182,7 +239,7 @@ const Form4: React.FC = () => {
<div className="text-slate-900"> <div className="text-slate-900">
{Array.isArray(loan.loaned_items_name) {Array.isArray(loan.loaned_items_name)
? loan.loaned_items_name.join(", ") ? loan.loaned_items_name.join(", ")
: "-"} : ""}
</div> </div>
</td> </td>
<td className="px-4 py-3 text-right"> <td className="px-4 py-3 text-right">

View File

@@ -23,6 +23,16 @@ const Header: React.FC<HeaderProps> = ({ onLogout }) => {
> >
Logout Logout
</button> </button>
<a href="https://git.the1s.de/Matthias-Claudius-Schule/borrow-system/src/branch/dev/Docs/HELP.md">
<button className="h-9 px-3 rounded-md border border-slate-300 text-slate-700 hover:bg-slate-100 transition">
Hilfe
</button>
</a>
<a href="https://git.the1s.de/Matthias-Claudius-Schule/borrow-system">
<button className="h-9 px-3 rounded-md border border-slate-300 text-slate-700 hover:bg-slate-100 transition">
Source Code
</button>
</a>
</div> </div>
</header> </header>
); );

View File

@@ -1,4 +1,5 @@
import React from "react"; import React from "react";
import Footer from "./Footer";
import { useState } from "react"; import { useState } from "react";
import { loginUser } from "../utils/fetchData"; import { loginUser } from "../utils/fetchData";
import { myToast } from "../utils/toastify"; import { myToast } from "../utils/toastify";
@@ -66,6 +67,7 @@ const LoginForm: React.FC<LoginFormProps> = ({ onLogin }) => {
</button> </button>
</form> </form>
</div> </div>
<Footer />
</div> </div>
); );
}; };

View File

@@ -70,7 +70,9 @@ const Sidebar: React.FC = () => {
<Object <Object
title={item.item_name} title={item.item_name}
description={ description={
item.inSafe ? "Im Schließfach" : "Nicht im Schließfach" item.inSafe
? "Aktuell im Schließfach"
: "Aktuell nicht im Schließfach"
} }
/> />
</div> </div>
@@ -81,7 +83,7 @@ const Sidebar: React.FC = () => {
<div className="mt-4 pt-3 border-t border-slate-200/70 text-[10px] sm:text-xs text-slate-500 items-center gap-4 hidden md:flex"> <div className="mt-4 pt-3 border-t border-slate-200/70 text-[10px] sm:text-xs text-slate-500 items-center gap-4 hidden md:flex">
<span className="inline-flex items-center gap-1"> <span className="inline-flex items-center gap-1">
<span className="inline-block w-3 h-3 bg-emerald-500 rounded-full ring-2 ring-white shadow-sm"></span> <span className="inline-block w-3 h-3 bg-emerald-500 rounded-full ring-2 ring-white shadow-sm"></span>
Verfügbar Im Schließfach
</span> </span>
<span className="inline-flex items-center gap-1"> <span className="inline-flex items-center gap-1">
<span className="inline-block w-3 h-3 bg-red-500 rounded-full ring-2 ring-white shadow-sm"></span> <span className="inline-block w-3 h-3 bg-red-500 rounded-full ring-2 ring-white shadow-sm"></span>

View File

@@ -2,6 +2,7 @@ import React from "react";
import "../App.css"; import "../App.css";
import Header from "../components/Header"; import Header from "../components/Header";
import Sidebar from "../components/Sidebar"; import Sidebar from "../components/Sidebar";
import Footer from "../components/Footer";
type LayoutProps = { type LayoutProps = {
children: React.ReactNode; children: React.ReactNode;
@@ -10,15 +11,13 @@ type LayoutProps = {
const Layout: React.FC<LayoutProps> = ({ children, onLogout }) => { const Layout: React.FC<LayoutProps> = ({ children, onLogout }) => {
return ( return (
<div className="h-screen overflow-hidden flex bg-slate-50 text-slate-800"> <div className="h-screen flex flex-col bg-slate-50 text-slate-800">
{/* Main */} {/* Main */}
<main className="flex-1 min-h-0 overflow-hidden flex flex-col items-center px-3 sm:px-5 py-4 sm:py-8"> <main className="flex-1 min-h-0 overflow-hidden flex flex-col items-center px-3 sm:px-5 py-4 sm:py-8 pb-12">
{/* Sidebar on mobile appears inline on top; on desktop it's a sticky column */}
<div className="w-full max-w-5xl flex flex-col gap-3 md:flex-row md:gap-6 md:items-stretch min-h-0 h-full"> <div className="w-full max-w-5xl flex flex-col gap-3 md:flex-row md:gap-6 md:items-stretch min-h-0 h-full">
<div className="hidden md:flex md:flex-col md:shrink-0 md:w-72 md:min-h-0 md:h-full"> <div className="hidden md:flex md:flex-col md:shrink-0 md:w-72 md:min-h-0 md:h-full">
<Sidebar /> <Sidebar />
</div> </div>
<div className="flex-1 min-w-0 min-h-0 h-full flex flex-col overflow-hidden"> <div className="flex-1 min-w-0 min-h-0 h-full flex flex-col overflow-hidden">
<div className="w-full"> <div className="w-full">
<Header onLogout={onLogout} /> <Header onLogout={onLogout} />
@@ -29,6 +28,7 @@ const Layout: React.FC<LayoutProps> = ({ children, onLogout }) => {
</div> </div>
</div> </div>
</main> </main>
<Footer />
</div> </div>
); );
}; };

View File

@@ -4,18 +4,44 @@ import { myToast } from "./toastify";
// Event name used to notify the app when the list of items has been updated // Event name used to notify the app when the list of items has been updated
export const ALL_ITEMS_UPDATED_EVENT = "allItemsUpdated"; export const ALL_ITEMS_UPDATED_EVENT = "allItemsUpdated";
export const BORROWABLE_ITEMS_UPDATED_EVENT = "borrowableItemsUpdated"; export const BORROWABLE_ITEMS_UPDATED_EVENT = "borrowableItemsUpdated";
export const AUTH_LOGOUT_EVENT = "authLogout";
let sendError = false;
function logout() {
Cookies.remove("token");
Cookies.remove("startDate");
Cookies.remove("endDate");
localStorage.removeItem("allItems");
localStorage.removeItem("allLoans");
localStorage.removeItem("userLoans");
localStorage.removeItem("borrowableItems");
window.dispatchEvent(new Event(ALL_ITEMS_UPDATED_EVENT));
window.dispatchEvent(new Event(BORROWABLE_ITEMS_UPDATED_EVENT));
window.dispatchEvent(new Event(AUTH_LOGOUT_EVENT));
}
export const fetchAllData = async (token: string | undefined) => { export const fetchAllData = async (token: string | undefined) => {
if (!token) return; if (!token) return;
// First we fetch all items that are potentially available for borrowing // First we fetch all items that are potentially available for borrowing
try { try {
const response = await fetch("http://localhost:8002/api/items", { const response = await fetch("https://backend.insta.the1s.de/api/items", {
method: "GET", method: "GET",
headers: { headers: {
Authorization: `Bearer ${token}`, Authorization: `Bearer ${token}`,
}, },
}); });
if (response.status === 500) {
if (!sendError) {
sendError = true;
myToast("Session expired. Please log in again.", "error");
logout();
return;
}
return;
}
if (!response.ok) { if (!response.ok) {
myToast("Failed to fetch items", "error"); myToast("Failed to fetch items", "error");
return; return;
@@ -31,13 +57,23 @@ export const fetchAllData = async (token: string | undefined) => {
// get all loans // get all loans
try { try {
const response = await fetch("http://localhost:8002/api/loans", { const response = await fetch("https://backend.insta.the1s.de/api/loans", {
method: "GET", method: "GET",
headers: { headers: {
Authorization: `Bearer ${token}`, Authorization: `Bearer ${token}`,
}, },
}); });
if (response.status === 500) {
if (!sendError) {
sendError = true;
myToast("Session expired. Please log in again.", "error");
logout();
return;
}
return;
}
if (!response.ok) { if (!response.ok) {
myToast("Failed to fetch loans!", "error"); myToast("Failed to fetch loans!", "error");
return; return;
@@ -53,13 +89,23 @@ export const fetchAllData = async (token: string | undefined) => {
// get user loans // get user loans
try { try {
const response = await fetch("http://localhost:8002/api/userLoans", { const response = await fetch("https://backend.insta.the1s.de/api/userLoans", {
method: "GET", method: "GET",
headers: { headers: {
Authorization: `Bearer ${token}`, Authorization: `Bearer ${token}`,
}, },
}); });
if (response.status === 500) {
if (!sendError) {
sendError = true;
myToast("Session expired. Please log in again.", "error");
logout();
return;
}
return;
}
if (!response.ok) { if (!response.ok) {
myToast("Failed to fetch user loans!", "error"); myToast("Failed to fetch user loans!", "error");
return; return;
@@ -76,7 +122,7 @@ export const fetchAllData = async (token: string | undefined) => {
export const loginUser = async (username: string, password: string) => { export const loginUser = async (username: string, password: string) => {
try { try {
const response = await fetch("http://localhost:8002/api/login", { const response = await fetch("https://backend.insta.the1s.de/api/login", {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@@ -112,7 +158,7 @@ export const getBorrowableItems = async () => {
} }
try { try {
const response = await fetch("http://localhost:8002/api/borrowableItems", { const response = await fetch("https://backend.insta.the1s.de/api/borrowableItems", {
method: "POST", method: "POST",
headers: { headers: {
Authorization: `Bearer ${Cookies.get("token") || ""}`, Authorization: `Bearer ${Cookies.get("token") || ""}`,
@@ -122,6 +168,16 @@ export const getBorrowableItems = async () => {
body: JSON.stringify({ startDate, endDate }), body: JSON.stringify({ startDate, endDate }),
}); });
if (response.status === 500) {
if (!sendError) {
sendError = true;
myToast("Session expired. Please log in again.", "error");
logout();
return;
}
return;
}
if (!response.ok) { if (!response.ok) {
myToast("Failed to fetch borrowable items", "error"); myToast("Failed to fetch borrowable items", "error");
return; return;

View File

@@ -5,7 +5,7 @@ import { queryClient } from "./queryClient";
export const handleDeleteLoan = async (loanID: number): Promise<boolean> => { export const handleDeleteLoan = async (loanID: number): Promise<boolean> => {
try { try {
const response = await fetch( const response = await fetch(
`http://localhost:8002/api/deleteLoan/${loanID}`, `https://backend.insta.the1s.de/api/deleteLoan/${loanID}`,
{ {
method: "DELETE", method: "DELETE",
headers: { headers: {
@@ -75,14 +75,17 @@ export const rmFromRemove = (itemID: number) => {
export const createLoan = async (startDate: string, endDate: string) => { export const createLoan = async (startDate: string, endDate: string) => {
const items = removeArr; const items = removeArr;
const response = await fetch("http://localhost:8002/api/createLoan", { const response = await fetch(
method: "POST", "https://backend.insta.the1s.de/api/createLoan",
headers: { {
"Content-Type": "application/json", method: "POST",
Authorization: `Bearer ${Cookies.get("token") || ""}`, headers: {
}, "Content-Type": "application/json",
body: JSON.stringify({ items, startDate, endDate }), Authorization: `Bearer ${Cookies.get("token") || ""}`,
}); },
body: JSON.stringify({ items, startDate, endDate }),
}
);
if (!response.ok) { if (!response.ok) {
myToast("Fehler beim Erstellen der Ausleihe", "error"); myToast("Fehler beim Erstellen der Ausleihe", "error");
@@ -100,3 +103,43 @@ export const createLoan = async (startDate: string, endDate: string) => {
return true; return true;
}; };
export const onReturn = async (loanID: number) => {
const response = await fetch(
`https://backend.insta.the1s.de/api/returnLoan/${loanID}`,
{
method: "POST",
headers: {
Authorization: `Bearer ${Cookies.get("token") || ""}`,
},
}
);
if (!response.ok) {
myToast("Fehler beim Zurückgeben der Ausleihe", "error");
return false;
}
myToast("Ausleihe erfolgreich zurückgegeben!", "success");
return true;
};
export const onTake = async (loanID: number) => {
const response = await fetch(
`https://backend.insta.the1s.de/api/takeLoan/${loanID}`,
{
method: "POST",
headers: {
Authorization: `Bearer ${Cookies.get("token") || ""}`,
},
}
);
if (!response.ok) {
myToast("Fehler beim Ausleihen der Ausleihe", "error");
return false;
}
myToast("Ausleihe erfolgreich ausgeliehen!", "success");
return true;
};

View File

@@ -1,15 +1,17 @@
import { defineConfig } from "vite"; import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import svgr from "vite-plugin-svgr";
import tailwindcss from "@tailwindcss/vite"; import tailwindcss from "@tailwindcss/vite";
export default defineConfig({ export default defineConfig({
plugins: [react(), svgr(), tailwindcss()], plugins: [tailwindcss()],
server: { server: {
host: "0.0.0.0", host: "0.0.0.0",
port: 8001, allowedHosts: ["insta.the1s.de"],
watch: { port: 8101,
usePolling: true, watch: { usePolling: true },
hmr: {
host: "insta.the1s.de",
port: 8101,
protocol: "wss",
}, },
}, },
}); });