Compare commits
33 Commits
5b73b44e79
...
dev
| Author | SHA1 | Date | |
|---|---|---|---|
| 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 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -109,7 +109,6 @@ backend/public/uploads/
|
|||||||
*.sqlite3
|
*.sqlite3
|
||||||
|
|
||||||
# API keys and secrets (additional protection)
|
# API keys and secrets (additional protection)
|
||||||
config/
|
|
||||||
secrets/
|
secrets/
|
||||||
keys/
|
keys/
|
||||||
|
|
||||||
|
|||||||
@@ -1,22 +0,0 @@
|
|||||||
# Changelog
|
|
||||||
v1.1
|
|
||||||
|
|
||||||
## Current hosted version
|
|
||||||
v1.1
|
|
||||||
|
|
||||||
> No changelog available.
|
|
||||||
|
|
||||||
## Upcoming changes
|
|
||||||
|
|
||||||
v1.2
|
|
||||||
|
|
||||||
### Fixes and improvements
|
|
||||||
|
|
||||||
- Implement user roles and permissions
|
|
||||||
- Improve form validation and error handling
|
|
||||||
- Add loading indicators for async actions
|
|
||||||
- Optimize performance for large datasets
|
|
||||||
|
|
||||||
### New features
|
|
||||||
|
|
||||||
- Admin panel for managing users, permissions and all of the system settings and database
|
|
||||||
@@ -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.
|
||||||
@@ -1,58 +1,87 @@
|
|||||||
# Backend API docs (apiV2)
|
# Backend API (V2) Documentation
|
||||||
|
|
||||||
If you want to cooperate with me, or build something new with my backend API, feel free to reach out!
|
This document describes the current backend API routes and their real response shapes, based on the code in `backendV2`.
|
||||||
|
|
||||||
On this page you will learn how my API works.
|
|
||||||
|
|
||||||
## 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` which is for my web frontend, because this file works together with my JWT token service.
|
|
||||||
|
|
||||||
But I have built a second API. You can see the second API file in the same directory, the file is called `apiV2.js`.
|
|
||||||
|
|
||||||
But first you have to get an API Key. You can get the API key from my admin dashboard. When you don't have any access to my admin dashboard, please contact your administrator or me.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Base URL
|
## Base URLs
|
||||||
|
|
||||||
- Frontend: `https://insta.the1s.de`
|
- Frontend: `https://insta.the1s.de`
|
||||||
- Backend: `https://backend.insta.the1s.de`
|
- Backend: `https://backend.insta.the1s.de`
|
||||||
- Base path for this API: `https://backend.insta.the1s.de/apiV2`
|
- Base path: `https://backend.insta.the1s.de/api`
|
||||||
|
|
||||||
You can see the status of this and all my other services at `https://status.the1s.de`.
|
Service status: `https://status.the1s.de`
|
||||||
|
|
||||||
_I have also build a [fallback page](https://git.the1s.de/theis.gaedigk/fallback-page). When only the application is down, you will see a friendly message and a link to the status page. (Only if the server is not down)_
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Authentication
|
## Authentication
|
||||||
|
|
||||||
All endpoints require an API key as a path parameter named `:key`.
|
All **protected** endpoints require an API key as a path parameter `:key`.
|
||||||
|
|
||||||
Example: `/apiV2/items/:key`
|
Rules for `:key`:
|
||||||
|
|
||||||
If the key is missing or invalid, the API responds with `401 Unauthorized`.
|
- Exactly 8 characters
|
||||||
|
- Digits only (`^[0-9]{8}$`)
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
```http
|
||||||
|
GET /api/items/12345678
|
||||||
|
```
|
||||||
|
|
||||||
|
On missing / invalid key:
|
||||||
|
|
||||||
|
- Status: `401 Unauthorized`
|
||||||
|
- Body (exact message depends on `authenticate` in `backendV2/services/authentication.js`)
|
||||||
|
|
||||||
|
Auth-related modules:
|
||||||
|
|
||||||
|
- `backendV2/services/authentication.js`
|
||||||
|
- `backendV2/services/database.js`
|
||||||
|
|
||||||
|
Route handlers:
|
||||||
|
|
||||||
|
- `backendV2/routes/api/api.route.js`
|
||||||
|
- `backendV2/routes/api/api.database.js`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Endpoints
|
## Endpoints (Overview)
|
||||||
|
|
||||||
### 1) Get all items
|
1. **Public**
|
||||||
|
- `GET /api/all-items` – List all items (no auth; from original docs)
|
||||||
|
|
||||||
GET `/apiV2/items/:key`
|
2. **Items (authenticated)**
|
||||||
|
- `GET /api/items/:key` – List all items
|
||||||
|
- `POST /api/change-state/:key/:itemId/:state` – Toggle item safe state
|
||||||
|
|
||||||
Returns a list of all items wrapped in a `data` object.
|
3. **Loans (authenticated)**
|
||||||
|
- `GET /api/get-loan-by-code/:key/:loan_code` – Get loan by code
|
||||||
|
- `POST /api/set-take-date/:key/:loan_code` – Set “take” date and mark items as out
|
||||||
|
- `POST /api/set-return-date/:key/:loan_code` – Set “return” date and mark items as returned
|
||||||
|
|
||||||
Example request:
|
---
|
||||||
|
|
||||||
```
|
## 1) Items
|
||||||
GET https://backend.insta.the1s.de/apiV2/items/12345
|
|
||||||
|
### 1.1 Get all items
|
||||||
|
|
||||||
|
**GET** `/api/items/:key`
|
||||||
|
|
||||||
|
Returns all items wrapped in a `data` property.
|
||||||
|
|
||||||
|
- Handler: `getItemsFromDatabaseV2` in `api.database.js`
|
||||||
|
- SQL: `SELECT * FROM items;`
|
||||||
|
|
||||||
|
#### Example request
|
||||||
|
|
||||||
|
```http
|
||||||
|
GET https://backend.insta.the1s.de/api/items/12345678
|
||||||
```
|
```
|
||||||
|
|
||||||
Example response:
|
#### Successful response
|
||||||
|
|
||||||
```
|
```json
|
||||||
{
|
{
|
||||||
"data": [
|
"data": [
|
||||||
{
|
{
|
||||||
@@ -60,151 +89,248 @@ Example response:
|
|||||||
"item_name": "DJI 1er Mikro",
|
"item_name": "DJI 1er Mikro",
|
||||||
"can_borrow_role": 4,
|
"can_borrow_role": 4,
|
||||||
"inSafe": 1,
|
"inSafe": 1,
|
||||||
"entry_created_at": "2025-08-19T22:02:16.000Z"
|
"safe_nr": "01",
|
||||||
|
"entry_created_at": "2025-08-19T22:02:16.000Z",
|
||||||
|
"entry_updated_at": "2025-08-19T22:02:16.000Z",
|
||||||
|
"last_borrowed_person": "alice",
|
||||||
|
"currently_borrowing": null
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Fields:
|
#### Error response
|
||||||
|
|
||||||
- `id`: Unique identifier
|
```json
|
||||||
- `item_name`: Item name
|
{ "message": "Failed to fetch items" }
|
||||||
- `can_borrow_role`: Role allowed to borrow
|
```
|
||||||
- `inSafe`: 1 if in locker, 0 otherwise
|
|
||||||
- `entry_created_at`: Creation timestamp
|
|
||||||
|
|
||||||
Status: 200 on success, 500 on failure.
|
#### Status codes
|
||||||
|
|
||||||
|
- `200 OK` – success, `data` is an array (possibly empty)
|
||||||
|
- `401 Unauthorized` – invalid / missing key
|
||||||
|
- `500 Internal Server Error` – database error or `success: false` from DB layer
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### 2) Change item safe state
|
### 2.2 Toggle item safe state
|
||||||
|
|
||||||
POST `/apiV2/controlInSafe/:key/:itemId/:state`
|
**POST** `/api/change-state/:key/:itemId/:state`
|
||||||
|
|
||||||
Updates `inSafe` (locker) state of an item.
|
> You do not need this endpoint to set the states of the items when the items are taken out or returned. When you take or return a loan, the item states are set automatically by the loan endpoints. This endpoint is only for manually toggling the `inSafe` state of an item.
|
||||||
|
|
||||||
- `state` must be `"1"` (in safe) or `"0"` (not in safe)
|
Path parameters:
|
||||||
|
|
||||||
Example request:
|
- `:key` – API key (8 digits)
|
||||||
|
- `:itemId` – numeric `id` of the item
|
||||||
|
- `:state` – must be `"1"` or `"0"`
|
||||||
|
|
||||||
```
|
Handler in `api.route.js` calls `changeInSafeStateV2(itemId)`, which executes:
|
||||||
POST https://backend.insta.the1s.de/apiV2/controlInSafe/12345/123/1
|
|
||||||
|
```sql
|
||||||
|
UPDATE items SET inSafe = NOT inSafe WHERE id = ?
|
||||||
```
|
```
|
||||||
|
|
||||||
Example response (shape depends on database service):
|
#### Example request
|
||||||
|
|
||||||
```
|
```http
|
||||||
{ "data": { /* update result */ } }
|
POST https://backend.insta.the1s.de/api/change-state/12345678/42/1
|
||||||
```
|
```
|
||||||
|
|
||||||
Status:
|
(Will toggle `inSafe` for item `42`, regardless of the final `1`.)
|
||||||
|
|
||||||
- 200 on success
|
#### Successful response (current implementation)
|
||||||
- 400 if `state` is invalid
|
|
||||||
- 500 on failure
|
|
||||||
|
|
||||||
**You can get the item id on the admin panel, from your system administrator.**
|
```json
|
||||||
|
{
|
||||||
|
"data": null
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Error responses
|
||||||
|
|
||||||
|
Invalid `state` (anything other than `"0"` or `"1"`):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "message": "Invalid state value" }
|
||||||
|
```
|
||||||
|
|
||||||
|
Failed update:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "message": "Failed to update item state" }
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Status codes
|
||||||
|
|
||||||
|
- `200 OK` – item state toggled
|
||||||
|
- `400 Bad Request` – invalid `state` parameter
|
||||||
|
- `401 Unauthorized` – invalid / missing key
|
||||||
|
- `500 Internal Server Error` – database/update failure or `success: false` from DB layer
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### 3) Get loan by code
|
## 3) Loans
|
||||||
|
|
||||||
GET `/apiV2/getLoanByCode/:key/:loan_code`
|
### 3.1 Get loan by code
|
||||||
|
|
||||||
Retrieves the details of a specific loan.
|
**GET** `/api/get-loan-by-code/:key/:loan_code`
|
||||||
|
|
||||||
Example request:
|
Path parameters:
|
||||||
|
|
||||||
```
|
- `:key` – API key
|
||||||
GET https://backend.insta.the1s.de/apiV2/getLoanByCode/12345/123456
|
- `:loan_code` – 6-digit loan code (`^[0-9]{6}$` per DB constraint)
|
||||||
|
|
||||||
|
Database layer (`getLoanByCodeV2`) currently selects:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT first_name, returned_date, take_date, lockers
|
||||||
|
FROM loans
|
||||||
|
WHERE loan_code = ?;
|
||||||
```
|
```
|
||||||
|
|
||||||
Example response:
|
#### Example request
|
||||||
|
|
||||||
|
```http
|
||||||
|
GET https://backend.insta.the1s.de/api/get-loan-by-code/12345678/646473
|
||||||
```
|
```
|
||||||
|
|
||||||
|
#### Successful response
|
||||||
|
|
||||||
|
```json
|
||||||
{
|
{
|
||||||
"data": {
|
"data": {
|
||||||
"id": 6,
|
"first_name": "Theis",
|
||||||
"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": "2025-08-25T13:23:00.000Z",
|
||||||
"loaned_items_id": [8, 9],
|
"lockers": ["01", "03"]
|
||||||
"loaned_items_name": ["SD Karten", "Kameragimbal"]
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Status:
|
#### Error response
|
||||||
|
|
||||||
- 200 on success
|
```json
|
||||||
- 404 if not found
|
{ "message": "Loan not found" }
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Status codes
|
||||||
|
|
||||||
|
- `200 OK` – loan found
|
||||||
|
- `401 Unauthorized` – invalid / missing key
|
||||||
|
- `404 Not Found` – no matching loan for this `loan_code`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### 4) Set return date (now) by loan code
|
### 3.2 Set take date
|
||||||
|
|
||||||
POST `/apiV2/setReturnDate/:key/:loan_code`
|
**POST** `/api/set-take-date/:key/:loan_code`
|
||||||
|
|
||||||
Sets the `returned_date` to the current server time.
|
Path parameters:
|
||||||
|
|
||||||
**Note:** I have updated this API route, so that everytime you return or take a loan, the state of the loaned items is automatically updated.
|
- `:key` – API key
|
||||||
|
- `:loan_code` – loan code
|
||||||
|
|
||||||
**DO NOT UPDATE THE STATE MANUALLY! (only if the item was taken with an admin key)**
|
#### Example request
|
||||||
|
|
||||||
Example request:
|
```http
|
||||||
|
POST https://backend.insta.the1s.de/api/set-take-date/12345678/646473
|
||||||
```
|
|
||||||
POST https://backend.insta.the1s.de/apiV2/setReturnDate/12345/123456
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Example response:
|
#### Successful response
|
||||||
|
|
||||||
```
|
```json
|
||||||
{ "data": { /* update result */ } }
|
{
|
||||||
|
"data": null
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Status: 200 on success, 500 on failure.
|
#### Error response
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "message": "Failed to set take date" }
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Status codes
|
||||||
|
|
||||||
|
- `200 OK` – take date set and items marked as out
|
||||||
|
- `401 Unauthorized` – invalid / missing key
|
||||||
|
- `500 Internal Server Error` – invalid loan, missing items, or DB error / `success: false`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### 5) Set take date (now) by loan code
|
### 3.3 Set return date
|
||||||
|
|
||||||
POST `/apiV2/setTakeDate/:key/:loan_code`
|
**POST** `/api/set-return-date/:key/:loan_code`
|
||||||
|
|
||||||
Sets the `take_date` to the current server time.
|
Path parameters:
|
||||||
|
|
||||||
**Note:** I have updated this API route, so that everytime you return or take a loan, the state of the loaned items is automatically updated.
|
- `:key` – API key
|
||||||
|
- `:loan_code` – loan code
|
||||||
|
|
||||||
**DO NOT UPDATE THE STATE MANUALLY! (only if the item was taken with an admin key)**
|
#### Example request
|
||||||
|
|
||||||
Example request:
|
```http
|
||||||
|
POST https://backend.insta.the1s.de/api/set-return-date/12345678/646473
|
||||||
```
|
|
||||||
POST https://backend.insta.the1s.de/apiV2/setTakeDate/12345/123456
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Example response:
|
#### Successful response (current implementation)
|
||||||
|
|
||||||
```
|
```json
|
||||||
{ "data": { /* update result */ } }
|
{
|
||||||
|
"data": null
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Status: 200 on success, 500 on failure.
|
#### Error response
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "message": "Failed to set return date" }
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Status codes
|
||||||
|
|
||||||
|
- `200 OK` – return date set and items marked as returned
|
||||||
|
- `401 Unauthorized` – invalid / missing key
|
||||||
|
- `500 Internal Server Error` – invalid loan, missing items, or DB error / `success: false`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Error handling
|
## Common Response Shapes
|
||||||
|
|
||||||
- 401 Unauthorized: Missing or invalid API key
|
**Success – list (authenticated items):**
|
||||||
- 400 Bad Request: Invalid parameters (e.g., wrong state value)
|
|
||||||
- 404 Not Found: Loan not found
|
|
||||||
- 500 Internal Server Error: Database or server error
|
|
||||||
|
|
||||||
---
|
```json
|
||||||
|
{ "data": [ /* array of rows */ ] }
|
||||||
|
```
|
||||||
|
|
||||||
If you have questions or want to collaborate, please reach out!
|
**Success – single loan:**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "data": { /* selected loan fields */ } }
|
||||||
|
```
|
||||||
|
|
||||||
|
**Success – mutations (current code):**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "data": null }
|
||||||
|
```
|
||||||
|
|
||||||
|
**Errors:**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "message": "Failed to fetch items" }
|
||||||
|
{ "message": "Failed to update item state" }
|
||||||
|
{ "message": "Invalid state value" }
|
||||||
|
{ "message": "Loan not found" }
|
||||||
|
{ "message": "Failed to set return date" }
|
||||||
|
{ "message": "Failed to set take date" }
|
||||||
|
```
|
||||||
|
|
||||||
|
**HTTP Status Codes:**
|
||||||
|
|
||||||
|
- `200 OK` – operation succeeded
|
||||||
|
- `400 Bad Request` – invalid `state` parameter
|
||||||
|
- `401 Unauthorized` – invalid/missing API key
|
||||||
|
- `404 Not Found` – loan not found
|
||||||
|
- `500 Internal Server Error` – database / server failure or `success: false` from DB layer
|
||||||
@@ -1,12 +1,19 @@
|
|||||||
FROM node:20-alpine
|
FROM node:18 as builder
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
COPY package*.json ./
|
COPY package.json package-lock.json ./
|
||||||
RUN npm install
|
RUN npm ci
|
||||||
|
|
||||||
COPY . .
|
COPY . .
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
EXPOSE 8001
|
FROM nginx:alpine AS runner
|
||||||
|
|
||||||
CMD ["npm", "run", "dev"]
|
WORKDIR /usr/share/nginx/html
|
||||||
|
COPY --from=builder /app/dist .
|
||||||
|
|
||||||
|
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
|
|
||||||
|
EXPOSE 80
|
||||||
|
CMD ["nginx", "-g", "daemon off;"]
|
||||||
18
FrontendV2/nginx.conf
Normal file
18
FrontendV2/nginx.conf
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name _;
|
||||||
|
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
index index.html;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -27,7 +27,7 @@ function App() {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (Cookies.get("token")) {
|
if (Cookies.get("token")) {
|
||||||
const verifyToken = async () => {
|
const verifyToken = async () => {
|
||||||
const response = await fetch(`${API_BASE}/api/verifyToken`, {
|
const response = await fetch(`${API_BASE}/verify`, {
|
||||||
method: "GET",
|
method: "GET",
|
||||||
headers: {
|
headers: {
|
||||||
Authorization: `Bearer ${Cookies.get("token")}`,
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
|
|||||||
@@ -64,7 +64,7 @@ export const Header = () => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const response = await fetch(`${API_BASE}/api/changePassword`, {
|
const response = await fetch(`${API_BASE}/api/users/change-password`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ export const useVersionInfoQuery = () =>
|
|||||||
useQuery({
|
useQuery({
|
||||||
queryKey: ["versionInfo"],
|
queryKey: ["versionInfo"],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const response = await fetch(`${API_BASE}/server-info`, {
|
const response = await fetch(`${API_BASE}/`, {
|
||||||
method: "GET",
|
method: "GET",
|
||||||
});
|
});
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
|
|||||||
4
FrontendV2/src/config/api.config.ts
Normal file
4
FrontendV2/src/config/api.config.ts
Normal file
@@ -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";
|
||||||
@@ -7,6 +7,8 @@ import {
|
|||||||
Spinner,
|
Spinner,
|
||||||
VStack,
|
VStack,
|
||||||
Table,
|
Table,
|
||||||
|
InputGroup,
|
||||||
|
Span,
|
||||||
} from "@chakra-ui/react";
|
} from "@chakra-ui/react";
|
||||||
import { useAtom } from "jotai";
|
import { useAtom } from "jotai";
|
||||||
import { getBorrowableItems } from "@/utils/Fetcher";
|
import { getBorrowableItems } from "@/utils/Fetcher";
|
||||||
@@ -31,6 +33,9 @@ export const HomePage = () => {
|
|||||||
const [isLoadingA, setIsLoadingA] = useState(false);
|
const [isLoadingA, setIsLoadingA] = useState(false);
|
||||||
const [selectedItems, setSelectedItems] = useState<number[]>([]);
|
const [selectedItems, setSelectedItems] = useState<number[]>([]);
|
||||||
|
|
||||||
|
const MAX_CHARACTERS = 500;
|
||||||
|
const [note, setNote] = useState("");
|
||||||
|
|
||||||
// Error handling states
|
// Error handling states
|
||||||
const [isMsg, setIsMsg] = useState(false);
|
const [isMsg, setIsMsg] = useState(false);
|
||||||
const [msgStatus, setMsgStatus] = useState<"error" | "success">("error");
|
const [msgStatus, setMsgStatus] = useState<"error" | "success">("error");
|
||||||
@@ -136,13 +141,29 @@ export const HomePage = () => {
|
|||||||
</Table.Row>
|
</Table.Row>
|
||||||
))}
|
))}
|
||||||
</Table.Body>
|
</Table.Body>
|
||||||
|
<InputGroup
|
||||||
|
endElement={
|
||||||
|
<Span color="fg.muted" textStyle="xs">
|
||||||
|
{note.length} / {MAX_CHARACTERS}
|
||||||
|
</Span>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Input
|
||||||
|
placeholder={t("optional-note")}
|
||||||
|
value={note}
|
||||||
|
maxLength={MAX_CHARACTERS}
|
||||||
|
onChange={(e) => {
|
||||||
|
setNote(e.currentTarget.value.slice(0, MAX_CHARACTERS));
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</InputGroup>
|
||||||
</Table.Root>
|
</Table.Root>
|
||||||
</Table.ScrollArea>
|
</Table.ScrollArea>
|
||||||
)}
|
)}
|
||||||
{selectedItems.length >= 1 && (
|
{selectedItems.length >= 1 && (
|
||||||
<Button
|
<Button
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
createLoan(selectedItems, startDate, endDate).then((response) => {
|
createLoan(selectedItems, startDate, endDate, note).then((response) => {
|
||||||
if (response.status === "error") {
|
if (response.status === "error") {
|
||||||
setMsgStatus("error");
|
setMsgStatus("error");
|
||||||
setMsgTitle(response.title || t("error"));
|
setMsgTitle(response.title || t("error"));
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import { Lock, LockOpen } from "lucide-react";
|
|||||||
import MyAlert from "@/components/myChakra/MyAlert";
|
import MyAlert from "@/components/myChakra/MyAlert";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { API_BASE } from "@/config/api.config";
|
import { API_BASE } from "@/config/api.config";
|
||||||
|
import Cookies from "js-cookie";
|
||||||
|
|
||||||
export const formatDateTime = (value: string | null | undefined) => {
|
export const formatDateTime = (value: string | null | undefined) => {
|
||||||
if (!value) return "N/A";
|
if (!value) return "N/A";
|
||||||
@@ -39,6 +40,8 @@ type Device = {
|
|||||||
can_borrow_role: string;
|
can_borrow_role: string;
|
||||||
inSafe: number;
|
inSafe: number;
|
||||||
entry_created_at: string;
|
entry_created_at: string;
|
||||||
|
last_borrowed_person: string | null;
|
||||||
|
currently_borrowing: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
const Landingpage: React.FC = () => {
|
const Landingpage: React.FC = () => {
|
||||||
@@ -68,7 +71,12 @@ const Landingpage: React.FC = () => {
|
|||||||
const fetchData = async () => {
|
const fetchData = async () => {
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
try {
|
try {
|
||||||
const loanRes = await fetch(`${API_BASE}/apiV2/allLoans`);
|
const loanRes = await fetch(`${API_BASE}/api/loans/all-loans`, {
|
||||||
|
method: "GET",
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
|
},
|
||||||
|
});
|
||||||
const loanData = await loanRes.json();
|
const loanData = await loanRes.json();
|
||||||
if (Array.isArray(loanData)) {
|
if (Array.isArray(loanData)) {
|
||||||
setLoans(loanData);
|
setLoans(loanData);
|
||||||
@@ -80,7 +88,12 @@ const Landingpage: React.FC = () => {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const deviceRes = await fetch(`${API_BASE}/apiV2/allItems`);
|
const deviceRes = await fetch(`${API_BASE}/api/loans/all-items`, {
|
||||||
|
method: "GET",
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
|
},
|
||||||
|
});
|
||||||
const deviceData = await deviceRes.json();
|
const deviceData = await deviceRes.json();
|
||||||
if (Array.isArray(deviceData)) {
|
if (Array.isArray(deviceData)) {
|
||||||
setDevices(deviceData);
|
setDevices(deviceData);
|
||||||
@@ -200,6 +213,14 @@ const Landingpage: React.FC = () => {
|
|||||||
<Text>
|
<Text>
|
||||||
{t("rent-role")}: {device.can_borrow_role}
|
{t("rent-role")}: {device.can_borrow_role}
|
||||||
</Text>
|
</Text>
|
||||||
|
<Text>
|
||||||
|
{t("last-borrowed-person")}:{" "}
|
||||||
|
{device.last_borrowed_person || "N/A"}
|
||||||
|
</Text>
|
||||||
|
<Text>
|
||||||
|
{t("currently-borrowed-by")}:{" "}
|
||||||
|
{device.currently_borrowing || "N/A"}
|
||||||
|
</Text>
|
||||||
</Card.Body>
|
</Card.Body>
|
||||||
</Card.Root>
|
</Card.Root>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ export const LoginPage = () => {
|
|||||||
}, [isLoggedIn, navigate]);
|
}, [isLoggedIn, navigate]);
|
||||||
|
|
||||||
const loginFnc = async (username: string, password: string) => {
|
const loginFnc = async (username: string, password: string) => {
|
||||||
const response = await fetch(`${API_BASE}/api/login`, {
|
const response = await fetch(`${API_BASE}/api/users/login`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ username, password }),
|
body: JSON.stringify({ username, password }),
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ export const MyLoansPage = () => {
|
|||||||
const fetchLoans = async () => {
|
const fetchLoans = async () => {
|
||||||
try {
|
try {
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
const res = await fetch(`${API_BASE}/api/userLoans`, {
|
const res = await fetch(`${API_BASE}/api/loans/loans`, {
|
||||||
method: "GET",
|
method: "GET",
|
||||||
headers: {
|
headers: {
|
||||||
Authorization: `Bearer ${Cookies.get("token")}`,
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
@@ -75,7 +75,7 @@ export const MyLoansPage = () => {
|
|||||||
|
|
||||||
const deleteLoan = async (loanId: number) => {
|
const deleteLoan = async (loanId: number) => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`${API_BASE}/api/SETdeleteLoan/${loanId}`, {
|
const res = await fetch(`${API_BASE}/api/loans/delete-loan/${loanId}`, {
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
headers: {
|
headers: {
|
||||||
Authorization: `Bearer ${Cookies.get("token")}`,
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
@@ -147,6 +147,8 @@ export const MyLoansPage = () => {
|
|||||||
<Table.Column style={{ width: "14%" }} />
|
<Table.Column style={{ width: "14%" }} />
|
||||||
{/* Rückgabedatum */}
|
{/* Rückgabedatum */}
|
||||||
<Table.Column style={{ width: "14%" }} />
|
<Table.Column style={{ width: "14%" }} />
|
||||||
|
{/* Notiz */}
|
||||||
|
<Table.Column style={{ width: "14%" }} />
|
||||||
{/* Aktionen */}
|
{/* Aktionen */}
|
||||||
<Table.Column style={{ width: "8%" }} />
|
<Table.Column style={{ width: "8%" }} />
|
||||||
</Table.ColumnGroup>
|
</Table.ColumnGroup>
|
||||||
@@ -158,6 +160,7 @@ export const MyLoansPage = () => {
|
|||||||
<Table.ColumnHeader>{t("devices")}</Table.ColumnHeader>
|
<Table.ColumnHeader>{t("devices")}</Table.ColumnHeader>
|
||||||
<Table.ColumnHeader>{t("take-date")}</Table.ColumnHeader>
|
<Table.ColumnHeader>{t("take-date")}</Table.ColumnHeader>
|
||||||
<Table.ColumnHeader>{t("return-date")}</Table.ColumnHeader>
|
<Table.ColumnHeader>{t("return-date")}</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader>{t("note")}</Table.ColumnHeader>
|
||||||
<Table.ColumnHeader>{t("actions")}</Table.ColumnHeader>
|
<Table.ColumnHeader>{t("actions")}</Table.ColumnHeader>
|
||||||
</Table.Row>
|
</Table.Row>
|
||||||
</Table.Header>
|
</Table.Header>
|
||||||
@@ -178,6 +181,7 @@ export const MyLoansPage = () => {
|
|||||||
</Table.Cell>
|
</Table.Cell>
|
||||||
<Table.Cell>{formatDate(loan.take_date)}</Table.Cell>
|
<Table.Cell>{formatDate(loan.take_date)}</Table.Cell>
|
||||||
<Table.Cell>{formatDate(loan.returned_date)}</Table.Cell>
|
<Table.Cell>{formatDate(loan.returned_date)}</Table.Cell>
|
||||||
|
<Table.Cell>{loan.note}</Table.Cell>
|
||||||
<Table.Cell>
|
<Table.Cell>
|
||||||
<Dialog.Root role="alertdialog">
|
<Dialog.Root role="alertdialog">
|
||||||
<Dialog.Trigger asChild>
|
<Dialog.Trigger asChild>
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ export const getBorrowableItems = async (
|
|||||||
endDate: string
|
endDate: string
|
||||||
) => {
|
) => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${API_BASE}/api/borrowableItems`, {
|
const response = await fetch(`${API_BASE}/api/loans/borrowable-items`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
Authorization: `Bearer ${Cookies.get("token") || ""}`,
|
Authorization: `Bearer ${Cookies.get("token") || ""}`,
|
||||||
@@ -47,15 +47,16 @@ export const getBorrowableItems = async (
|
|||||||
export const createLoan = async (
|
export const createLoan = async (
|
||||||
itemIds: number[],
|
itemIds: number[],
|
||||||
startDate: string,
|
startDate: string,
|
||||||
endDate: string
|
endDate: string,
|
||||||
|
note: string | null
|
||||||
) => {
|
) => {
|
||||||
const response = await fetch(`${API_BASE}/api/createLoan`, {
|
const response = await fetch(`${API_BASE}/api/loans/createLoan`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
Authorization: `Bearer ${Cookies.get("token") || ""}`,
|
Authorization: `Bearer ${Cookies.get("token") || ""}`,
|
||||||
},
|
},
|
||||||
body: JSON.stringify({ items: itemIds, startDate, endDate }),
|
body: JSON.stringify({ items: itemIds, startDate, endDate, note }),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
|
|||||||
@@ -60,5 +60,6 @@
|
|||||||
"sure-delete-loan-2": "Für den Admin bleibt sie weiterhin sichtbar.",
|
"sure-delete-loan-2": "Für den Admin bleibt sie weiterhin sichtbar.",
|
||||||
"delete": "Löschen",
|
"delete": "Löschen",
|
||||||
"change-language": "Sprache ändern",
|
"change-language": "Sprache ändern",
|
||||||
"timezone-info": "Die angezeigten Daten und Uhrzeiten werden in deutscher Zeitzone dargestellt und müssen auch so eingegeben werden."
|
"timezone-info": "Die angezeigten Daten und Uhrzeiten werden in deutscher Zeitzone dargestellt und müssen auch so eingegeben werden.",
|
||||||
|
"optional-note": "Optionale Notiz"
|
||||||
}
|
}
|
||||||
@@ -60,5 +60,6 @@
|
|||||||
"sure-delete-loan-2": "It will remain visible to the admin.",
|
"sure-delete-loan-2": "It will remain visible to the admin.",
|
||||||
"delete": "Delete",
|
"delete": "Delete",
|
||||||
"change-language": "Change language",
|
"change-language": "Change language",
|
||||||
"timezone-info": "The displayed dates and times are shown in Berlin timezone and must also be entered as such."
|
"timezone-info": "The displayed dates and times are shown in Berlin timezone and must also be entered as such.",
|
||||||
|
"optional-note": "Optional note"
|
||||||
}
|
}
|
||||||
@@ -1,12 +1,19 @@
|
|||||||
FROM node:20-alpine
|
FROM node:18 as builder
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
COPY package*.json ./
|
COPY package.json package-lock.json ./
|
||||||
RUN npm install
|
RUN npm ci
|
||||||
|
|
||||||
COPY . .
|
COPY . .
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
EXPOSE 8003
|
FROM nginx:alpine AS runner
|
||||||
|
|
||||||
CMD ["npm", "run", "dev"]
|
WORKDIR /usr/share/nginx/html
|
||||||
|
COPY --from=builder /app/dist .
|
||||||
|
|
||||||
|
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
|
|
||||||
|
EXPOSE 80
|
||||||
|
CMD ["nginx", "-g", "daemon off;"]
|
||||||
18
admin/nginx.conf
Normal file
18
admin/nginx.conf
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name _;
|
||||||
|
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
index index.html;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,11 +3,7 @@ import { useEffect } from "react";
|
|||||||
import Dashboard from "./Dashboard";
|
import Dashboard from "./Dashboard";
|
||||||
import Login from "./Login";
|
import Login from "./Login";
|
||||||
import Cookies from "js-cookie";
|
import Cookies from "js-cookie";
|
||||||
|
import { API_BASE } from "@/config/api.config";
|
||||||
const API_BASE =
|
|
||||||
(import.meta as any).env?.VITE_BACKEND_URL ||
|
|
||||||
import.meta.env.VITE_BACKEND_URL ||
|
|
||||||
"http://localhost:8002";
|
|
||||||
|
|
||||||
const Layout: React.FC = () => {
|
const Layout: React.FC = () => {
|
||||||
const [isLoggedIn, setIsLoggedIn] = useState(false);
|
const [isLoggedIn, setIsLoggedIn] = useState(false);
|
||||||
@@ -15,12 +11,15 @@ const Layout: React.FC = () => {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (Cookies.get("token")) {
|
if (Cookies.get("token")) {
|
||||||
const verifyToken = async () => {
|
const verifyToken = async () => {
|
||||||
const response = await fetch(`${API_BASE}/api/verifyToken`, {
|
const response = await fetch(
|
||||||
method: "GET",
|
`${API_BASE}/api/admin/user-mgmt/verify-token`,
|
||||||
headers: {
|
{
|
||||||
Authorization: `Bearer ${Cookies.get("token")}`,
|
method: "GET",
|
||||||
},
|
headers: {
|
||||||
});
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
setIsLoggedIn(true);
|
setIsLoggedIn(true);
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import React from "react";
|
import React from "react";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
import { Box, Flex, VStack, Heading, Text, Link } from "@chakra-ui/react";
|
import { Box, Flex, VStack, Heading, Text, Link } from "@chakra-ui/react";
|
||||||
|
import { API_BASE } from "@/config/api.config";
|
||||||
|
|
||||||
type SidebarProps = {
|
type SidebarProps = {
|
||||||
viewAusleihen: () => void;
|
viewAusleihen: () => void;
|
||||||
@@ -15,10 +17,22 @@ const Sidebar: React.FC<SidebarProps> = ({
|
|||||||
viewUser,
|
viewUser,
|
||||||
viewAPI,
|
viewAPI,
|
||||||
}) => {
|
}) => {
|
||||||
|
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 (
|
return (
|
||||||
<Box
|
<Box
|
||||||
as="aside"
|
as="aside"
|
||||||
w="260px"
|
w="180px"
|
||||||
minH="100vh"
|
minH="100vh"
|
||||||
bg="gray.800"
|
bg="gray.800"
|
||||||
color="gray.100"
|
color="gray.100"
|
||||||
@@ -72,7 +86,33 @@ const Sidebar: React.FC<SidebarProps> = ({
|
|||||||
</VStack>
|
</VStack>
|
||||||
|
|
||||||
<Box mt="auto" pt={8} fontSize="xs" color="gray.500">
|
<Box mt="auto" pt={8} fontSize="xs" color="gray.500">
|
||||||
<Text>© Made with ❤️ by Theis Gaedigk</Text>
|
<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>
|
</Box>
|
||||||
</Flex>
|
</Flex>
|
||||||
</Box>
|
</Box>
|
||||||
|
|||||||
@@ -17,17 +17,14 @@ import { useState, useEffect } from "react";
|
|||||||
import { deleteAPKey } from "@/utils/userActions";
|
import { deleteAPKey } from "@/utils/userActions";
|
||||||
import AddAPIKey from "./AddAPIKey";
|
import AddAPIKey from "./AddAPIKey";
|
||||||
import { formatDateTime } from "@/utils/userFuncs";
|
import { formatDateTime } from "@/utils/userFuncs";
|
||||||
|
import { API_BASE } from "@/config/api.config";
|
||||||
const API_BASE =
|
|
||||||
(import.meta as any).env?.VITE_BACKEND_URL ||
|
|
||||||
import.meta.env.VITE_BACKEND_URL ||
|
|
||||||
"http://localhost:8002";
|
|
||||||
|
|
||||||
type Items = {
|
type Items = {
|
||||||
id: number;
|
id: number;
|
||||||
apiKey: string;
|
api_key: string;
|
||||||
user: string;
|
entry_name: string;
|
||||||
entry_created_at: string;
|
entry_created_at: string;
|
||||||
|
last_used_at: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
const APIKeyTable: React.FC = () => {
|
const APIKeyTable: React.FC = () => {
|
||||||
@@ -56,13 +53,17 @@ const APIKeyTable: React.FC = () => {
|
|||||||
const fetchData = async () => {
|
const fetchData = async () => {
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${API_BASE}/api/apiKeys`, {
|
const response = await fetch(
|
||||||
method: "GET",
|
`${API_BASE}/api/admin/api-data/get-api-keys`,
|
||||||
headers: {
|
{
|
||||||
Authorization: `Bearer ${Cookies.get("token")}`,
|
method: "GET",
|
||||||
},
|
headers: {
|
||||||
});
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
|
console.log(data);
|
||||||
return data;
|
return data;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
setError("error", "Failed to fetch items", "There is an error");
|
setError("error", "Failed to fetch items", "There is an error");
|
||||||
@@ -149,39 +150,55 @@ const APIKeyTable: React.FC = () => {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<Table.Root size="sm" striped>
|
<Table.Root
|
||||||
|
size="sm"
|
||||||
|
striped
|
||||||
|
w="100%"
|
||||||
|
// table-layout: auto => Spaltenbreite nach Content; volle Breite nutzen
|
||||||
|
style={{ tableLayout: "auto" }}
|
||||||
|
>
|
||||||
<Table.Header>
|
<Table.Header>
|
||||||
<Table.Row>
|
<Table.Row>
|
||||||
<Table.ColumnHeader>
|
<Table.ColumnHeader width="1%" whiteSpace="nowrap">
|
||||||
<strong>#</strong>
|
<strong>#</strong>
|
||||||
</Table.ColumnHeader>
|
</Table.ColumnHeader>
|
||||||
<Table.ColumnHeader>
|
<Table.ColumnHeader>
|
||||||
<strong>API Key</strong>
|
<strong>API Key</strong>
|
||||||
</Table.ColumnHeader>
|
</Table.ColumnHeader>
|
||||||
<Table.ColumnHeader>
|
<Table.ColumnHeader>
|
||||||
<strong>Benutzer</strong>
|
<strong>Name</strong>
|
||||||
</Table.ColumnHeader>
|
</Table.ColumnHeader>
|
||||||
<Table.ColumnHeader>
|
<Table.ColumnHeader whiteSpace="nowrap">
|
||||||
<strong>Eintrag erstellt am</strong>
|
<strong>Eintrag erstellt am</strong>
|
||||||
</Table.ColumnHeader>
|
</Table.ColumnHeader>
|
||||||
<Table.ColumnHeader>
|
<Table.ColumnHeader whiteSpace="nowrap">
|
||||||
|
<strong>Zuletzt benutzt am</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader width="1%" whiteSpace="nowrap">
|
||||||
<strong>Aktionen</strong>
|
<strong>Aktionen</strong>
|
||||||
</Table.ColumnHeader>
|
</Table.ColumnHeader>
|
||||||
</Table.Row>
|
</Table.Row>
|
||||||
</Table.Header>
|
</Table.Header>
|
||||||
<Table.Body>
|
<Table.Body>
|
||||||
{items.map((apiKey) => (
|
{items.map((item) => (
|
||||||
<Table.Row key={apiKey.id}>
|
<Table.Row key={item.id}>
|
||||||
<Table.Cell>{apiKey.id}</Table.Cell>
|
<Table.Cell whiteSpace="nowrap">{item.id}</Table.Cell>
|
||||||
<Table.Cell>{apiKey.apiKey}</Table.Cell>
|
<Table.Cell fontFamily="mono">{item.api_key}</Table.Cell>
|
||||||
<Table.Cell>{apiKey.user}</Table.Cell>
|
<Table.Cell>{item.entry_name}</Table.Cell>
|
||||||
<Table.Cell>{formatDateTime(apiKey.entry_created_at)}</Table.Cell>
|
<Table.Cell whiteSpace="nowrap">
|
||||||
<Table.Cell>
|
{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
|
<Button
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
deleteAPKey(apiKey.id).then((response) => {
|
deleteAPKey(item.id).then((response) => {
|
||||||
if (response.success) {
|
if (response.success) {
|
||||||
setItems(items.filter((i) => i.id !== apiKey.id));
|
setItems(items.filter((i) => i.id !== item.id));
|
||||||
setError(
|
setError(
|
||||||
"success",
|
"success",
|
||||||
"Gegenstand gelöscht",
|
"Gegenstand gelöscht",
|
||||||
|
|||||||
@@ -1,6 +1,15 @@
|
|||||||
import React from "react";
|
import React from "react";
|
||||||
import { Button, Card, Field, Input, Stack } from "@chakra-ui/react";
|
import {
|
||||||
|
Button,
|
||||||
|
Card,
|
||||||
|
Field,
|
||||||
|
Input,
|
||||||
|
Stack,
|
||||||
|
InputGroup,
|
||||||
|
Span,
|
||||||
|
} from "@chakra-ui/react";
|
||||||
import { createAPIentry } from "@/utils/userActions";
|
import { createAPIentry } from "@/utils/userActions";
|
||||||
|
import { useState } from "react";
|
||||||
|
|
||||||
type AddAPIKeyProps = {
|
type AddAPIKeyProps = {
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
@@ -12,6 +21,8 @@ type AddAPIKeyProps = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const AddAPIKey: React.FC<AddAPIKeyProps> = ({ onClose, alert }) => {
|
const AddAPIKey: React.FC<AddAPIKeyProps> = ({ onClose, alert }) => {
|
||||||
|
const [value, setValue] = useState("");
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
|
<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.Root maxW="sm">
|
||||||
@@ -23,13 +34,26 @@ const AddAPIKey: React.FC<AddAPIKeyProps> = ({ onClose, alert }) => {
|
|||||||
</Card.Header>
|
</Card.Header>
|
||||||
<Card.Body>
|
<Card.Body>
|
||||||
<Stack gap="4" w="full">
|
<Stack gap="4" w="full">
|
||||||
|
<InputGroup
|
||||||
|
endElement={
|
||||||
|
<Span color="fg.muted" textStyle="xs">
|
||||||
|
{value.length} / {15}
|
||||||
|
</Span>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Input
|
||||||
|
placeholder="Er muss 15 Zeichen lang sein"
|
||||||
|
value={value}
|
||||||
|
id="apiKey"
|
||||||
|
maxLength={15}
|
||||||
|
onChange={(e) => {
|
||||||
|
setValue(e.currentTarget.value.slice(0, 15));
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</InputGroup>
|
||||||
<Field.Root>
|
<Field.Root>
|
||||||
<Field.Label>API key</Field.Label>
|
<Field.Label>Name</Field.Label>
|
||||||
<Input type="number" id="apiKey" />
|
<Input id="name" type="text" />
|
||||||
</Field.Root>
|
|
||||||
<Field.Root>
|
|
||||||
<Field.Label>Benutzer</Field.Label>
|
|
||||||
<Input id="user" type="text" />
|
|
||||||
</Field.Root>
|
</Field.Root>
|
||||||
</Stack>
|
</Stack>
|
||||||
</Card.Body>
|
</Card.Body>
|
||||||
@@ -44,14 +68,14 @@ const AddAPIKey: React.FC<AddAPIKeyProps> = ({ onClose, alert }) => {
|
|||||||
(
|
(
|
||||||
document.getElementById("apiKey") as HTMLInputElement
|
document.getElementById("apiKey") as HTMLInputElement
|
||||||
)?.value.trim() || "";
|
)?.value.trim() || "";
|
||||||
const user =
|
const name =
|
||||||
(
|
(
|
||||||
document.getElementById("user") as HTMLInputElement
|
document.getElementById("name") as HTMLInputElement
|
||||||
)?.value.trim() || "";
|
)?.value.trim() || "";
|
||||||
|
|
||||||
if (!apiKey || !user) return;
|
if (!apiKey || !name) return;
|
||||||
|
|
||||||
const res = await createAPIentry(apiKey, user);
|
const res = await createAPIentry(apiKey, name);
|
||||||
if (res.success) {
|
if (res.success) {
|
||||||
alert(
|
alert(
|
||||||
"success",
|
"success",
|
||||||
|
|||||||
@@ -1,5 +1,13 @@
|
|||||||
import React from "react";
|
import React from "react";
|
||||||
import { Button, Card, Field, Input, Stack } from "@chakra-ui/react";
|
import {
|
||||||
|
Button,
|
||||||
|
Card,
|
||||||
|
Field,
|
||||||
|
Input,
|
||||||
|
Stack,
|
||||||
|
Text,
|
||||||
|
Checkbox,
|
||||||
|
} from "@chakra-ui/react";
|
||||||
import { createUser } from "@/utils/userActions";
|
import { createUser } from "@/utils/userActions";
|
||||||
|
|
||||||
type AddFormProps = {
|
type AddFormProps = {
|
||||||
@@ -12,73 +20,128 @@ type AddFormProps = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const AddForm: React.FC<AddFormProps> = ({ onClose, alert }) => {
|
const AddForm: React.FC<AddFormProps> = ({ onClose, alert }) => {
|
||||||
|
const [admin, setAdmin] = React.useState(false);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
|
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
|
||||||
<Card.Root maxW="sm">
|
<form
|
||||||
<Card.Header>
|
onSubmit={(e) => {
|
||||||
<Card.Title>Neuen Nutzer erstellen</Card.Title>
|
e.preventDefault();
|
||||||
<Card.Description>
|
}}
|
||||||
Füllen Sie das folgende Formular aus, um einen Nutzer zu erstellen.
|
>
|
||||||
</Card.Description>
|
<Card.Root maxW="sm">
|
||||||
</Card.Header>
|
<Card.Header>
|
||||||
<Card.Body>
|
<Card.Title>Neuen Nutzer erstellen</Card.Title>
|
||||||
<Stack gap="4" w="full">
|
<Card.Description>
|
||||||
<Field.Root>
|
Füllen Sie das folgende Formular aus, um einen Nutzer zu
|
||||||
<Field.Label>Username</Field.Label>
|
erstellen.
|
||||||
<Input id="username" />
|
</Card.Description>
|
||||||
</Field.Root>
|
</Card.Header>
|
||||||
<Field.Root>
|
|
||||||
<Field.Label>Password</Field.Label>
|
|
||||||
<Input id="password" type="password" />
|
|
||||||
</Field.Root>
|
|
||||||
<Field.Root>
|
|
||||||
<Field.Label>Role</Field.Label>
|
|
||||||
<Input id="role" type="number" />
|
|
||||||
</Field.Root>
|
|
||||||
</Stack>
|
|
||||||
</Card.Body>
|
|
||||||
<Card.Footer justifyContent="flex-end">
|
|
||||||
<Button variant="outline" onClick={onClose}>
|
|
||||||
Abbrechen
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant="solid"
|
|
||||||
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
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!username || !password || Number.isNaN(role)) return;
|
<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>
|
||||||
|
|
||||||
const res = await createUser(username, role, password);
|
{/* Kontrollierte Checkbox */}
|
||||||
if (res.success) {
|
<Checkbox.Root
|
||||||
alert(
|
checked={admin}
|
||||||
"success",
|
onCheckedChange={(e: any) => setAdmin(Boolean(e?.checked ?? e))}
|
||||||
"Nutzer erstellt",
|
>
|
||||||
"Der Nutzer wurde erfolgreich erstellt."
|
<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
|
||||||
);
|
);
|
||||||
onClose();
|
const firstname =
|
||||||
} else {
|
(
|
||||||
alert(
|
document.getElementById("firstname") as HTMLInputElement
|
||||||
"error",
|
)?.value.trim() || "";
|
||||||
"Fehler beim Erstellen des Nutzers",
|
const lastname =
|
||||||
"Es gab einen Fehler beim Erstellen des Nutzers. Vielleicht gibt es bereits einen Nutzer mit diesem Benutzernamen."
|
(
|
||||||
|
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
|
||||||
);
|
);
|
||||||
onClose();
|
|
||||||
}
|
if (res.success) {
|
||||||
}}
|
alert(
|
||||||
>
|
"success",
|
||||||
Erstellen
|
"Nutzer erstellt",
|
||||||
</Button>
|
"Der Nutzer wurde erfolgreich erstellt."
|
||||||
</Card.Footer>
|
);
|
||||||
</Card.Root>
|
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>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
Heading,
|
Heading,
|
||||||
Icon,
|
Icon,
|
||||||
Input,
|
Input,
|
||||||
|
Box, // added
|
||||||
} from "@chakra-ui/react";
|
} from "@chakra-ui/react";
|
||||||
import { Tooltip } from "@/components/ui/tooltip";
|
import { Tooltip } from "@/components/ui/tooltip";
|
||||||
import MyAlert from "./myChakra/MyAlert";
|
import MyAlert from "./myChakra/MyAlert";
|
||||||
@@ -30,18 +31,17 @@ import {
|
|||||||
} from "@/utils/userActions";
|
} from "@/utils/userActions";
|
||||||
import AddItemForm from "./AddItemForm";
|
import AddItemForm from "./AddItemForm";
|
||||||
import { formatDateTime } from "@/utils/userFuncs";
|
import { formatDateTime } from "@/utils/userFuncs";
|
||||||
|
import { API_BASE } from "@/config/api.config";
|
||||||
const API_BASE =
|
|
||||||
(import.meta as any).env?.VITE_BACKEND_URL ||
|
|
||||||
import.meta.env.VITE_BACKEND_URL ||
|
|
||||||
"http://localhost:8002";
|
|
||||||
|
|
||||||
type Items = {
|
type Items = {
|
||||||
id: number;
|
id: number;
|
||||||
item_name: string;
|
item_name: string;
|
||||||
can_borrow_role: string;
|
can_borrow_role: string;
|
||||||
inSafe: boolean;
|
in_safe: boolean;
|
||||||
entry_created_at: string;
|
entry_created_at: string;
|
||||||
|
entry_updated_at: string;
|
||||||
|
last_borrowed_person: string | null;
|
||||||
|
currently_borrowing: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
const ItemTable: React.FC = () => {
|
const ItemTable: React.FC = () => {
|
||||||
@@ -82,12 +82,15 @@ const ItemTable: React.FC = () => {
|
|||||||
const fetchData = async () => {
|
const fetchData = async () => {
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${API_BASE}/api/allItems`, {
|
const response = await fetch(
|
||||||
method: "GET",
|
`${API_BASE}/api/admin/item-data/all-items`,
|
||||||
headers: {
|
{
|
||||||
Authorization: `Bearer ${Cookies.get("token")}`,
|
method: "GET",
|
||||||
},
|
headers: {
|
||||||
});
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
return data;
|
return data;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -175,136 +178,161 @@ const ItemTable: React.FC = () => {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<Table.Root size="sm" striped>
|
{/* make table content-sized with horizontal scroll if needed */}
|
||||||
<Table.Header>
|
<Box overflowX="auto">
|
||||||
<Table.Row>
|
<Table.Root
|
||||||
<Table.ColumnHeader>
|
size="sm"
|
||||||
<strong>#</strong>
|
striped
|
||||||
</Table.ColumnHeader>
|
tableLayout="auto"
|
||||||
<Table.ColumnHeader>
|
w="max-content"
|
||||||
<strong>Gegenstand</strong>
|
whiteSpace="nowrap"
|
||||||
</Table.ColumnHeader>
|
>
|
||||||
<Table.ColumnHeader>
|
<Table.Header>
|
||||||
<strong>Ausleih Berechtigung</strong>
|
<Table.Row>
|
||||||
</Table.ColumnHeader>
|
<Table.ColumnHeader>
|
||||||
<Table.ColumnHeader>
|
<strong>#</strong>
|
||||||
<strong>Im Schließfach</strong>
|
</Table.ColumnHeader>
|
||||||
</Table.ColumnHeader>
|
<Table.ColumnHeader>
|
||||||
<Table.ColumnHeader>
|
<strong>Gegenstand</strong>
|
||||||
<strong>Eintrag erstellt am</strong>
|
</Table.ColumnHeader>
|
||||||
</Table.ColumnHeader>
|
<Table.ColumnHeader>
|
||||||
<Table.ColumnHeader>
|
<strong>Ausleih Berechtigung</strong>
|
||||||
<strong>Aktionen</strong>
|
</Table.ColumnHeader>
|
||||||
</Table.ColumnHeader>
|
<Table.ColumnHeader>
|
||||||
</Table.Row>
|
<strong>Im Schließfach</strong>
|
||||||
</Table.Header>
|
</Table.ColumnHeader>
|
||||||
<Table.Body>
|
<Table.ColumnHeader>
|
||||||
{items.map((item) => (
|
<strong>Eintrag erstellt am</strong>
|
||||||
<Table.Row key={item.id}>
|
</Table.ColumnHeader>
|
||||||
<Table.Cell>{item.id}</Table.Cell>
|
<Table.ColumnHeader>
|
||||||
<Table.Cell>
|
<strong>Eintrag aktualisiert am</strong>
|
||||||
<Input
|
</Table.ColumnHeader>
|
||||||
onChange={(e) =>
|
<Table.ColumnHeader>
|
||||||
handleItemNameChange(item.id, e.target.value)
|
<strong>Letzte ausleihende Person</strong>
|
||||||
}
|
</Table.ColumnHeader>
|
||||||
value={item.item_name}
|
<Table.ColumnHeader>
|
||||||
/>
|
<strong>Derzeit ausgeliehen von</strong>
|
||||||
</Table.Cell>
|
</Table.ColumnHeader>
|
||||||
<Table.Cell>
|
<Table.ColumnHeader>
|
||||||
<Input
|
<strong>Aktionen</strong>
|
||||||
onChange={(e) =>
|
</Table.ColumnHeader>
|
||||||
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.inSafe ? "green.600" : "red.600"}
|
|
||||||
borderWidth="1px"
|
|
||||||
borderColor={item.inSafe ? "green.300" : "red.300"}
|
|
||||||
_hover={{
|
|
||||||
bg: item.inSafe ? "green.50" : "red.50",
|
|
||||||
borderColor: item.inSafe ? "green.400" : "red.400",
|
|
||||||
transform: "translateY(-1px)",
|
|
||||||
shadow: "sm",
|
|
||||||
}}
|
|
||||||
_active={{ transform: "translateY(0)" }}
|
|
||||||
aria-label={
|
|
||||||
item.inSafe ? "Mark as not in safe" : "Mark as in safe"
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<Icon
|
|
||||||
as={item.inSafe ? CheckCircle2 : XCircle}
|
|
||||||
boxSize={3.5}
|
|
||||||
mr={2}
|
|
||||||
/>
|
|
||||||
<Text as="span" fontSize="xs" fontWeight="semibold">
|
|
||||||
{item.inSafe ? "Yes" : "No"}
|
|
||||||
</Text>
|
|
||||||
</Button>
|
|
||||||
</Table.Cell>
|
|
||||||
<Table.Cell>{formatDateTime(item.entry_created_at)}</Table.Cell>
|
|
||||||
<Table.Cell>
|
|
||||||
<Button
|
|
||||||
onClick={() =>
|
|
||||||
handleEditItems(
|
|
||||||
item.id,
|
|
||||||
item.item_name,
|
|
||||||
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.Row>
|
||||||
))}
|
</Table.Header>
|
||||||
</Table.Body>
|
<Table.Body>
|
||||||
</Table.Root>
|
{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>{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>
|
||||||
|
<Button
|
||||||
|
onClick={() =>
|
||||||
|
handleEditItems(
|
||||||
|
item.id,
|
||||||
|
item.item_name,
|
||||||
|
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>
|
||||||
|
</Box>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -17,11 +17,7 @@ import MyAlert from "./myChakra/MyAlert";
|
|||||||
import { formatDateTime } from "@/utils/userFuncs";
|
import { formatDateTime } from "@/utils/userFuncs";
|
||||||
import { Trash2, RefreshCcwDot } from "lucide-react";
|
import { Trash2, RefreshCcwDot } from "lucide-react";
|
||||||
import { deleteLoan } from "@/utils/userActions";
|
import { deleteLoan } from "@/utils/userActions";
|
||||||
|
import { API_BASE } from "@/config/api.config";
|
||||||
const API_BASE =
|
|
||||||
(import.meta as any).env?.VITE_BACKEND_URL ||
|
|
||||||
import.meta.env.VITE_BACKEND_URL ||
|
|
||||||
"http://localhost:8002";
|
|
||||||
|
|
||||||
const LoanTable: React.FC = () => {
|
const LoanTable: React.FC = () => {
|
||||||
const [items, setItems] = useState<Loan[]>([]);
|
const [items, setItems] = useState<Loan[]>([]);
|
||||||
@@ -55,18 +51,22 @@ const LoanTable: React.FC = () => {
|
|||||||
created_at: string;
|
created_at: string;
|
||||||
loaned_items_name: string[];
|
loaned_items_name: string[];
|
||||||
deleted: boolean;
|
deleted: boolean;
|
||||||
|
note: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const fetchData = async () => {
|
const fetchData = async () => {
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${API_BASE}/api/allLoans`, {
|
const response = await fetch(
|
||||||
method: "GET",
|
`${API_BASE}/api/admin/loan-data/all-loans`,
|
||||||
headers: {
|
{
|
||||||
Authorization: `Bearer ${Cookies.get("token")}`,
|
method: "GET",
|
||||||
},
|
headers: {
|
||||||
});
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
return data;
|
return data;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -161,6 +161,9 @@ const LoanTable: React.FC = () => {
|
|||||||
<Table.ColumnHeader>
|
<Table.ColumnHeader>
|
||||||
<strong>Ausgeliehene Artikel</strong>
|
<strong>Ausgeliehene Artikel</strong>
|
||||||
</Table.ColumnHeader>
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader>
|
||||||
|
<strong>Notiz</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
<Table.ColumnHeader>
|
<Table.ColumnHeader>
|
||||||
<strong>Aktionen</strong>
|
<strong>Aktionen</strong>
|
||||||
</Table.ColumnHeader>
|
</Table.ColumnHeader>
|
||||||
@@ -180,6 +183,7 @@ const LoanTable: React.FC = () => {
|
|||||||
<Table.Cell>{formatDateTime(item.returned_date)}</Table.Cell>
|
<Table.Cell>{formatDateTime(item.returned_date)}</Table.Cell>
|
||||||
<Table.Cell>{formatDateTime(item.created_at)}</Table.Cell>
|
<Table.Cell>{formatDateTime(item.created_at)}</Table.Cell>
|
||||||
<Table.Cell>{item.loaned_items_name.join(", ")}</Table.Cell>
|
<Table.Cell>{item.loaned_items_name.join(", ")}</Table.Cell>
|
||||||
|
<Table.Cell>{item.note}</Table.Cell>
|
||||||
<Table.Cell>
|
<Table.Cell>
|
||||||
<Button
|
<Button
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
HStack,
|
HStack,
|
||||||
IconButton,
|
IconButton,
|
||||||
Heading,
|
Heading,
|
||||||
|
Switch, // neu
|
||||||
} from "@chakra-ui/react";
|
} from "@chakra-ui/react";
|
||||||
import { Tooltip } from "@/components/ui/tooltip";
|
import { Tooltip } from "@/components/ui/tooltip";
|
||||||
import { fetchUserData } from "@/utils/fetcher";
|
import { fetchUserData } from "@/utils/fetcher";
|
||||||
@@ -23,9 +24,13 @@ import ChangePWform from "./ChangePWform";
|
|||||||
type User = {
|
type User = {
|
||||||
id: number;
|
id: number;
|
||||||
username: string;
|
username: string;
|
||||||
password: string;
|
first_name: string;
|
||||||
role: string;
|
last_name: string;
|
||||||
|
email: string;
|
||||||
|
is_admin: boolean;
|
||||||
|
role: number;
|
||||||
entry_created_at: string;
|
entry_created_at: string;
|
||||||
|
entry_updated_at: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
const UserTable: React.FC = () => {
|
const UserTable: React.FC = () => {
|
||||||
@@ -52,10 +57,20 @@ const UserTable: React.FC = () => {
|
|||||||
setIsError(true);
|
setIsError(true);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleInputChange = (userId: number, field: string, value: string) => {
|
const handleInputChange = (userId: number, field: string, value: any) => {
|
||||||
setUsers((prevUsers) =>
|
setUsers((prevUsers) =>
|
||||||
prevUsers.map((user) =>
|
prevUsers.map((user) =>
|
||||||
user.id === userId ? { ...user, [field]: value } : user
|
user.id === userId
|
||||||
|
? {
|
||||||
|
...user,
|
||||||
|
[field]:
|
||||||
|
field === "role"
|
||||||
|
? Number(value)
|
||||||
|
: field === "is_admin"
|
||||||
|
? value === true || value === "true" || value === 1
|
||||||
|
: value,
|
||||||
|
}
|
||||||
|
: user
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@@ -70,7 +85,7 @@ const UserTable: React.FC = () => {
|
|||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
try {
|
try {
|
||||||
const data = await fetchUserData();
|
const data = await fetchUserData();
|
||||||
console.log("user api response", data);
|
console.log(data);
|
||||||
if (Array.isArray(data)) {
|
if (Array.isArray(data)) {
|
||||||
setUsers(data);
|
setUsers(data);
|
||||||
} else {
|
} else {
|
||||||
@@ -180,25 +195,45 @@ const UserTable: React.FC = () => {
|
|||||||
</VStack>
|
</VStack>
|
||||||
)}
|
)}
|
||||||
{!isLoading && (
|
{!isLoading && (
|
||||||
<Table.Root size="sm" striped>
|
<Table.Root
|
||||||
|
size="sm"
|
||||||
|
striped
|
||||||
|
w="100%"
|
||||||
|
style={{ tableLayout: "auto" }} // Spalten nach Content
|
||||||
|
>
|
||||||
<Table.Header>
|
<Table.Header>
|
||||||
<Table.Row>
|
<Table.Row>
|
||||||
<Table.ColumnHeader>
|
<Table.ColumnHeader width="1%" whiteSpace="nowrap">
|
||||||
<strong>#</strong>
|
<strong>#</strong>
|
||||||
</Table.ColumnHeader>
|
</Table.ColumnHeader>
|
||||||
<Table.ColumnHeader>
|
<Table.ColumnHeader>
|
||||||
<strong>Benutzername</strong>
|
<strong>Benutzername</strong>
|
||||||
</Table.ColumnHeader>
|
</Table.ColumnHeader>
|
||||||
<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>
|
<strong>Passwort ändern</strong>
|
||||||
</Table.ColumnHeader>
|
</Table.ColumnHeader>
|
||||||
<Table.ColumnHeader>
|
<Table.ColumnHeader width="1%" whiteSpace="nowrap">
|
||||||
<strong>Rolle</strong>
|
<strong>Rolle</strong>
|
||||||
</Table.ColumnHeader>
|
</Table.ColumnHeader>
|
||||||
<Table.ColumnHeader>
|
<Table.ColumnHeader whiteSpace="nowrap">
|
||||||
<strong>Eintrag erstellt am</strong>
|
<strong>Eintrag erstellt am</strong>
|
||||||
</Table.ColumnHeader>
|
</Table.ColumnHeader>
|
||||||
<Table.ColumnHeader>
|
<Table.ColumnHeader whiteSpace="nowrap">
|
||||||
|
<strong>Eintrag aktualisiert am</strong>
|
||||||
|
</Table.ColumnHeader>
|
||||||
|
<Table.ColumnHeader width="1%" whiteSpace="nowrap">
|
||||||
<strong>Aktionen</strong>
|
<strong>Aktionen</strong>
|
||||||
</Table.ColumnHeader>
|
</Table.ColumnHeader>
|
||||||
</Table.Row>
|
</Table.Row>
|
||||||
@@ -206,37 +241,86 @@ const UserTable: React.FC = () => {
|
|||||||
<Table.Body>
|
<Table.Body>
|
||||||
{users.map((user) => (
|
{users.map((user) => (
|
||||||
<Table.Row key={user.id}>
|
<Table.Row key={user.id}>
|
||||||
<Table.Cell>{user.id}</Table.Cell>
|
<Table.Cell whiteSpace="nowrap">{user.id}</Table.Cell>
|
||||||
|
<Table.Cell>{user.username}</Table.Cell>
|
||||||
<Table.Cell>
|
<Table.Cell>
|
||||||
<Input
|
<Input
|
||||||
|
size="sm"
|
||||||
|
value={user.first_name ?? ""}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
handleInputChange(user.id, "username", e.target.value)
|
handleInputChange(user.id, "first_name", e.target.value)
|
||||||
}
|
}
|
||||||
value={user.username}
|
|
||||||
/>
|
/>
|
||||||
</Table.Cell>
|
</Table.Cell>
|
||||||
<Table.Cell>
|
<Table.Cell>
|
||||||
<Button onClick={() => handlePasswordChange(user.username)}>
|
<Input
|
||||||
Passwort ändern
|
size="sm"
|
||||||
</Button>
|
value={user.last_name ?? ""}
|
||||||
|
onChange={(e) =>
|
||||||
|
handleInputChange(user.id, "last_name", e.target.value)
|
||||||
|
}
|
||||||
|
/>
|
||||||
</Table.Cell>
|
</Table.Cell>
|
||||||
<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
|
<Input
|
||||||
type="number"
|
type="number"
|
||||||
|
size="sm"
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
handleInputChange(user.id, "role", e.target.value)
|
handleInputChange(user.id, "role", e.target.value)
|
||||||
}
|
}
|
||||||
value={user.role}
|
value={user.role}
|
||||||
|
width="70px"
|
||||||
/>
|
/>
|
||||||
</Table.Cell>
|
</Table.Cell>
|
||||||
<Table.Cell>{formatDateTime(user.entry_created_at)}</Table.Cell>
|
<Table.Cell whiteSpace="nowrap">
|
||||||
<Table.Cell>
|
{formatDateTime(user.entry_created_at)}
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell whiteSpace="nowrap">
|
||||||
|
{formatDateTime(user.entry_updated_at)}
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell whiteSpace="nowrap">
|
||||||
<Button
|
<Button
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
handleEdit(
|
handleEdit(
|
||||||
user.id,
|
user.id,
|
||||||
user.username,
|
user.first_name,
|
||||||
user.role,
|
user.last_name,
|
||||||
|
user.email,
|
||||||
|
user.is_admin,
|
||||||
|
Number(user.role)
|
||||||
).then((response) => {
|
).then((response) => {
|
||||||
if (response.success) {
|
if (response.success) {
|
||||||
setError(
|
setError(
|
||||||
|
|||||||
4
admin/src/config/api.config.ts
Normal file
4
admin/src/config/api.config.ts
Normal file
@@ -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";
|
||||||
@@ -1,12 +1,8 @@
|
|||||||
import Cookies from "js-cookie";
|
import Cookies from "js-cookie";
|
||||||
|
import { API_BASE } from "@/config/api.config";
|
||||||
const API_BASE =
|
|
||||||
(import.meta as any).env?.VITE_BACKEND_URL ||
|
|
||||||
import.meta.env.VITE_BACKEND_URL ||
|
|
||||||
"http://localhost:8002";
|
|
||||||
|
|
||||||
export const fetchUserData = async () => {
|
export const fetchUserData = async () => {
|
||||||
const response = await fetch(`${API_BASE}/api/allUsers`, {
|
const response = await fetch(`${API_BASE}/api/admin/user-data/users`, {
|
||||||
headers: {
|
headers: {
|
||||||
Authorization: `Bearer ${Cookies.get("token")}`,
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,9 +1,5 @@
|
|||||||
import Cookies from "js-cookie";
|
import Cookies from "js-cookie";
|
||||||
|
import { API_BASE } from "@/config/api.config";
|
||||||
const API_BASE =
|
|
||||||
(import.meta as any).env?.VITE_BACKEND_URL ||
|
|
||||||
import.meta.env.VITE_BACKEND_URL ||
|
|
||||||
"http://localhost:8002";
|
|
||||||
|
|
||||||
export type LoginSuccess = { success: true };
|
export type LoginSuccess = { success: true };
|
||||||
export type LoginFailure = {
|
export type LoginFailure = {
|
||||||
@@ -18,12 +14,20 @@ export const loginFunc = async (
|
|||||||
password: string
|
password: string
|
||||||
): Promise<LoginResult> => {
|
): Promise<LoginResult> => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${API_BASE}/api/loginAdmin`, {
|
const response = await fetch(`${API_BASE}/api/admin/user-mgmt/login`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ username, password }),
|
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) {
|
if (!response.ok) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
@@ -39,6 +43,7 @@ export const loginFunc = async (
|
|||||||
return { success: true };
|
return { success: true };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error logging in:", error);
|
console.error("Error logging in:", error);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
message: "Login failed!",
|
message: "Login failed!",
|
||||||
|
|||||||
@@ -1,14 +1,10 @@
|
|||||||
import Cookies from "js-cookie";
|
import Cookies from "js-cookie";
|
||||||
|
import { API_BASE } from "@/config/api.config";
|
||||||
const API_BASE =
|
|
||||||
(import.meta as any).env?.VITE_BACKEND_URL ||
|
|
||||||
import.meta.env.VITE_BACKEND_URL ||
|
|
||||||
"http://localhost:8002";
|
|
||||||
|
|
||||||
export const handleDelete = async (userId: number) => {
|
export const handleDelete = async (userId: number) => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(
|
const response = await fetch(
|
||||||
`${API_BASE}/api/deleteUser/${userId}`,
|
`${API_BASE}/api/admin/user-data/delete-user/${userId}`,
|
||||||
{
|
{
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
headers: {
|
headers: {
|
||||||
@@ -28,19 +24,28 @@ export const handleDelete = async (userId: number) => {
|
|||||||
|
|
||||||
export const handleEdit = async (
|
export const handleEdit = async (
|
||||||
userId: number,
|
userId: number,
|
||||||
username: string,
|
first_name: string,
|
||||||
role: string
|
last_name: string,
|
||||||
|
email: string,
|
||||||
|
is_admin: boolean,
|
||||||
|
role: number
|
||||||
) => {
|
) => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(
|
const response = await fetch(
|
||||||
`${API_BASE}/api/editUser/${userId}`,
|
`${API_BASE}/api/admin/user-data/edit-user/${userId}`,
|
||||||
{
|
{
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
Authorization: `Bearer ${Cookies.get("token")}`,
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
},
|
},
|
||||||
body: JSON.stringify({ username, role }),
|
body: JSON.stringify({
|
||||||
|
first_name,
|
||||||
|
last_name,
|
||||||
|
role,
|
||||||
|
email,
|
||||||
|
is_admin,
|
||||||
|
}),
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
@@ -56,17 +61,32 @@ export const handleEdit = async (
|
|||||||
export const createUser = async (
|
export const createUser = async (
|
||||||
username: string,
|
username: string,
|
||||||
role: number,
|
role: number,
|
||||||
password: string
|
password: string,
|
||||||
|
first_name: string,
|
||||||
|
last_name: string,
|
||||||
|
email: string,
|
||||||
|
isAdmin: boolean
|
||||||
) => {
|
) => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${API_BASE}/api/createUser`, {
|
const response = await fetch(
|
||||||
method: "POST",
|
`${API_BASE}/api/admin/user-data/create-user`,
|
||||||
headers: {
|
{
|
||||||
"Content-Type": "application/json",
|
method: "POST",
|
||||||
Authorization: `Bearer ${Cookies.get("token")}`,
|
headers: {
|
||||||
},
|
"Content-Type": "application/json",
|
||||||
body: JSON.stringify({ username, role, password }),
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
});
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
username,
|
||||||
|
role,
|
||||||
|
password,
|
||||||
|
isAdmin,
|
||||||
|
email,
|
||||||
|
first_name,
|
||||||
|
last_name,
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
);
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error("Failed to create user");
|
throw new Error("Failed to create user");
|
||||||
}
|
}
|
||||||
@@ -79,14 +99,17 @@ export const createUser = async (
|
|||||||
|
|
||||||
export const changePW = async (newPassword: string, username: string) => {
|
export const changePW = async (newPassword: string, username: string) => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${API_BASE}/api/changePWadmin`, {
|
const response = await fetch(
|
||||||
method: "POST",
|
`${API_BASE}/api/admin/user-data/change-password`,
|
||||||
headers: {
|
{
|
||||||
"Content-Type": "application/json",
|
method: "POST",
|
||||||
Authorization: `Bearer ${Cookies.get("token")}`,
|
headers: {
|
||||||
},
|
"Content-Type": "application/json",
|
||||||
body: JSON.stringify({ newPassword, username }),
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
});
|
},
|
||||||
|
body: JSON.stringify({ username, password: newPassword }),
|
||||||
|
}
|
||||||
|
);
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error("Failed to change password");
|
throw new Error("Failed to change password");
|
||||||
}
|
}
|
||||||
@@ -100,7 +123,7 @@ export const changePW = async (newPassword: string, username: string) => {
|
|||||||
export const deleteLoan = async (loanId: number) => {
|
export const deleteLoan = async (loanId: number) => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(
|
const response = await fetch(
|
||||||
`${API_BASE}/api/deleteLoan/${loanId}`,
|
`${API_BASE}/api/admin/loan-data/delete-loan/${loanId}`,
|
||||||
{
|
{
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
headers: {
|
headers: {
|
||||||
@@ -121,7 +144,7 @@ export const deleteLoan = async (loanId: number) => {
|
|||||||
export const deleteItem = async (itemId: number) => {
|
export const deleteItem = async (itemId: number) => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(
|
const response = await fetch(
|
||||||
`${API_BASE}/api/deleteItem/${itemId}`,
|
`${API_BASE}/api/admin/item-data/delete-item/${itemId}`,
|
||||||
{
|
{
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
headers: {
|
headers: {
|
||||||
@@ -144,14 +167,17 @@ export const createItem = async (
|
|||||||
can_borrow_role: number
|
can_borrow_role: number
|
||||||
) => {
|
) => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${API_BASE}/api/createItem`, {
|
const response = await fetch(
|
||||||
method: "POST",
|
`${API_BASE}/api/admin/item-data/create-item`,
|
||||||
headers: {
|
{
|
||||||
"Content-Type": "application/json",
|
method: "POST",
|
||||||
Authorization: `Bearer ${Cookies.get("token")}`,
|
headers: {
|
||||||
},
|
"Content-Type": "application/json",
|
||||||
body: JSON.stringify({ item_name, can_borrow_role }),
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
});
|
},
|
||||||
|
body: JSON.stringify({ item_name, can_borrow_role }),
|
||||||
|
}
|
||||||
|
);
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
@@ -172,14 +198,17 @@ export const handleEditItems = async (
|
|||||||
can_borrow_role: string
|
can_borrow_role: string
|
||||||
) => {
|
) => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${API_BASE}/api/updateItemByID`, {
|
const response = await fetch(
|
||||||
method: "POST",
|
`${API_BASE}/api/admin/item-data/edit-item/${itemId}`,
|
||||||
headers: {
|
{
|
||||||
"Content-Type": "application/json",
|
method: "POST",
|
||||||
Authorization: `Bearer ${Cookies.get("token")}`,
|
headers: {
|
||||||
},
|
"Content-Type": "application/json",
|
||||||
body: JSON.stringify({ itemId, item_name, can_borrow_role }),
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
});
|
},
|
||||||
|
body: JSON.stringify({ item_name, can_borrow_role }),
|
||||||
|
}
|
||||||
|
);
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error("Failed to edit item");
|
throw new Error("Failed to edit item");
|
||||||
}
|
}
|
||||||
@@ -193,9 +222,9 @@ export const handleEditItems = async (
|
|||||||
export const changeSafeState = async (itemId: number) => {
|
export const changeSafeState = async (itemId: number) => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(
|
const response = await fetch(
|
||||||
`${API_BASE}/api/changeSafeState/${itemId}`,
|
`${API_BASE}/api/admin/item-data/change-safe-state/${itemId}`,
|
||||||
{
|
{
|
||||||
method: "PUT",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
Authorization: `Bearer ${Cookies.get("token")}`,
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
},
|
},
|
||||||
@@ -211,16 +240,19 @@ export const changeSafeState = async (itemId: number) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const createAPIentry = async (apiKey: string, user: string) => {
|
export const createAPIentry = async (apiKey: string, name: string) => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${API_BASE}/api/createAPIentry`, {
|
const response = await fetch(
|
||||||
method: "POST",
|
`${API_BASE}/api/admin/api-data/create-api-key`,
|
||||||
headers: {
|
{
|
||||||
"Content-Type": "application/json",
|
method: "POST",
|
||||||
Authorization: `Bearer ${Cookies.get("token")}`,
|
headers: {
|
||||||
},
|
"Content-Type": "application/json",
|
||||||
body: JSON.stringify({ apiKey, user }),
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
});
|
},
|
||||||
|
body: JSON.stringify({ apiKey, entryName: name }),
|
||||||
|
}
|
||||||
|
);
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
@@ -238,7 +270,7 @@ export const createAPIentry = async (apiKey: string, user: string) => {
|
|||||||
export const deleteAPKey = async (apiKeyId: number) => {
|
export const deleteAPKey = async (apiKeyId: number) => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(
|
const response = await fetch(
|
||||||
`${API_BASE}/api/deleteAPKey/${apiKeyId}`,
|
`${API_BASE}/api/admin/api-data/delete-api-key/${apiKeyId}`,
|
||||||
{
|
{
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
headers: {
|
headers: {
|
||||||
|
|||||||
@@ -30,7 +30,7 @@
|
|||||||
},
|
},
|
||||||
|
|
||||||
"forceConsistentCasingInFileNames": true,
|
"forceConsistentCasingInFileNames": true,
|
||||||
"ignoreDeprecations": "6.0"
|
"ignoreDeprecations": "5.0"
|
||||||
},
|
},
|
||||||
"include": ["src"]
|
"include": ["src"]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
FROM node:20-alpine
|
FROM node:20-alpine
|
||||||
|
|
||||||
|
ENV NODE_ENV=production
|
||||||
WORKDIR /backend
|
WORKDIR /backend
|
||||||
|
|
||||||
COPY package*.json ./
|
COPY package*.json ./
|
||||||
RUN npm install
|
RUN npm ci --omit=dev
|
||||||
|
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
EXPOSE 8002
|
EXPOSE 8002
|
||||||
|
|
||||||
CMD ["npm", "start"]
|
CMD ["npm", "start"]
|
||||||
@@ -1,12 +1,12 @@
|
|||||||
FROM node:20-alpine
|
FROM node:20-alpine
|
||||||
|
|
||||||
WORKDIR /backendV2
|
ENV NODE_ENV=production
|
||||||
|
WORKDIR /backend
|
||||||
|
|
||||||
COPY package*.json ./
|
COPY package*.json ./
|
||||||
RUN npm install
|
RUN npm ci --omit=dev
|
||||||
|
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
EXPOSE 8004
|
EXPOSE 8004
|
||||||
|
|
||||||
CMD ["npm", "start"]
|
CMD ["npm", "start"]
|
||||||
@@ -4,5 +4,8 @@
|
|||||||
},
|
},
|
||||||
"frontend-info": {
|
"frontend-info": {
|
||||||
"version": "v2.0 (dev)"
|
"version": "v2.0 (dev)"
|
||||||
|
},
|
||||||
|
"admin-panel-info": {
|
||||||
|
"version": "v1.2 (dev)"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
41
backendV2/routes/admin/apiDataMgmt.route.js
Normal file
41
backendV2/routes/admin/apiDataMgmt.route.js
Normal file
@@ -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;
|
||||||
37
backendV2/routes/admin/database/apiDataMgmt.database.js
Normal file
37
backendV2/routes/admin/database/apiDataMgmt.database.js
Normal file
@@ -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 };
|
||||||
|
};
|
||||||
70
backendV2/routes/admin/database/itemDataMgmt.database.js
Normal file
70
backendV2/routes/admin/database/itemDataMgmt.database.js
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
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, in_safe) => {
|
||||||
|
const [result] = await pool.query(
|
||||||
|
"INSERT INTO items (item_name, can_borrow_role, in_safe) VALUES (?, ?, ?)",
|
||||||
|
[item_name, can_borrow_role, true]
|
||||||
|
);
|
||||||
|
if (result.affectedRows > 0) return { success: true };
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const editItemById = async (itemId, item_name, can_borrow_role) => {
|
||||||
|
const [result] = await pool.query(
|
||||||
|
"UPDATE items SET item_name = ?, can_borrow_role = ?, entry_updated_at = NOW() WHERE id = ?",
|
||||||
|
[item_name, can_borrow_role, 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 };
|
||||||
|
};
|
||||||
23
backendV2/routes/admin/database/loanDataMgmt.database.js
Normal file
23
backendV2/routes/admin/database/loanDataMgmt.database.js
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
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");
|
||||||
|
return { success: true, data: rows };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const deleteLoanById = async (loanId) => {
|
||||||
|
const [result] = await pool.query("DELETE FROM loans WHERE id = ?", [loanId]);
|
||||||
|
if (result.affectedRows > 0) return { success: true };
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
79
backendV2/routes/admin/database/userDataMgmt.database.js
Normal file
79
backendV2/routes/admin/database/userDataMgmt.database.js
Normal file
@@ -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 (userId, newPassword) => {
|
||||||
|
const [result] = await pool.query(
|
||||||
|
"UPDATE users SET password = ? WHERE id = ?",
|
||||||
|
[newPassword, userId]
|
||||||
|
);
|
||||||
|
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 = ? 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] };
|
||||||
|
};
|
||||||
47
backendV2/routes/admin/database/userMgmt.database.js
Normal file
47
backendV2/routes/admin/database/userMgmt.database.js
Normal file
@@ -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 };
|
||||||
|
};
|
||||||
65
backendV2/routes/admin/itemDataMgmt.route.js
Normal file
65
backendV2/routes/admin/itemDataMgmt.route.js
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
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 } = req.body;
|
||||||
|
const result = await createItem(item_name, can_borrow_role);
|
||||||
|
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 } = req.body;
|
||||||
|
const result = await editItemById(
|
||||||
|
itemId,
|
||||||
|
item_name,
|
||||||
|
can_borrow_role
|
||||||
|
);
|
||||||
|
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;
|
||||||
30
backendV2/routes/admin/loanDataMgmt.route.js
Normal file
30
backendV2/routes/admin/loanDataMgmt.route.js
Normal file
@@ -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;
|
||||||
123
backendV2/routes/admin/userDataMgmt.route.js
Normal file
123
backendV2/routes/admin/userDataMgmt.route.js
Normal file
@@ -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;
|
||||||
54
backendV2/routes/admin/userMgmt.route.js
Normal file
54
backendV2/routes/admin/userMgmt.route.js
Normal file
@@ -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;
|
||||||
116
backendV2/routes/api/api.database.js
Normal file
116
backendV2/routes/api/api.database.js
Normal file
@@ -0,0 +1,116 @@
|
|||||||
|
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 first_name, 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 inSafe = NOT inSafe WHERE id = ?",
|
||||||
|
[itemId]
|
||||||
|
);
|
||||||
|
if (result.affectedRows > 0) {
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const setReturnDateV2 = 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 inSafe = 1, currently_borrowing = NULL, last_borrowed_person = (?) WHERE id IN (?)",
|
||||||
|
[owner[0].username, itemIds]
|
||||||
|
);
|
||||||
|
|
||||||
|
const [result] = await pool.query(
|
||||||
|
"UPDATE loans SET returned_date = NOW() WHERE loan_code = ?",
|
||||||
|
[loanCode]
|
||||||
|
);
|
||||||
|
|
||||||
|
if (result.affectedRows > 0 && setItemStates.affectedRows > 0) {
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const setTakeDateV2 = async (loanCode) => {
|
||||||
|
const [items] = await pool.query(
|
||||||
|
"SELECT loaned_items_id FROM loans WHERE loan_code = ?",
|
||||||
|
[loanCode]
|
||||||
|
);
|
||||||
|
|
||||||
|
const [owner] = await pool.query(
|
||||||
|
"SELECT username FROM loans WHERE loan_code = ?",
|
||||||
|
[loanCode]
|
||||||
|
);
|
||||||
|
|
||||||
|
if (items.length === 0) return { success: false };
|
||||||
|
|
||||||
|
const itemIds = Array.isArray(items[0].loaned_items_id)
|
||||||
|
? items[0].loaned_items_id
|
||||||
|
: JSON.parse(items[0].loaned_items_id || "[]");
|
||||||
|
|
||||||
|
const [setItemStates] = await pool.query(
|
||||||
|
"UPDATE items SET inSafe = 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 };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getAllLoansV2 = async () => {
|
||||||
|
const [result] = await pool.query("SELECT * FROM loans;");
|
||||||
|
if (result.length > 0) {
|
||||||
|
return { success: true, data: result };
|
||||||
|
}
|
||||||
|
return { success: false };
|
||||||
|
};
|
||||||
91
backendV2/routes/api/api.route.js
Normal file
91
backendV2/routes/api/api.route.js
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
import express from "express";
|
||||||
|
import { authenticate } from "../../services/authentication.js";
|
||||||
|
const router = express.Router();
|
||||||
|
import dotenv from "dotenv";
|
||||||
|
dotenv.config();
|
||||||
|
|
||||||
|
import {
|
||||||
|
getItemsFromDatabaseV2,
|
||||||
|
changeInSafeStateV2,
|
||||||
|
setTakeDateV2,
|
||||||
|
setReturnDateV2,
|
||||||
|
getLoanByCodeV2,
|
||||||
|
} 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/:state",
|
||||||
|
authenticate,
|
||||||
|
async (req, res) => {
|
||||||
|
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" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// Route for API to get a loan by its code
|
||||||
|
router.get(
|
||||||
|
"/get-loan-by-code/:key/:loan_code",
|
||||||
|
authenticate,
|
||||||
|
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,
|
||||||
|
async (req, res) => {
|
||||||
|
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" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// Route for API to set the take away date by the loan code
|
||||||
|
router.post(
|
||||||
|
"/set-take-date/:key/:loan_code",
|
||||||
|
authenticate,
|
||||||
|
async (req, res) => {
|
||||||
|
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" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
export default router;
|
||||||
254
backendV2/routes/app/database/loansMgmt.database.js
Normal file
254
backendV2/routes/app/database/loansMgmt.database.js
Normal file
@@ -0,0 +1,254 @@
|
|||||||
|
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
|
||||||
|
)
|
||||||
|
.filter(Boolean);
|
||||||
|
|
||||||
|
// Build lockers array (unique, only 2-digit strings)
|
||||||
|
const lockers = [
|
||||||
|
...new Set(
|
||||||
|
itemsRows
|
||||||
|
.map((r) => r.safe_nr)
|
||||||
|
.filter((sn) => typeof sn === "string" && /^\d{2}$/.test(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",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate unique loan_code (retry a few times)
|
||||||
|
let loanCode = null;
|
||||||
|
for (let i = 0; i < 6; i++) {
|
||||||
|
const candidate = Math.floor(100000 + Math.random() * 899999); // 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 (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 [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 };
|
||||||
|
};
|
||||||
55
backendV2/routes/app/database/userMgmt.database.js
Normal file
55
backendV2/routes/app/database/userMgmt.database.js
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
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 };
|
||||||
|
};
|
||||||
150
backendV2/routes/app/loanMgmt.route.js
Normal file
150
backendV2/routes/app/loanMgmt.route.js
Normal file
@@ -0,0 +1,150 @@
|
|||||||
|
import express from "express";
|
||||||
|
import { authenticate, generateToken } from "../../services/authentication.js";
|
||||||
|
const router = express.Router();
|
||||||
|
import dotenv from "dotenv";
|
||||||
|
dotenv.config();
|
||||||
|
|
||||||
|
// database funcs import
|
||||||
|
import {
|
||||||
|
createLoanInDatabase,
|
||||||
|
getLoanInfoWithID,
|
||||||
|
getLoansFromDatabase,
|
||||||
|
getBorrowableItemsFromDatabase,
|
||||||
|
getALLLoans,
|
||||||
|
getItems,
|
||||||
|
SETdeleteLoanFromDatabase,
|
||||||
|
} from "./database/loansMgmt.database.js";
|
||||||
|
import { sendMailLoan } from "./services/mailer.js";
|
||||||
|
|
||||||
|
router.post("/createLoan", authenticate, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { items, startDate, endDate, note } = req.body || {};
|
||||||
|
|
||||||
|
if (!Array.isArray(items) || items.length === 0) {
|
||||||
|
return res.status(400).json({ message: "Items array is required" });
|
||||||
|
}
|
||||||
|
|
||||||
|
// If dates are not provided, default to now .. +7 days
|
||||||
|
const start =
|
||||||
|
startDate ?? new Date().toISOString().slice(0, 19).replace("T", " ");
|
||||||
|
const end =
|
||||||
|
endDate ??
|
||||||
|
new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
|
||||||
|
.toISOString()
|
||||||
|
.slice(0, 19)
|
||||||
|
.replace("T", " ");
|
||||||
|
|
||||||
|
// Coerce item IDs to numbers and filter invalids
|
||||||
|
const itemIds = items
|
||||||
|
.map((v) => Number(v))
|
||||||
|
.filter((n) => Number.isFinite(n));
|
||||||
|
|
||||||
|
if (itemIds.length === 0) {
|
||||||
|
return res.status(400).json({ message: "No valid item IDs provided" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await createLoanInDatabase(
|
||||||
|
req.user.username,
|
||||||
|
start,
|
||||||
|
end,
|
||||||
|
note,
|
||||||
|
itemIds
|
||||||
|
);
|
||||||
|
|
||||||
|
if (result.success) {
|
||||||
|
const mailInfo = await getLoanInfoWithID(result.data.id);
|
||||||
|
console.log(mailInfo);
|
||||||
|
sendMailLoan(
|
||||||
|
mailInfo.data.username,
|
||||||
|
mailInfo.data.loaned_items_name,
|
||||||
|
mailInfo.data.start_date,
|
||||||
|
mailInfo.data.end_date,
|
||||||
|
mailInfo.data.created_at
|
||||||
|
);
|
||||||
|
return res.status(201).json({
|
||||||
|
message: "Loan created successfully",
|
||||||
|
loanId: result.data.id,
|
||||||
|
loanCode: result.data.loan_code,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.code === "CONFLICT") {
|
||||||
|
return res
|
||||||
|
.status(409)
|
||||||
|
.json({ message: "Items not available in the selected period" });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.code === "BAD_REQUEST") {
|
||||||
|
return res.status(400).json({ message: result.message });
|
||||||
|
}
|
||||||
|
|
||||||
|
return res.status(500).json({ message: "Failed to create loan" });
|
||||||
|
} catch (err) {
|
||||||
|
console.error("createLoan error:", err);
|
||||||
|
return res.status(500).json({ message: "Failed to create loan" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.get("/loans", authenticate, async (req, res) => {
|
||||||
|
const result = await getLoansFromDatabase(req.user.username);
|
||||||
|
if (result.success) {
|
||||||
|
res.status(200).json(result.data);
|
||||||
|
} else if (result.status) {
|
||||||
|
res.status(200).json([]);
|
||||||
|
} else {
|
||||||
|
res.status(500).json({ message: "Failed to fetch loans" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.get("/all-items", authenticate, async (req, res) => {
|
||||||
|
const result = await getItems();
|
||||||
|
if (result.success) {
|
||||||
|
res.status(200).json(result.data);
|
||||||
|
} else {
|
||||||
|
res.status(500).json({ message: "Failed to fetch items" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.delete("/delete-loan/:id", authenticate, async (req, res) => {
|
||||||
|
const loanId = req.params.id;
|
||||||
|
const result = await SETdeleteLoanFromDatabase(loanId);
|
||||||
|
if (result.success) {
|
||||||
|
res.status(200).json({ message: "Loan deleted successfully" });
|
||||||
|
} else {
|
||||||
|
res.status(500).json({ message: "Failed to delete loan" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.get("/all-loans", authenticate, async (req, res) => {
|
||||||
|
const result = await getALLLoans();
|
||||||
|
if (result.success) {
|
||||||
|
res.status(200).json(result.data);
|
||||||
|
} else {
|
||||||
|
res.status(500).json({ message: "Failed to fetch loans" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post("/borrowable-items", authenticate, async (req, res) => {
|
||||||
|
const { startDate, endDate } = req.body || {};
|
||||||
|
if (!startDate || !endDate) {
|
||||||
|
return res
|
||||||
|
.status(400)
|
||||||
|
.json({ message: "startDate and endDate are required" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await getBorrowableItemsFromDatabase(
|
||||||
|
startDate,
|
||||||
|
endDate,
|
||||||
|
req.user.role
|
||||||
|
);
|
||||||
|
if (result.success) {
|
||||||
|
// return the array directly for consistency with /items
|
||||||
|
return res.status(200).json(result.data);
|
||||||
|
} else {
|
||||||
|
return res
|
||||||
|
.status(500)
|
||||||
|
.json({ message: "Failed to fetch borrowable items" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export default router;
|
||||||
148
backendV2/routes/app/services/mailer.js
Normal file
148
backendV2/routes/app/services/mailer.js
Normal file
@@ -0,0 +1,148 @@
|
|||||||
|
import nodemailer from "nodemailer";
|
||||||
|
import dotenv from "dotenv";
|
||||||
|
dotenv.config();
|
||||||
|
|
||||||
|
function buildLoanEmail({ user, items, startDate, endDate, createdDate }) {
|
||||||
|
const brand = process.env.MAIL_BRAND_COLOR || "#0ea5e9";
|
||||||
|
const itemsList =
|
||||||
|
Array.isArray(items) && items.length
|
||||||
|
? `<ul style="margin:4px 0 0 18px; padding:0;">${items
|
||||||
|
.map(
|
||||||
|
(i) =>
|
||||||
|
`<li style="margin:2px 0; color:#111827; line-height:1.3;">${i}</li>`
|
||||||
|
)
|
||||||
|
.join("")}</ul>`
|
||||||
|
: "<span style='color:#111827;'>N/A</span>";
|
||||||
|
|
||||||
|
return `<!doctype html>
|
||||||
|
<html lang="de">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="color-scheme" content="light">
|
||||||
|
<meta name="supported-color-schemes" content="light">
|
||||||
|
<meta name="x-apple-disable-message-reformatting">
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
|
<style>
|
||||||
|
:root { color-scheme: light; supported-color-schemes: light; }
|
||||||
|
body { margin:0; padding:0; }
|
||||||
|
/* Mobile stacking */
|
||||||
|
@media (max-width:480px) {
|
||||||
|
.outer { width:100% !important; }
|
||||||
|
.pad-sm { padding:16px !important; }
|
||||||
|
.w-label { width:120px !important; }
|
||||||
|
}
|
||||||
|
/* Dark-mode override safety */
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
body, table, td, p, a, h1, h2, h3 { background:#ffffff !important; color:#111827 !important; }
|
||||||
|
.brand-header { background:${brand} !important; color:#ffffff !important; }
|
||||||
|
a { color:${brand} !important; }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body bgcolor="#ffffff" style="background:#ffffff; font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Arial,sans-serif; color:#111827; -webkit-text-size-adjust:100%;">
|
||||||
|
<!-- Preheader (hidden) -->
|
||||||
|
<div style="display:none; max-height:0; overflow:hidden; opacity:0; mso-hide:all;">
|
||||||
|
Neue Ausleihe erstellt – Übersicht der Buchung.
|
||||||
|
</div>
|
||||||
|
<div role="article" aria-roledescription="email" lang="de" style="padding:24px; background:#f2f4f7;">
|
||||||
|
<table role="presentation" cellpadding="0" cellspacing="0" width="100%" class="outer" style="max-width:600px; margin:0 auto; background:#ffffff; border:1px solid #e5e7eb; border-radius:14px; overflow:hidden;">
|
||||||
|
<tr>
|
||||||
|
<td class="brand-header" style="padding:22px 26px; background:${brand}; color:#ffffff;">
|
||||||
|
<h1 style="margin:0; font-size:18px; line-height:1.35; font-weight:600;">Neue Ausleihe erstellt</h1>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td class="pad-sm" style="padding:24px 26px; color:#111827;">
|
||||||
|
<p style="margin:0 0 14px 0; line-height:1.4;">Es wurde eine neue Ausleihe angelegt. Hier sind die Details:</p>
|
||||||
|
<table role="presentation" cellpadding="0" cellspacing="0" width="100%" style="border-collapse:collapse; font-size:14px; line-height:1.3; background:#fcfcfd; border:1px solid #e5e7eb; border-radius:10px; overflow:hidden;">
|
||||||
|
<tbody>
|
||||||
|
<tr>
|
||||||
|
<td class="w-label" style="padding:10px 14px; color:#6b7280; width:170px; border-bottom:1px solid #ececec;">Benutzer</td>
|
||||||
|
<td style="padding:10px 14px; font-weight:600; border-bottom:1px solid #ececec; color:#111827;">${
|
||||||
|
user || "N/A"
|
||||||
|
}</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td style="padding:10px 14px; color:#6b7280; vertical-align:top; border-bottom:1px solid #ececec;">Ausgeliehene Gegenstände</td>
|
||||||
|
<td style="padding:10px 14px; font-weight:600; border-bottom:1px solid #ececec; color:#111827;">${itemsList}</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td style="padding:10px 14px; color:#6b7280; border-bottom:1px solid #ececec;">Startdatum</td>
|
||||||
|
<td style="padding:10px 14px; font-weight:600; border-bottom:1px solid #ececec; color:#111827;">${formatDateTime(
|
||||||
|
startDate
|
||||||
|
)}</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td style="padding:10px 14px; color:#6b7280; border-bottom:1px solid #ececec;">Enddatum</td>
|
||||||
|
<td style="padding:10px 14px; font-weight:600; border-bottom:1px solid #ececec; color:#111827;">${formatDateTime(
|
||||||
|
endDate
|
||||||
|
)}</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td style="padding:10px 14px; color:#6b7280;">Erstellt am</td>
|
||||||
|
<td style="padding:10px 14px; font-weight:600; color:#111827;">${formatDateTime(
|
||||||
|
createdDate
|
||||||
|
)}</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
<p style="margin:22px 0 0 0; font-size:14px;">
|
||||||
|
<a href="https://admin.insta.the1s.de/api" style="display:inline-block; background:${brand}; color:#ffffff; text-decoration:none; padding:10px 16px; border-radius:6px; font-weight:600; font-size:14px;" target="_blank" rel="noopener noreferrer">
|
||||||
|
Übersicht öffnen
|
||||||
|
</a>
|
||||||
|
</p>
|
||||||
|
<p style="margin:18px 0 0 0; font-size:12px; color:#6b7280; line-height:1.4;">
|
||||||
|
Diese E-Mail wurde automatisch vom Ausleihsystem gesendet. Bitte nicht antworten.
|
||||||
|
</p>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildLoanEmailText({ user, items, startDate, endDate, createdDate }) {
|
||||||
|
const itemsText =
|
||||||
|
Array.isArray(items) && items.length ? items.join(", ") : "N/A";
|
||||||
|
return [
|
||||||
|
"Neue Ausleihe erstellt",
|
||||||
|
"",
|
||||||
|
`Benutzer: ${user || "N/A"}`,
|
||||||
|
`Gegenstände: ${itemsText}`,
|
||||||
|
`Start: ${formatDateTime(startDate)}`,
|
||||||
|
`Ende: ${formatDateTime(endDate)}`,
|
||||||
|
`Erstellt am: ${formatDateTime(createdDate)}`,
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sendMailLoan(user, items, startDate, endDate, createdDate) {
|
||||||
|
const transporter = nodemailer.createTransport({
|
||||||
|
host: process.env.MAIL_HOST,
|
||||||
|
port: process.env.MAIL_PORT,
|
||||||
|
secure: true,
|
||||||
|
auth: {
|
||||||
|
user: process.env.MAIL_USER,
|
||||||
|
pass: process.env.MAIL_PASSWORD,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
const info = await transporter.sendMail({
|
||||||
|
from: '"Ausleihsystem" <noreply@mcs-medien.de>',
|
||||||
|
to: process.env.MAIL_SENDEES,
|
||||||
|
subject: "Eine neue Ausleihe wurde erstellt!",
|
||||||
|
text: buildLoanEmailText({
|
||||||
|
user,
|
||||||
|
items,
|
||||||
|
startDate,
|
||||||
|
endDate,
|
||||||
|
createdDate,
|
||||||
|
}),
|
||||||
|
html: buildLoanEmail({ user, items, startDate, endDate, createdDate }),
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log("Message sent:", info.messageId);
|
||||||
|
})();
|
||||||
|
console.log("sendMailLoan called");
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import express from "express";
|
||||||
|
import { authenticate, generateToken } from "../../services/authentication.js";
|
||||||
|
const router = express.Router();
|
||||||
|
import dotenv from "dotenv";
|
||||||
|
dotenv.config();
|
||||||
|
|
||||||
|
// database funcs import
|
||||||
|
import { loginFunc, changePassword } from "./database/userMgmt.database.js";
|
||||||
|
|
||||||
|
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.post("/change-password", authenticate, async (req, res) => {
|
||||||
|
const oldPassword = req.body.oldPassword;
|
||||||
|
const newPassword = req.body.newPassword;
|
||||||
|
const username = req.user.username;
|
||||||
|
const result = await changePassword(username, oldPassword, newPassword);
|
||||||
|
if (result.success) {
|
||||||
|
res.status(200).json({ message: "Password changed successfully" });
|
||||||
|
} else {
|
||||||
|
res.status(500).json({ message: "Failed to change password" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export default router;
|
||||||
|
|||||||
Binary file not shown.
@@ -1,91 +1,120 @@
|
|||||||
-- MUST BE UPDATED BEFORE USE
|
|
||||||
|
|
||||||
USE borrow_system_new;
|
USE borrow_system_new;
|
||||||
|
|
||||||
-- Optional: keep insert order predictable
|
-- Reset tables (no FKs defined, so order is safe)
|
||||||
SET time_zone = '+00:00';
|
SET FOREIGN_KEY_CHECKS = 0;
|
||||||
|
TRUNCATE TABLE loans;
|
||||||
|
TRUNCATE TABLE apiKeys;
|
||||||
|
TRUNCATE TABLE items;
|
||||||
|
TRUNCATE TABLE users;
|
||||||
|
SET FOREIGN_KEY_CHECKS = 1;
|
||||||
|
|
||||||
-- Users
|
-- Users (roles 1–6, plain-text passwords)
|
||||||
INSERT INTO users (username, password, first_name, last_name, role, is_admin)
|
INSERT INTO users (username, password, email, first_name, last_name, role, is_admin) VALUES
|
||||||
VALUES
|
('admin', 'adminpass', 'admin@example.com', 'System', 'Admin', 6, true),
|
||||||
('alice', 'password123', 'Alice', 'Andersen', 1, false),
|
('alice', 'alice123', 'alice@example.com', 'Alice', 'Andersen',1, false),
|
||||||
('bob', 'password123', 'Bob', 'Berg', 2, false),
|
('bob', 'bob12345', 'bob@example.com', 'Bob', 'Berg', 2, false),
|
||||||
('carol', 'password123', 'Carol', 'Christie', 2, false),
|
('carol', 'carol123', 'carol@example.com', 'Carol', 'Christensen', 3, false),
|
||||||
('dave', 'password123', 'Dave', 'Dawson', 1, false),
|
('dave', 'dave123', 'dave@example.com', 'Dave', 'Dahl', 4, false),
|
||||||
('eve', 'password123', 'Eve', 'Evans', 1, false),
|
('erin', 'erin123', 'erin@example.com', 'Erin', 'Enevoldsen', 5, false),
|
||||||
('admin', 'password123', 'Admin', 'User', 3, true);
|
('frank', 'frank123', 'frank@example.com', 'Frank', 'Fisher', 2, false),
|
||||||
|
('grace', 'grace123', 'grace@example.com', 'Grace', 'Gundersen',1, false),
|
||||||
|
('heidi', 'heidi123', 'heidi@example.com', 'Heidi', 'Hansen', 4, false),
|
||||||
|
('tech', 'techpass', 'tech@example.com', 'Tech', 'User', 5, true);
|
||||||
|
|
||||||
-- Items
|
-- Items (safe_nr is two digits or NULL; currently_borrowing aligns with active loans)
|
||||||
INSERT INTO items (item_name, can_borrow_role, in_safe, last_borrowed_person, currently_borrowing)
|
INSERT INTO items (item_name, can_borrow_role, in_safe, safe_nr, last_borrowed_person, currently_borrowing) VALUES
|
||||||
VALUES
|
('Laptop A', 2, false, NULL, 'grace', 'bob'),
|
||||||
('Canon EOS 90D Camera', 1, false, 'bob', 'alice'),
|
('Laptop B', 2, true, '01', NULL, NULL),
|
||||||
('Rode NT1 Microphone', 1, true, 'dave', NULL),
|
('Camera Canon', 3, true, '02', 'erin', NULL),
|
||||||
('MacBook Pro 13', 2, false, 'bob', 'carol'),
|
('Microphone Rode', 1, true, '03', 'grace', NULL),
|
||||||
('Tripod Manfrotto', 1, false, 'carol', 'alice'),
|
('Tripod Manfrotto', 1, true, '04', 'frank', NULL),
|
||||||
('LED Panel Aputure', 1, true, NULL, NULL),
|
('Oscilloscope Tek', 4, true, '05', NULL, NULL),
|
||||||
('Zoom H6 Recorder', 1, true, 'dave', NULL),
|
('VR Headset', 3, false, NULL, 'heidi', 'carol'),
|
||||||
('Wacom Intuos Tablet', 1, true, NULL, NULL),
|
('Keycard Programmer', 6, true, '06', 'admin', NULL);
|
||||||
('DJI Ronin-S Gimbal', 2, true, NULL, NULL),
|
|
||||||
('Sony A7 III Body', 2, false, 'carol', 'eve'),
|
|
||||||
('Sigma 24-70mm Lens', 2, false, 'carol', 'eve');
|
|
||||||
|
|
||||||
-- Capture item IDs for JSON arrays
|
-- Loans (JSON arrays, 6-digit numeric loan_code)
|
||||||
SET @id_canon = (SELECT id FROM items WHERE item_name='Canon EOS 90D Camera');
|
-- Assumes the items above have ids 1..8 in insert order
|
||||||
SET @id_rode = (SELECT id FROM items WHERE item_name='Rode NT1 Microphone');
|
|
||||||
SET @id_mac13 = (SELECT id FROM items WHERE item_name='MacBook Pro 13');
|
|
||||||
SET @id_tripod = (SELECT id FROM items WHERE item_name='Tripod Manfrotto');
|
|
||||||
SET @id_led = (SELECT id FROM items WHERE item_name='LED Panel Aputure');
|
|
||||||
SET @id_zoom = (SELECT id FROM items WHERE item_name='Zoom H6 Recorder');
|
|
||||||
SET @id_tablet = (SELECT id FROM items WHERE item_name='Wacom Intuos Tablet');
|
|
||||||
SET @id_ronin = (SELECT id FROM items WHERE item_name='DJI Ronin-S Gimbal');
|
|
||||||
SET @id_sony = (SELECT id FROM items WHERE item_name='Sony A7 III Body');
|
|
||||||
SET @id_sigma = (SELECT id FROM items WHERE item_name='Sigma 24-70mm Lens');
|
|
||||||
|
|
||||||
-- Loans
|
|
||||||
INSERT INTO loans (
|
INSERT INTO loans (
|
||||||
username, loan_code, start_date, end_date, take_date, returned_date, loaned_items_id, loaned_items_name, deleted
|
username,
|
||||||
|
lockers,
|
||||||
|
loan_code,
|
||||||
|
start_date,
|
||||||
|
end_date,
|
||||||
|
take_date,
|
||||||
|
returned_date,
|
||||||
|
loaned_items_id,
|
||||||
|
loaned_items_name,
|
||||||
|
deleted,
|
||||||
|
note
|
||||||
) VALUES
|
) VALUES
|
||||||
-- Ongoing loan: Alice has Canon + Tripod
|
-- Active loan: bob has Laptop A
|
||||||
('alice', 100001, '2025-10-01 09:00:00', '2025-10-08 17:00:00', '2025-10-01 09:15:00', NULL,
|
('bob',
|
||||||
JSON_ARRAY(@id_canon, @id_tripod),
|
'["01"]',
|
||||||
JSON_ARRAY('Canon EOS 90D Camera','Tripod Manfrotto'),
|
'123456',
|
||||||
false
|
'2025-11-15 09:00:00',
|
||||||
),
|
'2025-11-22 17:00:00',
|
||||||
-- Ongoing loan: Carol has MacBook Pro 13
|
'2025-11-15 09:15:00',
|
||||||
('carol', 100002, '2025-10-03 10:00:00', '2025-10-10 16:00:00', '2025-10-03 10:05:00', NULL,
|
NULL,
|
||||||
JSON_ARRAY(@id_mac13),
|
'[1]',
|
||||||
JSON_ARRAY('MacBook Pro 13'),
|
'["Laptop A"]',
|
||||||
false
|
false,
|
||||||
),
|
'Active loan - Laptop A'
|
||||||
-- Returned loan: Dave had Zoom + Rode
|
),
|
||||||
('dave', 100003, '2025-09-10 08:30:00', '2025-09-12 16:00:00', '2025-09-10 08:45:00', '2025-09-12 15:40:00',
|
-- Returned loan: frank had Tripod Manfrotto
|
||||||
JSON_ARRAY(@id_zoom, @id_rode),
|
('frank',
|
||||||
JSON_ARRAY('Zoom H6 Recorder','Rode NT1 Microphone'),
|
'["04"]',
|
||||||
false
|
'234567',
|
||||||
),
|
'2025-10-01 10:00:00',
|
||||||
-- Cancelled/deleted booking (never taken): Bob reserved Tablet
|
'2025-10-07 16:00:00',
|
||||||
('bob', 100004, '2025-10-05 09:00:00', '2025-10-06 09:00:00', NULL, NULL,
|
'2025-10-01 10:05:00',
|
||||||
JSON_ARRAY(@id_tablet),
|
'2025-10-05 15:30:00',
|
||||||
JSON_ARRAY('Wacom Intuos Tablet'),
|
'[5]',
|
||||||
true
|
'["Tripod Manfrotto"]',
|
||||||
),
|
false,
|
||||||
-- Ongoing loan, likely overdue: Eve has Sony + Sigma
|
'Completed loan'
|
||||||
('eve', 100005, '2025-10-15 11:00:00', '2025-10-20 12:00:00', '2025-10-15 11:10:00', NULL,
|
),
|
||||||
JSON_ARRAY(@id_sony, @id_sigma),
|
-- Future reservation: dave will take Oscilloscope Tek
|
||||||
JSON_ARRAY('Sony A7 III Body','Sigma 24-70mm Lens'),
|
('dave',
|
||||||
false
|
'["05"]',
|
||||||
),
|
'345678',
|
||||||
-- Completed single-day loan: Bob used LED panel
|
'2025-12-10 09:00:00',
|
||||||
('bob', 100006, '2025-09-20 13:00:00', '2025-09-20 18:00:00', '2025-09-20 13:05:00', '2025-09-20 17:30:00',
|
'2025-12-12 17:00:00',
|
||||||
JSON_ARRAY(@id_led),
|
NULL,
|
||||||
JSON_ARRAY('LED Panel Aputure'),
|
NULL,
|
||||||
false
|
'[6]',
|
||||||
);
|
'["Oscilloscope Tek"]',
|
||||||
|
false,
|
||||||
|
'Reserved'
|
||||||
|
),
|
||||||
|
-- Active loan: carol has VR Headset
|
||||||
|
('carol',
|
||||||
|
'["02"]',
|
||||||
|
'456789',
|
||||||
|
'2025-11-10 13:00:00',
|
||||||
|
'2025-11-20 12:00:00',
|
||||||
|
'2025-11-10 13:10:00',
|
||||||
|
NULL,
|
||||||
|
'[7]',
|
||||||
|
'["VR Headset"]',
|
||||||
|
false,
|
||||||
|
'Active loan - VR Headset'
|
||||||
|
),
|
||||||
|
-- Soft-deleted historic loan: grace had Microphone + Tripod
|
||||||
|
('grace',
|
||||||
|
'["03","04"]',
|
||||||
|
'567890',
|
||||||
|
'2025-09-01 09:00:00',
|
||||||
|
'2025-09-03 17:00:00',
|
||||||
|
'2025-09-01 09:10:00',
|
||||||
|
'2025-09-03 16:45:00',
|
||||||
|
'[4,5]',
|
||||||
|
'["Microphone Rode","Tripod Manfrotto"]',
|
||||||
|
true,
|
||||||
|
'Canceled/soft-deleted record'
|
||||||
|
);
|
||||||
|
|
||||||
-- API keys
|
-- API keys (8-digit numeric keys)
|
||||||
INSERT INTO apiKeys (api_key, username)
|
INSERT INTO apiKeys (api_key, entry_name, last_used_at) VALUES
|
||||||
VALUES
|
('12345678', 'CI token', '2025-11-15 08:00:00'),
|
||||||
(71002123, 'alice'),
|
('87654321', 'Local dev', NULL),
|
||||||
(71002124, 'bob'),
|
('00000001', 'Monitoring', '2025-11-10 12:30:00');
|
||||||
(71002125, 'carol'),
|
|
||||||
(99999999, 'admin');
|
|
||||||
@@ -4,6 +4,7 @@ CREATE TABLE users (
|
|||||||
id int NOT NULL AUTO_INCREMENT,
|
id int NOT NULL AUTO_INCREMENT,
|
||||||
username varchar(100) NOT NULL UNIQUE,
|
username varchar(100) NOT NULL UNIQUE,
|
||||||
password varchar(255) NOT NULL,
|
password varchar(255) NOT NULL,
|
||||||
|
email varchar(255) NOT NULL,
|
||||||
first_name varchar(255) NOT NULL,
|
first_name varchar(255) NOT NULL,
|
||||||
last_name varchar(255) NOT NULL,
|
last_name varchar(255) NOT NULL,
|
||||||
role int NOT NULL,
|
role int NOT NULL,
|
||||||
@@ -16,7 +17,8 @@ CREATE TABLE users (
|
|||||||
CREATE TABLE loans (
|
CREATE TABLE loans (
|
||||||
id int NOT NULL AUTO_INCREMENT,
|
id int NOT NULL AUTO_INCREMENT,
|
||||||
username varchar(100) NOT NULL,
|
username varchar(100) NOT NULL,
|
||||||
loan_code int NOT NULL UNIQUE,
|
lockers json NOT NULL DEFAULT ('[]'),
|
||||||
|
loan_code Char(6) NOT NULL UNIQUE,
|
||||||
start_date timestamp NOT NULL,
|
start_date timestamp NOT NULL,
|
||||||
end_date timestamp NOT NULL,
|
end_date timestamp NOT NULL,
|
||||||
take_date timestamp NULL DEFAULT NULL,
|
take_date timestamp NULL DEFAULT NULL,
|
||||||
@@ -27,10 +29,7 @@ CREATE TABLE loans (
|
|||||||
deleted bool NOT NULL DEFAULT false,
|
deleted bool NOT NULL DEFAULT false,
|
||||||
note varchar(500) DEFAULT NULL,
|
note varchar(500) DEFAULT NULL,
|
||||||
PRIMARY KEY (id),
|
PRIMARY KEY (id),
|
||||||
CONSTRAINT fk_loans_username
|
CHECK (loan_code REGEXP '^[0-9]{6}$')
|
||||||
FOREIGN KEY (username) REFERENCES users(username)
|
|
||||||
ON UPDATE CASCADE
|
|
||||||
ON DELETE RESTRICT
|
|
||||||
) ENGINE=InnoDB;
|
) ENGINE=InnoDB;
|
||||||
|
|
||||||
CREATE TABLE items (
|
CREATE TABLE items (
|
||||||
@@ -38,23 +37,21 @@ CREATE TABLE items (
|
|||||||
item_name varchar(255) NOT NULL UNIQUE,
|
item_name varchar(255) NOT NULL UNIQUE,
|
||||||
can_borrow_role INT NOT NULL,
|
can_borrow_role INT NOT NULL,
|
||||||
in_safe bool NOT NULL DEFAULT true,
|
in_safe bool NOT NULL DEFAULT true,
|
||||||
|
safe_nr CHAR(2) DEFAULT NULL,
|
||||||
entry_created_at timestamp NULL DEFAULT CURRENT_TIMESTAMP,
|
entry_created_at timestamp NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
entry_updated_at timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
entry_updated_at timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
last_borrowed_person varchar(255) DEFAULT NULL,
|
last_borrowed_person varchar(255) DEFAULT NULL,
|
||||||
currently_borrowing varchar(255) DEFAULT NULL,
|
currently_borrowing varchar(255) DEFAULT NULL,
|
||||||
PRIMARY KEY (id)
|
PRIMARY KEY (id),
|
||||||
);
|
CHECK (safe_nr REGEXP '^[0-9]{2}$' OR safe_nr IS NULL)
|
||||||
|
) ENGINE=InnoDB;
|
||||||
|
|
||||||
CREATE TABLE apiKeys (
|
CREATE TABLE apiKeys (
|
||||||
id int NOT NULL AUTO_INCREMENT,
|
id INT NOT NULL AUTO_INCREMENT,
|
||||||
api_key CHAR(15) NOT NULL UNIQUE,
|
api_key CHAR(8) NOT NULL UNIQUE,
|
||||||
username VARCHAR(100) NOT NULL,
|
entry_name VARCHAR(100) NOT NULL,
|
||||||
last_used_at timestamp DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
|
last_used_at TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
|
||||||
entry_created_at timestamp NULL DEFAULT CURRENT_TIMESTAMP,
|
entry_created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
PRIMARY KEY (id),
|
PRIMARY KEY (id),
|
||||||
CONSTRAINT chk_api_key_len CHECK (CHAR_LENGTH(api_key) = 15),
|
CHECK (api_key REGEXP '^[0-9]{8}$')
|
||||||
CONSTRAINT fk_apikeys_username
|
|
||||||
FOREIGN KEY (username) REFERENCES users(username)
|
|
||||||
ON UPDATE CASCADE
|
|
||||||
ON DELETE RESTRICT
|
|
||||||
) ENGINE=InnoDB;
|
) ENGINE=InnoDB;
|
||||||
@@ -1,22 +1,62 @@
|
|||||||
import express from "express";
|
import express from "express";
|
||||||
import cors from "cors";
|
import cors from "cors";
|
||||||
import env from "dotenv";
|
import env from "dotenv";
|
||||||
|
import info from "./info.json" assert { type: "json" };
|
||||||
|
import { authenticate } from "./services/authentication.js";
|
||||||
|
|
||||||
|
// 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";
|
||||||
|
|
||||||
|
// API routes
|
||||||
|
import apiRouter from "./routes/api/api.route.js";
|
||||||
|
|
||||||
env.config();
|
env.config();
|
||||||
const app = express();
|
const app = express();
|
||||||
const port = 8002;
|
const port = 8004;
|
||||||
|
|
||||||
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);
|
||||||
|
|
||||||
|
// API routes
|
||||||
|
app.use("/api", apiRouter);
|
||||||
|
|
||||||
|
app.set("view engine", "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("/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!");
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { SignJWT, jwtVerify } from "jose";
|
import { SignJWT, jwtVerify } from "jose";
|
||||||
import env from "dotenv";
|
import env from "dotenv";
|
||||||
import { getAllApiKeys } from "./database";
|
import { verifyAPIKeyDB } from "./database.js";
|
||||||
env.config();
|
env.config();
|
||||||
|
|
||||||
const secretKey = process.env.SECRET_KEY;
|
const secretKey = process.env.SECRET_KEY;
|
||||||
@@ -17,9 +17,32 @@ export async function generateToken(payload) {
|
|||||||
.sign(secret);
|
.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) {
|
export async function authenticate(req, res, next) {
|
||||||
const authHeader = req.headers["authorization"];
|
const authHeader = req.headers["authorization"];
|
||||||
const apiKey = req.params.apiKey;
|
const apiKey = req.params.key;
|
||||||
|
|
||||||
if (authHeader) {
|
if (authHeader) {
|
||||||
const parts = authHeader.split(" ");
|
const parts = authHeader.split(" ");
|
||||||
@@ -35,14 +58,14 @@ export async function authenticate(req, res, next) {
|
|||||||
req.user = payload;
|
req.user = payload;
|
||||||
return next();
|
return next();
|
||||||
} catch {
|
} catch {
|
||||||
return res.sendStatus(403); // present token invalid
|
return res.status(403).json({ message: "Present token invalid" }); // present token invalid
|
||||||
}
|
}
|
||||||
} else if (apiKey) {
|
} else if (apiKey) {
|
||||||
try {
|
try {
|
||||||
await verifyAPIKey(apiKey);
|
await verifyAPIKey(apiKey);
|
||||||
return next();
|
return next();
|
||||||
} catch {
|
} catch {
|
||||||
return res.sendStatus(403); // API Key invalid
|
return res.status(403).json({ message: "API Key invalid" }); // fix: don't chain after sendStatus
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
return res.status(401).json({ message: "Unauthorized" }); // no credentials
|
return res.status(401).json({ message: "Unauthorized" }); // no credentials
|
||||||
@@ -50,9 +73,11 @@ export async function authenticate(req, res, next) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function verifyAPIKey(apiKey) {
|
async function verifyAPIKey(apiKey) {
|
||||||
const apiKeys = await getAllApiKeys();
|
const result = await verifyAPIKeyDB(apiKey);
|
||||||
const validKey = apiKeys.find((k) => k.key === apiKey);
|
|
||||||
if (!validKey) {
|
if (result.valid) {
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
throw new Error("Invalid API Key");
|
throw new Error("Invalid API Key");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,541 +11,14 @@ 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] };
|
return { valid: true };
|
||||||
}
|
|
||||||
return { success: false };
|
|
||||||
};
|
|
||||||
|
|
||||||
export const changeInSafeStateV2 = async (itemId) => {
|
|
||||||
const [result] = await pool.query(
|
|
||||||
"UPDATE items SET inSafe = NOT inSafe WHERE id = ?",
|
|
||||||
[itemId]
|
|
||||||
);
|
|
||||||
if (result.affectedRows > 0) {
|
|
||||||
return { success: true };
|
|
||||||
}
|
|
||||||
return { success: false };
|
|
||||||
};
|
|
||||||
|
|
||||||
export const setReturnDateV2 = async (loanCode) => {
|
|
||||||
const [items] = await pool.query(
|
|
||||||
"SELECT loaned_items_id 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 inSafe = 1 WHERE id IN (?)",
|
|
||||||
[itemIds]
|
|
||||||
);
|
|
||||||
|
|
||||||
const [result] = await pool.query(
|
|
||||||
"UPDATE loans SET returned_date = NOW() WHERE loan_code = ?",
|
|
||||||
[loanCode]
|
|
||||||
);
|
|
||||||
|
|
||||||
if (result.affectedRows > 0 && setItemStates.affectedRows > 0) {
|
|
||||||
return { success: true };
|
|
||||||
}
|
|
||||||
return { success: false };
|
|
||||||
};
|
|
||||||
|
|
||||||
export const setTakeDateV2 = async (loanCode) => {
|
|
||||||
const [items] = await pool.query(
|
|
||||||
"SELECT loaned_items_id FROM loans WHERE loan_code = ?",
|
|
||||||
[loanCode]
|
|
||||||
);
|
|
||||||
|
|
||||||
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 inSafe = 0 WHERE id IN (?)",
|
|
||||||
[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 };
|
|
||||||
};
|
|
||||||
|
|
||||||
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 [rows] = await pool.query("SELECT * FROM loans;");
|
|
||||||
return { success: true, data: rows.length > 0 ? rows : null };
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getUserLoansFromDatabase = async (username) => {
|
|
||||||
const [result] = await pool.query(
|
|
||||||
"SELECT * FROM loans WHERE username = ? AND deleted = 0;",
|
|
||||||
[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 SETdeleteLoanFromDatabase = async (loanId) => {
|
|
||||||
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 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 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 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.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",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generate unique loan_code (retry a few times)
|
|
||||||
let loanCode = null;
|
|
||||||
for (let i = 0; i < 6; i++) {
|
|
||||||
const candidate = Math.floor(100000 + Math.random() * 899999); // 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();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// These functions are only temporary, and will be deleted when the full bin is set up.
|
|
||||||
export const onTake = async (loanId) => {
|
|
||||||
const [items] = await pool.query(
|
|
||||||
"SELECT loaned_items_id FROM loans WHERE id = ?",
|
|
||||||
[loanId]
|
|
||||||
);
|
|
||||||
|
|
||||||
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 inSafe = 0 WHERE id IN (?)",
|
|
||||||
[itemIds]
|
|
||||||
);
|
|
||||||
|
|
||||||
const [result] = await pool.query(
|
|
||||||
"UPDATE loans SET take_date = NOW() WHERE id = ?",
|
|
||||||
[loanId]
|
|
||||||
);
|
|
||||||
|
|
||||||
if (result.affectedRows > 0 && setItemStates.affectedRows > 0) {
|
|
||||||
return { success: true };
|
|
||||||
}
|
|
||||||
return { success: false };
|
|
||||||
};
|
|
||||||
|
|
||||||
export const onReturn = async (loanId) => {
|
|
||||||
const [items] = await pool.query(
|
|
||||||
"SELECT loaned_items_id FROM loans WHERE id = ?",
|
|
||||||
[loanId]
|
|
||||||
);
|
|
||||||
|
|
||||||
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 inSafe = 1 WHERE id IN (?)",
|
|
||||||
[itemIds]
|
|
||||||
);
|
|
||||||
|
|
||||||
const [result] = await pool.query(
|
|
||||||
"UPDATE loans SET returned_date = NOW() WHERE id = ?",
|
|
||||||
[loanId]
|
|
||||||
);
|
|
||||||
|
|
||||||
if (result.affectedRows > 0 && setItemStates.affectedRows > 0) {
|
|
||||||
return { success: true };
|
|
||||||
}
|
|
||||||
return { success: false };
|
|
||||||
};
|
|
||||||
// Temporary functions end here.
|
|
||||||
|
|
||||||
export const loginAdmin = async (username, password) => {
|
|
||||||
const [result] = await pool.query(
|
|
||||||
"SELECT * FROM admins WHERE username = ? AND password = ?",
|
|
||||||
[username, password]
|
|
||||||
);
|
|
||||||
if (result.length > 0) return { success: true, data: result[0] };
|
|
||||||
return { success: false };
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getAllUsers = async () => {
|
|
||||||
const [result] = await pool.query(
|
|
||||||
"SELECT id, username, role, entry_created_at FROM users"
|
|
||||||
);
|
|
||||||
if (result.length > 0) return { success: true, data: result };
|
|
||||||
return { success: false };
|
|
||||||
};
|
|
||||||
|
|
||||||
export const deleteUserID = 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 handleEdit = async (userId, username, role) => {
|
|
||||||
const [result] = await pool.query(
|
|
||||||
"UPDATE users SET username = ?, role = ? WHERE id = ?",
|
|
||||||
[username, role, userId]
|
|
||||||
);
|
|
||||||
if (result.affectedRows > 0) return { success: true };
|
|
||||||
return { success: false };
|
|
||||||
};
|
|
||||||
|
|
||||||
export const createUser = async (username, role, password) => {
|
|
||||||
const [result] = await pool.query(
|
|
||||||
"INSERT INTO users (username, role, password) VALUES (?, ?, ?)",
|
|
||||||
[username, role, password]
|
|
||||||
);
|
|
||||||
if (result.affectedRows > 0) return { success: true };
|
|
||||||
return { success: false };
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getAllLoans = async () => {
|
|
||||||
const [result] = await pool.query("SELECT * FROM loans");
|
|
||||||
if (result.length > 0) return { success: true, data: result };
|
|
||||||
return { success: false };
|
|
||||||
};
|
|
||||||
|
|
||||||
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 deleteItemID = 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) => {
|
|
||||||
const [result] = await pool.query(
|
|
||||||
"INSERT INTO items (item_name, can_borrow_role) VALUES (?, ?)",
|
|
||||||
[item_name, can_borrow_role]
|
|
||||||
);
|
|
||||||
if (result.affectedRows > 0) return { success: true };
|
|
||||||
return { success: false };
|
|
||||||
};
|
|
||||||
|
|
||||||
export const changeUserPassword = async (username, newPassword) => {
|
|
||||||
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 changeUserPasswordFRONTEND = async (
|
|
||||||
username,
|
|
||||||
oldPassword,
|
|
||||||
newPassword
|
|
||||||
) => {
|
|
||||||
const [result] = await pool.query(
|
|
||||||
"UPDATE users SET password = ? WHERE username = ? AND password = ?",
|
|
||||||
[newPassword, username, oldPassword]
|
|
||||||
);
|
|
||||||
if (result.affectedRows > 0) return { success: true };
|
|
||||||
return { success: false };
|
|
||||||
};
|
|
||||||
|
|
||||||
export const updateItemByID = async (itemId, item_name, can_borrow_role) => {
|
|
||||||
const [result] = await pool.query(
|
|
||||||
"UPDATE items SET item_name = ?, can_borrow_role = ? WHERE id = ?",
|
|
||||||
[item_name, can_borrow_role, itemId]
|
|
||||||
);
|
|
||||||
if (result.affectedRows > 0) return { success: true };
|
|
||||||
return { success: false };
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getAllLoansV2 = async () => {
|
|
||||||
const [rows] = await pool.query(
|
|
||||||
"SELECT id, username, start_date, end_date, loaned_items_name, returned_date, take_date FROM loans"
|
|
||||||
);
|
|
||||||
if (rows.length > 0) {
|
|
||||||
return { success: true, data: rows };
|
|
||||||
}
|
|
||||||
return { success: false };
|
|
||||||
};
|
|
||||||
|
|
||||||
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, user) => {
|
|
||||||
const [result] = await pool.query(
|
|
||||||
"INSERT INTO apiKeys (apiKey, user) VALUES (?, ?)",
|
|
||||||
[apiKey, user]
|
|
||||||
);
|
|
||||||
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 };
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getAPIkey = async () => {
|
|
||||||
const [rows] = await pool.query("SELECT apiKey FROM apiKeys");
|
|
||||||
if (rows.length > 0) {
|
|
||||||
return { success: true, data: rows };
|
|
||||||
}
|
|
||||||
return { success: false };
|
|
||||||
};
|
|
||||||
|
|||||||
@@ -1,42 +1,51 @@
|
|||||||
services:
|
services:
|
||||||
# borrow_system-frontend:
|
# usr-frontend_v2:
|
||||||
# container_name: borrow_system-frontend
|
# container_name: borrow_system-usr-frontend
|
||||||
# build: ./FrontendV2
|
# build: ./FrontendV2
|
||||||
# ports:
|
# ports:
|
||||||
# - "8001:8001"
|
# - "8001:80"
|
||||||
# environment:
|
|
||||||
# - CHOKIDAR_USEPOLLING=true
|
|
||||||
# volumes:
|
|
||||||
# - ./FrontendV2:/app
|
|
||||||
# - /app/node_modules
|
|
||||||
# restart: unless-stopped
|
# restart: unless-stopped
|
||||||
|
|
||||||
# admin-frontend:
|
# admin-frontend:
|
||||||
# container_name: admin-frontend
|
# container_name: borrow_system-admin-frontend
|
||||||
# build: ./admin
|
# build: ./admin
|
||||||
# ports:
|
# ports:
|
||||||
# - "8003:8003"
|
# - "8003:80"
|
||||||
# environment:
|
|
||||||
# - CHOKIDAR_USEPOLLING=true
|
|
||||||
# volumes:
|
|
||||||
# - ./admin:/app
|
|
||||||
# - /app/node_modules
|
|
||||||
# restart: unless-stopped
|
# restart: unless-stopped
|
||||||
|
|
||||||
borrow_system-backend:
|
#backend:
|
||||||
container_name: borrow_system-backend
|
# container_name: borrow_system-backend
|
||||||
build: ./backend
|
# build: ./backend
|
||||||
|
# ports:
|
||||||
|
# - "8002:8002"
|
||||||
|
# environment:
|
||||||
|
# NODE_ENV: production
|
||||||
|
# DB_HOST: mysql
|
||||||
|
# DB_USER: root
|
||||||
|
# DB_PASSWORD: ${DB_PASSWORD}
|
||||||
|
# DB_NAME: borrow_system
|
||||||
|
# depends_on:
|
||||||
|
# - mysql
|
||||||
|
# restart: unless-stopped
|
||||||
|
# healthcheck:
|
||||||
|
# test: ["CMD", "wget", "-qO-", "http://localhost:8002/server-info"]
|
||||||
|
# interval: 30s
|
||||||
|
# timeout: 5s
|
||||||
|
# retries: 3
|
||||||
|
|
||||||
|
backend_v2:
|
||||||
|
container_name: borrow_system-backend_v2
|
||||||
|
build: ./backendV2
|
||||||
ports:
|
ports:
|
||||||
- "8002:8002"
|
- "8004:8004"
|
||||||
environment:
|
environment:
|
||||||
DB_HOST: mysql
|
NODE_ENV: production
|
||||||
|
DB_HOST: mysql_v2
|
||||||
DB_USER: root
|
DB_USER: root
|
||||||
DB_PASSWORD: ${DB_PASSWORD}
|
DB_PASSWORD: ${DB_PASSWORD_V2}
|
||||||
DB_NAME: borrow_system
|
DB_NAME: borrow_system_new
|
||||||
depends_on:
|
depends_on:
|
||||||
- mysql
|
- mysql_v2
|
||||||
volumes:
|
|
||||||
- ./backend:/borrow_system-backend
|
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|
||||||
mysql:
|
mysql:
|
||||||
@@ -53,20 +62,20 @@ services:
|
|||||||
ports:
|
ports:
|
||||||
- "3309:3306"
|
- "3309:3306"
|
||||||
|
|
||||||
mysql-new:
|
mysql_v2:
|
||||||
container_name: borrow_system-mysql-new
|
container_name: borrow_system-mysql-v2
|
||||||
image: mysql:8.0
|
image: mysql:8.0
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
environment:
|
environment:
|
||||||
MYSQL_ROOT_PASSWORD: ${DB_PASSWORD}
|
MYSQL_ROOT_PASSWORD: ${DB_PASSWORD_V2}
|
||||||
MYSQL_DATABASE: borrow_system_new
|
MYSQL_DATABASE: borrow_system_new
|
||||||
TZ: Europe/Berlin
|
TZ: Europe/Berlin
|
||||||
volumes:
|
volumes:
|
||||||
- mysql-data-new:/var/lib/mysql
|
- mysql-v2-data:/var/lib/mysql
|
||||||
- ./mysql-timezone.cnf:/etc/mysql/conf.d/timezone.cnf:ro
|
- ./mysql-timezone.cnf:/etc/mysql/conf.d/timezone.cnf:ro
|
||||||
ports:
|
ports:
|
||||||
- "3310:3306"
|
- "3310:3306"
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
mysql-data:
|
mysql-data:
|
||||||
mysql-data-new:
|
mysql-v2-data:
|
||||||
|
|||||||
Reference in New Issue
Block a user