Compare commits
237
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cc2c3d7f54 | ||
|
|
8b89f31178 | ||
|
|
c7933dfa3b | ||
|
|
c1bb628f22 | ||
|
|
941f9105d6 | ||
|
|
0070b0e7a0 | ||
|
|
63d3e2db07 | ||
|
|
9c17b2a495 | ||
|
|
929ec5ef10 | ||
|
|
67c704009e | ||
|
|
831de8b610 | ||
|
|
fd43e84c0c | ||
|
|
1ce8d33b0d | ||
|
|
c48da71cd5 | ||
|
|
8e35e81e8f | ||
|
|
95aae1c050 | ||
|
|
2cc5545ea8 | ||
|
|
f8e29dca10 | ||
|
|
e52fc13da4 | ||
|
|
4291552b6d | ||
|
|
5191871681 | ||
|
|
c61a283127 | ||
|
|
4a3c948386 | ||
|
|
6fb03530df | ||
|
|
d2c36e71be | ||
|
|
40d784ab36 | ||
|
|
60c85efd37 | ||
|
|
747932cf03 | ||
|
|
0964109c4b | ||
|
|
5442f2f1f3 | ||
|
|
56e073244f | ||
|
|
d2dc74971f | ||
|
|
25709ea0d9 | ||
|
|
f8ab2490fe | ||
|
|
3de877dd2b | ||
|
|
5d0134017a | ||
|
|
07503ec079 | ||
|
|
4155982aac | ||
|
|
59e05e5c4c | ||
|
|
2facdab011 | ||
|
|
04db0bd7e0 | ||
|
|
40dd34bcac | ||
|
|
939d3e89c5 | ||
|
|
a355c42964 | ||
|
|
c8a230979f | ||
|
|
581cd4a1fd | ||
|
|
c53e6e095a | ||
|
|
eaa325668c | ||
|
|
1fa8b4a9a7 | ||
|
|
3ba3c1c0cb | ||
|
|
ee54d51f8b | ||
|
|
a8dab549af | ||
|
|
06976f7972 | ||
|
|
977a6c1b16 | ||
|
|
38c647c62f | ||
|
|
757b316b49 | ||
|
|
d05e9ab3ee | ||
|
|
3f59ed6951 | ||
|
|
6efb0fee80 | ||
|
|
2e98fa50de | ||
|
|
7221ee1843 | ||
|
|
ae0cb5af81 | ||
|
|
80f38fcd3d | ||
|
|
70f3d1fdcc | ||
|
|
4b08a574d8 | ||
|
|
5aa8a32020 | ||
|
|
b58a04b030 | ||
|
|
e1615f9345 | ||
|
|
ce760eb721 | ||
|
|
109cd7660a | ||
|
|
727bd832dc | ||
|
|
3b93b1fa23 | ||
|
|
9963731b10 | ||
|
|
5546401aa4 | ||
|
|
2f405539fb | ||
|
|
c803e42a76 | ||
|
|
76c0e6a64b | ||
|
|
ebda6424c7 | ||
|
|
e362515eff | ||
|
|
31960d1ff8 | ||
|
|
3bf5560834 | ||
|
|
4c60fea4c4 | ||
|
|
0577a63205 | ||
|
|
fd2ccaa747 | ||
|
|
df6b5eac59 | ||
|
|
d64489aed4 | ||
|
|
cb6b5858e5 | ||
|
|
85e6d7fe00 | ||
|
|
4b9f55268c | ||
|
|
90ca266793 | ||
|
|
b9d67cd147 | ||
|
|
58b5d29040 | ||
|
|
baa74adcc1 | ||
|
|
07d194ee6a | ||
|
|
0a4d981808 | ||
|
|
a78118da8d | ||
|
|
8ce882a745 | ||
|
|
c6571033b0 | ||
|
|
238cd9254a | ||
|
|
ca8030afbd | ||
|
|
1076b12668 | ||
|
|
80cb393768 | ||
|
|
79486fe1cb | ||
|
|
09ea1cb301 | ||
|
|
db21bcf1b4 | ||
|
|
4ec14416ca | ||
|
|
6556d2c01d | ||
|
|
903e360c29 | ||
|
|
c5a9a09ef3 | ||
|
|
a191c9c053 | ||
|
|
084a0fa2e2 | ||
|
|
88a2c74e88 | ||
|
|
3a03457f5a | ||
|
|
757e13efe4 | ||
|
|
d2ee9d73c7 | ||
|
|
8c10e6e63f | ||
|
|
24bf5fcaaf | ||
|
|
6f03fd8032 | ||
|
|
17010d5480 | ||
|
|
a8c5ef25f7 | ||
|
|
eccd0135fc | ||
|
|
8f294278d4 | ||
|
|
16e48aaf3f | ||
|
|
e49700071b | ||
|
|
a8b4ac3d60 | ||
|
|
974a5a75d8 | ||
|
|
b9783a1909 | ||
|
|
304e73b459 | ||
|
|
12277abb9e | ||
|
|
20d22d6ce4 | ||
|
|
27d21efefa | ||
|
|
3e67bf9052 | ||
|
|
3438321765 | ||
|
|
29d47ddd9b | ||
|
|
7b298180e0 | ||
|
|
9b3bd76c42 | ||
|
|
5b73b44e79 | ||
|
|
cf4a003c51 | ||
|
|
592b60082b | ||
|
|
a34292bda1 | ||
|
|
2f37ae8067 | ||
|
|
f49da68e15 | ||
|
|
9491da2950 | ||
|
|
a75ba12897 | ||
|
|
b52fe07618 | ||
|
|
0d3de4f705 | ||
|
|
ef3f953ebd | ||
|
|
1db4e69322 | ||
|
|
83f1c9d191 | ||
|
|
af513034ef | ||
|
|
3358c8f669 | ||
|
|
d3f7a7570f | ||
|
|
c502601a2f | ||
|
|
070a390da8 | ||
|
|
bcf93ee9eb | ||
|
|
9daff3ea5c | ||
|
|
71fea52da7 | ||
|
|
a8821ceca8 | ||
|
|
7e668e17d3 | ||
|
|
965a4b97ee | ||
|
|
6054173b03 | ||
|
|
5ba35bb471 | ||
|
|
47b5590394 | ||
|
|
47fec60b5b | ||
|
|
e9319b49ec | ||
|
|
b98e38b38b | ||
|
|
a24a3033d3 | ||
|
|
d94d68aa33 | ||
|
|
cc0dcaf664 | ||
|
|
7a79bf4436 | ||
|
|
4b00dd6554 | ||
|
|
ba34a97328 | ||
|
|
a013ad0bb8 | ||
|
|
d7240584f9 | ||
|
|
a0bdf5539c | ||
|
|
770025f8fc | ||
|
|
960e91c38a | ||
|
|
b99f52f09a | ||
|
|
86af1a5edf | ||
|
|
49d4d13afc | ||
|
|
45fa095eaf | ||
|
|
23be7e12c7 | ||
|
|
6ea1ff799c | ||
|
|
5131266242 | ||
|
|
bb17bc735c | ||
|
|
af7d15c97a | ||
|
|
04453fd885 | ||
|
|
bf36a6605f | ||
|
|
8f9696991f | ||
|
|
9cad1e8b6b | ||
|
|
880029a0cf | ||
|
|
32abe60d98 | ||
|
|
ea965971f1 | ||
|
|
eff1f61422 | ||
|
|
a4c0323100 | ||
|
|
fc755edadf | ||
|
|
0fca896cc2 | ||
|
|
f83f321876 | ||
|
|
b9d637665c | ||
|
|
378720b235 | ||
|
|
49f4ba8483 | ||
|
|
ea5d31384a | ||
|
|
7f5f464841 | ||
|
|
ab93c9959d | ||
|
|
679ef7dcbd | ||
|
|
c3572a3d70 | ||
|
|
4fc60a08d9 | ||
|
|
5159877d8d | ||
|
|
b3ddfd9aa5 | ||
|
|
755ebfd06b | ||
|
|
e198fce791 | ||
|
|
8341404f45 | ||
|
|
5291752403 | ||
|
|
c0ae12185a | ||
|
|
68f13f369c | ||
|
|
a24b2697b0 | ||
|
|
13a654561e | ||
|
|
5a058de2f0 | ||
|
|
b8f13a37fd | ||
|
|
423075e746 | ||
|
|
99810d2b7d | ||
|
|
a1972f26d3 | ||
|
|
866f860d5a | ||
|
|
16e1dca43c | ||
|
|
c47c311ecd | ||
|
|
bd504f7817 | ||
|
|
b0914314bb | ||
|
|
48c16350b7 | ||
|
|
b217769961 | ||
|
|
769d1117eb | ||
|
|
c77bef5cf3 | ||
|
|
217803ba8f | ||
|
|
8fb70ccccd | ||
|
|
311de4f78b | ||
|
|
7b36514e27 | ||
|
|
7be418ad75 | ||
|
|
478f03452d |
@@ -0,0 +1,14 @@
|
|||||||
|
**/node_modules
|
||||||
|
**/dist
|
||||||
|
**/dist-ssr
|
||||||
|
.git
|
||||||
|
.idea
|
||||||
|
.vscode
|
||||||
|
**/.env
|
||||||
|
**/.env.*
|
||||||
|
**/.DS_Store
|
||||||
|
**/*.log
|
||||||
|
docs
|
||||||
|
pics
|
||||||
|
icon
|
||||||
|
no-as-a-service
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
DB_PASSWORD=
|
||||||
|
BACKEND_URL=
|
||||||
|
MAIL_HOST=
|
||||||
|
MAIL_PORT=
|
||||||
|
MAIL_USER=
|
||||||
|
MAIL_PASSWORD=
|
||||||
|
MAIL_SENDEES_CONTACT=
|
||||||
|
MAIL_SENDEES=
|
||||||
|
NAAS_URL=
|
||||||
|
SECRET_KEY=
|
||||||
+11
-1
@@ -11,6 +11,8 @@ dist/
|
|||||||
build/
|
build/
|
||||||
out/
|
out/
|
||||||
|
|
||||||
|
docker-compose.override.yml
|
||||||
|
|
||||||
# Environment variables
|
# Environment variables
|
||||||
.env
|
.env
|
||||||
.env.local
|
.env.local
|
||||||
@@ -109,8 +111,16 @@ backend/public/uploads/
|
|||||||
*.sqlite3
|
*.sqlite3
|
||||||
|
|
||||||
# API keys and secrets (additional protection)
|
# API keys and secrets (additional protection)
|
||||||
config/
|
|
||||||
secrets/
|
secrets/
|
||||||
keys/
|
keys/
|
||||||
|
|
||||||
ToDo.txt
|
ToDo.txt
|
||||||
|
|
||||||
|
|
||||||
|
# only in development branch
|
||||||
|
next-env.d.ts
|
||||||
|
|
||||||
|
# psd files from footage
|
||||||
|
pics/*.psd
|
||||||
|
|
||||||
|
icon/
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
[submodule "no-as-a-service"]
|
||||||
|
path = no-as-a-service
|
||||||
|
url = https://github.com/hotheadhacker/no-as-a-service.git
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"semi": true,
|
||||||
|
"singleQuote": false,
|
||||||
|
"trailingComma": "all",
|
||||||
|
"printWidth": 80,
|
||||||
|
"tabWidth": 2
|
||||||
|
}
|
||||||
@@ -3,3 +3,5 @@
|
|||||||
This document provides an overview of the backend API endpoints and their usage.
|
This document provides an overview of the backend API endpoints and their usage.
|
||||||
|
|
||||||
To get to that information, go to the `backend_API_docs` directory.
|
To get to that information, go to the `backend_API_docs` directory.
|
||||||
|
|
||||||
|
If you need help, see HELP.md file in this directory.
|
||||||
+120
-249
@@ -1,306 +1,177 @@
|
|||||||
# Backend API docs
|
# Borrow System API Documentation
|
||||||
|
|
||||||
If you want to cooperate with me, or build something new with my backend API, feel free to reach out!
|
## Overview
|
||||||
|
|
||||||
On this page you will learn how my API works.
|
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.
|
||||||
|
|
||||||
## General information
|
|
||||||
|
|
||||||
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`.**
|
|
||||||
|
|
||||||
This is the file that you can use to build an API.
|
|
||||||
|
|
||||||
But first you have to get the Admin API key, stored in an `.env` file on my server.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Authentication
|
## Authentication
|
||||||
|
|
||||||
All endpoints require the Admin API key (`ADMIN_ID`) as a URL parameter.
|
All requests must include a valid API key in the URL path as the `:key` parameter. API keys are 8-digit numeric strings.
|
||||||
|
|
||||||
Example: `/apiV2/items/{ADMIN_ID}`
|
## Endpoints
|
||||||
|
|
||||||
---
|
The Base URL for all endpoints is: `https://insta.the1s.de/backend/api`
|
||||||
|
|
||||||
## URL
|
### Get All Items
|
||||||
|
|
||||||
- The frontend is currently running on `https://insta.the1s.de`.
|
`GET /items/:key`
|
||||||
|
|
||||||
- The backend is currently running on `https://backend.insta.the1s.de`.
|
Returns all items in the system.
|
||||||
|
|
||||||
You can see the status of this and all my other services at `https://status.the1s.de`.
|
**Response 200:**
|
||||||
|
|
||||||
---
|
```json
|
||||||
|
|
||||||
## Current endpoints
|
|
||||||
|
|
||||||
### 1. Get All Items
|
|
||||||
|
|
||||||
**GET** `/apiV2/items/:key`
|
|
||||||
|
|
||||||
Returns a list of all items and their details.
|
|
||||||
|
|
||||||
#### Example Request
|
|
||||||
|
|
||||||
```
|
|
||||||
GET https://backend.insta.the1s.de/apiV2/items/your_admin_key
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Example Response
|
|
||||||
|
|
||||||
```
|
|
||||||
{
|
{
|
||||||
"data": [
|
"data": [
|
||||||
{
|
{
|
||||||
"id": 1,
|
"id": 1,
|
||||||
"item_name": "DJI 1er Mikro",
|
"item_name": "Laptop",
|
||||||
"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,
|
"can_borrow_role": 1,
|
||||||
"inSafe": 1,
|
"in_safe": true,
|
||||||
"entry_created_at": "2025-08-19T22:02:16.000Z"
|
"safe_nr": 3,
|
||||||
},
|
"door_key": 101,
|
||||||
{
|
"last_borrowed_person": "jdoe",
|
||||||
"id": 6,
|
"currently_borrowing": null
|
||||||
"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:
|
**Response 500:**
|
||||||
|
|
||||||
- `id`: The unique identifier for the item.
|
```json
|
||||||
- `item_name`: The name of the item.
|
{ "message": "Failed to fetch items" }
|
||||||
- `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.
|
|
||||||
|
|
||||||
_You also get an http 200 status code._
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### 2. Change Item Safe State
|
### Change Item Safe State
|
||||||
|
|
||||||
**POST** `/apiV2/controlInSafe/:key/:itemId/:state`
|
`POST /change-state/:key/:itemId`
|
||||||
|
|
||||||
Updates the `inSafe` state of an item (whether it is in the locker).
|
Toggles the `in_safe` boolean state of an item.
|
||||||
|
|
||||||
- `state` must be `"1"` (in safe) or `"0"` (not in safe).
|
**URL Parameters:**
|
||||||
|
|
||||||
#### Example Request
|
- **key** - API key
|
||||||
|
- **itemId** - The item's ID
|
||||||
|
|
||||||
|
**Response 200:** Returns on successful toggle.
|
||||||
|
|
||||||
|
**Response 500:**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "message": "Failed to update item state" }
|
||||||
```
|
```
|
||||||
POST https://backend.insta.the1s.de/apiV2/controlInSafe/your_admin_key/item_id/new_item_state
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Example Response
|
|
||||||
|
|
||||||
```
|
|
||||||
{}
|
|
||||||
```
|
|
||||||
|
|
||||||
_An empty object means, that the operation was successful and no further information is returned._
|
|
||||||
|
|
||||||
_You also get an http 200 status code._
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### 3. Set Return Date
|
### Get Loan by Code
|
||||||
|
|
||||||
**POST** `/apiV2/setReturnDate/:key/:loan_code`
|
`GET /get-loan-by-code/:key/:loan_code`
|
||||||
|
|
||||||
Sets the `returned_date` of a loan to the current server time.
|
Retrieves loan details by its 6-digit loan code.
|
||||||
|
|
||||||
- `loan_code`: The unique code of the loan.
|
**URL Parameters:**
|
||||||
|
|
||||||
#### Example Request
|
- **key** - API key
|
||||||
|
- **loan_code** - A 6-digit numeric loan code
|
||||||
|
|
||||||
```
|
**Response 200:**
|
||||||
POST https://backend.insta.the1s.de/apiV2/setReturnDate/your_admin_key/your_loan_code
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Example Response
|
```json
|
||||||
|
|
||||||
```
|
|
||||||
{}
|
|
||||||
```
|
|
||||||
|
|
||||||
_An empty object means, that the operation was successful and no further information is returned._
|
|
||||||
|
|
||||||
_You also get an http 200 status code._
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 4. Set Take Date
|
|
||||||
|
|
||||||
**POST** `/apiV2/setTakeDate/:key/:loan_code`
|
|
||||||
|
|
||||||
Sets the `take_date` of a loan to the current server time.
|
|
||||||
|
|
||||||
- `loan_code`: The unique code of the loan.
|
|
||||||
|
|
||||||
#### Example Request
|
|
||||||
|
|
||||||
```
|
|
||||||
POST https://backend.insta.the1s.de/apiV2/setTakeDate/your_admin_key/your_loan_code
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Example Response
|
|
||||||
|
|
||||||
```
|
|
||||||
{}
|
|
||||||
```
|
|
||||||
|
|
||||||
_An empty object means, that the operation was successful and no further information is returned._
|
|
||||||
|
|
||||||
_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": {
|
"data": {
|
||||||
"id": 6,
|
"username": "jdoe",
|
||||||
"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,
|
"returned_date": null,
|
||||||
"created_at": "2025-08-20T11:23:40.000Z",
|
"take_date": "2024-01-15T10:30:00.000Z",
|
||||||
"loaned_items_id": [
|
"lockers": [1, 3]
|
||||||
8,
|
|
||||||
9
|
|
||||||
],
|
|
||||||
"loaned_items_name": [
|
|
||||||
"SD Karten",
|
|
||||||
"Kameragimbal"
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
_You also get an http 200 status code._
|
**Response 404:**
|
||||||
|
|
||||||
If the loan id does not exist, you will receive a 404 status code and an error message.
|
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "message": "Loan not found" }
|
||||||
```
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Set Take Date
|
||||||
|
|
||||||
|
`POST /set-take-date/:key/:loan_code`
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
**URL Parameters:**
|
||||||
|
|
||||||
|
- **key** - API key
|
||||||
|
- **loan_code** - A 6-digit numeric loan code
|
||||||
|
|
||||||
|
**Response 200:** Empty JSON object on success.
|
||||||
|
|
||||||
|
**Response 500:**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "message": "Loan not found or already taken" }
|
||||||
|
```
|
||||||
|
|
||||||
|
> **Note:** This endpoint will fail if the loan has already been taken or does not exist.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Set Return Date
|
||||||
|
|
||||||
|
`POST /set-return-date/:key/:loan_code`
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
**URL Parameters:**
|
||||||
|
|
||||||
|
- **key** - API key
|
||||||
|
- **loan_code** - A 6-digit numeric loan code
|
||||||
|
|
||||||
|
**Response 200:** Empty JSON object on success.
|
||||||
|
|
||||||
|
**Response 500:**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "message": "Failed to set return date" }
|
||||||
|
```
|
||||||
|
|
||||||
|
> **Note:** This endpoint will fail if the loan has already been returned (i.e., `returned_date` is not `NULL`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Open Door
|
||||||
|
|
||||||
|
`GET /open-door/:key/:doorKey`
|
||||||
|
|
||||||
|
Toggles the safe state of an item identified by its door key and returns the associated safe number.
|
||||||
|
|
||||||
|
**URL Parameters:**
|
||||||
|
|
||||||
|
- **key** - API key
|
||||||
|
- **doorKey** - The door key identifier assigned to an item
|
||||||
|
|
||||||
|
**Response 200:**
|
||||||
|
|
||||||
|
```json
|
||||||
{
|
{
|
||||||
"message": "Loan not found"
|
"data": {
|
||||||
|
"safe_nr": 3,
|
||||||
|
"id": 1
|
||||||
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
**Response 500:**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "message": "Failed to open door" }
|
||||||
|
```
|
||||||
|
|
||||||
## Error Handling
|
## Error Handling
|
||||||
|
|
||||||
- `403 Forbidden`: Invalid or missing API key.
|
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.
|
||||||
- `400 Bad Request`: Invalid parameters (e.g., wrong state value).
|
|
||||||
- `500 Internal Server Error`: Database or server error.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
If you have questions or want to collaborate, please reach out to me!
|
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
# 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 [ ]
|
||||||
|
```
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
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,276 +0,0 @@
|
|||||||
import React, { useState } from "react";
|
|
||||||
|
|
||||||
// Beispiel-Daten für die Übersicht in der Seitenleiste
|
|
||||||
const allItems = [
|
|
||||||
{ id: 1, name: "Kamera" },
|
|
||||||
{ id: 2, name: "Mikrofon" },
|
|
||||||
{ id: 3, name: "Licht-Set" },
|
|
||||||
{ id: 4, name: "Stativ" },
|
|
||||||
];
|
|
||||||
|
|
||||||
// Beispiel-Ausleihen, später per API dynamisch!
|
|
||||||
const loans = [
|
|
||||||
{
|
|
||||||
itemId: 1,
|
|
||||||
username: "max",
|
|
||||||
start: "2025-01-01T08:00",
|
|
||||||
end: "2025-01-01T18:00",
|
|
||||||
loanCode: "123456",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
itemId: 3,
|
|
||||||
username: "sara",
|
|
||||||
start: "2025-01-02T10:00",
|
|
||||||
end: "2025-01-02T16:00",
|
|
||||||
loanCode: "654321",
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
// Dummy: Für das Beispiel sind einige Items "nicht verfügbar" bei bestimmten Zeiträumen
|
|
||||||
function getAvailableItems(start: string, end: string) {
|
|
||||||
if (start.startsWith("2025-01-01")) {
|
|
||||||
return allItems.filter(
|
|
||||||
(item) => item.name === "Kamera" || item.name === "Stativ"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return allItems;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function App() {
|
|
||||||
const [step, setStep] = useState<1 | 2 | 3>(1);
|
|
||||||
const [startDate, setStartDate] = useState("");
|
|
||||||
const [endDate, setEndDate] = useState("");
|
|
||||||
const [availableItems, setAvailableItems] = useState<typeof allItems>([]);
|
|
||||||
const [selectedItem, setSelectedItem] = useState<number | null>(null);
|
|
||||||
|
|
||||||
// Dummy Code für das Design
|
|
||||||
const loanCode = "123456";
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen flex bg-gradient-to-r from-blue-50 via-white to-blue-100">
|
|
||||||
{/* Seitenleiste */}
|
|
||||||
<aside className="w-80 min-h-screen bg-white/90 backdrop-blur border-r border-blue-100 shadow-xl flex flex-col p-8">
|
|
||||||
<h2 className="text-2xl font-extrabold mb-6 text-blue-700 tracking-tight flex items-center gap-2">
|
|
||||||
<svg
|
|
||||||
className="w-7 h-7 text-blue-500"
|
|
||||||
fill="none"
|
|
||||||
stroke="currentColor"
|
|
||||||
strokeWidth={2}
|
|
||||||
viewBox="0 0 24 24"
|
|
||||||
>
|
|
||||||
<path
|
|
||||||
strokeLinecap="round"
|
|
||||||
strokeLinejoin="round"
|
|
||||||
d="M16.5 7.5V4.75A2.25 2.25 0 0 0 14.25 2.5h-4.5A2.25 2.25 0 0 0 7.5 4.75V7.5m9 0h-9m9 0v11.75A2.25 2.25 0 0 1 14.25 21.5h-4.5A2.25 2.25 0 0 1 7.5 19.25V7.5m9 0h-9"
|
|
||||||
/>
|
|
||||||
</svg>
|
|
||||||
Ausleih-Übersicht
|
|
||||||
</h2>
|
|
||||||
<ul className="space-y-5 flex-1">
|
|
||||||
{allItems.map((item) => {
|
|
||||||
const itemLoans = loans.filter((loan) => loan.itemId === item.id);
|
|
||||||
return (
|
|
||||||
<li
|
|
||||||
key={item.id}
|
|
||||||
className="bg-white/80 rounded-xl p-4 shadow hover:shadow-md transition"
|
|
||||||
>
|
|
||||||
<div className="font-semibold text-gray-900 flex items-center gap-2">
|
|
||||||
<span
|
|
||||||
className="inline-block w-2 h-2 rounded-full"
|
|
||||||
style={{
|
|
||||||
background:
|
|
||||||
itemLoans.length === 0 ? "#34d399" : "#60a5fa",
|
|
||||||
}}
|
|
||||||
></span>
|
|
||||||
{item.name}
|
|
||||||
</div>
|
|
||||||
{itemLoans.length === 0 ? (
|
|
||||||
<div className="text-green-500 text-xs mt-1 font-medium">
|
|
||||||
Verfügbar
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<ul className="mt-2 space-y-1">
|
|
||||||
{itemLoans.map((loan, idx) => (
|
|
||||||
<li
|
|
||||||
key={idx}
|
|
||||||
className="text-xs text-blue-800 bg-blue-100/60 p-1 rounded"
|
|
||||||
>
|
|
||||||
<span className="font-bold">{loan.username}</span>
|
|
||||||
<span className="ml-2">
|
|
||||||
{formatDateTime(loan.start)} –{" "}
|
|
||||||
{formatDateTime(loan.end)}
|
|
||||||
</span>
|
|
||||||
<span className="ml-2 text-gray-400">
|
|
||||||
({loan.loanCode})
|
|
||||||
</span>
|
|
||||||
</li>
|
|
||||||
))}
|
|
||||||
</ul>
|
|
||||||
)}
|
|
||||||
</li>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</ul>
|
|
||||||
<div className="mt-10 text-xs text-gray-400 flex items-center gap-4">
|
|
||||||
<span className="inline-block w-3 h-3 bg-green-400 rounded-full mr-1"></span>
|
|
||||||
Verfügbar
|
|
||||||
<span className="inline-block w-3 h-3 bg-blue-400 rounded-full ml-4 mr-1"></span>
|
|
||||||
Verliehen
|
|
||||||
</div>
|
|
||||||
</aside>
|
|
||||||
|
|
||||||
{/* Hauptbereich */}
|
|
||||||
<main className="flex-1 flex flex-col items-center py-14 px-4">
|
|
||||||
<header className="mb-12">
|
|
||||||
<h1 className="text-4xl font-extrabold text-blue-800 tracking-tight drop-shadow-sm">
|
|
||||||
Gegenstand ausleihen
|
|
||||||
</h1>
|
|
||||||
<p className="text-blue-400 mt-2 text-lg font-medium">
|
|
||||||
Schnell und unkompliziert Equipment reservieren
|
|
||||||
</p>
|
|
||||||
</header>
|
|
||||||
<div className="bg-white/90 shadow-2xl rounded-3xl p-10 w-full max-w-xl ring-1 ring-blue-100">
|
|
||||||
{step === 1 && (
|
|
||||||
<form
|
|
||||||
className="space-y-6"
|
|
||||||
onSubmit={(e) => {
|
|
||||||
e.preventDefault();
|
|
||||||
setAvailableItems(getAvailableItems(startDate, endDate));
|
|
||||||
setStep(2);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<h2 className="text-xl font-bold mb-2 text-blue-700">
|
|
||||||
1. Zeitraum wählen
|
|
||||||
</h2>
|
|
||||||
<div>
|
|
||||||
<label className="block font-medium mb-1 text-blue-900">
|
|
||||||
Startdatum
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
type="datetime-local"
|
|
||||||
className="w-full border border-blue-200 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-400 focus:outline-none"
|
|
||||||
value={startDate}
|
|
||||||
onChange={(e) => setStartDate(e.target.value)}
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label className="block font-medium mb-1 text-blue-900">
|
|
||||||
Enddatum
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
type="datetime-local"
|
|
||||||
className="w-full border border-blue-200 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-400 focus:outline-none"
|
|
||||||
value={endDate}
|
|
||||||
onChange={(e) => setEndDate(e.target.value)}
|
|
||||||
required
|
|
||||||
min={startDate}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<button
|
|
||||||
type="submit"
|
|
||||||
className="w-full bg-gradient-to-r from-blue-600 to-blue-400 hover:from-blue-700 hover:to-blue-500 text-white font-bold py-2 px-4 rounded-xl shadow transition disabled:bg-gray-300"
|
|
||||||
disabled={!startDate || !endDate || endDate <= startDate}
|
|
||||||
>
|
|
||||||
Verfügbare Gegenstände anzeigen
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{step === 2 && (
|
|
||||||
<div>
|
|
||||||
<h2 className="text-xl font-bold mb-6 text-blue-700">
|
|
||||||
2. Gegenstand auswählen
|
|
||||||
</h2>
|
|
||||||
{availableItems.length === 0 ? (
|
|
||||||
<div className="text-red-600 mb-8 font-medium text-center">
|
|
||||||
Keine Gegenstände verfügbar für diesen Zeitraum.
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<ul className="mb-8 space-y-3">
|
|
||||||
{availableItems.map((item) => (
|
|
||||||
<li
|
|
||||||
key={item.id}
|
|
||||||
className={`flex justify-between items-center p-4 rounded-xl shadow-sm border ${
|
|
||||||
selectedItem === item.id
|
|
||||||
? "bg-blue-100 border-blue-400"
|
|
||||||
: "bg-green-50 border-green-100 hover:bg-blue-50"
|
|
||||||
} transition`}
|
|
||||||
>
|
|
||||||
<span className="font-medium text-lg">{item.name}</span>
|
|
||||||
<button
|
|
||||||
className={`px-4 py-1 rounded-lg bg-gradient-to-r from-blue-500 to-blue-400 text-white text-sm font-semibold shadow hover:from-blue-600 hover:to-blue-500 ${
|
|
||||||
selectedItem === item.id ? "ring-2 ring-blue-400" : ""
|
|
||||||
}`}
|
|
||||||
onClick={() => setSelectedItem(item.id)}
|
|
||||||
>
|
|
||||||
{selectedItem === item.id ? "Ausgewählt" : "Auswählen"}
|
|
||||||
</button>
|
|
||||||
</li>
|
|
||||||
))}
|
|
||||||
</ul>
|
|
||||||
)}
|
|
||||||
<div className="flex justify-between">
|
|
||||||
<button
|
|
||||||
className="px-5 py-2 bg-gray-100 text-gray-600 rounded-xl hover:bg-gray-200 font-semibold shadow"
|
|
||||||
onClick={() => setStep(1)}
|
|
||||||
>
|
|
||||||
Zurück
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
className="px-5 py-2 bg-gradient-to-r from-blue-600 to-blue-400 text-white rounded-xl hover:from-blue-700 hover:to-blue-500 font-bold shadow transition disabled:bg-gray-300"
|
|
||||||
disabled={selectedItem === null}
|
|
||||||
onClick={() => setStep(3)}
|
|
||||||
>
|
|
||||||
Ausleihen
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{step === 3 && (
|
|
||||||
<div className="mt-2 p-8 bg-blue-50/80 border border-blue-200 rounded-2xl text-center shadow-lg">
|
|
||||||
<h3 className="font-extrabold text-blue-700 mb-3 text-2xl">
|
|
||||||
Ausleihe bestätigt!
|
|
||||||
</h3>
|
|
||||||
<p className="mb-2 text-lg">
|
|
||||||
Ihr Ausleih-Code lautet:{" "}
|
|
||||||
<span className="font-mono text-2xl text-blue-900 bg-white px-2 py-1 rounded shadow">
|
|
||||||
{loanCode}
|
|
||||||
</span>
|
|
||||||
</p>
|
|
||||||
<p className="mt-2 text-blue-600 text-sm">
|
|
||||||
Bitte merken Sie sich diesen Code, um das Schließfach zu öffnen.
|
|
||||||
</p>
|
|
||||||
<button
|
|
||||||
className="mt-8 px-6 py-2 bg-gradient-to-r from-blue-600 to-blue-400 text-white rounded-xl hover:from-blue-700 hover:to-blue-500 font-bold shadow"
|
|
||||||
onClick={() => {
|
|
||||||
setStep(1);
|
|
||||||
setStartDate("");
|
|
||||||
setEndDate("");
|
|
||||||
setSelectedItem(null);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Neue Ausleihe
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</main>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Hilfsfunktion: Datumsformatierung (z.B. 01.01.2025 08:00)
|
|
||||||
function formatDateTime(dt: string) {
|
|
||||||
const d = new Date(dt);
|
|
||||||
return (
|
|
||||||
d.toLocaleDateString("de-DE", {
|
|
||||||
day: "2-digit",
|
|
||||||
month: "2-digit",
|
|
||||||
year: "numeric",
|
|
||||||
}) +
|
|
||||||
" " +
|
|
||||||
d.toLocaleTimeString("de-DE", { hour: "2-digit", minute: "2-digit" })
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
[
|
|
||||||
{
|
|
||||||
"id": 1,
|
|
||||||
"title": "Mock Book 1",
|
|
||||||
"author": "Author 1",
|
|
||||||
"description": "Description for Mock Book 1"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": 2,
|
|
||||||
"title": "Mock Book 2",
|
|
||||||
"author": "Author 2",
|
|
||||||
"description": "Description for Mock Book 2"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": 3,
|
|
||||||
"title": "Mock Book 3",
|
|
||||||
"author": "Author 3",
|
|
||||||
"description": "Description for Mock Book 3"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
@@ -19,17 +19,21 @@ 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 config: [frontend/vite.config.ts](frontend/vite.config.ts), [frontend/tailwind.config.js](frontend/tailwind.config.js)
|
- Vite/Tailwind
|
||||||
- App entry: [frontend/src/main.tsx](frontend/src/main.tsx), [frontend/src/App.tsx](frontend/src/App.tsx)
|
config: [frontend/vite.config.ts](frontend/vite.config.ts), [frontend/tailwind.config.js](frontend/tailwind.config.js)
|
||||||
- UI: [frontend/src/layout/Layout.tsx](frontend/src/layout/Layout.tsx), [frontend/src/components](frontend/src/components)
|
- App entry: [frontend/src/main.tsx](frontend/src/main.tsx), [frontend/src/App.tsx](frontend/src/App.tsx)
|
||||||
- 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)
|
-
|
||||||
|
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)
|
- 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 + services: [backend/services/database.js](backend/services/database.js), [backend/services/tokenService.js](backend/services/tokenService.js)
|
- DB +
|
||||||
- Schema/seed: [backend/scheme.sql](backend/scheme.sql)
|
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)
|
- 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)
|
||||||
|
|
||||||
## Features (high‑level)
|
## Features (high‑level)
|
||||||
|
|
||||||
@@ -41,7 +45,8 @@ 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 time range.
|
- [`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.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.
|
||||||
@@ -54,20 +59,18 @@ UI flow (main screens):
|
|||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
- Scripts: see [frontend/package.json](frontend/package.json) and [backend/package.json](backend/package.json)
|
- The NAAS (no-as-a-service) and the mysql database are running in a docker container
|
||||||
- Frontend: `npm run dev`, `npm run build`, `npm run preview`, `npm run lint`
|
- `frontend`, `backend` and `admin` are both in a vite dev server and can be started by `npm run dev` in the root
|
||||||
- Backend: `npm start`
|
directory.
|
||||||
- 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 uses `@import "tailwindcss"` in [frontend/src/index.css](frontend/src/index.css).
|
- 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`.
|
- 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 updates are signaled via window events from [`utils.fetchData`](frontend/src/utils/fetchData.ts).
|
- 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).
|
||||||
|
|
||||||
## API documentation
|
## API documentation
|
||||||
|
|
||||||
Refer to the dedicated API docs:
|
Refer to the dedicated [API-Docs](docs/backend_API_docs/README.md)
|
||||||
|
|
||||||
`docs/backend_API_docs/README.md`
|
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# Logs
|
||||||
|
logs
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
lerna-debug.log*
|
||||||
|
|
||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
dist-ssr
|
||||||
|
*.local
|
||||||
|
|
||||||
|
# Editor directories and files
|
||||||
|
.vscode/*
|
||||||
|
!.vscode/extensions.json
|
||||||
|
.idea
|
||||||
|
.DS_Store
|
||||||
|
*.suo
|
||||||
|
*.ntvs*
|
||||||
|
*.njsproj
|
||||||
|
*.sln
|
||||||
|
*.sw?
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
# Build context is the repo root (npm workspaces share one root package-lock.json)
|
||||||
|
FROM node:22-alpine AS builder
|
||||||
|
|
||||||
|
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 admin
|
||||||
|
|
||||||
|
ARG VITE_BACKEND_URL
|
||||||
|
ENV VITE_BACKEND_URL=$VITE_BACKEND_URL
|
||||||
|
|
||||||
|
COPY admin/ admin/
|
||||||
|
RUN npm run build -w admin
|
||||||
|
|
||||||
|
FROM nginx:alpine AS runner
|
||||||
|
|
||||||
|
WORKDIR /usr/share/nginx/html
|
||||||
|
COPY --from=builder /app/admin/dist .
|
||||||
|
|
||||||
|
COPY admin/nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
|
|
||||||
|
EXPOSE 80
|
||||||
|
CMD ["nginx", "-g", "daemon off;"]
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
# React + TypeScript + Vite
|
||||||
|
|
||||||
|
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||||
|
|
||||||
|
Currently, two official plugins are available:
|
||||||
|
|
||||||
|
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) for Fast Refresh
|
||||||
|
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
|
||||||
|
|
||||||
|
## Expanding the ESLint configuration
|
||||||
|
|
||||||
|
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
|
||||||
|
|
||||||
|
```js
|
||||||
|
export default tseslint.config([
|
||||||
|
globalIgnores(['dist']),
|
||||||
|
{
|
||||||
|
files: ['**/*.{ts,tsx}'],
|
||||||
|
extends: [
|
||||||
|
// Other configs...
|
||||||
|
|
||||||
|
// Remove tseslint.configs.recommended and replace with this
|
||||||
|
...tseslint.configs.recommendedTypeChecked,
|
||||||
|
// Alternatively, use this for stricter rules
|
||||||
|
...tseslint.configs.strictTypeChecked,
|
||||||
|
// Optionally, add this for stylistic rules
|
||||||
|
...tseslint.configs.stylisticTypeChecked,
|
||||||
|
|
||||||
|
// Other configs...
|
||||||
|
],
|
||||||
|
languageOptions: {
|
||||||
|
parserOptions: {
|
||||||
|
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||||
|
tsconfigRootDir: import.meta.dirname,
|
||||||
|
},
|
||||||
|
// other options...
|
||||||
|
},
|
||||||
|
},
|
||||||
|
])
|
||||||
|
```
|
||||||
|
|
||||||
|
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
|
||||||
|
|
||||||
|
```js
|
||||||
|
// eslint.config.js
|
||||||
|
import reactX from 'eslint-plugin-react-x'
|
||||||
|
import reactDom from 'eslint-plugin-react-dom'
|
||||||
|
|
||||||
|
export default tseslint.config([
|
||||||
|
globalIgnores(['dist']),
|
||||||
|
{
|
||||||
|
files: ['**/*.{ts,tsx}'],
|
||||||
|
extends: [
|
||||||
|
// Other configs...
|
||||||
|
// Enable lint rules for React
|
||||||
|
reactX.configs['recommended-typescript'],
|
||||||
|
// Enable lint rules for React DOM
|
||||||
|
reactDom.configs.recommended,
|
||||||
|
],
|
||||||
|
languageOptions: {
|
||||||
|
parserOptions: {
|
||||||
|
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||||
|
tsconfigRootDir: import.meta.dirname,
|
||||||
|
},
|
||||||
|
// other options...
|
||||||
|
},
|
||||||
|
},
|
||||||
|
])
|
||||||
|
```
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import js from '@eslint/js'
|
||||||
|
import globals from 'globals'
|
||||||
|
import reactHooks from 'eslint-plugin-react-hooks'
|
||||||
|
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||||
|
import tseslint from 'typescript-eslint'
|
||||||
|
import { globalIgnores } from 'eslint/config'
|
||||||
|
|
||||||
|
export default tseslint.config([
|
||||||
|
globalIgnores(['dist']),
|
||||||
|
{
|
||||||
|
files: ['**/*.{ts,tsx}'],
|
||||||
|
extends: [
|
||||||
|
js.configs.recommended,
|
||||||
|
tseslint.configs.recommended,
|
||||||
|
reactHooks.configs['recommended-latest'],
|
||||||
|
reactRefresh.configs.vite,
|
||||||
|
],
|
||||||
|
languageOptions: {
|
||||||
|
ecmaVersion: 2020,
|
||||||
|
globals: globals.browser,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
])
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<link rel="icon" type="image/svg+xml" href="/user-star.svg" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>Adminpanel</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name _;
|
||||||
|
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
index index.html;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
}
|
||||||
|
|
||||||
|
location = /backend {
|
||||||
|
return 301 /backend/;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /backend/ {
|
||||||
|
proxy_pass http://borrow-system_backend:8004/;
|
||||||
|
}
|
||||||
|
|
||||||
|
location ~* \.(?:js|mjs|css|png|jpg|jpeg|gif|ico|svg|woff2?)$ {
|
||||||
|
expires 1y;
|
||||||
|
access_log off;
|
||||||
|
add_header Cache-Control "public, immutable";
|
||||||
|
try_files $uri =404;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
{
|
||||||
|
"name": "admin",
|
||||||
|
"private": true,
|
||||||
|
"version": "1.3.2-dev",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "tsc -b && vite build",
|
||||||
|
"lint": "eslint .",
|
||||||
|
"preview": "vite preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@chakra-ui/react": "^3.26.0",
|
||||||
|
"@emotion/react": "^11.14.0",
|
||||||
|
"@tailwindcss/vite": "^4.1.11",
|
||||||
|
"@tanstack/react-query": "^5.85.5",
|
||||||
|
"jotai": "^2.15.0",
|
||||||
|
"js-cookie": "^3.0.5",
|
||||||
|
"lucide-react": "^0.539.0",
|
||||||
|
"next-themes": "^0.4.6",
|
||||||
|
"primeicons": "^7.0.0",
|
||||||
|
"primereact": "^10.9.6",
|
||||||
|
"react": "^19.1.1",
|
||||||
|
"react-dom": "^19.1.1",
|
||||||
|
"react-icons": "^5.5.0",
|
||||||
|
"react-router-dom": "^7.8.0",
|
||||||
|
"react-toastify": "^11.0.5",
|
||||||
|
"split-lines": "^3.0.0",
|
||||||
|
"tailwind-merge": "^3.3.1",
|
||||||
|
"tailwindcss": "^4.1.11",
|
||||||
|
"tailwindcss-animate": "^1.0.7",
|
||||||
|
"tw-animate-css": "^1.3.5",
|
||||||
|
"vite-plugin-svgr": "^4.3.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@eslint/js": "^9.32.0",
|
||||||
|
"@types/js-cookie": "^3.0.6",
|
||||||
|
"@types/react": "^19.1.9",
|
||||||
|
"@types/react-dom": "^19.1.7",
|
||||||
|
"@vitejs/plugin-react": "^4.7.0",
|
||||||
|
"eslint": "^9.32.0",
|
||||||
|
"eslint-plugin-react-hooks": "^5.2.0",
|
||||||
|
"eslint-plugin-react-refresh": "^0.4.20",
|
||||||
|
"globals": "^16.3.0",
|
||||||
|
"typescript": "~5.8.3",
|
||||||
|
"typescript-eslint": "^8.39.0",
|
||||||
|
"vite": "^7.1.0",
|
||||||
|
"vite-tsconfig-paths": "^5.1.4"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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-user-star-icon lucide-user-star"><path d="M16.051 12.616a1 1 0 0 1 1.909.024l.737 1.452a1 1 0 0 0 .737.535l1.634.256a1 1 0 0 1 .588 1.806l-1.172 1.168a1 1 0 0 0-.282.866l.259 1.613a1 1 0 0 1-1.541 1.134l-1.465-.75a1 1 0 0 0-.912 0l-1.465.75a1 1 0 0 1-1.539-1.133l.258-1.613a1 1 0 0 0-.282-.866l-1.156-1.153a1 1 0 0 1 .572-1.822l1.633-.256a1 1 0 0 0 .737-.535z"/><path d="M8 15H7a4 4 0 0 0-4 4v2"/><circle cx="10" cy="7" r="4"/></svg>
|
||||||
|
After Width: | Height: | Size: 635 B |
@@ -0,0 +1 @@
|
|||||||
|
@import "tailwindcss";
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import "./App.css";
|
||||||
|
import Layout from "./Layout/Layout";
|
||||||
|
|
||||||
|
function App() {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Layout />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default App;
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
import React from "react";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useEffect } from "react";
|
||||||
|
import { Box, Heading, Text, Flex, Button } from "@chakra-ui/react";
|
||||||
|
import Sidebar from "./Sidebar";
|
||||||
|
import UserTable from "../components/UserTable";
|
||||||
|
import ItemTable from "../components/ItemTable";
|
||||||
|
import LoanTable from "../components/LoanTable";
|
||||||
|
import APIKeyTable from "@/components/APIKeyTable";
|
||||||
|
import ServerConfig from "@/components/ServerConfig";
|
||||||
|
import { MoveLeft } from "lucide-react";
|
||||||
|
|
||||||
|
type DashboardProps = {
|
||||||
|
onLogout?: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
const Dashboard: React.FC<DashboardProps> = ({ onLogout }) => {
|
||||||
|
const userName = localStorage.getItem("userName") || "Admin";
|
||||||
|
|
||||||
|
const [activeView, setActiveView] = useState("");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (typeof window === "undefined") return;
|
||||||
|
const raw = window.location.pathname.slice(1);
|
||||||
|
if (raw) {
|
||||||
|
setActiveView(decodeURIComponent(raw));
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Sync URL when activeView changes, without reloading
|
||||||
|
useEffect(() => {
|
||||||
|
if (typeof window === "undefined") return;
|
||||||
|
if (!activeView) return;
|
||||||
|
const desired = `/${encodeURIComponent(activeView)}`;
|
||||||
|
if (window.location.pathname !== desired) {
|
||||||
|
window.history.replaceState(null, "", desired);
|
||||||
|
}
|
||||||
|
}, [activeView]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Flex h="100vh">
|
||||||
|
<Sidebar
|
||||||
|
viewAusleihen={() => setActiveView("Ausleihen")}
|
||||||
|
viewGegenstaende={() => setActiveView("Gegenstände")}
|
||||||
|
viewSchliessfaecher={() => setActiveView("Schließfächer")}
|
||||||
|
viewUser={() => setActiveView("User")}
|
||||||
|
viewAPI={() => setActiveView("API")}
|
||||||
|
viewConfig={() => setActiveView("Server Konfiguration")}
|
||||||
|
/>
|
||||||
|
<Box flex="1" display="flex" flexDirection="column" minH={0}>
|
||||||
|
<Flex
|
||||||
|
as="header"
|
||||||
|
align="center"
|
||||||
|
justify="space-between"
|
||||||
|
px={6}
|
||||||
|
py={4}
|
||||||
|
borderBottom="1px"
|
||||||
|
borderColor="gray.200"
|
||||||
|
bg="gray.900"
|
||||||
|
>
|
||||||
|
<Heading size="xl">Dashboard</Heading>
|
||||||
|
<Flex align="center" gap={6}>
|
||||||
|
<Text fontSize="sm" color="white">
|
||||||
|
Willkommen {userName}, im Admin-Dashboard!
|
||||||
|
</Text>
|
||||||
|
<Button variant="solid" onClick={onLogout}>
|
||||||
|
Logout
|
||||||
|
</Button>
|
||||||
|
</Flex>
|
||||||
|
</Flex>
|
||||||
|
<Box as="main" flex="1" p={6} minH={0} overflow="hidden">
|
||||||
|
{activeView === "" && (
|
||||||
|
<Flex
|
||||||
|
align="center"
|
||||||
|
gap={3}
|
||||||
|
p={4}
|
||||||
|
border="1px dashed"
|
||||||
|
borderColor="gray.300"
|
||||||
|
borderRadius="md"
|
||||||
|
bg="gray.50"
|
||||||
|
color="gray.700"
|
||||||
|
fontSize="lg"
|
||||||
|
fontWeight="semibold"
|
||||||
|
>
|
||||||
|
<MoveLeft size={20} />
|
||||||
|
Bitte wählen Sie eine Ansicht aus.
|
||||||
|
</Flex>
|
||||||
|
)}
|
||||||
|
{activeView === "User" && <UserTable />}
|
||||||
|
{activeView === "Ausleihen" && <LoanTable />}
|
||||||
|
{activeView === "Gegenstände" && <ItemTable />}
|
||||||
|
{activeView === "API" && <APIKeyTable />}
|
||||||
|
{activeView === "Server Konfiguration" && <ServerConfig />}
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
</Flex>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default Dashboard;
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import React, { useState } from "react";
|
||||||
|
import { useEffect } from "react";
|
||||||
|
import Dashboard from "./Dashboard";
|
||||||
|
import Login from "./Login";
|
||||||
|
import Cookies from "js-cookie";
|
||||||
|
import { API_BASE } from "@/config/api.config";
|
||||||
|
|
||||||
|
const Layout: React.FC = () => {
|
||||||
|
const [isLoggedIn, setIsLoggedIn] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (Cookies.get("token")) {
|
||||||
|
const verifyToken = async () => {
|
||||||
|
const response = await fetch(
|
||||||
|
`${API_BASE}/api/admin/user-mgmt/verify-token`,
|
||||||
|
{
|
||||||
|
method: "GET",
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
if (response.ok) {
|
||||||
|
setIsLoggedIn(true);
|
||||||
|
} else {
|
||||||
|
Cookies.remove("token");
|
||||||
|
setIsLoggedIn(false);
|
||||||
|
window.location.reload();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
verifyToken();
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleLogout = () => {
|
||||||
|
Cookies.remove("token");
|
||||||
|
window.location.pathname = "/";
|
||||||
|
setIsLoggedIn(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main>
|
||||||
|
{isLoggedIn ? (
|
||||||
|
<Dashboard onLogout={() => handleLogout()} />
|
||||||
|
) : (
|
||||||
|
<Login onSuccess={() => setIsLoggedIn(true)} />
|
||||||
|
)}
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default Layout;
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import React from "react";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { loginFunc } from "@/utils/loginUser";
|
||||||
|
import MyAlert from "../components/myChakra/MyAlert";
|
||||||
|
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 [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 loginFunc(username, password);
|
||||||
|
if (!result.success) {
|
||||||
|
setErrorMsg(result.message);
|
||||||
|
setErrorDsc(result.description);
|
||||||
|
setIsError(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
onSuccess();
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center p-4">
|
||||||
|
<form onSubmit={(e) => e.preventDefault()}>
|
||||||
|
<Card.Root maxW="sm">
|
||||||
|
<Card.Header>
|
||||||
|
<Card.Title>Login</Card.Title>
|
||||||
|
<Card.Description>
|
||||||
|
Bitte unten Ihre Admin Zugangsdaten eingeben.
|
||||||
|
</Card.Description>
|
||||||
|
</Card.Header>
|
||||||
|
<Card.Body>
|
||||||
|
<Stack gap="4" w="full">
|
||||||
|
<Field.Root>
|
||||||
|
<Field.Label>username</Field.Label>
|
||||||
|
<Input
|
||||||
|
value={username}
|
||||||
|
onChange={(e) => setUsername(e.target.value)}
|
||||||
|
/>
|
||||||
|
</Field.Root>
|
||||||
|
<Field.Root>
|
||||||
|
<Field.Label>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.Root>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default Login;
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
import React from "react";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { Box, Flex, VStack, Heading, Text, Link } from "@chakra-ui/react";
|
||||||
|
import { API_BASE } from "@/config/api.config";
|
||||||
|
|
||||||
|
type SidebarProps = {
|
||||||
|
viewAusleihen: () => void;
|
||||||
|
viewGegenstaende: () => void;
|
||||||
|
viewSchliessfaecher: () => void;
|
||||||
|
viewUser: () => void;
|
||||||
|
viewAPI: () => void;
|
||||||
|
viewConfig: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
const Sidebar: React.FC<SidebarProps> = ({
|
||||||
|
viewAusleihen,
|
||||||
|
viewGegenstaende,
|
||||||
|
viewUser,
|
||||||
|
viewAPI,
|
||||||
|
viewConfig
|
||||||
|
}) => {
|
||||||
|
const [info, setInfo] = useState<any>(null);
|
||||||
|
|
||||||
|
const fetchInfo = async () => {
|
||||||
|
const response = await fetch(`${API_BASE}/`);
|
||||||
|
const data = await response.json();
|
||||||
|
setInfo(data);
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchInfo();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box
|
||||||
|
as="aside"
|
||||||
|
w="180px"
|
||||||
|
minH="100vh"
|
||||||
|
bg="gray.800"
|
||||||
|
color="gray.100"
|
||||||
|
px={6}
|
||||||
|
py={8}
|
||||||
|
borderRight="1px solid"
|
||||||
|
borderColor="gray.700"
|
||||||
|
>
|
||||||
|
<Flex direction="column" h="full">
|
||||||
|
<Heading size="md" mb={8} letterSpacing="wide">
|
||||||
|
Borrow System
|
||||||
|
</Heading>
|
||||||
|
|
||||||
|
<VStack align="stretch" gap={4} fontSize="sm">
|
||||||
|
<Link
|
||||||
|
px={3}
|
||||||
|
py={2}
|
||||||
|
rounded="md"
|
||||||
|
_hover={{ bg: "gray.700", textDecoration: "none" }}
|
||||||
|
onClick={viewUser}
|
||||||
|
>
|
||||||
|
Benutzer
|
||||||
|
</Link>
|
||||||
|
<Link
|
||||||
|
px={3}
|
||||||
|
py={2}
|
||||||
|
rounded="md"
|
||||||
|
_hover={{ bg: "gray.700", textDecoration: "none" }}
|
||||||
|
onClick={viewAusleihen}
|
||||||
|
>
|
||||||
|
Ausleihen
|
||||||
|
</Link>
|
||||||
|
<Link
|
||||||
|
px={3}
|
||||||
|
py={2}
|
||||||
|
rounded="md"
|
||||||
|
_hover={{ bg: "gray.700", textDecoration: "none" }}
|
||||||
|
onClick={viewGegenstaende}
|
||||||
|
>
|
||||||
|
Gegenstände
|
||||||
|
</Link>
|
||||||
|
<Link
|
||||||
|
px={3}
|
||||||
|
py={2}
|
||||||
|
rounded="md"
|
||||||
|
_hover={{ bg: "gray.700", textDecoration: "none" }}
|
||||||
|
onClick={viewAPI}
|
||||||
|
>
|
||||||
|
API Keys
|
||||||
|
</Link>
|
||||||
|
<Link
|
||||||
|
px={3}
|
||||||
|
py={2}
|
||||||
|
rounded="md"
|
||||||
|
_hover={{ bg: "gray.700", textDecoration: "none" }}
|
||||||
|
onClick={viewConfig}
|
||||||
|
>
|
||||||
|
Server Konfiguration
|
||||||
|
</Link>
|
||||||
|
</VStack>
|
||||||
|
|
||||||
|
<Box mt="auto" pt={8} fontSize="xs" color="gray.500">
|
||||||
|
<Text mb={2}>© Made with ❤️ by Theis Gaedigk</Text>
|
||||||
|
{info ? (
|
||||||
|
<Flex gap={2} wrap="wrap">
|
||||||
|
<Box
|
||||||
|
as="span"
|
||||||
|
px={2}
|
||||||
|
py={0.5}
|
||||||
|
rounded="full"
|
||||||
|
bg="gray.700"
|
||||||
|
color="gray.200"
|
||||||
|
>
|
||||||
|
Panel {info?.["admin-panel-info"]?.version ?? "—"}
|
||||||
|
</Box>
|
||||||
|
<Box
|
||||||
|
as="span"
|
||||||
|
px={2}
|
||||||
|
py={0.5}
|
||||||
|
rounded="full"
|
||||||
|
bg="gray.700"
|
||||||
|
color="gray.200"
|
||||||
|
>
|
||||||
|
Backend {info?.["backend-info"]?.version ?? "—"}
|
||||||
|
</Box>
|
||||||
|
</Flex>
|
||||||
|
) : (
|
||||||
|
<Text color="gray.600">Lade Versionsinfos…</Text>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
</Flex>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default Sidebar;
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
import { atom } from "jotai";
|
||||||
|
|
||||||
|
export const testAtom = atom<number>(0);
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# How to use Atoms
|
||||||
|
Atoms are the fundamental building blocks of state management in this system. They represent individual pieces of state that can be shared and manipulated across different components.
|
||||||
|
|
||||||
|
You can also name it global state.
|
||||||
|
|
||||||
|
## Creating an Atom
|
||||||
|
to create an atom you have to declare an atom like this:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { atom } from 'jotai';
|
||||||
|
|
||||||
|
export const NAME_OF_YOUR_ATOM = atom<type_of_your_atom>(initial_value);
|
||||||
|
```
|
||||||
|
|
||||||
|
In this project we declare all atoms in the `States/Atoms.tsx`file. Which you can find above this README file.
|
||||||
|
|
||||||
|
## Using an Atom
|
||||||
|
To use an atom in your component, you can use the `useAtom` hook provided by Jotai. Here's an example of how to use an atom in a React component:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { useAtom } from 'jotai';
|
||||||
|
import { NAME_OF_YOUR_ATOM } from '@/States/Atoms';
|
||||||
|
|
||||||
|
const MyComponent = () => {
|
||||||
|
const [value, setValue] = useAtom(NAME_OF_YOUR_ATOM);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<p>Current value: {value}</p>
|
||||||
|
<button onClick={() => setValue(newValue)}>Update Value</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
As you can see, you can use `useAtom` like `useState` but the state is global. In this example `value` is the current state of the atom, and `setValue` is a function to update the state, which is also known as the setter function.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||||
|
After Width: | Height: | Size: 4.0 KiB |
@@ -0,0 +1,224 @@
|
|||||||
|
import React from "react";
|
||||||
|
import {
|
||||||
|
Table,
|
||||||
|
Spinner,
|
||||||
|
Text,
|
||||||
|
VStack,
|
||||||
|
Button,
|
||||||
|
HStack,
|
||||||
|
IconButton,
|
||||||
|
Heading,
|
||||||
|
} from "@chakra-ui/react";
|
||||||
|
import { Tooltip } from "@/components/ui/tooltip";
|
||||||
|
import MyAlert from "./myChakra/MyAlert";
|
||||||
|
import { Trash2, RefreshCcwDot, CirclePlus } from "lucide-react";
|
||||||
|
import Cookies from "js-cookie";
|
||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import { deleteAPKey } from "@/utils/userActions";
|
||||||
|
import AddAPIKey from "./AddAPIKey";
|
||||||
|
import { formatDateTime } from "@/utils/userFuncs";
|
||||||
|
import { API_BASE } from "@/config/api.config";
|
||||||
|
|
||||||
|
type Items = {
|
||||||
|
id: number;
|
||||||
|
api_key: string;
|
||||||
|
entry_name: string;
|
||||||
|
entry_created_at: string;
|
||||||
|
last_used_at: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const APIKeyTable: 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 [addAPIForm, setAddAPIForm] = useState(false);
|
||||||
|
|
||||||
|
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/api-data/get-api-keys`,
|
||||||
|
{
|
||||||
|
method: "GET",
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
const data = await response.json();
|
||||||
|
return 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 (
|
||||||
|
<>
|
||||||
|
{/* Action toolbar */}
|
||||||
|
<HStack
|
||||||
|
mb={4}
|
||||||
|
gap={3}
|
||||||
|
justify="flex-start"
|
||||||
|
align="center"
|
||||||
|
flexWrap="wrap"
|
||||||
|
>
|
||||||
|
<Tooltip content="API Keys neu laden" openDelay={300}>
|
||||||
|
<IconButton
|
||||||
|
aria-label="Refresh API Keys"
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
rounded="md"
|
||||||
|
shadow="sm"
|
||||||
|
_hover={{ shadow: "md", transform: "translateY(-2px)" }}
|
||||||
|
_active={{ transform: "translateY(0)" }}
|
||||||
|
onClick={() => setReload(!reload)}
|
||||||
|
>
|
||||||
|
<RefreshCcwDot size={18} />
|
||||||
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
|
|
||||||
|
<Tooltip content="Neuen API Key hinzufügen" openDelay={300}>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
colorPalette="teal"
|
||||||
|
variant="solid"
|
||||||
|
rounded="md"
|
||||||
|
fontWeight="semibold"
|
||||||
|
shadow="sm"
|
||||||
|
_hover={{ shadow: "md", bg: "colorPalette.600" }}
|
||||||
|
_active={{ bg: "colorPalette.700" }}
|
||||||
|
onClick={() => {
|
||||||
|
setAddAPIForm(true);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<CirclePlus size={18} style={{ marginRight: 6 }} />
|
||||||
|
Neuen API Key hinzufügen
|
||||||
|
</Button>
|
||||||
|
</Tooltip>
|
||||||
|
</HStack>
|
||||||
|
{/* End action toolbar */}
|
||||||
|
|
||||||
|
<Heading marginBottom={4} size="2xl">
|
||||||
|
API Keys
|
||||||
|
</Heading>
|
||||||
|
{isError && (
|
||||||
|
<MyAlert
|
||||||
|
status={errorStatus}
|
||||||
|
description={errorDsc}
|
||||||
|
title={errorMessage}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{isLoading && (
|
||||||
|
<VStack colorPalette="teal">
|
||||||
|
<Spinner color="colorPalette.600" />
|
||||||
|
<Text color="colorPalette.600">Loading...</Text>
|
||||||
|
</VStack>
|
||||||
|
)}
|
||||||
|
{addAPIForm && (
|
||||||
|
<AddAPIKey
|
||||||
|
onClose={() => {
|
||||||
|
setAddAPIForm(false);
|
||||||
|
setReload(!reload);
|
||||||
|
}}
|
||||||
|
alert={setError}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Table.Root
|
||||||
|
size="sm"
|
||||||
|
striped
|
||||||
|
w="100%"
|
||||||
|
// table-layout: auto => Spaltenbreite nach Content; volle Breite nutzen
|
||||||
|
style={{ tableLayout: "auto" }}
|
||||||
|
>
|
||||||
|
<Table.Header>
|
||||||
|
<Table.Row>
|
||||||
|
<Table.ColumnHeader width="1%" whiteSpace="nowrap">
|
||||||
|
<strong>#</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader>
|
||||||
|
<strong>API Key</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader>
|
||||||
|
<strong>Name</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader whiteSpace="nowrap">
|
||||||
|
<strong>Eintrag erstellt am</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader whiteSpace="nowrap">
|
||||||
|
<strong>Zuletzt benutzt am</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader width="1%" whiteSpace="nowrap">
|
||||||
|
<strong>Aktionen</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.api_key}</Table.Cell>
|
||||||
|
<Table.Cell>{item.entry_name}</Table.Cell>
|
||||||
|
<Table.Cell whiteSpace="nowrap">
|
||||||
|
{formatDateTime(item.entry_created_at)}
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell whiteSpace="nowrap">
|
||||||
|
{!item.last_used_at
|
||||||
|
? "Nie benutzt"
|
||||||
|
: formatDateTime(item.last_used_at)}
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell whiteSpace="nowrap">
|
||||||
|
<Button
|
||||||
|
onClick={() =>
|
||||||
|
deleteAPKey(item.id).then((response) => {
|
||||||
|
if (response.success) {
|
||||||
|
setItems(items.filter((i) => i.id !== item.id));
|
||||||
|
setError(
|
||||||
|
"success",
|
||||||
|
"Gegenstand gelöscht",
|
||||||
|
"Der Gegenstand wurde erfolgreich gelöscht."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
colorPalette="red"
|
||||||
|
size="sm"
|
||||||
|
ml={2}
|
||||||
|
>
|
||||||
|
<Trash2 />
|
||||||
|
</Button>
|
||||||
|
</Table.Cell>
|
||||||
|
</Table.Row>
|
||||||
|
))}
|
||||||
|
</Table.Body>
|
||||||
|
</Table.Root>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default APIKeyTable;
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
import React from "react";
|
||||||
|
import {
|
||||||
|
Button,
|
||||||
|
Card,
|
||||||
|
Field,
|
||||||
|
Input,
|
||||||
|
Stack,
|
||||||
|
InputGroup,
|
||||||
|
Span,
|
||||||
|
} from "@chakra-ui/react";
|
||||||
|
import { createAPIentry } from "@/utils/userActions";
|
||||||
|
import { useState } from "react";
|
||||||
|
|
||||||
|
type AddAPIKeyProps = {
|
||||||
|
onClose: () => void;
|
||||||
|
alert: (
|
||||||
|
status: "success" | "error",
|
||||||
|
message: string,
|
||||||
|
description: string
|
||||||
|
) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
const AddAPIKey: React.FC<AddAPIKeyProps> = ({ onClose, alert }) => {
|
||||||
|
const [value, setValue] = useState("");
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
|
||||||
|
<Card.Root maxW="sm">
|
||||||
|
<Card.Header>
|
||||||
|
<Card.Title>Neuen API Key erstellen</Card.Title>
|
||||||
|
<Card.Description>
|
||||||
|
Füllen Sie das folgende Formular aus, um einen API Key zu erstellen.
|
||||||
|
</Card.Description>
|
||||||
|
</Card.Header>
|
||||||
|
<Card.Body>
|
||||||
|
<Stack gap="4" w="full">
|
||||||
|
<InputGroup
|
||||||
|
endElement={
|
||||||
|
<Span color="fg.muted" textStyle="xs">
|
||||||
|
{value.length} / {8}
|
||||||
|
</Span>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Input
|
||||||
|
placeholder="Er muss 8 zahlen lang sein"
|
||||||
|
value={value}
|
||||||
|
id="apiKey"
|
||||||
|
maxLength={8}
|
||||||
|
onChange={(e) => {
|
||||||
|
setValue(e.currentTarget.value.slice(0, 8));
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</InputGroup>
|
||||||
|
<Field.Root>
|
||||||
|
<Field.Label>Name</Field.Label>
|
||||||
|
<Input id="name" type="text" />
|
||||||
|
</Field.Root>
|
||||||
|
</Stack>
|
||||||
|
</Card.Body>
|
||||||
|
<Card.Footer justifyContent="flex-end">
|
||||||
|
<Button variant="outline" onClick={onClose}>
|
||||||
|
Abbrechen
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="solid"
|
||||||
|
onClick={async () => {
|
||||||
|
const apiKey =
|
||||||
|
(
|
||||||
|
document.getElementById("apiKey") as HTMLInputElement
|
||||||
|
)?.value.trim() || "";
|
||||||
|
const name =
|
||||||
|
(
|
||||||
|
document.getElementById("name") as HTMLInputElement
|
||||||
|
)?.value.trim() || "";
|
||||||
|
|
||||||
|
if (!apiKey || !name) return;
|
||||||
|
|
||||||
|
const res = await createAPIentry(apiKey, name);
|
||||||
|
if (res.success) {
|
||||||
|
alert(
|
||||||
|
"success",
|
||||||
|
"API Key erstellt",
|
||||||
|
"Der API Key wurde erfolgreich erstellt."
|
||||||
|
);
|
||||||
|
onClose();
|
||||||
|
} else {
|
||||||
|
alert(
|
||||||
|
"error",
|
||||||
|
"Fehler beim Erstellen des API Keys",
|
||||||
|
res.message ||
|
||||||
|
"Beim Erstellen des API Keys ist ein Fehler aufgetreten. (frontend bug)"
|
||||||
|
);
|
||||||
|
onClose();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Erstellen
|
||||||
|
</Button>
|
||||||
|
</Card.Footer>
|
||||||
|
</Card.Root>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default AddAPIKey;
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
import React from "react";
|
||||||
|
import {
|
||||||
|
Button,
|
||||||
|
Card,
|
||||||
|
Field,
|
||||||
|
Input,
|
||||||
|
Stack,
|
||||||
|
Text,
|
||||||
|
Checkbox,
|
||||||
|
} from "@chakra-ui/react";
|
||||||
|
import { createUser } from "@/utils/userActions";
|
||||||
|
|
||||||
|
type AddFormProps = {
|
||||||
|
onClose: () => void;
|
||||||
|
alert: (
|
||||||
|
status: "success" | "error",
|
||||||
|
message: string,
|
||||||
|
description: string
|
||||||
|
) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
const AddForm: React.FC<AddFormProps> = ({ onClose, alert }) => {
|
||||||
|
const [admin, setAdmin] = React.useState(false);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
|
||||||
|
<form
|
||||||
|
onSubmit={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Card.Root maxW="sm">
|
||||||
|
<Card.Header>
|
||||||
|
<Card.Title>Neuen Nutzer erstellen</Card.Title>
|
||||||
|
<Card.Description>
|
||||||
|
Füllen Sie das folgende Formular aus, um einen Nutzer zu
|
||||||
|
erstellen.
|
||||||
|
</Card.Description>
|
||||||
|
</Card.Header>
|
||||||
|
|
||||||
|
<Card.Body>
|
||||||
|
<Stack gap="4" w="full">
|
||||||
|
<Field.Root>
|
||||||
|
<Field.Label>Benutzername</Field.Label>
|
||||||
|
<Input id="username" />
|
||||||
|
</Field.Root>
|
||||||
|
<Field.Root>
|
||||||
|
<Field.Label>Passwort</Field.Label>
|
||||||
|
<Input id="password" type="password" />
|
||||||
|
</Field.Root>
|
||||||
|
<Field.Root>
|
||||||
|
<Field.Label>Vorname</Field.Label>
|
||||||
|
<Input id="firstname" />
|
||||||
|
</Field.Root>
|
||||||
|
<Field.Root>
|
||||||
|
<Field.Label>Nachname</Field.Label>
|
||||||
|
<Input id="lastname" />
|
||||||
|
</Field.Root>
|
||||||
|
<Field.Root>
|
||||||
|
<Field.Label>E-Mail</Field.Label>
|
||||||
|
<Input id="email" type="email" />
|
||||||
|
</Field.Root>
|
||||||
|
|
||||||
|
{/* Kontrollierte Checkbox */}
|
||||||
|
<Checkbox.Root
|
||||||
|
checked={admin}
|
||||||
|
onCheckedChange={(e: any) => setAdmin(Boolean(e?.checked ?? e))}
|
||||||
|
>
|
||||||
|
<Checkbox.HiddenInput />
|
||||||
|
<Checkbox.Control />
|
||||||
|
<Checkbox.Label>Admin</Checkbox.Label>
|
||||||
|
</Checkbox.Root>
|
||||||
|
|
||||||
|
<Field.Root>
|
||||||
|
<Field.Label>Rolle</Field.Label>
|
||||||
|
<Input id="role" type="number" />
|
||||||
|
</Field.Root>
|
||||||
|
</Stack>
|
||||||
|
</Card.Body>
|
||||||
|
<Card.Footer justifyContent="flex-end">
|
||||||
|
<Text>Der Benutzername kann nicht mehr geändert werden.</Text>
|
||||||
|
<Button variant="outline" onClick={onClose}>
|
||||||
|
Abbrechen
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="solid"
|
||||||
|
type="submit"
|
||||||
|
onClick={async () => {
|
||||||
|
const username =
|
||||||
|
(
|
||||||
|
document.getElementById("username") as HTMLInputElement
|
||||||
|
)?.value.trim() || "";
|
||||||
|
const password =
|
||||||
|
(document.getElementById("password") as HTMLInputElement)
|
||||||
|
?.value || "";
|
||||||
|
const role = Number(
|
||||||
|
(document.getElementById("role") as HTMLInputElement)?.value
|
||||||
|
);
|
||||||
|
const firstname =
|
||||||
|
(
|
||||||
|
document.getElementById("firstname") as HTMLInputElement
|
||||||
|
)?.value.trim() || "";
|
||||||
|
const lastname =
|
||||||
|
(
|
||||||
|
document.getElementById("lastname") as HTMLInputElement
|
||||||
|
)?.value.trim() || "";
|
||||||
|
const email =
|
||||||
|
(
|
||||||
|
document.getElementById("email") as HTMLInputElement
|
||||||
|
)?.value.trim() || "";
|
||||||
|
|
||||||
|
// admin kommt jetzt zuverlässig aus dem State
|
||||||
|
const res = await createUser(
|
||||||
|
username,
|
||||||
|
role,
|
||||||
|
password,
|
||||||
|
firstname,
|
||||||
|
lastname,
|
||||||
|
email,
|
||||||
|
admin
|
||||||
|
);
|
||||||
|
|
||||||
|
if (res.success) {
|
||||||
|
alert(
|
||||||
|
"success",
|
||||||
|
"Nutzer erstellt",
|
||||||
|
"Der Nutzer wurde erfolgreich erstellt."
|
||||||
|
);
|
||||||
|
onClose();
|
||||||
|
} else {
|
||||||
|
alert(
|
||||||
|
"error",
|
||||||
|
"Fehler beim Erstellen des Nutzers",
|
||||||
|
"Es gab einen Fehler beim Erstellen des Nutzers. Vielleicht gibt es bereits einen Nutzer mit diesem Benutzernamen."
|
||||||
|
);
|
||||||
|
onClose();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Erstellen
|
||||||
|
</Button>
|
||||||
|
</Card.Footer>
|
||||||
|
</Card.Root>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default AddForm;
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
import React from "react";
|
||||||
|
import { Button, Card, Field, Input, Stack } from "@chakra-ui/react";
|
||||||
|
import { createItem } from "@/utils/userActions";
|
||||||
|
|
||||||
|
type AddItemFormProps = {
|
||||||
|
onClose: () => void;
|
||||||
|
alert: (
|
||||||
|
status: "success" | "error",
|
||||||
|
message: string,
|
||||||
|
description: string
|
||||||
|
) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
const AddItemForm: React.FC<AddItemFormProps> = ({ onClose, alert }) => {
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
|
||||||
|
<Card.Root maxW="sm">
|
||||||
|
<Card.Header>
|
||||||
|
<Card.Title>Neuen Gegenstand erstellen</Card.Title>
|
||||||
|
<Card.Description>
|
||||||
|
Füllen Sie das folgende Formular aus, um einen Gegenstand zu
|
||||||
|
erstellen.
|
||||||
|
</Card.Description>
|
||||||
|
</Card.Header>
|
||||||
|
<Card.Body>
|
||||||
|
<Stack gap="4" w="full">
|
||||||
|
<Field.Root>
|
||||||
|
<Field.Label>Gegenstandsname (muss einzigartig sein)</Field.Label>
|
||||||
|
<Input id="item_name" placeholder="z.B. Laptop" />
|
||||||
|
</Field.Root>
|
||||||
|
<Field.Root>
|
||||||
|
<Field.Label>Schließfachnummer</Field.Label>
|
||||||
|
<Input id="safe_nr" placeholder="Nummer 1 - 6" />
|
||||||
|
</Field.Root>
|
||||||
|
<Field.Root>
|
||||||
|
<Field.Label>Ausleih-Berechtigung (Rolle)</Field.Label>
|
||||||
|
<Input
|
||||||
|
id="can_borrow_role"
|
||||||
|
type="number"
|
||||||
|
placeholder="Zahl (1 - 6)"
|
||||||
|
/>
|
||||||
|
</Field.Root>
|
||||||
|
</Stack>
|
||||||
|
</Card.Body>
|
||||||
|
<Card.Footer justifyContent="flex-end" gap="2">
|
||||||
|
<Button variant="outline" onClick={onClose}>
|
||||||
|
Abbrechen
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="solid"
|
||||||
|
onClick={async () => {
|
||||||
|
const name =
|
||||||
|
(
|
||||||
|
document.getElementById("item_name") as HTMLInputElement
|
||||||
|
)?.value.trim() || "";
|
||||||
|
const role = Number(
|
||||||
|
(document.getElementById("can_borrow_role") as HTMLInputElement)
|
||||||
|
?.value
|
||||||
|
);
|
||||||
|
const safeNrValue = (
|
||||||
|
document.getElementById("safe_nr") as HTMLInputElement
|
||||||
|
)?.value.trim();
|
||||||
|
|
||||||
|
const safeNr = safeNrValue === "" ? null : safeNrValue;
|
||||||
|
|
||||||
|
if (!name || Number.isNaN(role)) return;
|
||||||
|
|
||||||
|
const res = await createItem(name, role, safeNr);
|
||||||
|
if (res.success) {
|
||||||
|
alert(
|
||||||
|
"success",
|
||||||
|
"Gegenstand erstellt",
|
||||||
|
"Der Gegenstand wurde erfolgreich erstellt."
|
||||||
|
);
|
||||||
|
onClose();
|
||||||
|
} else {
|
||||||
|
alert(
|
||||||
|
"error",
|
||||||
|
"Fehler",
|
||||||
|
res.message ||
|
||||||
|
"Der Gegenstand konnte nicht erstellt werden. (frontend bug)"
|
||||||
|
);
|
||||||
|
onClose();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Erstellen
|
||||||
|
</Button>
|
||||||
|
</Card.Footer>
|
||||||
|
</Card.Root>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default AddItemForm;
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
import React from "react";
|
||||||
|
import { Button, Card, Field, Input, Stack, Alert } from "@chakra-ui/react";
|
||||||
|
import { changePW } from "@/utils/userActions";
|
||||||
|
import { useState } from "react";
|
||||||
|
|
||||||
|
type ChangePWformProps = {
|
||||||
|
onClose: () => void;
|
||||||
|
alert: (
|
||||||
|
status: "success" | "error",
|
||||||
|
message: string,
|
||||||
|
description: string
|
||||||
|
) => void;
|
||||||
|
username: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const ChangePWform: React.FC<ChangePWformProps> = ({
|
||||||
|
onClose,
|
||||||
|
alert,
|
||||||
|
username,
|
||||||
|
}) => {
|
||||||
|
const [showSubAlert, setShowSubAlert] = useState(false);
|
||||||
|
const [subAlertMessage, setSubAlertMessage] = useState("");
|
||||||
|
|
||||||
|
const subAlert = (message: string) => {
|
||||||
|
setSubAlertMessage(message);
|
||||||
|
setShowSubAlert(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
|
||||||
|
<Card.Root maxW="sm">
|
||||||
|
<Card.Header>
|
||||||
|
<Card.Title>Passwort ändern</Card.Title>
|
||||||
|
<Card.Description>
|
||||||
|
Füllen Sie das folgende Formular aus, um das Passwort zu ändern.
|
||||||
|
</Card.Description>
|
||||||
|
</Card.Header>
|
||||||
|
<Card.Body>
|
||||||
|
<Stack gap="4" w="full">
|
||||||
|
<Field.Root>
|
||||||
|
<Field.Label>Neues Passwort</Field.Label>
|
||||||
|
<Input
|
||||||
|
id="new_password"
|
||||||
|
type="password"
|
||||||
|
placeholder="Neues Passwort"
|
||||||
|
/>
|
||||||
|
</Field.Root>
|
||||||
|
<Field.Root>
|
||||||
|
<Field.Label>Neues Passwort widerholen</Field.Label>
|
||||||
|
<Input
|
||||||
|
id="confirm_new_password"
|
||||||
|
type="password"
|
||||||
|
placeholder="Wiederholen Sie das neue Passwort"
|
||||||
|
/>
|
||||||
|
</Field.Root>
|
||||||
|
</Stack>
|
||||||
|
</Card.Body>
|
||||||
|
<Card.Footer gap="2">
|
||||||
|
<Stack w="full" gap="3">
|
||||||
|
<Stack direction="row" justify="flex-end" gap="2">
|
||||||
|
<Button variant="outline" onClick={onClose}>
|
||||||
|
Abbrechen
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="solid"
|
||||||
|
onClick={async () => {
|
||||||
|
const newPassword =
|
||||||
|
(
|
||||||
|
document.getElementById(
|
||||||
|
"new_password"
|
||||||
|
) as HTMLInputElement
|
||||||
|
)?.value.trim() || "";
|
||||||
|
const confirmNewPassword =
|
||||||
|
(
|
||||||
|
document.getElementById(
|
||||||
|
"confirm_new_password"
|
||||||
|
) as HTMLInputElement
|
||||||
|
)?.value.trim() || "";
|
||||||
|
|
||||||
|
if (!newPassword || newPassword !== confirmNewPassword) {
|
||||||
|
subAlert("Passwörter stimmen nicht überein!");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await changePW(newPassword, username);
|
||||||
|
if (res.success) {
|
||||||
|
alert(
|
||||||
|
"success",
|
||||||
|
"Passwort geändert",
|
||||||
|
"Das Passwort wurde erfolgreich geändert."
|
||||||
|
);
|
||||||
|
onClose();
|
||||||
|
} else {
|
||||||
|
alert(
|
||||||
|
"error",
|
||||||
|
"Fehler",
|
||||||
|
"Das Passwort konnte nicht geändert werden."
|
||||||
|
);
|
||||||
|
onClose();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Ändern
|
||||||
|
</Button>
|
||||||
|
</Stack>
|
||||||
|
|
||||||
|
{showSubAlert && (
|
||||||
|
<Alert.Root status="error">
|
||||||
|
<Alert.Indicator />
|
||||||
|
<Alert.Content>
|
||||||
|
<Alert.Title>{subAlertMessage}</Alert.Title>
|
||||||
|
</Alert.Content>
|
||||||
|
</Alert.Root>
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
|
</Card.Footer>
|
||||||
|
</Card.Root>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default ChangePWform;
|
||||||
@@ -0,0 +1,426 @@
|
|||||||
|
import React from "react";
|
||||||
|
import {
|
||||||
|
Table,
|
||||||
|
Spinner,
|
||||||
|
Text,
|
||||||
|
VStack,
|
||||||
|
Button,
|
||||||
|
HStack,
|
||||||
|
IconButton,
|
||||||
|
Heading,
|
||||||
|
Icon,
|
||||||
|
Input,
|
||||||
|
} from "@chakra-ui/react";
|
||||||
|
import { Tooltip } from "@/components/ui/tooltip";
|
||||||
|
import MyAlert from "./myChakra/MyAlert";
|
||||||
|
import {
|
||||||
|
Trash2,
|
||||||
|
RefreshCcwDot,
|
||||||
|
CirclePlus,
|
||||||
|
CheckCircle2,
|
||||||
|
XCircle,
|
||||||
|
Save,
|
||||||
|
} from "lucide-react";
|
||||||
|
import Cookies from "js-cookie";
|
||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import {
|
||||||
|
deleteItem,
|
||||||
|
handleEditItems,
|
||||||
|
changeSafeState,
|
||||||
|
} from "@/utils/userActions";
|
||||||
|
import AddItemForm from "./AddItemForm";
|
||||||
|
import { formatDateTime } from "@/utils/userFuncs";
|
||||||
|
import { API_BASE } from "@/config/api.config";
|
||||||
|
|
||||||
|
type Items = {
|
||||||
|
id: number;
|
||||||
|
item_name: string;
|
||||||
|
can_borrow_role: string;
|
||||||
|
in_safe: boolean;
|
||||||
|
safe_nr: string;
|
||||||
|
door_key: string;
|
||||||
|
entry_created_at: string;
|
||||||
|
entry_updated_at: string;
|
||||||
|
last_borrowed_person: string | null;
|
||||||
|
currently_borrowing: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const ItemTable: 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 [addForm, setAddForm] = useState(false);
|
||||||
|
|
||||||
|
const handleItemNameChange = (id: number, value: string) => {
|
||||||
|
setItems((prev) =>
|
||||||
|
prev.map((it) => (it.id === id ? { ...it, item_name: value } : it)),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCanBorrowRoleChange = (id: number, value: string) => {
|
||||||
|
setItems((prev) =>
|
||||||
|
prev.map((it) => (it.id === id ? { ...it, can_borrow_role: value } : it)),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleLockerNumberChange = (id: number, value: string) => {
|
||||||
|
setItems((prev) =>
|
||||||
|
prev.map((it) => (it.id === id ? { ...it, safe_nr: value } : it)),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDoorKeyChange = (id: number, value: string) => {
|
||||||
|
setItems((prev) =>
|
||||||
|
prev.map((it) => (it.id === id ? { ...it, door_key: value } : it)),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
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/item-data/all-items`,
|
||||||
|
{
|
||||||
|
method: "GET",
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
const data = await response.json();
|
||||||
|
return 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 (
|
||||||
|
<>
|
||||||
|
{/* Action toolbar */}
|
||||||
|
<HStack
|
||||||
|
mb={4}
|
||||||
|
gap={3}
|
||||||
|
justify="flex-start"
|
||||||
|
align="center"
|
||||||
|
flexWrap="wrap"
|
||||||
|
>
|
||||||
|
<Tooltip content="Gegenstände neu laden" openDelay={300}>
|
||||||
|
<IconButton
|
||||||
|
aria-label="Refresh items"
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
rounded="md"
|
||||||
|
shadow="sm"
|
||||||
|
_hover={{ shadow: "md", transform: "translateY(-2px)" }}
|
||||||
|
_active={{ transform: "translateY(0)" }}
|
||||||
|
onClick={() => setReload(!reload)}
|
||||||
|
>
|
||||||
|
<RefreshCcwDot size={18} />
|
||||||
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
|
|
||||||
|
<Tooltip content="Neuen Gegenstand hinzufügen" openDelay={300}>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
colorPalette="teal"
|
||||||
|
variant="solid"
|
||||||
|
rounded="md"
|
||||||
|
fontWeight="semibold"
|
||||||
|
shadow="sm"
|
||||||
|
_hover={{ shadow: "md", bg: "colorPalette.600" }}
|
||||||
|
_active={{ bg: "colorPalette.700" }}
|
||||||
|
onClick={() => {
|
||||||
|
setAddForm(true);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<CirclePlus size={18} style={{ marginRight: 6 }} />
|
||||||
|
Neuen Gegenstand hinzufügen
|
||||||
|
</Button>
|
||||||
|
</Tooltip>
|
||||||
|
</HStack>
|
||||||
|
{/* End action toolbar */}
|
||||||
|
|
||||||
|
<Heading marginBottom={4} size="2xl">
|
||||||
|
Gegenstände
|
||||||
|
</Heading>
|
||||||
|
{isError && (
|
||||||
|
<MyAlert
|
||||||
|
status={errorStatus}
|
||||||
|
description={errorDsc}
|
||||||
|
title={errorMessage}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{isLoading && (
|
||||||
|
<VStack colorPalette="teal">
|
||||||
|
<Spinner color="colorPalette.600" />
|
||||||
|
<Text color="colorPalette.600">Loading...</Text>
|
||||||
|
</VStack>
|
||||||
|
)}
|
||||||
|
{addForm && (
|
||||||
|
<AddItemForm
|
||||||
|
onClose={() => {
|
||||||
|
setAddForm(false);
|
||||||
|
setReload(!reload);
|
||||||
|
}}
|
||||||
|
alert={setError}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* make table fill available width, like UserTable */}
|
||||||
|
{!isLoading && (
|
||||||
|
<Table.ScrollArea flex="1" minH={0} rounded="md" mt={4}>
|
||||||
|
<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.Row>
|
||||||
|
<Table.ColumnHeader>
|
||||||
|
<strong>#</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader>
|
||||||
|
<strong>Gegenstand</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader>
|
||||||
|
<strong>Ausleih Berechtigung</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader>
|
||||||
|
<strong>Im Schließfach</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader width="1%" whiteSpace="nowrap">
|
||||||
|
<strong>Schließfachnummer</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader width="1%" whiteSpace="nowrap">
|
||||||
|
<strong>Schlüssel</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader>
|
||||||
|
<strong>Eintrag erstellt am</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader>
|
||||||
|
<strong>Eintrag aktualisiert am</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader>
|
||||||
|
<strong>LaP *</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader>
|
||||||
|
<strong>Dav **</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader width="1%" whiteSpace="nowrap">
|
||||||
|
<strong>Aktionen</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
</Table.Row>
|
||||||
|
</Table.Header>
|
||||||
|
<Table.Body>
|
||||||
|
{items.map((item) => (
|
||||||
|
<Table.Row key={item.id}>
|
||||||
|
<Table.Cell>{item.id}</Table.Cell>
|
||||||
|
<Table.Cell>
|
||||||
|
<Input
|
||||||
|
size="sm"
|
||||||
|
w="max-content"
|
||||||
|
onChange={(e) =>
|
||||||
|
handleItemNameChange(item.id, e.target.value)
|
||||||
|
}
|
||||||
|
value={item.item_name}
|
||||||
|
/>
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell>
|
||||||
|
<Input
|
||||||
|
size="sm"
|
||||||
|
w="max-content"
|
||||||
|
onChange={(e) =>
|
||||||
|
handleCanBorrowRoleChange(item.id, e.target.value)
|
||||||
|
}
|
||||||
|
value={item.can_borrow_role}
|
||||||
|
/>
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell>
|
||||||
|
<Button
|
||||||
|
onClick={() =>
|
||||||
|
changeSafeState(item.id).then(() => setReload(!reload))
|
||||||
|
}
|
||||||
|
size="xs"
|
||||||
|
rounded="full"
|
||||||
|
px={3}
|
||||||
|
py={1}
|
||||||
|
gap={2}
|
||||||
|
variant="ghost"
|
||||||
|
color={item.in_safe ? "green.600" : "red.600"}
|
||||||
|
borderWidth="1px"
|
||||||
|
borderColor={item.in_safe ? "green.300" : "red.300"}
|
||||||
|
_hover={{
|
||||||
|
bg: item.in_safe ? "green.50" : "red.50",
|
||||||
|
borderColor: item.in_safe ? "green.400" : "red.400",
|
||||||
|
transform: "translateY(-1px)",
|
||||||
|
shadow: "sm",
|
||||||
|
}}
|
||||||
|
_active={{ transform: "translateY(0)" }}
|
||||||
|
aria-label={
|
||||||
|
item.in_safe ? "Mark as not in safe" : "Mark as in safe"
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Icon
|
||||||
|
as={item.in_safe ? CheckCircle2 : XCircle}
|
||||||
|
boxSize={3.5}
|
||||||
|
mr={2}
|
||||||
|
/>
|
||||||
|
<Text as="span" fontSize="xs" fontWeight="semibold">
|
||||||
|
{item.in_safe ? "Yes" : "No"}
|
||||||
|
</Text>
|
||||||
|
</Button>
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell>
|
||||||
|
<Input
|
||||||
|
size="sm"
|
||||||
|
w="max-content"
|
||||||
|
onChange={(e) =>
|
||||||
|
handleLockerNumberChange(item.id, e.target.value)
|
||||||
|
}
|
||||||
|
value={item.safe_nr}
|
||||||
|
/>
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell>
|
||||||
|
<Input
|
||||||
|
size="sm"
|
||||||
|
w="max-content"
|
||||||
|
onChange={(e) =>
|
||||||
|
handleDoorKeyChange(item.id, e.target.value)
|
||||||
|
}
|
||||||
|
value={item.door_key}
|
||||||
|
/>
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell>
|
||||||
|
{formatDateTime(item.entry_created_at)}
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell>
|
||||||
|
{formatDateTime(item.entry_updated_at)}
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell>{item.last_borrowed_person}</Table.Cell>
|
||||||
|
<Table.Cell>{item.currently_borrowing}</Table.Cell>
|
||||||
|
<Table.Cell whiteSpace="nowrap">
|
||||||
|
<Button
|
||||||
|
onClick={() =>
|
||||||
|
handleEditItems(
|
||||||
|
item.id,
|
||||||
|
item.item_name,
|
||||||
|
item.safe_nr,
|
||||||
|
item.door_key,
|
||||||
|
item.can_borrow_role,
|
||||||
|
).then((response) => {
|
||||||
|
if (response.success) {
|
||||||
|
setError(
|
||||||
|
"success",
|
||||||
|
"Gegenstand erfolgreich bearbeitet!",
|
||||||
|
"Gegenstand " +
|
||||||
|
'"' +
|
||||||
|
item.item_name +
|
||||||
|
'" mit ID ' +
|
||||||
|
item.id +
|
||||||
|
" bearbeitet.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
colorPalette="teal"
|
||||||
|
size="sm"
|
||||||
|
>
|
||||||
|
<Save />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={() =>
|
||||||
|
deleteItem(item.id).then((response) => {
|
||||||
|
if (response.success) {
|
||||||
|
setItems(items.filter((i) => i.id !== item.id));
|
||||||
|
setError(
|
||||||
|
"success",
|
||||||
|
"Gegenstand gelöscht",
|
||||||
|
"Der Gegenstand wurde erfolgreich gelöscht.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
colorPalette="red"
|
||||||
|
size="sm"
|
||||||
|
ml={2}
|
||||||
|
>
|
||||||
|
<Trash2 />
|
||||||
|
</Button>
|
||||||
|
</Table.Cell>
|
||||||
|
</Table.Row>
|
||||||
|
))}
|
||||||
|
</Table.Body>
|
||||||
|
</Table.Root>
|
||||||
|
</Table.ScrollArea>
|
||||||
|
)}
|
||||||
|
<Text>* LaP = Letzte ausleihende Person</Text>
|
||||||
|
<Text>** Dav = Derzeit ausgeliehen von</Text>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default ItemTable;
|
||||||
@@ -0,0 +1,263 @@
|
|||||||
|
import React from "react";
|
||||||
|
import {
|
||||||
|
Box,
|
||||||
|
Table,
|
||||||
|
Spinner,
|
||||||
|
Text,
|
||||||
|
VStack,
|
||||||
|
Button,
|
||||||
|
HStack,
|
||||||
|
IconButton,
|
||||||
|
Heading,
|
||||||
|
Code,
|
||||||
|
} from "@chakra-ui/react";
|
||||||
|
import { Tooltip } from "@/components/ui/tooltip";
|
||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import Cookies from "js-cookie";
|
||||||
|
import MyAlert from "./myChakra/MyAlert";
|
||||||
|
import { formatDateTime } from "@/utils/userFuncs";
|
||||||
|
import { Trash2, RefreshCcwDot } from "lucide-react";
|
||||||
|
import { deleteLoan } from "@/utils/userActions";
|
||||||
|
import { API_BASE } from "@/config/api.config";
|
||||||
|
|
||||||
|
const LoanTable: React.FC = () => {
|
||||||
|
const [items, setItems] = useState<Loan[]>([]);
|
||||||
|
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 setError = (
|
||||||
|
status: "error" | "success",
|
||||||
|
message: string,
|
||||||
|
description: string,
|
||||||
|
) => {
|
||||||
|
setIsError(false);
|
||||||
|
setErrorStatus(status);
|
||||||
|
setErrorMessage(message);
|
||||||
|
setErrorDsc(description);
|
||||||
|
setIsError(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
type Loan = {
|
||||||
|
id: number;
|
||||||
|
username: string;
|
||||||
|
loan_code: string;
|
||||||
|
start_date: string;
|
||||||
|
end_date: string;
|
||||||
|
take_date: string;
|
||||||
|
returned_date: string;
|
||||||
|
created_at: string;
|
||||||
|
loaned_items_name: string[];
|
||||||
|
deleted: boolean;
|
||||||
|
note: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const fetchData = async () => {
|
||||||
|
setIsLoading(true);
|
||||||
|
try {
|
||||||
|
const response = await fetch(
|
||||||
|
`${API_BASE}/api/admin/loan-data/all-loans`,
|
||||||
|
{
|
||||||
|
method: "GET",
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
const data = await response.json();
|
||||||
|
return data;
|
||||||
|
} catch (error) {
|
||||||
|
setError("error", "Failed to fetch loans", "There is an error");
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
fetchData().then((data) => {
|
||||||
|
if (Array.isArray(data)) {
|
||||||
|
setItems(data);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}, [reload]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box h="full" display="flex" flexDirection="column" minH={0}>
|
||||||
|
{/* Action toolbar */}
|
||||||
|
<HStack
|
||||||
|
mb={4}
|
||||||
|
gap={3}
|
||||||
|
justify="flex-start"
|
||||||
|
align="center"
|
||||||
|
flexWrap="wrap"
|
||||||
|
>
|
||||||
|
<Tooltip content="Ausleihen neu laden" openDelay={300}>
|
||||||
|
<IconButton
|
||||||
|
aria-label="Refresh loans"
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
rounded="md"
|
||||||
|
shadow="sm"
|
||||||
|
_hover={{ shadow: "md", transform: "translateY(-2px)" }}
|
||||||
|
_active={{ transform: "translateY(0)" }}
|
||||||
|
onClick={() => setReload(!reload)}
|
||||||
|
>
|
||||||
|
<RefreshCcwDot size={18} />
|
||||||
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
|
</HStack>
|
||||||
|
{/* End action toolbar */}
|
||||||
|
|
||||||
|
<Heading marginBottom={4} size="2xl">
|
||||||
|
Ausleihen
|
||||||
|
</Heading>
|
||||||
|
<Text>
|
||||||
|
Die Ausleihen die rot sind, wurden gelöscht und sind nur für den Admin
|
||||||
|
sichtbar.
|
||||||
|
</Text>
|
||||||
|
|
||||||
|
{isError && (
|
||||||
|
<MyAlert
|
||||||
|
status={errorStatus}
|
||||||
|
description={errorDsc}
|
||||||
|
title={errorMessage}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{isLoading && (
|
||||||
|
<VStack colorPalette="teal">
|
||||||
|
<Spinner color="colorPalette.600" />
|
||||||
|
<Text color="colorPalette.600">Loading...</Text>
|
||||||
|
</VStack>
|
||||||
|
)}
|
||||||
|
{!isLoading && (
|
||||||
|
<Table.ScrollArea flex="1" minH={0} rounded="md" mt={4}>
|
||||||
|
<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.Row>
|
||||||
|
<Table.ColumnHeader>
|
||||||
|
<strong>#</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader>
|
||||||
|
<strong>Besitzer</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader>
|
||||||
|
<strong>Ausleihcode</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader>
|
||||||
|
<strong>Startdatum</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader>
|
||||||
|
<strong>Enddatum</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader>
|
||||||
|
<strong>Ausleihdatum</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader>
|
||||||
|
<strong>Rückgabedatum</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader>
|
||||||
|
<strong>Erstellt am</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader>
|
||||||
|
<strong>Ausgeliehene Artikel</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader>
|
||||||
|
<strong>Notiz</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader>
|
||||||
|
<strong>Aktionen</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
</Table.Row>
|
||||||
|
</Table.Header>
|
||||||
|
<Table.Body>
|
||||||
|
{items.map((item) => (
|
||||||
|
<Table.Row color={item.deleted ? "red" : "white"} key={item.id}>
|
||||||
|
<Table.Cell>{item.id}</Table.Cell>
|
||||||
|
<Table.Cell>{item.username}</Table.Cell>
|
||||||
|
<Table.Cell>
|
||||||
|
<Code>{item.loan_code}</Code>
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell>{formatDateTime(item.start_date)}</Table.Cell>
|
||||||
|
<Table.Cell>{formatDateTime(item.end_date)}</Table.Cell>
|
||||||
|
<Table.Cell>{formatDateTime(item.take_date)}</Table.Cell>
|
||||||
|
<Table.Cell>{formatDateTime(item.returned_date)}</Table.Cell>
|
||||||
|
<Table.Cell>{formatDateTime(item.created_at)}</Table.Cell>
|
||||||
|
<Table.Cell>{item.loaned_items_name.join(", ")}</Table.Cell>
|
||||||
|
<Table.Cell>{item.note}</Table.Cell>
|
||||||
|
<Table.Cell>
|
||||||
|
<Button
|
||||||
|
onClick={() =>
|
||||||
|
deleteLoan(item.id).then((response) => {
|
||||||
|
if (response.success) {
|
||||||
|
setItems(items.filter((i) => i.id !== item.id));
|
||||||
|
setError(
|
||||||
|
"success",
|
||||||
|
"Loan deleted",
|
||||||
|
"The loan has been successfully deleted.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
colorPalette="red"
|
||||||
|
size="sm"
|
||||||
|
ml={2}
|
||||||
|
>
|
||||||
|
<Trash2 />
|
||||||
|
</Button>
|
||||||
|
</Table.Cell>
|
||||||
|
</Table.Row>
|
||||||
|
))}
|
||||||
|
</Table.Body>
|
||||||
|
</Table.Root>
|
||||||
|
</Table.ScrollArea>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default LoanTable;
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
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;
|
||||||
@@ -0,0 +1,367 @@
|
|||||||
|
import React from "react";
|
||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import {
|
||||||
|
Table,
|
||||||
|
Spinner,
|
||||||
|
Text,
|
||||||
|
VStack,
|
||||||
|
Button,
|
||||||
|
Input,
|
||||||
|
HStack,
|
||||||
|
IconButton,
|
||||||
|
Heading,
|
||||||
|
Switch, // neu
|
||||||
|
} from "@chakra-ui/react";
|
||||||
|
import { Tooltip } from "@/components/ui/tooltip";
|
||||||
|
import { fetchUserData } from "@/utils/fetcher";
|
||||||
|
import { Save, Trash2, RefreshCcwDot, CirclePlus } from "lucide-react";
|
||||||
|
import { handleDelete, handleEdit } from "@/utils/userActions";
|
||||||
|
import MyAlert from "./myChakra/MyAlert";
|
||||||
|
import AddForm from "./AddForm";
|
||||||
|
import { formatDateTime } from "@/utils/userFuncs";
|
||||||
|
import ChangePWform from "./ChangePWform";
|
||||||
|
|
||||||
|
type User = {
|
||||||
|
id: number;
|
||||||
|
username: string;
|
||||||
|
first_name: string;
|
||||||
|
last_name: string;
|
||||||
|
email: string;
|
||||||
|
is_admin: boolean;
|
||||||
|
role: number;
|
||||||
|
entry_created_at: string;
|
||||||
|
entry_updated_at: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const UserTable: React.FC = () => {
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
const [users, setUsers] = useState<User[]>([]);
|
||||||
|
const [isError, setIsError] = useState(false);
|
||||||
|
const [errorStatus, setErrorStatus] = useState<"error" | "success">("error");
|
||||||
|
const [errorMessage, setErrorMessage] = useState("");
|
||||||
|
const [errorDsc, setErrorDsc] = useState("");
|
||||||
|
const [reload, setReload] = useState(false);
|
||||||
|
const [addForm, setAddForm] = useState(false);
|
||||||
|
const [changePWform, setChangePWform] = useState(false);
|
||||||
|
const [changeUsr, setChangeUsr] = useState("");
|
||||||
|
|
||||||
|
const setError = (
|
||||||
|
status: "error" | "success",
|
||||||
|
message: string,
|
||||||
|
description: string
|
||||||
|
) => {
|
||||||
|
setIsError(false);
|
||||||
|
setErrorStatus(status);
|
||||||
|
setErrorMessage(message);
|
||||||
|
setErrorDsc(description);
|
||||||
|
setIsError(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleInputChange = (userId: number, field: string, value: any) => {
|
||||||
|
setUsers((prevUsers) =>
|
||||||
|
prevUsers.map((user) =>
|
||||||
|
user.id === userId
|
||||||
|
? {
|
||||||
|
...user,
|
||||||
|
[field]:
|
||||||
|
field === "role"
|
||||||
|
? Number(value)
|
||||||
|
: field === "is_admin"
|
||||||
|
? value === true || value === "true" || value === 1
|
||||||
|
: value,
|
||||||
|
}
|
||||||
|
: user
|
||||||
|
)
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handlePasswordChange = (username: string) => {
|
||||||
|
setChangeUsr(username);
|
||||||
|
setChangePWform(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const fetchUsers = async () => {
|
||||||
|
setIsLoading(true);
|
||||||
|
try {
|
||||||
|
const data = await fetchUserData();
|
||||||
|
if (Array.isArray(data)) {
|
||||||
|
setUsers(data);
|
||||||
|
} else {
|
||||||
|
setError(
|
||||||
|
"error",
|
||||||
|
"Failed to load users",
|
||||||
|
"Invalid data format received"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Failed to fetch users", e);
|
||||||
|
if (e instanceof Error) {
|
||||||
|
setError(
|
||||||
|
"error",
|
||||||
|
"Failed to fetch users",
|
||||||
|
e.message || "Unknown error"
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
setError("error", "Failed to fetch users", "Unknown error");
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
fetchUsers();
|
||||||
|
}, [reload]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{/* Action toolbar */}
|
||||||
|
<HStack
|
||||||
|
mb={4}
|
||||||
|
gap={3}
|
||||||
|
justify="flex-start"
|
||||||
|
align="center"
|
||||||
|
flexWrap="wrap"
|
||||||
|
>
|
||||||
|
<Tooltip content="Benutzer neu laden" openDelay={300}>
|
||||||
|
<IconButton
|
||||||
|
aria-label="Refresh users"
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
rounded="md"
|
||||||
|
shadow="sm"
|
||||||
|
_hover={{ shadow: "md", transform: "translateY(-2px)" }}
|
||||||
|
_active={{ transform: "translateY(0)" }}
|
||||||
|
onClick={() => setReload(!reload)}
|
||||||
|
>
|
||||||
|
<RefreshCcwDot size={18} />
|
||||||
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
|
|
||||||
|
<Tooltip content="Neuen Nutzer hinzufügen" openDelay={300}>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
colorPalette="teal"
|
||||||
|
variant="solid"
|
||||||
|
rounded="md"
|
||||||
|
fontWeight="semibold"
|
||||||
|
shadow="sm"
|
||||||
|
_hover={{ shadow: "md", bg: "colorPalette.600" }}
|
||||||
|
_active={{ bg: "colorPalette.700" }}
|
||||||
|
onClick={() => {
|
||||||
|
setAddForm(true);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<CirclePlus size={18} style={{ marginRight: 6 }} />
|
||||||
|
Neuen Nutzer hinzufügen
|
||||||
|
</Button>
|
||||||
|
</Tooltip>
|
||||||
|
</HStack>
|
||||||
|
{/* End action toolbar */}
|
||||||
|
|
||||||
|
<Heading marginBottom={4} size="2xl">
|
||||||
|
Benutzer
|
||||||
|
</Heading>
|
||||||
|
{changePWform && (
|
||||||
|
<ChangePWform
|
||||||
|
onClose={() => {
|
||||||
|
setChangePWform(false);
|
||||||
|
setReload(!reload);
|
||||||
|
}}
|
||||||
|
alert={setError}
|
||||||
|
username={changeUsr}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{isError && (
|
||||||
|
<MyAlert
|
||||||
|
status={errorStatus}
|
||||||
|
description={errorDsc}
|
||||||
|
title={errorMessage}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{addForm && (
|
||||||
|
<AddForm
|
||||||
|
onClose={() => {
|
||||||
|
setAddForm(false);
|
||||||
|
setReload(!reload);
|
||||||
|
}}
|
||||||
|
alert={setError}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{isLoading && (
|
||||||
|
<VStack colorPalette="teal">
|
||||||
|
<Spinner color="colorPalette.600" />
|
||||||
|
<Text color="colorPalette.600">Loading...</Text>
|
||||||
|
</VStack>
|
||||||
|
)}
|
||||||
|
{!isLoading && (
|
||||||
|
<Table.Root
|
||||||
|
size="sm"
|
||||||
|
striped
|
||||||
|
w="100%"
|
||||||
|
style={{ tableLayout: "auto" }} // Spalten nach Content
|
||||||
|
>
|
||||||
|
<Table.Header>
|
||||||
|
<Table.Row>
|
||||||
|
<Table.ColumnHeader width="1%" whiteSpace="nowrap">
|
||||||
|
<strong>#</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader>
|
||||||
|
<strong>Benutzername</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader>
|
||||||
|
<strong>Vorname</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader>
|
||||||
|
<strong>Nachname</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader>
|
||||||
|
<strong>E-Mail</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader width="1%" whiteSpace="nowrap">
|
||||||
|
<strong>Admin</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader whiteSpace="nowrap">
|
||||||
|
<strong>Passwort ändern</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader width="1%" whiteSpace="nowrap">
|
||||||
|
<strong>Rolle</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader whiteSpace="nowrap">
|
||||||
|
<strong>Eintrag erstellt am</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader whiteSpace="nowrap">
|
||||||
|
<strong>Eintrag aktualisiert am</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader width="1%" whiteSpace="nowrap">
|
||||||
|
<strong>Aktionen</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
</Table.Row>
|
||||||
|
</Table.Header>
|
||||||
|
<Table.Body>
|
||||||
|
{users.map((user) => (
|
||||||
|
<Table.Row key={user.id}>
|
||||||
|
<Table.Cell whiteSpace="nowrap">{user.id}</Table.Cell>
|
||||||
|
<Table.Cell>{user.username}</Table.Cell>
|
||||||
|
<Table.Cell>
|
||||||
|
<Input
|
||||||
|
size="sm"
|
||||||
|
value={user.first_name ?? ""}
|
||||||
|
onChange={(e) =>
|
||||||
|
handleInputChange(user.id, "first_name", e.target.value)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell>
|
||||||
|
<Input
|
||||||
|
size="sm"
|
||||||
|
value={user.last_name ?? ""}
|
||||||
|
onChange={(e) =>
|
||||||
|
handleInputChange(user.id, "last_name", e.target.value)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell>
|
||||||
|
<Input
|
||||||
|
type="email"
|
||||||
|
size="sm"
|
||||||
|
value={user.email ?? ""}
|
||||||
|
onChange={(e) =>
|
||||||
|
handleInputChange(user.id, "email", e.target.value)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell whiteSpace="nowrap">
|
||||||
|
<Switch.Root
|
||||||
|
size="sm"
|
||||||
|
checked={!!user.is_admin}
|
||||||
|
onCheckedChange={(d) =>
|
||||||
|
handleInputChange(user.id, "is_admin", d.checked)
|
||||||
|
}
|
||||||
|
aria-label="Adminrechte umschalten"
|
||||||
|
>
|
||||||
|
<Switch.Control>
|
||||||
|
<Switch.Thumb />
|
||||||
|
</Switch.Control>
|
||||||
|
<Switch.HiddenInput />
|
||||||
|
</Switch.Root>
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell whiteSpace="nowrap">
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
onClick={() => handlePasswordChange(user.username)}
|
||||||
|
>
|
||||||
|
Passwort ändern
|
||||||
|
</Button>
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell whiteSpace="nowrap">
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
size="sm"
|
||||||
|
onChange={(e) =>
|
||||||
|
handleInputChange(user.id, "role", e.target.value)
|
||||||
|
}
|
||||||
|
value={user.role}
|
||||||
|
width="70px"
|
||||||
|
/>
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell whiteSpace="nowrap">
|
||||||
|
{formatDateTime(user.entry_created_at)}
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell whiteSpace="nowrap">
|
||||||
|
{formatDateTime(user.entry_updated_at)}
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell whiteSpace="nowrap">
|
||||||
|
<Button
|
||||||
|
onClick={() =>
|
||||||
|
handleEdit(
|
||||||
|
user.id,
|
||||||
|
user.first_name,
|
||||||
|
user.last_name,
|
||||||
|
user.email,
|
||||||
|
user.is_admin,
|
||||||
|
Number(user.role)
|
||||||
|
).then((response) => {
|
||||||
|
if (response.success) {
|
||||||
|
setError(
|
||||||
|
"success",
|
||||||
|
"User edited",
|
||||||
|
"The user has been successfully edited."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
colorPalette="teal"
|
||||||
|
size="sm"
|
||||||
|
>
|
||||||
|
<Save />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={() =>
|
||||||
|
handleDelete(user.id).then((response) => {
|
||||||
|
if (response.success) {
|
||||||
|
setUsers(users.filter((u) => u.id !== user.id));
|
||||||
|
setError(
|
||||||
|
"success",
|
||||||
|
"User deleted",
|
||||||
|
"The user has been successfully deleted."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
colorPalette="red"
|
||||||
|
size="sm"
|
||||||
|
ml={2}
|
||||||
|
>
|
||||||
|
<Trash2 />
|
||||||
|
</Button>
|
||||||
|
</Table.Cell>
|
||||||
|
</Table.Row>
|
||||||
|
))}
|
||||||
|
</Table.Body>
|
||||||
|
</Table.Root>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default UserTable;
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import React from "react";
|
||||||
|
import { Alert } from "@chakra-ui/react";
|
||||||
|
|
||||||
|
type MyAlertProps = {
|
||||||
|
status: "error" | "success";
|
||||||
|
title: string;
|
||||||
|
description: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const MyAlert: React.FC<MyAlertProps> = ({ title, description, status }) => {
|
||||||
|
return (
|
||||||
|
<Alert.Root status={status}>
|
||||||
|
<Alert.Indicator />
|
||||||
|
<Alert.Content>
|
||||||
|
<Alert.Title>{title}</Alert.Title>
|
||||||
|
<Alert.Description>{description}</Alert.Description>
|
||||||
|
</Alert.Content>
|
||||||
|
</Alert.Root>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default MyAlert;
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import type { IconButtonProps, SpanProps } from "@chakra-ui/react"
|
||||||
|
import { ClientOnly, IconButton, Skeleton, Span } from "@chakra-ui/react"
|
||||||
|
import { ThemeProvider, useTheme } from "next-themes"
|
||||||
|
import type { ThemeProviderProps } from "next-themes"
|
||||||
|
import * as React from "react"
|
||||||
|
import { LuMoon, LuSun } from "react-icons/lu"
|
||||||
|
|
||||||
|
export interface ColorModeProviderProps extends ThemeProviderProps {}
|
||||||
|
|
||||||
|
export function ColorModeProvider(props: ColorModeProviderProps) {
|
||||||
|
return (
|
||||||
|
<ThemeProvider attribute="class" disableTransitionOnChange {...props} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ColorMode = "light" | "dark"
|
||||||
|
|
||||||
|
export interface UseColorModeReturn {
|
||||||
|
colorMode: ColorMode
|
||||||
|
setColorMode: (colorMode: ColorMode) => void
|
||||||
|
toggleColorMode: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useColorMode(): UseColorModeReturn {
|
||||||
|
const { resolvedTheme, setTheme, forcedTheme } = useTheme()
|
||||||
|
const colorMode = forcedTheme || resolvedTheme
|
||||||
|
const toggleColorMode = () => {
|
||||||
|
setTheme(resolvedTheme === "dark" ? "light" : "dark")
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
colorMode: colorMode as ColorMode,
|
||||||
|
setColorMode: setTheme,
|
||||||
|
toggleColorMode,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useColorModeValue<T>(light: T, dark: T) {
|
||||||
|
const { colorMode } = useColorMode()
|
||||||
|
return colorMode === "dark" ? dark : light
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ColorModeIcon() {
|
||||||
|
const { colorMode } = useColorMode()
|
||||||
|
return colorMode === "dark" ? <LuMoon /> : <LuSun />
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ColorModeButtonProps extends Omit<IconButtonProps, "aria-label"> {}
|
||||||
|
|
||||||
|
export const ColorModeButton = React.forwardRef<
|
||||||
|
HTMLButtonElement,
|
||||||
|
ColorModeButtonProps
|
||||||
|
>(function ColorModeButton(props, ref) {
|
||||||
|
const { toggleColorMode } = useColorMode()
|
||||||
|
return (
|
||||||
|
<ClientOnly fallback={<Skeleton boxSize="8" />}>
|
||||||
|
<IconButton
|
||||||
|
onClick={toggleColorMode}
|
||||||
|
variant="ghost"
|
||||||
|
aria-label="Toggle color mode"
|
||||||
|
size="sm"
|
||||||
|
ref={ref}
|
||||||
|
{...props}
|
||||||
|
css={{
|
||||||
|
_icon: {
|
||||||
|
width: "5",
|
||||||
|
height: "5",
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<ColorModeIcon />
|
||||||
|
</IconButton>
|
||||||
|
</ClientOnly>
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
export const LightMode = React.forwardRef<HTMLSpanElement, SpanProps>(
|
||||||
|
function LightMode(props, ref) {
|
||||||
|
return (
|
||||||
|
<Span
|
||||||
|
color="fg"
|
||||||
|
display="contents"
|
||||||
|
className="chakra-theme light"
|
||||||
|
colorPalette="gray"
|
||||||
|
colorScheme="light"
|
||||||
|
ref={ref}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
export const DarkMode = React.forwardRef<HTMLSpanElement, SpanProps>(
|
||||||
|
function DarkMode(props, ref) {
|
||||||
|
return (
|
||||||
|
<Span
|
||||||
|
color="fg"
|
||||||
|
display="contents"
|
||||||
|
className="chakra-theme dark"
|
||||||
|
colorPalette="gray"
|
||||||
|
colorScheme="dark"
|
||||||
|
ref={ref}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
)
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
"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" }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { ChakraProvider, defaultSystem } from "@chakra-ui/react"
|
||||||
|
import {
|
||||||
|
ColorModeProvider,
|
||||||
|
type ColorModeProviderProps,
|
||||||
|
} from "./color-mode"
|
||||||
|
|
||||||
|
export function Provider(props: ColorModeProviderProps) {
|
||||||
|
return (
|
||||||
|
<ChakraProvider value={defaultSystem}>
|
||||||
|
<ColorModeProvider {...props} />
|
||||||
|
</ChakraProvider>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import {
|
||||||
|
Toaster as ChakraToaster,
|
||||||
|
Portal,
|
||||||
|
Spinner,
|
||||||
|
Stack,
|
||||||
|
Toast,
|
||||||
|
createToaster,
|
||||||
|
} from "@chakra-ui/react"
|
||||||
|
|
||||||
|
export const toaster = createToaster({
|
||||||
|
placement: "bottom-end",
|
||||||
|
pauseOnPageIdle: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
export const Toaster = () => {
|
||||||
|
return (
|
||||||
|
<Portal>
|
||||||
|
<ChakraToaster toaster={toaster} insetInline={{ mdDown: "4" }}>
|
||||||
|
{(toast) => (
|
||||||
|
<Toast.Root width={{ md: "sm" }}>
|
||||||
|
{toast.type === "loading" ? (
|
||||||
|
<Spinner size="sm" color="blue.solid" />
|
||||||
|
) : (
|
||||||
|
<Toast.Indicator />
|
||||||
|
)}
|
||||||
|
<Stack gap="1" flex="1" maxWidth="100%">
|
||||||
|
{toast.title && <Toast.Title>{toast.title}</Toast.Title>}
|
||||||
|
{toast.description && (
|
||||||
|
<Toast.Description>{toast.description}</Toast.Description>
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
|
{toast.action && (
|
||||||
|
<Toast.ActionTrigger>{toast.action.label}</Toast.ActionTrigger>
|
||||||
|
)}
|
||||||
|
{toast.closable && <Toast.CloseTrigger />}
|
||||||
|
</Toast.Root>
|
||||||
|
)}
|
||||||
|
</ChakraToaster>
|
||||||
|
</Portal>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import { Tooltip as ChakraTooltip, Portal } from "@chakra-ui/react"
|
||||||
|
import * as React from "react"
|
||||||
|
|
||||||
|
export interface TooltipProps extends ChakraTooltip.RootProps {
|
||||||
|
showArrow?: boolean
|
||||||
|
portalled?: boolean
|
||||||
|
portalRef?: React.RefObject<HTMLElement>
|
||||||
|
content: React.ReactNode
|
||||||
|
contentProps?: ChakraTooltip.ContentProps
|
||||||
|
disabled?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export const Tooltip = React.forwardRef<HTMLDivElement, TooltipProps>(
|
||||||
|
function Tooltip(props, ref) {
|
||||||
|
const {
|
||||||
|
showArrow,
|
||||||
|
children,
|
||||||
|
disabled,
|
||||||
|
portalled = true,
|
||||||
|
content,
|
||||||
|
contentProps,
|
||||||
|
portalRef,
|
||||||
|
...rest
|
||||||
|
} = props
|
||||||
|
|
||||||
|
if (disabled) return children
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ChakraTooltip.Root {...rest}>
|
||||||
|
<ChakraTooltip.Trigger asChild>{children}</ChakraTooltip.Trigger>
|
||||||
|
<Portal disabled={!portalled} container={portalRef}>
|
||||||
|
<ChakraTooltip.Positioner>
|
||||||
|
<ChakraTooltip.Content ref={ref} {...contentProps}>
|
||||||
|
{showArrow && (
|
||||||
|
<ChakraTooltip.Arrow>
|
||||||
|
<ChakraTooltip.ArrowTip />
|
||||||
|
</ChakraTooltip.Arrow>
|
||||||
|
)}
|
||||||
|
{content}
|
||||||
|
</ChakraTooltip.Content>
|
||||||
|
</ChakraTooltip.Positioner>
|
||||||
|
</Portal>
|
||||||
|
</ChakraTooltip.Root>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
)
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
export const API_BASE =
|
||||||
|
(import.meta as any).env?.VITE_BACKEND_URL ||
|
||||||
|
import.meta.env.VITE_BACKEND_URL ||
|
||||||
|
"http://localhost:8002";
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
@import "tailwindcss";
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { Provider } from "@/components/ui/provider";
|
||||||
|
import { StrictMode } from "react";
|
||||||
|
import { createRoot } from "react-dom/client";
|
||||||
|
import "./index.css";
|
||||||
|
import App from "./App.tsx";
|
||||||
|
|
||||||
|
createRoot(document.getElementById("root")!).render(
|
||||||
|
<StrictMode>
|
||||||
|
<Provider>
|
||||||
|
<App />
|
||||||
|
</Provider>
|
||||||
|
</StrictMode>
|
||||||
|
);
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import Cookies from "js-cookie";
|
||||||
|
import { API_BASE } from "@/config/api.config";
|
||||||
|
|
||||||
|
export const fetchUserData = async () => {
|
||||||
|
const response = await fetch(`${API_BASE}/api/admin/user-data/users`, {
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const data = await response.json();
|
||||||
|
return data;
|
||||||
|
};
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import Cookies from "js-cookie";
|
||||||
|
import { API_BASE } from "@/config/api.config";
|
||||||
|
|
||||||
|
export type LoginSuccess = { success: true };
|
||||||
|
export type LoginFailure = {
|
||||||
|
success: false;
|
||||||
|
message: string;
|
||||||
|
description: string;
|
||||||
|
};
|
||||||
|
export type LoginResult = LoginSuccess | LoginFailure;
|
||||||
|
|
||||||
|
export const loginFunc = async (
|
||||||
|
username: string,
|
||||||
|
password: string
|
||||||
|
): Promise<LoginResult> => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${API_BASE}/api/admin/user-mgmt/login`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ username, password }),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.status === 403) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message: "Login failed!",
|
||||||
|
description: "You are not an admin user.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message: "Login failed!",
|
||||||
|
description: "Invalid username or password.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Successful login
|
||||||
|
const data = await response.json();
|
||||||
|
Cookies.set("token", data.token);
|
||||||
|
localStorage.setItem("userName", data.first_name);
|
||||||
|
return { success: true };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error logging in:", error);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message: "Login failed!",
|
||||||
|
description: "Server error.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,292 @@
|
|||||||
|
import Cookies from "js-cookie";
|
||||||
|
import { API_BASE } from "@/config/api.config";
|
||||||
|
|
||||||
|
export const handleDelete = async (userId: number) => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(
|
||||||
|
`${API_BASE}/api/admin/user-data/delete-user/${userId}`,
|
||||||
|
{
|
||||||
|
method: "DELETE",
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error("Failed to delete user");
|
||||||
|
}
|
||||||
|
return { success: true };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error deleting user:", error);
|
||||||
|
return { success: false };
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const handleEdit = async (
|
||||||
|
userId: number,
|
||||||
|
first_name: string,
|
||||||
|
last_name: string,
|
||||||
|
email: string,
|
||||||
|
is_admin: boolean,
|
||||||
|
role: number
|
||||||
|
) => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(
|
||||||
|
`${API_BASE}/api/admin/user-data/edit-user/${userId}`,
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
first_name,
|
||||||
|
last_name,
|
||||||
|
role,
|
||||||
|
email,
|
||||||
|
is_admin,
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error("Failed to edit user");
|
||||||
|
}
|
||||||
|
return { success: true };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error editing user:", error);
|
||||||
|
return { success: false };
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const createUser = async (
|
||||||
|
username: string,
|
||||||
|
role: number,
|
||||||
|
password: string,
|
||||||
|
first_name: string,
|
||||||
|
last_name: string,
|
||||||
|
email: string,
|
||||||
|
isAdmin: boolean
|
||||||
|
) => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(
|
||||||
|
`${API_BASE}/api/admin/user-data/create-user`,
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
username,
|
||||||
|
role,
|
||||||
|
password,
|
||||||
|
isAdmin,
|
||||||
|
email,
|
||||||
|
first_name,
|
||||||
|
last_name,
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error("Failed to create user");
|
||||||
|
}
|
||||||
|
return { success: true };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error creating user:", error);
|
||||||
|
return { success: false };
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const changePW = async (newPassword: string, username: string) => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(
|
||||||
|
`${API_BASE}/api/admin/user-data/change-password`,
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ username, password: newPassword }),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error("Failed to change password");
|
||||||
|
}
|
||||||
|
return { success: true };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error changing password:", error);
|
||||||
|
return { success: false };
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const deleteLoan = async (loanId: number) => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(
|
||||||
|
`${API_BASE}/api/admin/loan-data/delete-loan/${loanId}`,
|
||||||
|
{
|
||||||
|
method: "DELETE",
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error("Failed to delete loan");
|
||||||
|
}
|
||||||
|
return { success: true };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error deleting loan:", error);
|
||||||
|
return { success: false };
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const deleteItem = async (itemId: number) => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(
|
||||||
|
`${API_BASE}/api/admin/item-data/delete-item/${itemId}`,
|
||||||
|
{
|
||||||
|
method: "DELETE",
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error("Failed to delete item");
|
||||||
|
}
|
||||||
|
return { success: true };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error deleting item:", error);
|
||||||
|
return { success: false };
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const createItem = async (
|
||||||
|
item_name: string,
|
||||||
|
can_borrow_role: number,
|
||||||
|
lockerNumber: string | null
|
||||||
|
) => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(
|
||||||
|
`${API_BASE}/api/admin/item-data/create-item`,
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ item_name, can_borrow_role, lockerNumber }),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
if (!response.ok) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message:
|
||||||
|
"Fehler beim Erstellen des Gegenstands. Der Name des Gegenstandes und die Schließfachnummer dürfen nicht mehrmals vergeben werden.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return { success: true };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error creating item:", error);
|
||||||
|
return { success: false };
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const handleEditItems = async (
|
||||||
|
itemId: number,
|
||||||
|
item_name: string,
|
||||||
|
safe_nr: string | null,
|
||||||
|
door_key: string | null,
|
||||||
|
can_borrow_role: string
|
||||||
|
) => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(
|
||||||
|
`${API_BASE}/api/admin/item-data/edit-item/${itemId}`,
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ item_name, safe_nr, door_key, can_borrow_role }),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error("Failed to edit item");
|
||||||
|
}
|
||||||
|
return { success: true };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error editing item:", error);
|
||||||
|
return { success: false };
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const changeSafeState = async (itemId: number) => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(
|
||||||
|
`${API_BASE}/api/admin/item-data/change-safe-state/${itemId}`,
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error("Failed to change safe state");
|
||||||
|
}
|
||||||
|
return { success: true };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error changing safe state:", error);
|
||||||
|
return { success: false };
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const createAPIentry = async (apiKey: string, name: string) => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(
|
||||||
|
`${API_BASE}/api/admin/api-data/create-api-key`,
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ apiKey, entryName: name }),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
if (!response.ok) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message:
|
||||||
|
"Fehler beim Erstellen des API Keys. Achten Sie darauf, dass alle Felder ausgefüllt sind und der API Key nicht doppelt vergeben wird.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return { success: true };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error creating API entry:", error);
|
||||||
|
return { success: false };
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const deleteAPKey = async (apiKeyId: number) => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(
|
||||||
|
`${API_BASE}/api/admin/api-data/delete-api-key/${apiKeyId}`,
|
||||||
|
{
|
||||||
|
method: "DELETE",
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error("Failed to delete API key");
|
||||||
|
}
|
||||||
|
return { success: true };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error deleting API key:", error);
|
||||||
|
return { success: false };
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
export const formatDateTime = (value: string | null | undefined) => {
|
||||||
|
if (!value) return "N/A";
|
||||||
|
const m = value.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/);
|
||||||
|
if (!m) return "N/A";
|
||||||
|
const [, y, M, d, h, min] = m;
|
||||||
|
return `${d}.${M}.${y} ${h}:${min} Uhr`;
|
||||||
|
};
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
module.exports = {
|
||||||
|
content: [
|
||||||
|
"./index.html",
|
||||||
|
"./src/**/*.{js,jsx,ts,tsx}",
|
||||||
|
// add other paths if needed
|
||||||
|
],
|
||||||
|
theme: {
|
||||||
|
extend: {},
|
||||||
|
},
|
||||||
|
plugins: [],
|
||||||
|
};
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||||
|
"target": "ES2022",
|
||||||
|
"useDefineForClassFields": true,
|
||||||
|
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||||
|
"module": "ESNext",
|
||||||
|
"types": ["vite/client"],
|
||||||
|
"skipLibCheck": true,
|
||||||
|
|
||||||
|
/* Bundler mode */
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"verbatimModuleSyntax": true,
|
||||||
|
"moduleDetection": "force",
|
||||||
|
"noEmit": true,
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
|
||||||
|
/* Linting */
|
||||||
|
"strict": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
"erasableSyntaxOnly": true,
|
||||||
|
"noFallthroughCasesInSwitch": true,
|
||||||
|
"noUncheckedSideEffectImports": true,
|
||||||
|
|
||||||
|
/* Path aliases */
|
||||||
|
"paths": {
|
||||||
|
"@/*": ["./src/*"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"include": ["src"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"files": [],
|
||||||
|
"references": [
|
||||||
|
{ "path": "./tsconfig.app.json" },
|
||||||
|
{ "path": "./tsconfig.node.json" }
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||||
|
"target": "ES2023",
|
||||||
|
"lib": ["ES2023"],
|
||||||
|
"module": "ESNext",
|
||||||
|
"skipLibCheck": true,
|
||||||
|
|
||||||
|
/* Bundler mode */
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"verbatimModuleSyntax": true,
|
||||||
|
"moduleDetection": "force",
|
||||||
|
"noEmit": true,
|
||||||
|
|
||||||
|
/* Linting */
|
||||||
|
"strict": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
"erasableSyntaxOnly": true,
|
||||||
|
"noFallthroughCasesInSwitch": true,
|
||||||
|
"noUncheckedSideEffectImports": true
|
||||||
|
},
|
||||||
|
"include": ["vite.config.ts"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { defineConfig } from "vite";
|
||||||
|
import react from "@vitejs/plugin-react";
|
||||||
|
import svgr from "vite-plugin-svgr";
|
||||||
|
import tailwindcss from "@tailwindcss/vite";
|
||||||
|
import tsconfigPaths from "vite-tsconfig-paths";
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react(), svgr(), tailwindcss(), tsconfigPaths()],
|
||||||
|
server: {
|
||||||
|
host: "0.0.0.0",
|
||||||
|
port: 8003,
|
||||||
|
watch: {
|
||||||
|
usePolling: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
+21
-5
@@ -1,12 +1,28 @@
|
|||||||
|
# Build context is the repo root (npm workspaces share one root package-lock.json)
|
||||||
FROM node:20-alpine
|
FROM node:20-alpine
|
||||||
|
|
||||||
WORKDIR /backend
|
ENV NODE_ENV=production
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
COPY package*.json ./
|
COPY package.json package-lock.json ./
|
||||||
RUN npm install
|
COPY frontend/package.json frontend/
|
||||||
|
COPY admin/package.json admin/
|
||||||
|
COPY backend/package.json backend/
|
||||||
|
RUN npm ci -w backend --omit=dev
|
||||||
|
|
||||||
COPY . .
|
COPY backend/ backend/
|
||||||
|
|
||||||
EXPOSE 8002
|
# 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"]
|
CMD ["npm", "start"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
"backend-info": {
|
||||||
|
"version": "v2.2 (dev)"
|
||||||
|
},
|
||||||
|
"frontend-info": {
|
||||||
|
"version": "v2.2 (dev)"
|
||||||
|
},
|
||||||
|
"admin-panel-info": {
|
||||||
|
"version": "v1.4 (dev)"
|
||||||
|
}
|
||||||
|
}
|
||||||
Generated
-1062
File diff suppressed because it is too large
Load Diff
@@ -1,10 +1,11 @@
|
|||||||
{
|
{
|
||||||
"name": "backend",
|
"name": "backend",
|
||||||
"version": "1.0.0",
|
"version": "2.1.1-dev",
|
||||||
"main": "index.js",
|
"private": true,
|
||||||
|
"main": "server.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "echo \"Error: no test specified\" && exit 1",
|
"dev": "node --watch server.js",
|
||||||
"start": "node server.js"
|
"start": "NODE_ENV=production node server.js"
|
||||||
},
|
},
|
||||||
"keywords": [],
|
"keywords": [],
|
||||||
"author": "",
|
"author": "",
|
||||||
@@ -15,7 +16,9 @@
|
|||||||
"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"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import express from "express";
|
||||||
|
import { authenticateAdmin } from "../../services/authentication.js";
|
||||||
|
const router = express.Router();
|
||||||
|
import dotenv from "dotenv";
|
||||||
|
dotenv.config();
|
||||||
|
|
||||||
|
// database funcs import
|
||||||
|
import {
|
||||||
|
getAllApiKeys,
|
||||||
|
createAPIentry,
|
||||||
|
deleteAPKey,
|
||||||
|
} from "./database/apiDataMgmt.database.js";
|
||||||
|
|
||||||
|
router.get("/get-api-keys", authenticateAdmin, async (req, res) => {
|
||||||
|
const result = await getAllApiKeys();
|
||||||
|
if (result.success) {
|
||||||
|
return res.status(200).json(result.data);
|
||||||
|
}
|
||||||
|
return res.status(500).json({ message: "Failed to retrieve API keys" });
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post("/create-api-key", authenticateAdmin, async (req, res) => {
|
||||||
|
const apiKey = req.body.apiKey;
|
||||||
|
const entryName = req.body.entryName;
|
||||||
|
const result = await createAPIentry(apiKey, entryName);
|
||||||
|
if (result.success) {
|
||||||
|
return res.status(201).json({ message: "API key created successfully" });
|
||||||
|
}
|
||||||
|
return res.status(500).json({ message: "Failed to create API key" });
|
||||||
|
});
|
||||||
|
|
||||||
|
router.delete("/delete-api-key/:id", authenticateAdmin, async (req, res) => {
|
||||||
|
const apiKeyId = req.params.id;
|
||||||
|
const result = await deleteAPKey(apiKeyId);
|
||||||
|
if (result.success) {
|
||||||
|
return res.status(200).json({ message: "API key deleted successfully" });
|
||||||
|
}
|
||||||
|
return res.status(500).json({ message: "Failed to delete API key" });
|
||||||
|
});
|
||||||
|
|
||||||
|
export default router;
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
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 getAllApiKeys = async () => {
|
||||||
|
const [rows] = await pool.query("SELECT * FROM apiKeys");
|
||||||
|
if (rows.length > 0) {
|
||||||
|
return { success: true, data: rows };
|
||||||
|
}
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const createAPIentry = async (apiKey, entryName) => {
|
||||||
|
const [result] = await pool.query(
|
||||||
|
"INSERT INTO apiKeys (api_key, entry_name) VALUES (?, ?)",
|
||||||
|
[apiKey, entryName]
|
||||||
|
);
|
||||||
|
if (result.affectedRows > 0) return { success: true };
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const deleteAPKey = async (apiKeyId) => {
|
||||||
|
const [result] = await pool.query("DELETE FROM apiKeys WHERE id = ?", [
|
||||||
|
apiKeyId,
|
||||||
|
]);
|
||||||
|
if (result.affectedRows > 0) return { success: true };
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
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 getAllItems = async () => {
|
||||||
|
const [result] = await pool.query("SELECT * FROM items");
|
||||||
|
if (result.length > 0) return { success: true, data: result };
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const deleteItemById = async (itemId) => {
|
||||||
|
const [result] = await pool.query("DELETE FROM items WHERE id = ?", [itemId]);
|
||||||
|
if (result.affectedRows > 0) return { success: true };
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const createItem = async (item_name, can_borrow_role, lockerNumber) => {
|
||||||
|
const [result] = await pool.query(
|
||||||
|
"INSERT INTO items (item_name, can_borrow_role, in_safe, safe_nr) VALUES (?, ?, ?, ?)",
|
||||||
|
[item_name, can_borrow_role, true, lockerNumber]
|
||||||
|
);
|
||||||
|
if (result.affectedRows > 0) return { success: true };
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const editItemById = async (
|
||||||
|
itemId,
|
||||||
|
item_name,
|
||||||
|
can_borrow_role,
|
||||||
|
safe_nr,
|
||||||
|
door_key
|
||||||
|
) => {
|
||||||
|
let newSafeNr;
|
||||||
|
if (safe_nr === null || safe_nr === "") {
|
||||||
|
newSafeNr = null;
|
||||||
|
} else {
|
||||||
|
newSafeNr = safe_nr;
|
||||||
|
}
|
||||||
|
const [result] = await pool.query(
|
||||||
|
"UPDATE items SET item_name = ?, can_borrow_role = ?, safe_nr = ?, door_key = ?, entry_updated_at = NOW() WHERE id = ?",
|
||||||
|
[item_name, can_borrow_role, newSafeNr, door_key, itemId]
|
||||||
|
);
|
||||||
|
if (result.affectedRows > 0) return { success: true };
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const changeSafeState = async (itemId) => {
|
||||||
|
const currentState = await pool.query(
|
||||||
|
"SELECT in_safe FROM items WHERE id = ?",
|
||||||
|
[itemId]
|
||||||
|
);
|
||||||
|
if (currentState[0].length === 0) {
|
||||||
|
return { success: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (currentState[0][0].in_safe) {
|
||||||
|
const [result] = await pool.query(
|
||||||
|
"UPDATE items SET in_safe = false WHERE id = ?",
|
||||||
|
[itemId]
|
||||||
|
);
|
||||||
|
if (result.affectedRows > 0) return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!currentState[0][0].in_safe) {
|
||||||
|
const [result] = await pool.query(
|
||||||
|
"UPDATE items SET in_safe = true WHERE id = ?",
|
||||||
|
[itemId]
|
||||||
|
);
|
||||||
|
if (result.affectedRows > 0) return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
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 getAllLoans = async () => {
|
||||||
|
const [rows] = await pool.query("SELECT * FROM loans WHERE deleted_admin = 0;");
|
||||||
|
return { success: true, data: rows };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const deleteLoanById = async (loanId) => {
|
||||||
|
const [result] = await pool.query(
|
||||||
|
"UPDATE loans SET deleted = true, deleted_admin = true WHERE id = ?",
|
||||||
|
[loanId],
|
||||||
|
);
|
||||||
|
if (result.affectedRows > 0) return { success: true };
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
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 };
|
||||||
|
};
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
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 createUser = async (
|
||||||
|
username,
|
||||||
|
role,
|
||||||
|
password,
|
||||||
|
isAdmin,
|
||||||
|
email,
|
||||||
|
first_name,
|
||||||
|
last_name,
|
||||||
|
) => {
|
||||||
|
const [result] = await pool.query(
|
||||||
|
"INSERT INTO users (username, role, password, is_admin, email, first_name, last_name) VALUES (?, ?, ?, ?, ?, ?, ?)",
|
||||||
|
[username, role, password, isAdmin, email, first_name, last_name],
|
||||||
|
);
|
||||||
|
if (result.affectedRows > 0) return { success: true };
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const deleteUserById = async (userId) => {
|
||||||
|
const [result] = await pool.query("DELETE FROM users WHERE id = ?", [userId]);
|
||||||
|
if (result.affectedRows > 0) return { success: true };
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const changePassword = async (username, newPassword) => {
|
||||||
|
const [result] = await pool.query(
|
||||||
|
"UPDATE users SET password = ?, entry_updated_at = NOW() WHERE username = ?",
|
||||||
|
[newPassword, username],
|
||||||
|
);
|
||||||
|
if (result.affectedRows > 0) return { success: true };
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const editUserById = async (
|
||||||
|
userId,
|
||||||
|
first_name,
|
||||||
|
last_name,
|
||||||
|
role,
|
||||||
|
email,
|
||||||
|
is_admin,
|
||||||
|
) => {
|
||||||
|
const [result] = await pool.query(
|
||||||
|
"UPDATE users SET first_name = ?, last_name = ?, role = ?, email = ?, is_admin = ?, entry_updated_at = NOW() WHERE id = ?",
|
||||||
|
[first_name, last_name, role, email, is_admin, userId],
|
||||||
|
);
|
||||||
|
if (result.affectedRows > 0) return { success: true };
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getAllUsers = async () => {
|
||||||
|
const [result] = await pool.query(
|
||||||
|
"SELECT id, username, first_name, last_name, role, email, is_admin, entry_created_at, entry_updated_at FROM users",
|
||||||
|
);
|
||||||
|
if (result.length > 0) return { success: true, data: result };
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getUserById = async (userId) => {
|
||||||
|
const [rows] = await pool.query(
|
||||||
|
"SELECT id, username, first_name, last_name, role, email, is_admin FROM users WHERE id = ?",
|
||||||
|
[userId],
|
||||||
|
);
|
||||||
|
if (rows.length === 0) {
|
||||||
|
return { success: false };
|
||||||
|
}
|
||||||
|
return { success: true, data: rows[0] };
|
||||||
|
};
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
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 loginAdmin = async (username, password) => {
|
||||||
|
const [rows] = await pool.query(
|
||||||
|
"SELECT id, username, first_name, last_name, role, is_admin FROM users WHERE username = ? AND password = ?",
|
||||||
|
[username, password]
|
||||||
|
);
|
||||||
|
|
||||||
|
if (rows.length === 0) {
|
||||||
|
return { success: false, reason: "invalid_credentials" };
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = rows[0];
|
||||||
|
if (!user.is_admin) {
|
||||||
|
return { success: false, reason: "not_admin" };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: true, data: user };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const executeQuery = async (query, password, username) => {
|
||||||
|
let verified = false;
|
||||||
|
const [user] = await pool.query(
|
||||||
|
"SELECT * FROM users WHERE username = ? AND password = ?",
|
||||||
|
[username, password]
|
||||||
|
);
|
||||||
|
if (user.length > 0 && user[0].is_admin) {
|
||||||
|
verified = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!verified) {
|
||||||
|
return { success: false, message: "Unauthorized" };
|
||||||
|
}
|
||||||
|
const [result] = await pool.query(`${query}`);
|
||||||
|
return { success: true, data: result };
|
||||||
|
};
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import express from "express";
|
||||||
|
import { authenticateAdmin } from "../../services/authentication.js";
|
||||||
|
const router = express.Router();
|
||||||
|
import dotenv from "dotenv";
|
||||||
|
dotenv.config();
|
||||||
|
|
||||||
|
// database funcs import
|
||||||
|
import {
|
||||||
|
editItemById,
|
||||||
|
getAllItems,
|
||||||
|
deleteItemById,
|
||||||
|
createItem,
|
||||||
|
changeSafeState,
|
||||||
|
} from "./database/itemDataMgmt.database.js";
|
||||||
|
|
||||||
|
router.get("/all-items", authenticateAdmin, async (req, res) => {
|
||||||
|
const result = await getAllItems();
|
||||||
|
if (result.success) {
|
||||||
|
return res.status(200).json(result.data);
|
||||||
|
}
|
||||||
|
return res.status(500).json({ message: "Failed to retrieve items" });
|
||||||
|
});
|
||||||
|
|
||||||
|
router.delete("/delete-item/:id", authenticateAdmin, async (req, res) => {
|
||||||
|
const itemId = req.params.id;
|
||||||
|
const result = await deleteItemById(itemId);
|
||||||
|
if (result.success) {
|
||||||
|
return res.status(200).json({ message: "Item deleted successfully" });
|
||||||
|
}
|
||||||
|
return res.status(500).json({ message: "Failed to delete item" });
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post("/create-item", authenticateAdmin, async (req, res) => {
|
||||||
|
const { item_name, can_borrow_role, lockerNumber } = req.body;
|
||||||
|
const result = await createItem(item_name, can_borrow_role, lockerNumber);
|
||||||
|
if (result.success) {
|
||||||
|
return res.status(201).json({ message: "Item created successfully" });
|
||||||
|
}
|
||||||
|
return res.status(500).json({ message: "Failed to create item" });
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post("/edit-item/:id", authenticateAdmin, async (req, res) => {
|
||||||
|
const itemId = req.params.id;
|
||||||
|
const { item_name, can_borrow_role, safe_nr, door_key } = req.body;
|
||||||
|
|
||||||
|
const result = await editItemById(
|
||||||
|
itemId,
|
||||||
|
item_name,
|
||||||
|
can_borrow_role,
|
||||||
|
safe_nr,
|
||||||
|
door_key
|
||||||
|
);
|
||||||
|
if (result.success) {
|
||||||
|
return res.status(200).json({ message: "Item edited successfully" });
|
||||||
|
}
|
||||||
|
return res.status(500).json({ message: "Failed to edit item" });
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post("/change-safe-state/:id", authenticateAdmin, async (req, res) => {
|
||||||
|
const itemId = req.params.id;
|
||||||
|
const result = await changeSafeState(itemId);
|
||||||
|
if (result.success) {
|
||||||
|
return res.status(200).json({ message: "Safe state changed successfully" });
|
||||||
|
}
|
||||||
|
return res.status(500).json({ message: "Failed to change safe state" });
|
||||||
|
});
|
||||||
|
|
||||||
|
export default router;
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import express from "express";
|
||||||
|
import { authenticateAdmin } from "../../services/authentication.js";
|
||||||
|
const router = express.Router();
|
||||||
|
import dotenv from "dotenv";
|
||||||
|
dotenv.config();
|
||||||
|
|
||||||
|
// database funcs import
|
||||||
|
import {
|
||||||
|
deleteLoanById,
|
||||||
|
getAllLoans,
|
||||||
|
} from "./database/loanDataMgmt.database.js";
|
||||||
|
|
||||||
|
router.get("/all-loans", authenticateAdmin, async (req, res) => {
|
||||||
|
const result = await getAllLoans();
|
||||||
|
if (result.success) {
|
||||||
|
return res.status(200).json(result.data);
|
||||||
|
}
|
||||||
|
return res.status(500).json({ message: "Failed to retrieve loans" });
|
||||||
|
});
|
||||||
|
|
||||||
|
router.delete("/delete-loan/:id", authenticateAdmin, async (req, res) => {
|
||||||
|
const loanId = req.params.id;
|
||||||
|
const result = await deleteLoanById(loanId);
|
||||||
|
if (result.success) {
|
||||||
|
return res.status(200).json({ message: "Loan deleted successfully" });
|
||||||
|
}
|
||||||
|
return res.status(500).json({ message: "Failed to delete loan" });
|
||||||
|
});
|
||||||
|
|
||||||
|
export default router;
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
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;
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
import express from "express";
|
||||||
|
import { authenticateAdmin } from "../../services/authentication.js";
|
||||||
|
const router = express.Router();
|
||||||
|
import dotenv from "dotenv";
|
||||||
|
dotenv.config();
|
||||||
|
|
||||||
|
// database funcs import
|
||||||
|
import {
|
||||||
|
createUser,
|
||||||
|
deleteUserById,
|
||||||
|
editUserById,
|
||||||
|
changePassword,
|
||||||
|
getAllUsers,
|
||||||
|
getUserById,
|
||||||
|
} from "./database/userDataMgmt.database.js";
|
||||||
|
|
||||||
|
router.post("/create-user", authenticateAdmin, async (req, res) => {
|
||||||
|
const username = req.body.username;
|
||||||
|
const role = req.body.role;
|
||||||
|
const password = req.body.password;
|
||||||
|
const isAdmin = req.body.isAdmin;
|
||||||
|
const email = req.body.email;
|
||||||
|
const first_name = req.body.first_name;
|
||||||
|
const last_name = req.body.last_name;
|
||||||
|
const result = await createUser(
|
||||||
|
username,
|
||||||
|
role,
|
||||||
|
password,
|
||||||
|
isAdmin,
|
||||||
|
email,
|
||||||
|
first_name,
|
||||||
|
last_name
|
||||||
|
);
|
||||||
|
if (result.success) {
|
||||||
|
return res.status(201).json({ message: "User created successfully" });
|
||||||
|
}
|
||||||
|
return res.status(500).json({ message: "Failed to create user" });
|
||||||
|
});
|
||||||
|
|
||||||
|
router.delete("/delete-user/:id", authenticateAdmin, async (req, res) => {
|
||||||
|
const userId = req.params.id;
|
||||||
|
const result = await deleteUserById(userId);
|
||||||
|
if (result.success) {
|
||||||
|
return res.status(200).json({ message: "User deleted successfully" });
|
||||||
|
}
|
||||||
|
return res.status(500).json({ message: "Failed to delete user" });
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post("/edit-user/:id", authenticateAdmin, async (req, res) => {
|
||||||
|
const first_name = req.body.first_name;
|
||||||
|
const last_name = req.body.last_name;
|
||||||
|
const role = req.body.role;
|
||||||
|
const email = req.body.email;
|
||||||
|
const userId = req.params.id;
|
||||||
|
const is_admin = req.body.is_admin;
|
||||||
|
|
||||||
|
const result = await editUserById(
|
||||||
|
userId,
|
||||||
|
first_name,
|
||||||
|
last_name,
|
||||||
|
role,
|
||||||
|
email,
|
||||||
|
is_admin
|
||||||
|
);
|
||||||
|
|
||||||
|
if (result.success) {
|
||||||
|
return res.status(200).json({ message: "User edited successfully" });
|
||||||
|
}
|
||||||
|
return res.status(500).json({ message: "Failed to edit user" });
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post("/change-password", authenticateAdmin, async (req, res) => {
|
||||||
|
const username = req.body.username;
|
||||||
|
const password = req.body.password;
|
||||||
|
|
||||||
|
const result = await changePassword(username, password);
|
||||||
|
|
||||||
|
if (result.success) {
|
||||||
|
return res.status(200).json({ message: "Password reset successfully" });
|
||||||
|
}
|
||||||
|
return res.status(500).json({ message: "Failed to reset password" });
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post("/edit-user/:id", authenticateAdmin, async (req, res) => {
|
||||||
|
const userId = req.params.id;
|
||||||
|
const first_name = req.body.first_name;
|
||||||
|
const last_name = req.body.last_name;
|
||||||
|
const role = req.body.role;
|
||||||
|
const email = req.body.email;
|
||||||
|
const is_admin = req.body.is_admin;
|
||||||
|
|
||||||
|
const result = await editUserById(
|
||||||
|
userId,
|
||||||
|
first_name,
|
||||||
|
last_name,
|
||||||
|
role,
|
||||||
|
email,
|
||||||
|
is_admin
|
||||||
|
);
|
||||||
|
|
||||||
|
if (result.success) {
|
||||||
|
return res.status(200).json({ message: "User edited successfully" });
|
||||||
|
}
|
||||||
|
return res.status(500).json({ message: "Failed to edit user" });
|
||||||
|
});
|
||||||
|
|
||||||
|
router.get("/users", authenticateAdmin, async (req, res) => {
|
||||||
|
const result = await getAllUsers();
|
||||||
|
if (result.success) {
|
||||||
|
return res.status(200).json(result.data);
|
||||||
|
}
|
||||||
|
return res.status(500).json({ message: "Failed to retrieve users" });
|
||||||
|
});
|
||||||
|
|
||||||
|
router.get("/user/:id", authenticateAdmin, async (req, res) => {
|
||||||
|
const result = await getUserById(req.params.id);
|
||||||
|
if (result.success) {
|
||||||
|
return res.status(200).json({ user: result.data });
|
||||||
|
}
|
||||||
|
return res.status(500).json({ message: "Failed to retrieve user" });
|
||||||
|
});
|
||||||
|
|
||||||
|
export default router;
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import express from "express";
|
||||||
|
import {
|
||||||
|
generateToken,
|
||||||
|
authenticateAdmin,
|
||||||
|
} from "../../services/authentication.js";
|
||||||
|
const router = express.Router();
|
||||||
|
import dotenv from "dotenv";
|
||||||
|
dotenv.config();
|
||||||
|
|
||||||
|
// database funcs import
|
||||||
|
import { loginAdmin, executeQuery } from "./database/userMgmt.database.js";
|
||||||
|
|
||||||
|
router.post("/login", async (req, res) => {
|
||||||
|
const { username, password } = req.body || {};
|
||||||
|
if (!username || !password) {
|
||||||
|
return res.status(400).json({ message: "Missing username or password" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await loginAdmin(username, password);
|
||||||
|
|
||||||
|
if (result.success) {
|
||||||
|
const token = await generateToken({
|
||||||
|
username: result.data.username,
|
||||||
|
first_name: result.data.first_name,
|
||||||
|
last_name: result.data.last_name,
|
||||||
|
admin: result.data.is_admin,
|
||||||
|
});
|
||||||
|
return res.status(200).json({
|
||||||
|
message: "Login erfolgreich",
|
||||||
|
token,
|
||||||
|
first_name: result.data.first_name,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.reason === "not_admin") {
|
||||||
|
return res.status(403).json({ message: "Du bist kein Admin" });
|
||||||
|
}
|
||||||
|
|
||||||
|
return res.status(401).json({ message: "Ungültige Anmeldedaten" });
|
||||||
|
});
|
||||||
|
|
||||||
|
router.get("/verify-token", authenticateAdmin, async (req, res) => {
|
||||||
|
return res.status(200).json({ message: "Token is valid" });
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post("/database-query", authenticateAdmin, async (req, res) => {
|
||||||
|
const query = req.body.query;
|
||||||
|
const password = req.body.password;
|
||||||
|
const username = req.body.username;
|
||||||
|
|
||||||
|
const result = await executeQuery(query, password, username);
|
||||||
|
});
|
||||||
|
|
||||||
|
export default router;
|
||||||
@@ -1,147 +0,0 @@
|
|||||||
import express from "express";
|
|
||||||
import {
|
|
||||||
loginFunc,
|
|
||||||
getItemsFromDatabase,
|
|
||||||
getLoansFromDatabase,
|
|
||||||
getUserLoansFromDatabase,
|
|
||||||
deleteLoanFromDatabase,
|
|
||||||
getBorrowableItemsFromDatabase,
|
|
||||||
createLoanInDatabase,
|
|
||||||
} from "../services/database.js";
|
|
||||||
import { authenticate, generateToken } from "../services/tokenService.js";
|
|
||||||
const router = express.Router();
|
|
||||||
|
|
||||||
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,
|
|
||||||
role: result.data.role,
|
|
||||||
});
|
|
||||||
res.status(200).json({ message: "Login successful", token });
|
|
||||||
} else {
|
|
||||||
res.status(401).json({ message: "Invalid credentials" });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
router.get("/items", authenticate, async (req, res) => {
|
|
||||||
console.log(req);
|
|
||||||
const result = await getItemsFromDatabase(req.user.role);
|
|
||||||
if (result.success) {
|
|
||||||
res.status(200).json(result.data);
|
|
||||||
} else {
|
|
||||||
res.status(500).json({ message: "Failed to fetch items" });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
router.get("/loans", authenticate, async (req, res) => {
|
|
||||||
const result = await getLoansFromDatabase();
|
|
||||||
if (result.success) {
|
|
||||||
res.status(200).json(result.data);
|
|
||||||
} else {
|
|
||||||
res.status(500).json({ message: "Failed to fetch loans" });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
router.get("/userLoans", authenticate, async (req, res) => {
|
|
||||||
const result = await getUserLoansFromDatabase(req.user.username);
|
|
||||||
if (result.success) {
|
|
||||||
res.status(200).json(result.data);
|
|
||||||
} else {
|
|
||||||
res.status(500).json({ message: "Failed to fetch user loans" });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
router.delete("/deleteLoan/:id", authenticate, async (req, res) => {
|
|
||||||
const loanId = req.params.id;
|
|
||||||
const result = await deleteLoanFromDatabase(loanId);
|
|
||||||
if (result.success) {
|
|
||||||
res.status(200).json({ message: "Loan deleted successfully" });
|
|
||||||
} else {
|
|
||||||
res.status(500).json({ message: "Failed to delete loan" });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
router.post("/borrowableItems", 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" });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
router.post("/createLoan", authenticate, async (req, res) => {
|
|
||||||
try {
|
|
||||||
const { items, startDate, endDate } = 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,
|
|
||||||
itemIds
|
|
||||||
);
|
|
||||||
|
|
||||||
if (result.success) {
|
|
||||||
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" });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
export default router;
|
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
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 getItemsFromDatabaseV2 = async () => {
|
||||||
|
const [rows] = await pool.query("SELECT * FROM items;");
|
||||||
|
if (rows.length > 0) {
|
||||||
|
return { success: true, data: rows };
|
||||||
|
}
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getLoanByCodeV2 = async (loan_code) => {
|
||||||
|
const [result] = await pool.query(
|
||||||
|
"SELECT username, returned_date, take_date, lockers FROM loans WHERE loan_code = ?;",
|
||||||
|
[loan_code],
|
||||||
|
);
|
||||||
|
if (result.length > 0) {
|
||||||
|
return { success: true, data: result[0] };
|
||||||
|
}
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const changeInSafeStateV2 = async (itemId) => {
|
||||||
|
const [result] = await pool.query(
|
||||||
|
"UPDATE items SET in_safe = NOT in_safe WHERE id = ?",
|
||||||
|
[itemId],
|
||||||
|
);
|
||||||
|
if (result.affectedRows > 0) {
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
|
|
||||||
|
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(
|
||||||
|
"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, 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 = 0, currently_borrowing = (?) WHERE id IN (?)",
|
||||||
|
[owner[0].username, itemIds],
|
||||||
|
);
|
||||||
|
|
||||||
|
const [result] = await pool.query(
|
||||||
|
"UPDATE loans SET take_date = NOW() WHERE loan_code = ? AND take_date IS NULL",
|
||||||
|
[loanCode],
|
||||||
|
);
|
||||||
|
|
||||||
|
if (result.affectedRows > 0 && setItemStates.affectedRows > 0) {
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
return { message: "Failed to set take date", success: false };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const openDoor = async (doorKey) => {
|
||||||
|
const [result] = await pool.query(
|
||||||
|
"SELECT safe_nr, id FROM items WHERE door_key = ?;",
|
||||||
|
[doorKey],
|
||||||
|
);
|
||||||
|
if (result.length > 0) {
|
||||||
|
const [changeItemSate] = await pool.query(
|
||||||
|
"UPDATE items SET in_safe = NOT in_safe WHERE id = ?",
|
||||||
|
[result[0].id],
|
||||||
|
);
|
||||||
|
if (changeItemSate.affectedRows > 0) {
|
||||||
|
return { success: true, data: result[0] };
|
||||||
|
} else {
|
||||||
|
return { success: false };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
import express from "express";
|
||||||
|
import { authenticate } from "../../services/authentication.js";
|
||||||
|
import { checkIfServiceIsActive } from "../../services/functions.js";
|
||||||
|
const router = express.Router();
|
||||||
|
import dotenv from "dotenv";
|
||||||
|
dotenv.config();
|
||||||
|
|
||||||
|
const loan_service = "Loan Service";
|
||||||
|
|
||||||
|
import {
|
||||||
|
getItemsFromDatabaseV2,
|
||||||
|
changeInSafeStateV2,
|
||||||
|
setTakeDateV2,
|
||||||
|
setReturnDateV2,
|
||||||
|
getLoanByCodeV2,
|
||||||
|
openDoor,
|
||||||
|
} from "./api.database.js";
|
||||||
|
|
||||||
|
// Route for API to get all items from the database
|
||||||
|
router.get("/items/:key", authenticate, async (req, res) => {
|
||||||
|
const result = await getItemsFromDatabaseV2();
|
||||||
|
if (result.success) {
|
||||||
|
res.status(200).json({ data: result.data });
|
||||||
|
} else {
|
||||||
|
res.status(500).json({ message: "Failed to fetch items" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Route for API to control the safe state of an item
|
||||||
|
router.post("/change-state/:key/:itemId", authenticate, async (req, res) => {
|
||||||
|
const itemId = req.params.itemId;
|
||||||
|
|
||||||
|
const result = await changeInSafeStateV2(itemId);
|
||||||
|
if (result.success) {
|
||||||
|
res.status(200).json({ data: result.data });
|
||||||
|
} else {
|
||||||
|
res.status(500).json({ message: "Failed to update item state" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Route for API to get a loan by its code
|
||||||
|
router.get(
|
||||||
|
"/get-loan-by-code/:key/:loan_code",
|
||||||
|
authenticate,
|
||||||
|
checkIfServiceIsActive(loan_service),
|
||||||
|
async (req, res) => {
|
||||||
|
const loan_code = req.params.loan_code;
|
||||||
|
const result = await getLoanByCodeV2(loan_code);
|
||||||
|
if (result.success) {
|
||||||
|
res.status(200).json({ data: result.data });
|
||||||
|
} else {
|
||||||
|
res.status(404).json({ message: "Loan not found" });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// Route for API to set the return date by the loan code
|
||||||
|
router.post(
|
||||||
|
"/set-return-date/:key/:loan_code",
|
||||||
|
authenticate,
|
||||||
|
checkIfServiceIsActive(loan_service),
|
||||||
|
async (req, res) => {
|
||||||
|
const loanCode = req.params.loan_code;
|
||||||
|
const result = await setReturnDateV2(loanCode);
|
||||||
|
if (result.success) {
|
||||||
|
res.status(200).json({});
|
||||||
|
} else {
|
||||||
|
res.status(500).json({ message: "Failed to set return date" });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// Route for API to set the take away date by the loan code
|
||||||
|
router.post(
|
||||||
|
"/set-take-date/:key/:loan_code",
|
||||||
|
authenticate,
|
||||||
|
checkIfServiceIsActive(loan_service),
|
||||||
|
async (req, res) => {
|
||||||
|
const loanCode = req.params.loan_code;
|
||||||
|
const result = await setTakeDateV2(loanCode);
|
||||||
|
if (result.success) {
|
||||||
|
res.status(200).json({});
|
||||||
|
} else {
|
||||||
|
res.status(500).json({ message: result.message });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// Route for API to open a door
|
||||||
|
router.get("/open-door/:key/:doorKey", authenticate, async (req, res) => {
|
||||||
|
const doorKey = req.params.doorKey;
|
||||||
|
|
||||||
|
const result = await openDoor(doorKey);
|
||||||
|
if (result.success) {
|
||||||
|
res.status(200).json({ data: result.data });
|
||||||
|
} else {
|
||||||
|
res.status(500).json({ message: "Failed to open door" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export default router;
|
||||||
@@ -1,93 +0,0 @@
|
|||||||
import express from "express";
|
|
||||||
import dotenv from "dotenv";
|
|
||||||
import {
|
|
||||||
getItemsFromDatabaseV2,
|
|
||||||
changeInSafeStateV2,
|
|
||||||
setReturnDateV2,
|
|
||||||
setTakeDateV2,
|
|
||||||
getLoanByCodeV2,
|
|
||||||
} from "../services/database.js";
|
|
||||||
|
|
||||||
dotenv.config();
|
|
||||||
const router = express.Router();
|
|
||||||
|
|
||||||
// Route for API to get ALL items from the database
|
|
||||||
router.get("/items/:key", async (req, res) => {
|
|
||||||
if (req.params.key === process.env.ADMIN_ID) {
|
|
||||||
const result = await getItemsFromDatabaseV2();
|
|
||||||
if (result.success) {
|
|
||||||
res.status(200).json({ data: result.data });
|
|
||||||
} else {
|
|
||||||
res.status(500).json({ message: "Failed to fetch items" });
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
res.status(403).json({ message: "Access denied" });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Route for API to control the position of an item
|
|
||||||
router.post("/controlInSafe/:key/:itemId/:state", async (req, res) => {
|
|
||||||
if (req.params.key === process.env.ADMIN_ID) {
|
|
||||||
const itemId = req.params.itemId;
|
|
||||||
const state = req.params.state;
|
|
||||||
if (state === "1" || state === "0") {
|
|
||||||
const result = await changeInSafeStateV2(itemId, state);
|
|
||||||
if (result.success) {
|
|
||||||
res.status(200).json({ data: result.data });
|
|
||||||
} else {
|
|
||||||
res.status(500).json({ message: "Failed to update item state" });
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
res.status(400).json({ message: "Invalid state value" });
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
res.status(403).json({ message: "Access denied" });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
router.get("/getLoanByCode/:key/:loan_code", async (req, res) => {
|
|
||||||
if (req.params.key === process.env.ADMIN_ID) {
|
|
||||||
const loan_code = req.params.loan_code;
|
|
||||||
|
|
||||||
const result = await getLoanByCodeV2(loan_code);
|
|
||||||
if (result.success) {
|
|
||||||
res.status(200).json({ data: result.data });
|
|
||||||
} else {
|
|
||||||
res.status(404).json({ message: "Loan not found" });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Route for API to set the return date
|
|
||||||
router.post("/setReturnDate/:key/:loan_code", async (req, res) => {
|
|
||||||
if (req.params.key === process.env.ADMIN_ID) {
|
|
||||||
const loanCode = req.params.loan_code;
|
|
||||||
|
|
||||||
const result = await setReturnDateV2(loanCode);
|
|
||||||
if (result.success) {
|
|
||||||
res.status(200).json({ data: result.data });
|
|
||||||
} else {
|
|
||||||
res.status(500).json({ message: "Failed to set return date" });
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
res.status(403).json({ message: "Access denied" });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Route for API to set the take away date
|
|
||||||
router.post("/setTakeDate/:key/:loan_code", async (req, res) => {
|
|
||||||
if (req.params.key === process.env.ADMIN_ID) {
|
|
||||||
const loanCode = req.params.loan_code;
|
|
||||||
|
|
||||||
const result = await setTakeDateV2(loanCode);
|
|
||||||
if (result.success) {
|
|
||||||
res.status(200).json({ data: result.data });
|
|
||||||
} else {
|
|
||||||
res.status(500).json({ message: "Failed to set take date" });
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
res.status(403).json({ message: "Access denied" });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
export default router;
|
|
||||||
@@ -0,0 +1,340 @@
|
|||||||
|
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 createLoanInDatabase = async (
|
||||||
|
username,
|
||||||
|
startDate,
|
||||||
|
endDate,
|
||||||
|
note,
|
||||||
|
itemIds,
|
||||||
|
) => {
|
||||||
|
if (!username)
|
||||||
|
return { success: false, code: "BAD_REQUEST", message: "Missing username" };
|
||||||
|
if (!Array.isArray(itemIds) || itemIds.length === 0)
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
code: "BAD_REQUEST",
|
||||||
|
message: "No items provided",
|
||||||
|
};
|
||||||
|
if (!startDate || !endDate)
|
||||||
|
return { success: false, code: "BAD_REQUEST", message: "Missing dates" };
|
||||||
|
|
||||||
|
const start = new Date(startDate);
|
||||||
|
const end = new Date(endDate);
|
||||||
|
if (
|
||||||
|
!(start instanceof Date) ||
|
||||||
|
isNaN(start.getTime()) ||
|
||||||
|
!(end instanceof Date) ||
|
||||||
|
isNaN(end.getTime()) ||
|
||||||
|
start >= end
|
||||||
|
) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
code: "BAD_REQUEST",
|
||||||
|
message: "Invalid date range",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const conn = await pool.getConnection();
|
||||||
|
try {
|
||||||
|
await conn.beginTransaction();
|
||||||
|
|
||||||
|
// Ensure all items exist and collect names + lockers
|
||||||
|
const [itemsRows] = await conn.query(
|
||||||
|
"SELECT id, item_name, safe_nr FROM items WHERE id IN (?)",
|
||||||
|
[itemIds],
|
||||||
|
);
|
||||||
|
if (!itemsRows || itemsRows.length !== itemIds.length) {
|
||||||
|
await conn.rollback();
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
code: "BAD_REQUEST",
|
||||||
|
message: "One or more items not found",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const itemNames = itemIds.map(
|
||||||
|
(id) => itemsRows.find((r) => Number(r.id) === Number(id)).item_name,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Build lockers array (unique, only 2-digit numbers from safe_nr)
|
||||||
|
const lockers = [
|
||||||
|
...new Set(
|
||||||
|
itemsRows
|
||||||
|
.map((r) => r.safe_nr)
|
||||||
|
.filter(
|
||||||
|
(sn) =>
|
||||||
|
sn !== null &&
|
||||||
|
sn !== undefined &&
|
||||||
|
Number.isInteger(Number(sn)) &&
|
||||||
|
Number(sn) >= 0 &&
|
||||||
|
Number(sn) <= 99,
|
||||||
|
)
|
||||||
|
.map((sn) => Number(sn)),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
|
||||||
|
// Check availability (no overlap with existing loans)
|
||||||
|
const [confRows] = await conn.query(
|
||||||
|
`
|
||||||
|
SELECT COUNT(*) AS conflicts
|
||||||
|
FROM loans l
|
||||||
|
JOIN JSON_TABLE(l.loaned_items_id, '$[*]' COLUMNS (item_id INT PATH '$')) jt
|
||||||
|
ON TRUE
|
||||||
|
WHERE jt.item_id IN (?)
|
||||||
|
AND l.deleted = 0
|
||||||
|
AND l.start_date < ?
|
||||||
|
AND COALESCE(l.returned_date, l.end_date) > ?
|
||||||
|
`,
|
||||||
|
[itemIds, end, start],
|
||||||
|
);
|
||||||
|
if (confRows?.[0]?.conflicts > 0) {
|
||||||
|
await conn.rollback();
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
code: "CONFLICT",
|
||||||
|
message: "One or more items are not available in the selected period",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
let index = false;
|
||||||
|
let candidate;
|
||||||
|
let loanCode;
|
||||||
|
|
||||||
|
// Generates 6-digit loan code
|
||||||
|
do {
|
||||||
|
candidate = Math.floor(100000 + Math.random() * 899999);
|
||||||
|
|
||||||
|
const [rows] = await conn.query(
|
||||||
|
"SELECT 1 FROM loans where loan_code = ? LIMIT 1",
|
||||||
|
[candidate],
|
||||||
|
);
|
||||||
|
|
||||||
|
if (rows.length == 0) {
|
||||||
|
index = true;
|
||||||
|
loanCode = candidate;
|
||||||
|
}
|
||||||
|
} while (index === false);
|
||||||
|
|
||||||
|
// Insert loan (now includes lockers)
|
||||||
|
const [insertRes] = await conn.query(
|
||||||
|
`
|
||||||
|
INSERT INTO loans (username, loan_code, start_date, end_date, lockers, loaned_items_id, loaned_items_name, note)
|
||||||
|
VALUES (?, ?, ?, ?, CAST(? AS JSON), CAST(? AS JSON), CAST(? AS JSON), ?)
|
||||||
|
`,
|
||||||
|
[
|
||||||
|
username,
|
||||||
|
loanCode,
|
||||||
|
new Date(start).toISOString().slice(0, 19).replace("T", " "),
|
||||||
|
new Date(end).toISOString().slice(0, 19).replace("T", " "),
|
||||||
|
JSON.stringify(lockers),
|
||||||
|
JSON.stringify(itemIds.map((n) => Number(n))),
|
||||||
|
JSON.stringify(itemNames),
|
||||||
|
note,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
await conn.commit();
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
data: {
|
||||||
|
id: insertRes.insertId,
|
||||||
|
loan_code: loanCode,
|
||||||
|
username,
|
||||||
|
start_date: start,
|
||||||
|
end_date: end,
|
||||||
|
items: itemIds,
|
||||||
|
item_names: itemNames,
|
||||||
|
lockers,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
} catch (err) {
|
||||||
|
await conn.rollback();
|
||||||
|
console.error("createLoanInDatabase error:", err);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
code: "SERVER_ERROR",
|
||||||
|
message: "Failed to create loan",
|
||||||
|
};
|
||||||
|
} finally {
|
||||||
|
conn.release();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getLoanInfoWithID = async (loanId) => {
|
||||||
|
const [rows] = await pool.query("SELECT * FROM loans WHERE id = ?;", [
|
||||||
|
loanId,
|
||||||
|
]);
|
||||||
|
if (rows.length > 0) {
|
||||||
|
return { success: true, data: rows[0] };
|
||||||
|
}
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getLoansFromDatabase = async (username) => {
|
||||||
|
const [result] = await pool.query(
|
||||||
|
"SELECT * FROM loans WHERE username = ? AND deleted = 0;",
|
||||||
|
[username],
|
||||||
|
);
|
||||||
|
if (result.length > 0) {
|
||||||
|
return { success: true, status: true, data: result };
|
||||||
|
} else if (result.length === 0) {
|
||||||
|
return { success: true, status: true, data: [] };
|
||||||
|
}
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getBorrowableItemsFromDatabase = async (
|
||||||
|
startDate,
|
||||||
|
endDate,
|
||||||
|
role = 0,
|
||||||
|
) => {
|
||||||
|
// Overlap if: loan.start < end AND effective_end > start
|
||||||
|
// effective_end is returned_date if set, otherwise end_date
|
||||||
|
const hasRoleFilter = Number(role) > 0;
|
||||||
|
|
||||||
|
const sql = `
|
||||||
|
SELECT i.*
|
||||||
|
FROM items i
|
||||||
|
WHERE ${hasRoleFilter ? "i.can_borrow_role >= ? AND " : ""}NOT EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM loans l
|
||||||
|
JOIN JSON_TABLE(l.loaned_items_id, '$[*]' COLUMNS (item_id INT PATH '$')) jt
|
||||||
|
WHERE jt.item_id = i.id
|
||||||
|
AND l.deleted = 0
|
||||||
|
AND l.start_date < ?
|
||||||
|
AND COALESCE(l.returned_date, l.end_date) > ?
|
||||||
|
);
|
||||||
|
`;
|
||||||
|
|
||||||
|
const params = hasRoleFilter
|
||||||
|
? [role, endDate, startDate]
|
||||||
|
: [endDate, startDate];
|
||||||
|
|
||||||
|
const [rows] = await pool.query(sql, params);
|
||||||
|
if (rows.length > 0) {
|
||||||
|
return { success: true, data: rows };
|
||||||
|
}
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
|
|
||||||
|
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(
|
||||||
|
"UPDATE loans SET deleted = 1 WHERE id = ?;",
|
||||||
|
[loanId],
|
||||||
|
);
|
||||||
|
if (result.affectedRows > 0) {
|
||||||
|
return { success: true };
|
||||||
|
} else {
|
||||||
|
return { success: false };
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getALLLoans = async () => {
|
||||||
|
const [result] = await pool.query("SELECT * FROM loans WHERE deleted = 0;");
|
||||||
|
if (result.length > 0) {
|
||||||
|
return { success: true, data: result };
|
||||||
|
}
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getItems = async () => {
|
||||||
|
const [result] = await pool.query("SELECT * FROM items;");
|
||||||
|
if (result.length > 0) {
|
||||||
|
return { success: true, data: result };
|
||||||
|
}
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const setReturnDate = 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)
|
||||||
|
? 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 setTakeDate = 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)
|
||||||
|
? items[0].loaned_items_id
|
||||||
|
: JSON.parse(items[0].loaned_items_id || "[]");
|
||||||
|
|
||||||
|
const [setItemStates] = await pool.query(
|
||||||
|
"UPDATE items SET in_safe = 0, currently_borrowing = (?) WHERE id IN (?)",
|
||||||
|
[owner[0].username, itemIds],
|
||||||
|
);
|
||||||
|
|
||||||
|
const [result] = await pool.query(
|
||||||
|
"UPDATE loans SET take_date = NOW() WHERE loan_code = ?",
|
||||||
|
[loanCode],
|
||||||
|
);
|
||||||
|
|
||||||
|
if (result.affectedRows > 0 && setItemStates.affectedRows > 0) {
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
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 loginFunc = async (username, password) => {
|
||||||
|
const [result] = await pool.query(
|
||||||
|
"SELECT * FROM users WHERE username = ? AND password = ?",
|
||||||
|
[username, password],
|
||||||
|
);
|
||||||
|
if (result.length > 0) return { success: true, data: result[0] };
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getItems = async () => {
|
||||||
|
const [rows] = await pool.query("SELECT * FROM items;");
|
||||||
|
if (rows.length > 0) {
|
||||||
|
return { success: true, data: rows };
|
||||||
|
}
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getALLLoans = async () => {
|
||||||
|
const [rows] = await pool.query("SELECT * FROM loans;");
|
||||||
|
if (rows.length > 0) {
|
||||||
|
return { success: true, data: rows };
|
||||||
|
}
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const changePassword = async (username, oldPassword, newPassword) => {
|
||||||
|
// get user current password
|
||||||
|
const [user] = await pool.query(
|
||||||
|
"SELECT * FROM users WHERE username = ? AND password = ?",
|
||||||
|
[username, oldPassword],
|
||||||
|
);
|
||||||
|
if (user.length === 0) return { success: false };
|
||||||
|
|
||||||
|
// update password
|
||||||
|
|
||||||
|
const [result] = await pool.query(
|
||||||
|
"UPDATE users SET password = ? WHERE username = ?",
|
||||||
|
[newPassword, username],
|
||||||
|
);
|
||||||
|
if (result.affectedRows > 0) return { success: true };
|
||||||
|
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,237 @@
|
|||||||
|
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;
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
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,80 +0,0 @@
|
|||||||
-- All necessary tables for the borrowing system
|
|
||||||
|
|
||||||
-- IMPORTANT: You need mySQL version 8.0 or newer!
|
|
||||||
|
|
||||||
CREATE TABLE `users` (
|
|
||||||
`id` int NOT NULL AUTO_INCREMENT,
|
|
||||||
`username` varchar(100) NOT NULL,
|
|
||||||
`password` varchar(255) NOT NULL,
|
|
||||||
`role` int DEFAULT NULL,
|
|
||||||
`entry_created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
|
|
||||||
PRIMARY KEY (`id`),
|
|
||||||
UNIQUE KEY `username` (`username`)
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE TABLE `loans` (
|
|
||||||
`id` int NOT NULL AUTO_INCREMENT,
|
|
||||||
`username` varchar(100) NOT NULL,
|
|
||||||
`loan_code` int NOT NULL,
|
|
||||||
`start_date` timestamp NOT NULL,
|
|
||||||
`end_date` timestamp NOT NULL,
|
|
||||||
`take_date` timestamp NULL DEFAULT NULL,
|
|
||||||
`returned_date` timestamp NULL DEFAULT NULL,
|
|
||||||
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
|
|
||||||
`loaned_items_id` json NOT NULL DEFAULT ('[]'),
|
|
||||||
`loaned_items_name` json NOT NULL DEFAULT ('[]'),
|
|
||||||
PRIMARY KEY (`id`),
|
|
||||||
UNIQUE KEY `loan_code` (`loan_code`)
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE TABLE `items` (
|
|
||||||
`id` int NOT NULL AUTO_INCREMENT,
|
|
||||||
`item_name` varchar(255) NOT NULL,
|
|
||||||
`can_borrow_role` INT NOT NULL,
|
|
||||||
`inSafe` tinyint(1) NOT NULL DEFAULT '1',
|
|
||||||
`entry_created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
|
|
||||||
PRIMARY KEY (`id`),
|
|
||||||
UNIQUE KEY `item_name` (`item_name`)
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE TABLE `lockers` (
|
|
||||||
`id` int NOT NULL AUTO_INCREMENT,
|
|
||||||
`item` varchar(255) NOT NULL,
|
|
||||||
`locker_number` int NOT NULL,
|
|
||||||
`entry_created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
|
|
||||||
PRIMARY KEY (`id`),
|
|
||||||
UNIQUE KEY `item` (`item`),
|
|
||||||
UNIQUE KEY `locker_number` (`locker_number`)
|
|
||||||
);
|
|
||||||
|
|
||||||
INSERT INTO `items` (`item_name`, `can_borrow_role`, `inSafe`) VALUES
|
|
||||||
('DJI 1er Mikro', 4, 1),
|
|
||||||
('DJI 2er Mikro 1', 4, 1),
|
|
||||||
('DJI 2er Mikro 2', 4, 1),
|
|
||||||
('Rode Richt Mikrofon', 2, 1),
|
|
||||||
('Kamera Stativ', 1, 0),
|
|
||||||
('SONY Kamera - inkl. Akkus und Objektiv', 1, 1),
|
|
||||||
('MacBook inkl. Adapter', 2, 0),
|
|
||||||
('SD Karten', 3, 0),
|
|
||||||
('Kameragimbal', 1, 0),
|
|
||||||
('ATEM MINI PRO', 1, 1),
|
|
||||||
('Handygimbal', 4, 0),
|
|
||||||
('Kameralüfter', 1, 1),
|
|
||||||
('Kleine Kamera 1 - inkl. Objektiv', 2, 1),
|
|
||||||
('Kleine Kamera 2 - inkl. Objektiv', 2, 1);
|
|
||||||
|
|
||||||
INSERT INTO `lockers` (`item`, `locker_number`) VALUES
|
|
||||||
('DJI 1er Mikro', 1),
|
|
||||||
('DJI 2er Mikro 1', 2),
|
|
||||||
('DJI 2er Mikro 2', 3),
|
|
||||||
('Rode Richt Mikrofon', 4),
|
|
||||||
('Kamera Stativ', 5),
|
|
||||||
('SONY Kamera - inkl. Akkus und Objektiv', 6),
|
|
||||||
('MacBook inkl. Adapter', 7),
|
|
||||||
('SD Karten', 8),
|
|
||||||
('Kameragimbal', 9),
|
|
||||||
('ATEM MINI PRO', 10),
|
|
||||||
('Handygimbal', 11),
|
|
||||||
('Kameralüfter', 12),
|
|
||||||
('Kleine Kamera 1 - inkl. Objektiv', 13),
|
|
||||||
('Kleine Kamera 2 - inkl. Objektiv', 14);
|
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
use borrow_system_new;
|
||||||
|
|
||||||
|
CREATE TABLE users (
|
||||||
|
id int NOT NULL AUTO_INCREMENT,
|
||||||
|
username varchar(100) NOT NULL UNIQUE,
|
||||||
|
password varchar(255) NOT NULL,
|
||||||
|
email varchar(255) NOT NULL,
|
||||||
|
first_name varchar(255) NOT NULL,
|
||||||
|
last_name varchar(255) NOT NULL,
|
||||||
|
role int NOT NULL,
|
||||||
|
is_admin bool NOT NULL DEFAULT false,
|
||||||
|
entry_created_at timestamp NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
entry_updated_at timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
PRIMARY KEY (id)
|
||||||
|
) ENGINE=InnoDB;
|
||||||
|
|
||||||
|
CREATE TABLE loans (
|
||||||
|
id int NOT NULL AUTO_INCREMENT,
|
||||||
|
username varchar(100) NOT NULL,
|
||||||
|
lockers json NOT NULL DEFAULT ('[]'),
|
||||||
|
loan_code Char(6) NOT NULL UNIQUE,
|
||||||
|
start_date timestamp NOT NULL,
|
||||||
|
end_date timestamp NOT NULL,
|
||||||
|
take_date timestamp NULL DEFAULT NULL,
|
||||||
|
returned_date timestamp NULL DEFAULT NULL,
|
||||||
|
created_at timestamp NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
loaned_items_id json NOT NULL DEFAULT ('[]'),
|
||||||
|
loaned_items_name json NOT NULL DEFAULT ('[]'),
|
||||||
|
deleted bool NOT NULL DEFAULT false,
|
||||||
|
deleted_admin bool NOT NULL DEFAULT false,
|
||||||
|
note varchar(500) DEFAULT NULL,
|
||||||
|
PRIMARY KEY (id),
|
||||||
|
CHECK (loan_code REGEXP '^[0-9]{6}$')
|
||||||
|
) ENGINE=InnoDB;
|
||||||
|
|
||||||
|
CREATE TABLE items (
|
||||||
|
id int NOT NULL AUTO_INCREMENT,
|
||||||
|
item_name varchar(255) NOT NULL UNIQUE,
|
||||||
|
can_borrow_role INT NOT NULL,
|
||||||
|
in_safe bool NOT NULL DEFAULT true,
|
||||||
|
safe_nr INT DEFAULT NULL UNIQUE,
|
||||||
|
door_key INT DEFAULT NULL UNIQUE,
|
||||||
|
entry_created_at timestamp NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
entry_updated_at timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
last_borrowed_person varchar(255) DEFAULT NULL,
|
||||||
|
currently_borrowing varchar(255) DEFAULT NULL,
|
||||||
|
PRIMARY KEY (id)
|
||||||
|
) ENGINE=InnoDB;
|
||||||
|
|
||||||
|
CREATE TABLE apiKeys (
|
||||||
|
id INT NOT NULL AUTO_INCREMENT,
|
||||||
|
api_key CHAR(8) NOT NULL UNIQUE,
|
||||||
|
entry_name VARCHAR(100) NOT NULL,
|
||||||
|
last_used_at TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
entry_created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
PRIMARY KEY (id),
|
||||||
|
CHECK (api_key REGEXP '^[0-9]{8}$')
|
||||||
|
) 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")
|
||||||
+72
-13
@@ -1,32 +1,91 @@
|
|||||||
import express from "express";
|
import express from "express";
|
||||||
import cors from "cors";
|
import cors from "cors";
|
||||||
import env from "dotenv";
|
import dotenv from "dotenv";
|
||||||
import apiRouter from "./routes/api.js";
|
import info from "./info.json" with { type: "json" };
|
||||||
import apiRouterV2 from "./routes/apiV2.js";
|
import { authenticate } from "./services/authentication.js";
|
||||||
env.config();
|
import { rateLimit } from "express-rate-limit";
|
||||||
|
|
||||||
|
dotenv.config();
|
||||||
const app = express();
|
const app = express();
|
||||||
const port = 8002;
|
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
|
||||||
|
import loansMgmtRouter from "./routes/app/loanMgmt.route.js";
|
||||||
|
import userMgmtRouterAPP from "./routes/app/userMgmt.route.js";
|
||||||
|
|
||||||
|
// admin routes
|
||||||
|
import userDataMgmtRouter from "./routes/admin/userDataMgmt.route.js";
|
||||||
|
import loanDataMgmtRouter from "./routes/admin/loanDataMgmt.route.js";
|
||||||
|
import itemDataMgmtRouter from "./routes/admin/itemDataMgmt.route.js";
|
||||||
|
import apiDataMgmtRouter from "./routes/admin/apiDataMgmt.route.js";
|
||||||
|
import userMgmtRouterADMIN from "./routes/admin/userMgmt.route.js";
|
||||||
|
import serverConfMgmtRouter from "./routes/admin/serverConfMgmt.route.js";
|
||||||
|
|
||||||
|
// API routes
|
||||||
|
import apiRouter from "./routes/api/api.route.js";
|
||||||
|
|
||||||
app.use(cors());
|
app.use(cors());
|
||||||
// Increase body size limits to support large CSV JSON payloads
|
// Body-Parser VOR den Routen registrieren
|
||||||
app.use(express.urlencoded({ extended: true, limit: "10mb" }));
|
|
||||||
app.set("view engine", "ejs");
|
|
||||||
app.use(express.json({ limit: "10mb" }));
|
app.use(express.json({ limit: "10mb" }));
|
||||||
|
app.use(express.urlencoded({ extended: true, limit: "10mb" }));
|
||||||
|
|
||||||
|
// frontend routes
|
||||||
|
app.use("/api/loans", loansMgmtRouter);
|
||||||
|
app.use("/api/users", userMgmtRouterAPP);
|
||||||
|
|
||||||
|
// admin routes
|
||||||
|
app.use("/api/admin/loan-data", loanDataMgmtRouter);
|
||||||
|
app.use("/api/admin/user-data", userDataMgmtRouter);
|
||||||
|
app.use("/api/admin/item-data", itemDataMgmtRouter);
|
||||||
|
app.use("/api/admin/api-data", apiDataMgmtRouter);
|
||||||
|
app.use("/api/admin/user-mgmt", userMgmtRouterADMIN);
|
||||||
|
app.use("/api/admin/server-config", serverConfMgmtRouter);
|
||||||
|
|
||||||
|
// API routes
|
||||||
app.use("/api", apiRouter);
|
app.use("/api", apiRouter);
|
||||||
app.use("/apiV2", apiRouterV2);
|
|
||||||
|
|
||||||
app.get("/", (req, res) => {
|
app.set("view engine", "ejs");
|
||||||
res.render("index.ejs");
|
|
||||||
});
|
|
||||||
|
|
||||||
app.listen(port, () => {
|
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) => {
|
||||||
|
res.status(200).json({ message: "Token is valid", user: req.user });
|
||||||
|
});
|
||||||
|
|
||||||
|
app.get("/", (req, res) => {
|
||||||
|
res.send(info);
|
||||||
|
});
|
||||||
|
|
||||||
// error handling code
|
// error handling code
|
||||||
app.use((err, req, res, next) => {
|
app.use((err, req, res, next) => {
|
||||||
// Log the error stack and send a generic error response
|
|
||||||
console.error(err.stack);
|
console.error(err.stack);
|
||||||
res.status(500).send("Something broke!");
|
res.status(500).send("Something broke!");
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,108 @@
|
|||||||
|
import { SignJWT, jwtVerify } from "jose";
|
||||||
|
import env from "dotenv";
|
||||||
|
import { verifyAPIKeyDB } from "./database.js";
|
||||||
|
import { checkIfServiceIsActive2 } from "./functions.js";
|
||||||
|
env.config();
|
||||||
|
|
||||||
|
const api_service = "API";
|
||||||
|
const user_frontend_service = "User Frontend";
|
||||||
|
|
||||||
|
const secretKey = process.env.SECRET_KEY;
|
||||||
|
if (!secretKey) {
|
||||||
|
throw new Error("Missing SECRET_KEY environment variable");
|
||||||
|
}
|
||||||
|
const secret = new TextEncoder().encode(secretKey);
|
||||||
|
|
||||||
|
export async function generateToken(payload) {
|
||||||
|
return await new SignJWT(payload)
|
||||||
|
.setProtectedHeader({ alg: "HS256" })
|
||||||
|
.setIssuedAt()
|
||||||
|
.setExpirationTime("2h")
|
||||||
|
.sign(secret);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function authenticateAdmin(req, res, next) {
|
||||||
|
const authHeader = req.headers["authorization"];
|
||||||
|
if (!authHeader) {
|
||||||
|
return res.status(401).json({ message: "Unauthorized" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const [scheme, token] = authHeader.split(" ");
|
||||||
|
if (!/^Bearer$/i.test(scheme) || !token) {
|
||||||
|
return res.status(401).json({ message: "Unauthorized" });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const payload = await verifyToken(token);
|
||||||
|
if (!payload?.admin) {
|
||||||
|
return res.status(403).json({ message: "Forbidden: admin only" });
|
||||||
|
}
|
||||||
|
req.user = payload;
|
||||||
|
return next();
|
||||||
|
} catch {
|
||||||
|
return res.status(403).json({ message: "Forbidden 403" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function authenticate(req, res, next) {
|
||||||
|
const authHeader = req.headers["authorization"];
|
||||||
|
const apiKey = req.params.key;
|
||||||
|
|
||||||
|
if (authHeader) {
|
||||||
|
const serviceActive = await checkIfServiceIsActive2(user_frontend_service);
|
||||||
|
if (!serviceActive) {
|
||||||
|
return res
|
||||||
|
.status(503)
|
||||||
|
.json({ message: "User Frontend is currently unavailable." });
|
||||||
|
}
|
||||||
|
|
||||||
|
const parts = authHeader.split(" ");
|
||||||
|
const scheme = parts[0];
|
||||||
|
const token = parts[1];
|
||||||
|
|
||||||
|
if (!/^Bearer$/i.test(scheme) || !token) {
|
||||||
|
return res.status(401).json({ message: "Unauthorized" });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const payload = await verifyToken(token);
|
||||||
|
req.user = payload;
|
||||||
|
return next();
|
||||||
|
} catch {
|
||||||
|
return res.status(403).json({ message: "Present token invalid" }); // present token invalid
|
||||||
|
}
|
||||||
|
} else if (apiKey) {
|
||||||
|
const serviceActive = await checkIfServiceIsActive2(api_service);
|
||||||
|
if (!serviceActive) {
|
||||||
|
return res
|
||||||
|
.status(503)
|
||||||
|
.json({ message: "API Service is currently unavailable." });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await verifyAPIKey(apiKey);
|
||||||
|
return next();
|
||||||
|
} catch {
|
||||||
|
return res.status(403).json({ message: "API Key invalid" }); // fix: don't chain after sendStatus
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return res.status(401).json({ message: "Unauthorized" }); // no credentials
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function verifyAPIKey(apiKey) {
|
||||||
|
const result = await verifyAPIKeyDB(apiKey);
|
||||||
|
|
||||||
|
if (result.valid) {
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
throw new Error("Invalid API Key");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function verifyToken(token) {
|
||||||
|
const { payload } = await jwtVerify(token, secret, {
|
||||||
|
algorithms: ["HS256"],
|
||||||
|
});
|
||||||
|
return payload;
|
||||||
|
}
|
||||||
+13
-276
@@ -11,285 +11,22 @@ const pool = mysql
|
|||||||
})
|
})
|
||||||
.promise();
|
.promise();
|
||||||
|
|
||||||
export const loginFunc = async (username, password) => {
|
export const verifyAPIKeyDB = async (apiKey) => {
|
||||||
const [result] = await pool.query(
|
const [result] = await pool.query(
|
||||||
"SELECT * FROM users WHERE username = ? AND password = ?",
|
"SELECT * FROM apiKeys WHERE api_key = ?;",
|
||||||
[username, password]
|
[apiKey]
|
||||||
);
|
|
||||||
if (result.length > 0) return { success: true, data: result[0] };
|
|
||||||
return { success: false };
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getItemsFromDatabaseV2 = async () => {
|
|
||||||
const [rows] = await pool.query("SELECT * FROM items;");
|
|
||||||
if (rows.length > 0) {
|
|
||||||
return { success: true, data: rows };
|
|
||||||
}
|
|
||||||
return { success: false };
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getLoanByCodeV2 = async (loan_code) => {
|
|
||||||
const [result] = await pool.query(
|
|
||||||
"SELECT * FROM loans WHERE loan_code = ?;",
|
|
||||||
[loan_code]
|
|
||||||
);
|
);
|
||||||
if (result.length > 0) {
|
if (result.length > 0) {
|
||||||
return { success: true, data: result[0] };
|
const [lastUsed] = await pool.query(
|
||||||
}
|
"UPDATE apiKeys SET last_used_at = NOW() WHERE api_key = ?;",
|
||||||
return { success: false };
|
[apiKey]
|
||||||
};
|
);
|
||||||
|
if (lastUsed.affectedRows > 0) {
|
||||||
export const changeInSafeStateV2 = async (itemId, state) => {
|
return { valid: true };
|
||||||
const [result] = await pool.query(
|
} else {
|
||||||
"UPDATE items SET inSafe = ? WHERE id = ?",
|
return { valid: false };
|
||||||
[state, itemId]
|
}
|
||||||
);
|
|
||||||
if (result.affectedRows > 0) {
|
|
||||||
return { success: true };
|
|
||||||
}
|
|
||||||
return { success: false };
|
|
||||||
};
|
|
||||||
|
|
||||||
export const setReturnDateV2 = async (loanCode) => {
|
|
||||||
const [result] = await pool.query(
|
|
||||||
"UPDATE loans SET returned_date = NOW() WHERE loan_code = ?",
|
|
||||||
[loanCode]
|
|
||||||
);
|
|
||||||
if (result.affectedRows > 0) {
|
|
||||||
return { success: true };
|
|
||||||
}
|
|
||||||
return { success: false };
|
|
||||||
};
|
|
||||||
|
|
||||||
export const setTakeDateV2 = async (loanCode) => {
|
|
||||||
const [result] = await pool.query(
|
|
||||||
"UPDATE loans SET take_date = NOW() WHERE loan_code = ?",
|
|
||||||
[loanCode]
|
|
||||||
);
|
|
||||||
if (result.affectedRows > 0) {
|
|
||||||
return { success: true };
|
|
||||||
}
|
|
||||||
return { success: false };
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getItemsFromDatabase = async (role) => {
|
|
||||||
const sql =
|
|
||||||
role == 0
|
|
||||||
? "SELECT * FROM items;"
|
|
||||||
: "SELECT * FROM items WHERE can_borrow_role >= ?";
|
|
||||||
const params = role == 0 ? [] : [role];
|
|
||||||
|
|
||||||
const [rows] = await pool.query(sql, params);
|
|
||||||
if (rows.length > 0) {
|
|
||||||
return { success: true, data: rows };
|
|
||||||
}
|
|
||||||
return { success: false };
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getLoansFromDatabase = async () => {
|
|
||||||
const [result] = await pool.query("SELECT * FROM loans;");
|
|
||||||
if (result.length > 0) {
|
|
||||||
return { success: true, data: result };
|
|
||||||
}
|
|
||||||
return { success: false };
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getUserLoansFromDatabase = async (username) => {
|
|
||||||
const [result] = await pool.query("SELECT * FROM loans WHERE username = ?;", [
|
|
||||||
username,
|
|
||||||
]);
|
|
||||||
if (result.length > 0) {
|
|
||||||
return { success: true, data: result };
|
|
||||||
} else if (result.length == 0) {
|
|
||||||
return { success: true, data: "No loans found for this user" };
|
|
||||||
} else {
|
} else {
|
||||||
return { success: false };
|
return { valid: false };
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export const deleteLoanFromDatabase = async (loanId) => {
|
|
||||||
const [result] = await pool.query("DELETE FROM loans WHERE id = ?;", [
|
|
||||||
loanId,
|
|
||||||
]);
|
|
||||||
if (result.affectedRows > 0) {
|
|
||||||
return { success: true };
|
|
||||||
} else {
|
|
||||||
return { success: false };
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getBorrowableItemsFromDatabase = async (
|
|
||||||
startDate,
|
|
||||||
endDate,
|
|
||||||
role = 0
|
|
||||||
) => {
|
|
||||||
// Overlap if: loan.start < end AND effective_end > start
|
|
||||||
// effective_end is returned_date if set, otherwise end_date
|
|
||||||
const hasRoleFilter = Number(role) > 0;
|
|
||||||
|
|
||||||
const sql = `
|
|
||||||
SELECT i.*
|
|
||||||
FROM items i
|
|
||||||
WHERE ${hasRoleFilter ? "i.can_borrow_role >= ? AND " : ""}NOT EXISTS (
|
|
||||||
SELECT 1
|
|
||||||
FROM loans l
|
|
||||||
JOIN JSON_TABLE(l.loaned_items_id, '$[*]' COLUMNS (item_id INT PATH '$')) jt
|
|
||||||
WHERE jt.item_id = i.id
|
|
||||||
AND l.start_date < ?
|
|
||||||
AND COALESCE(l.returned_date, l.end_date) > ?
|
|
||||||
);
|
|
||||||
`;
|
|
||||||
|
|
||||||
const params = hasRoleFilter
|
|
||||||
? [role, endDate, startDate]
|
|
||||||
: [endDate, startDate];
|
|
||||||
|
|
||||||
const [rows] = await pool.query(sql, params);
|
|
||||||
if (rows.length > 0) {
|
|
||||||
return { success: true, data: rows };
|
|
||||||
}
|
|
||||||
return { success: false };
|
|
||||||
};
|
|
||||||
|
|
||||||
export const createLoanInDatabase = async (
|
|
||||||
username,
|
|
||||||
startDate,
|
|
||||||
endDate,
|
|
||||||
itemIds
|
|
||||||
) => {
|
|
||||||
if (!username)
|
|
||||||
return { success: false, code: "BAD_REQUEST", message: "Missing username" };
|
|
||||||
if (!Array.isArray(itemIds) || itemIds.length === 0)
|
|
||||||
return {
|
|
||||||
success: false,
|
|
||||||
code: "BAD_REQUEST",
|
|
||||||
message: "No items provided",
|
|
||||||
};
|
|
||||||
if (!startDate || !endDate)
|
|
||||||
return { success: false, code: "BAD_REQUEST", message: "Missing dates" };
|
|
||||||
|
|
||||||
const start = new Date(startDate);
|
|
||||||
const end = new Date(endDate);
|
|
||||||
if (
|
|
||||||
!(start instanceof Date) ||
|
|
||||||
isNaN(start.getTime()) ||
|
|
||||||
!(end instanceof Date) ||
|
|
||||||
isNaN(end.getTime()) ||
|
|
||||||
start >= end
|
|
||||||
) {
|
|
||||||
return {
|
|
||||||
success: false,
|
|
||||||
code: "BAD_REQUEST",
|
|
||||||
message: "Invalid date range",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const conn = await pool.getConnection();
|
|
||||||
try {
|
|
||||||
await conn.beginTransaction();
|
|
||||||
|
|
||||||
// Ensure all items exist and collect names
|
|
||||||
const [itemsRows] = await conn.query(
|
|
||||||
"SELECT id, item_name FROM items WHERE id IN (?)",
|
|
||||||
[itemIds]
|
|
||||||
);
|
|
||||||
if (!itemsRows || itemsRows.length !== itemIds.length) {
|
|
||||||
await conn.rollback();
|
|
||||||
return {
|
|
||||||
success: false,
|
|
||||||
code: "BAD_REQUEST",
|
|
||||||
message: "One or more items not found",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
const itemNames = itemIds
|
|
||||||
.map(
|
|
||||||
(id) => itemsRows.find((r) => Number(r.id) === Number(id))?.item_name
|
|
||||||
)
|
|
||||||
.filter(Boolean);
|
|
||||||
|
|
||||||
// Check availability (no overlap with existing loans)
|
|
||||||
const [confRows] = await conn.query(
|
|
||||||
`
|
|
||||||
SELECT COUNT(*) AS conflicts
|
|
||||||
FROM loans l
|
|
||||||
JOIN JSON_TABLE(l.loaned_items_id, '$[*]' COLUMNS (item_id INT PATH '$')) jt
|
|
||||||
ON TRUE
|
|
||||||
WHERE jt.item_id IN (?)
|
|
||||||
AND l.start_date < ?
|
|
||||||
AND COALESCE(l.returned_date, l.end_date) > ?
|
|
||||||
`,
|
|
||||||
[itemIds, end, start]
|
|
||||||
);
|
|
||||||
if (confRows?.[0]?.conflicts > 0) {
|
|
||||||
await conn.rollback();
|
|
||||||
return {
|
|
||||||
success: false,
|
|
||||||
code: "CONFLICT",
|
|
||||||
message: "One or more items are not available in the selected period",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generate unique loan_code (retry a few times)
|
|
||||||
let loanCode = null;
|
|
||||||
for (let i = 0; i < 6; i++) {
|
|
||||||
const candidate = Math.floor(1000 + Math.random() * 900000); // 4-6 digits
|
|
||||||
const [exists] = await conn.query(
|
|
||||||
"SELECT 1 FROM loans WHERE loan_code = ? LIMIT 1",
|
|
||||||
[candidate]
|
|
||||||
);
|
|
||||||
if (exists.length === 0) {
|
|
||||||
loanCode = candidate;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!loanCode) {
|
|
||||||
await conn.rollback();
|
|
||||||
return {
|
|
||||||
success: false,
|
|
||||||
code: "SERVER_ERROR",
|
|
||||||
message: "Failed to generate unique loan code",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Insert loan
|
|
||||||
const [insertRes] = await conn.query(
|
|
||||||
`
|
|
||||||
INSERT INTO loans (username, loan_code, start_date, end_date, loaned_items_id, loaned_items_name)
|
|
||||||
VALUES (?, ?, ?, ?, CAST(? AS JSON), CAST(? AS JSON))
|
|
||||||
`,
|
|
||||||
[
|
|
||||||
username,
|
|
||||||
loanCode,
|
|
||||||
// Use DATETIME/TIMESTAMP friendly format
|
|
||||||
new Date(start).toISOString().slice(0, 19).replace("T", " "),
|
|
||||||
new Date(end).toISOString().slice(0, 19).replace("T", " "),
|
|
||||||
JSON.stringify(itemIds.map((n) => Number(n))),
|
|
||||||
JSON.stringify(itemNames),
|
|
||||||
]
|
|
||||||
);
|
|
||||||
|
|
||||||
await conn.commit();
|
|
||||||
return {
|
|
||||||
success: true,
|
|
||||||
data: {
|
|
||||||
id: insertRes.insertId,
|
|
||||||
loan_code: loanCode,
|
|
||||||
username,
|
|
||||||
start_date: start,
|
|
||||||
end_date: end,
|
|
||||||
items: itemIds,
|
|
||||||
item_names: itemNames,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
} catch (err) {
|
|
||||||
await conn.rollback();
|
|
||||||
console.error("createLoanInDatabase error:", err);
|
|
||||||
return {
|
|
||||||
success: false,
|
|
||||||
code: "SERVER_ERROR",
|
|
||||||
message: "Failed to create loan",
|
|
||||||
};
|
|
||||||
} finally {
|
|
||||||
conn.release();
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
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 };
|
||||||
|
}
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
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 };
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
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,
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
import { SignJWT, jwtVerify } from "jose";
|
|
||||||
import env from "dotenv";
|
|
||||||
env.config();
|
|
||||||
const secret = new TextEncoder().encode(process.env.SECRET_KEY);
|
|
||||||
|
|
||||||
export async function generateToken(payload) {
|
|
||||||
const newToken = await new SignJWT(payload)
|
|
||||||
.setProtectedHeader({ alg: "HS256" })
|
|
||||||
.setIssuedAt()
|
|
||||||
.setExpirationTime("2h") // Token valid for 2 hours
|
|
||||||
.sign(secret);
|
|
||||||
console.log("Generated token: ", newToken);
|
|
||||||
return newToken;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function authenticate(req, res, next) {
|
|
||||||
const authHeader = req.headers["authorization"];
|
|
||||||
const token = authHeader && authHeader.split(" ")[1]; // Bearer <token>
|
|
||||||
|
|
||||||
if (token == null) return res.sendStatus(401); // No token present
|
|
||||||
|
|
||||||
const { payload } = await jwtVerify(token, secret);
|
|
||||||
req.user = payload;
|
|
||||||
|
|
||||||
next();
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
services:
|
||||||
|
# usr-frontend_v2:
|
||||||
|
# container_name: borrow_system-usr-frontend
|
||||||
|
# build: ./FrontendV2
|
||||||
|
# ports:
|
||||||
|
# - "8001:80"
|
||||||
|
# restart: always
|
||||||
|
|
||||||
|
# admin-frontend:
|
||||||
|
# container_name: borrow_system-admin-frontend
|
||||||
|
# build: ./admin
|
||||||
|
# ports:
|
||||||
|
# - "8003:80"
|
||||||
|
# restart: always
|
||||||
|
|
||||||
|
# backend_v2:
|
||||||
|
# container_name: borrow_system-backend_v2
|
||||||
|
# build: ./backend
|
||||||
|
# ports:
|
||||||
|
# - "8004:8004"
|
||||||
|
# environment:
|
||||||
|
# NODE_ENV: production
|
||||||
|
# DB_HOST: mysql_v2
|
||||||
|
# DB_USER: root
|
||||||
|
# DB_PASSWORD: ${DB_PASSWORD_V2}
|
||||||
|
# DB_NAME: borrow_system_new
|
||||||
|
# depends_on:
|
||||||
|
# - mysql_v2
|
||||||
|
# restart: always
|
||||||
|
|
||||||
|
mysql:
|
||||||
|
container_name: borrow-system_mysql
|
||||||
|
image: mysql:8.0
|
||||||
|
restart: always
|
||||||
|
environment:
|
||||||
|
MYSQL_ROOT_PASSWORD: ${DB_PASSWORD_V2}
|
||||||
|
MYSQL_DATABASE: borrow_system_new
|
||||||
|
TZ: Europe/Berlin
|
||||||
|
volumes:
|
||||||
|
- mysql-v2-data:/var/lib/mysql
|
||||||
|
- ./mysql-timezone.cnf:/etc/mysql/conf.d/timezone.cnf:ro
|
||||||
|
ports:
|
||||||
|
- "3310:3306"
|
||||||
|
|
||||||
|
no-as-a-service:
|
||||||
|
container_name: borrow-system_naas
|
||||||
|
ports:
|
||||||
|
- "3000:3000"
|
||||||
|
build:
|
||||||
|
context: ./no-as-a-service
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
restart: always
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
mysql-data:
|
||||||
|
mysql-v2-data:
|
||||||
+48
-27
@@ -1,43 +1,64 @@
|
|||||||
services:
|
services:
|
||||||
# borrow_system-frontend:
|
usr-frontend:
|
||||||
# container_name: borrow_system-frontend
|
container_name: borrow-system_usr-frontend
|
||||||
# build: ./frontend
|
build:
|
||||||
# ports:
|
context: .
|
||||||
# - "8001:8001"
|
dockerfile: frontend/Dockerfile
|
||||||
# environment:
|
args:
|
||||||
# - CHOKIDAR_USEPOLLING=true
|
VITE_BACKEND_URL: ${BACKEND_URL}
|
||||||
# volumes:
|
restart: always
|
||||||
# - ./frontend:/app
|
|
||||||
# - /app/node_modules
|
|
||||||
# restart: unless-stopped
|
|
||||||
|
|
||||||
borrow_system-backend:
|
admin-frontend:
|
||||||
container_name: borrow_system-backend
|
container_name: borrow-system_admin-frontend
|
||||||
build: ./backend
|
build:
|
||||||
ports:
|
context: .
|
||||||
- "8002:8002"
|
dockerfile: admin/Dockerfile
|
||||||
|
args:
|
||||||
|
VITE_BACKEND_URL: ${BACKEND_URL}
|
||||||
|
restart: always
|
||||||
|
|
||||||
|
backend:
|
||||||
|
container_name: borrow-system_backend
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: backend/Dockerfile
|
||||||
environment:
|
environment:
|
||||||
DB_HOST: mysql
|
NODE_ENV: production
|
||||||
|
DB_HOST: borrow-system_mysql
|
||||||
DB_USER: root
|
DB_USER: root
|
||||||
DB_PASSWORD: ${DB_PASSWORD}
|
DB_PASSWORD: ${DB_PASSWORD}
|
||||||
DB_NAME: borrow_system
|
DB_NAME: borrow_system_new
|
||||||
|
MAIL_HOST: ${MAIL_HOST}
|
||||||
|
MAIL_PORT: ${MAIL_PORT}
|
||||||
|
MAIL_USER: ${MAIL_USER}
|
||||||
|
MAIL_PASSWORD: ${MAIL_PASSWORD}
|
||||||
|
MAIL_SENDEES_CONTACT: ${MAIL_SENDEES_CONTACT}
|
||||||
|
MAIL_SENDEES: ${MAIL_SENDEES}
|
||||||
|
NAAS_URL: ${NAAS_URL}
|
||||||
|
SECRET_KEY: ${SECRET_KEY}
|
||||||
depends_on:
|
depends_on:
|
||||||
- mysql
|
- mysql
|
||||||
volumes:
|
restart: always
|
||||||
- ./backend:/borrow_system-backend
|
|
||||||
restart: unless-stopped
|
|
||||||
|
|
||||||
mysql:
|
mysql:
|
||||||
container_name: borrow_system-mysql
|
container_name: borrow-system_mysql
|
||||||
image: mysql:8.0
|
image: mysql:8.0
|
||||||
restart: unless-stopped
|
restart: always
|
||||||
environment:
|
environment:
|
||||||
MYSQL_ROOT_PASSWORD: ${DB_PASSWORD}
|
MYSQL_ROOT_PASSWORD: ${DB_PASSWORD}
|
||||||
MYSQL_DATABASE: borrow_system
|
MYSQL_DATABASE: borrow_system_new
|
||||||
|
TZ: Europe/Berlin
|
||||||
volumes:
|
volumes:
|
||||||
- mysql-data:/var/lib/mysql
|
- mysql-v2-data:/var/lib/mysql
|
||||||
ports:
|
- ./mysql-timezone.cnf:/etc/mysql/conf.d/timezone.cnf:ro
|
||||||
- "3309:3306"
|
|
||||||
|
no-as-a-service:
|
||||||
|
container_name: borrow-system_naas
|
||||||
|
build:
|
||||||
|
context: ./no-as-a-service
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
restart: always
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
mysql-data:
|
mysql-data:
|
||||||
|
mysql-v2-data:
|
||||||
+20
-6
@@ -1,12 +1,26 @@
|
|||||||
FROM node:20-alpine
|
# Build context is the repo root (npm workspaces share one root package-lock.json)
|
||||||
|
FROM node:22-alpine AS builder
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
COPY package*.json ./
|
COPY package.json package-lock.json ./
|
||||||
RUN npm install
|
COPY frontend/package.json frontend/
|
||||||
|
COPY admin/package.json admin/
|
||||||
|
COPY backend/package.json backend/
|
||||||
|
RUN npm ci -w frontend
|
||||||
|
|
||||||
COPY . .
|
ARG VITE_BACKEND_URL
|
||||||
|
ENV VITE_BACKEND_URL=$VITE_BACKEND_URL
|
||||||
|
|
||||||
EXPOSE 8001
|
COPY frontend/ frontend/
|
||||||
|
RUN npm run build -w frontend
|
||||||
|
|
||||||
CMD ["npm", "run", "dev"]
|
FROM nginx:alpine AS runner
|
||||||
|
|
||||||
|
WORKDIR /usr/share/nginx/html
|
||||||
|
COPY --from=builder /app/frontend/dist .
|
||||||
|
|
||||||
|
COPY frontend/nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
|
|
||||||
|
EXPOSE 80
|
||||||
|
CMD ["nginx", "-g", "daemon off;"]
|
||||||
|
|||||||
+10
-6
@@ -4,15 +4,19 @@ This template provides a minimal setup to get React working in Vite with HMR and
|
|||||||
|
|
||||||
Currently, two official plugins are available:
|
Currently, two official plugins are available:
|
||||||
|
|
||||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) for Fast Refresh
|
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
|
||||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
|
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
|
||||||
|
|
||||||
|
## React Compiler
|
||||||
|
|
||||||
|
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||||
|
|
||||||
## Expanding the ESLint configuration
|
## Expanding the ESLint configuration
|
||||||
|
|
||||||
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
|
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
export default tseslint.config([
|
export default defineConfig([
|
||||||
globalIgnores(['dist']),
|
globalIgnores(['dist']),
|
||||||
{
|
{
|
||||||
files: ['**/*.{ts,tsx}'],
|
files: ['**/*.{ts,tsx}'],
|
||||||
@@ -20,11 +24,11 @@ export default tseslint.config([
|
|||||||
// Other configs...
|
// Other configs...
|
||||||
|
|
||||||
// Remove tseslint.configs.recommended and replace with this
|
// Remove tseslint.configs.recommended and replace with this
|
||||||
...tseslint.configs.recommendedTypeChecked,
|
tseslint.configs.recommendedTypeChecked,
|
||||||
// Alternatively, use this for stricter rules
|
// Alternatively, use this for stricter rules
|
||||||
...tseslint.configs.strictTypeChecked,
|
tseslint.configs.strictTypeChecked,
|
||||||
// Optionally, add this for stylistic rules
|
// Optionally, add this for stylistic rules
|
||||||
...tseslint.configs.stylisticTypeChecked,
|
tseslint.configs.stylisticTypeChecked,
|
||||||
|
|
||||||
// Other configs...
|
// Other configs...
|
||||||
],
|
],
|
||||||
@@ -46,7 +50,7 @@ You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-re
|
|||||||
import reactX from 'eslint-plugin-react-x'
|
import reactX from 'eslint-plugin-react-x'
|
||||||
import reactDom from 'eslint-plugin-react-dom'
|
import reactDom from 'eslint-plugin-react-dom'
|
||||||
|
|
||||||
export default tseslint.config([
|
export default defineConfig([
|
||||||
globalIgnores(['dist']),
|
globalIgnores(['dist']),
|
||||||
{
|
{
|
||||||
files: ['**/*.{ts,tsx}'],
|
files: ['**/*.{ts,tsx}'],
|
||||||
|
|||||||
@@ -3,9 +3,9 @@ import globals from 'globals'
|
|||||||
import reactHooks from 'eslint-plugin-react-hooks'
|
import reactHooks from 'eslint-plugin-react-hooks'
|
||||||
import reactRefresh from 'eslint-plugin-react-refresh'
|
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||||
import tseslint from 'typescript-eslint'
|
import tseslint from 'typescript-eslint'
|
||||||
import { globalIgnores } from 'eslint/config'
|
import { defineConfig, globalIgnores } from 'eslint/config'
|
||||||
|
|
||||||
export default tseslint.config([
|
export default defineConfig([
|
||||||
globalIgnores(['dist']),
|
globalIgnores(['dist']),
|
||||||
{
|
{
|
||||||
files: ['**/*.{ts,tsx}'],
|
files: ['**/*.{ts,tsx}'],
|
||||||
|
|||||||
+6
-2
@@ -1,8 +1,12 @@
|
|||||||
<!DOCTYPE html>
|
<!doctype html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<link rel="icon" type="image/svg+xml" href="/shapes.svg" />
|
<link
|
||||||
|
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>
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name _;
|
||||||
|
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
index index.html;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
}
|
||||||
|
|
||||||
|
location = /backend {
|
||||||
|
return 301 /backend/;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /backend/ {
|
||||||
|
proxy_pass http://borrow-system_backend:8004/;
|
||||||
|
}
|
||||||
|
|
||||||
|
location ~* \.(?:js|mjs|css|png|jpg|jpeg|gif|ico|svg|woff2?)$ {
|
||||||
|
expires 1y;
|
||||||
|
access_log off;
|
||||||
|
add_header Cache-Control "public, immutable";
|
||||||
|
try_files $uri =404;
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user