Compare commits
10 Commits
bf4b95dce9
...
8fb20f70c7
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8fb20f70c7 | ||
|
|
cd2aca8826 | ||
|
|
06720d400f | ||
|
|
fd9f805c44 | ||
|
|
83b207f4cb | ||
|
|
7c3ab76c79 | ||
|
|
483cb4b043 | ||
|
|
e3004bbc72 | ||
|
|
8b51809085 | ||
|
|
d3becdef72 |
Binary file not shown.
@@ -25,8 +25,8 @@ public class ControllerPathConfig {
|
||||
|
||||
//ArticleController
|
||||
public static final String ARTICLE_BASE = "/article";
|
||||
public static final String ARTICLE_GET_ALL = ARTICLE_BASE + "/all";
|
||||
public static final String ARTICLE_GET_ALL_WITH_IMAGE = ARTICLE_BASE + "/all/image";
|
||||
public static final String ARTICLE_GET_ALL = "/all";
|
||||
public static final String ARTICLE_GET_ALL_WITH_IMAGE = "/all/image";
|
||||
|
||||
//CustomerController
|
||||
public static final String CUSTOMER_BASE = "/customer";
|
||||
@@ -43,12 +43,12 @@ public class ControllerPathConfig {
|
||||
|
||||
//OrderController
|
||||
public static final String ORDER_BASE = "/order";
|
||||
public static final String ORDER_GET_ALL = ORDER_BASE + "/all";
|
||||
public static final String ORDER_GET_ALL_ADMIN = ORDER_BASE + "/all/all";
|
||||
public static final String ORDER_GET_ALL = "/all";
|
||||
public static final String ORDER_GET_ALL_ADMIN = "/all/all";
|
||||
|
||||
//ReviewController
|
||||
public static final String REVIEW_BASE = "/review";
|
||||
public static final String REVIEW_GET_ALL = REVIEW_BASE + "/all";
|
||||
public static final String REVIEW_GET_ALL = "/all";
|
||||
|
||||
//StatisticsController
|
||||
private static final String STATISTICS_BASE = "/statistics";
|
||||
|
||||
@@ -19,6 +19,7 @@ import static de.htwsaar.webshop.util.LoggerUtil.logRequest;
|
||||
|
||||
@RestController
|
||||
@Slf4j
|
||||
@RequestMapping(path = ARTICLE_BASE, produces = "application/json")
|
||||
public class ArticleController {
|
||||
private final ArticleService articleService;
|
||||
|
||||
@@ -27,26 +28,26 @@ public class ArticleController {
|
||||
this.articleService = articleService;
|
||||
}
|
||||
|
||||
@RequestMapping(path = ARTICLE_GET_ALL, method = RequestMethod.GET, produces = "application/json")
|
||||
@GetMapping(path = ARTICLE_GET_ALL)
|
||||
public ResponseEntity<List<ArticleModel>> getAll(HttpServletRequest request) {
|
||||
logRequest(request);
|
||||
return ResponseEntity.ok(articleService.from(articleService.findAll()));
|
||||
}
|
||||
|
||||
@RequestMapping(path = ARTICLE_GET_ALL_WITH_IMAGE, method = RequestMethod.GET, produces = "application/json")
|
||||
@GetMapping(path = ARTICLE_GET_ALL_WITH_IMAGE)
|
||||
public ResponseEntity<List<ArticleWithImageModel>> getAllWithImageData(HttpServletRequest request) {
|
||||
logRequest(request);
|
||||
return ResponseEntity.ok(articleService.fromWithImage(articleService.findAll()));
|
||||
}
|
||||
|
||||
@RequestMapping(path = ARTICLE_BASE, method = RequestMethod.GET, produces = "application/json")
|
||||
@GetMapping
|
||||
public ResponseEntity<ArticleModel> getByUUID(HttpServletRequest request,
|
||||
@RequestParam(value = PARAM_UUID) UUID uuid) {
|
||||
logRequest(request);
|
||||
return ResponseEntity.ok(articleService.from(articleService.findByUUID(uuid)));
|
||||
}
|
||||
|
||||
@RequestMapping(path = ARTICLE_BASE, method = RequestMethod.POST, produces = "application/json")
|
||||
@PostMapping
|
||||
public ResponseEntity<Boolean> add(HttpServletRequest request,
|
||||
@RequestBody Article article) {
|
||||
logRequest(request);
|
||||
@@ -60,7 +61,7 @@ public class ArticleController {
|
||||
return ResponseEntity.ok(a != null);
|
||||
}
|
||||
|
||||
@RequestMapping(path = ARTICLE_BASE, method = RequestMethod.PUT, produces = "application/json")
|
||||
@PutMapping
|
||||
public ResponseEntity<Boolean> update(HttpServletRequest request,
|
||||
@RequestParam(value = PARAM_UUID) UUID uuid,
|
||||
@RequestBody Article article) {
|
||||
@@ -80,7 +81,7 @@ public class ArticleController {
|
||||
return ResponseEntity.ok(true);
|
||||
}
|
||||
|
||||
@RequestMapping(path = ARTICLE_BASE, method = RequestMethod.DELETE, produces = "application/json")
|
||||
@DeleteMapping
|
||||
public ResponseEntity<Boolean> delete(HttpServletRequest request,
|
||||
@RequestParam(value = PARAM_UUID) UUID uuid) {
|
||||
logRequest(request);
|
||||
|
||||
@@ -22,6 +22,7 @@ import static de.htwsaar.webshop.util.LoggerUtil.logRequest;
|
||||
|
||||
@RestController
|
||||
@Slf4j
|
||||
@RequestMapping(path = ORDER_BASE, produces = "application/json")
|
||||
public class OrderController {
|
||||
|
||||
private final OrderService orderService;
|
||||
@@ -35,7 +36,7 @@ public class OrderController {
|
||||
this.sessionService = sessionService;
|
||||
}
|
||||
|
||||
@RequestMapping(path = ORDER_GET_ALL, method = RequestMethod.GET, produces = "application/json")
|
||||
@GetMapping(path = ORDER_GET_ALL)
|
||||
public ResponseEntity<List<OrderModel>> getAll(HttpServletRequest request,
|
||||
@RequestParam(value = PARAM_CUSTOMER_ID) Long customerId) {
|
||||
logRequest(request);
|
||||
@@ -46,7 +47,7 @@ public class OrderController {
|
||||
return ResponseEntity.ok(orders.stream().map(Order::toModel).toList());
|
||||
}
|
||||
|
||||
@RequestMapping(path = ORDER_GET_ALL_ADMIN, method = RequestMethod.GET, produces = "application/json")
|
||||
@GetMapping(path = ORDER_GET_ALL_ADMIN)
|
||||
public ResponseEntity<List<OrderModel>> getAll(HttpServletRequest request,
|
||||
@RequestParam(value = PARAM_EMAIL) String email,
|
||||
@RequestParam(value = PARAM_SESSION) UUID token) {
|
||||
@@ -59,7 +60,7 @@ public class OrderController {
|
||||
return ResponseEntity.ok(orderService.findAll().stream().map(Order::toModel).toList());
|
||||
}
|
||||
|
||||
@RequestMapping(path = ORDER_BASE, method = RequestMethod.GET, produces = "application/json")
|
||||
@GetMapping
|
||||
public ResponseEntity<OrderModel> get(HttpServletRequest request,
|
||||
@RequestParam(value = PARAM_ID) Long orderId) {
|
||||
logRequest(request);
|
||||
@@ -70,7 +71,7 @@ public class OrderController {
|
||||
return ResponseEntity.ok(order.toModel());
|
||||
}
|
||||
|
||||
@RequestMapping(path = ORDER_BASE, method = RequestMethod.POST, produces = "application/json")
|
||||
@PostMapping
|
||||
public ResponseEntity<Boolean> add(HttpServletRequest request,
|
||||
@RequestBody OrderModel order) {
|
||||
logRequest(request);
|
||||
@@ -85,8 +86,8 @@ public class OrderController {
|
||||
return ResponseEntity.ok(saved != null);
|
||||
}
|
||||
|
||||
@RequestMapping(path = ORDER_BASE, method = RequestMethod.PATCH, produces = "application/json")
|
||||
public ResponseEntity<Boolean> update(HttpServletRequest request,
|
||||
@PatchMapping
|
||||
public ResponseEntity<Boolean> patch(HttpServletRequest request,
|
||||
@RequestParam(value = PARAM_ID) Long orderId,
|
||||
@RequestParam(value = PARAM_STATUS) OrderStatus status) {
|
||||
logRequest(request);
|
||||
@@ -107,7 +108,7 @@ public class OrderController {
|
||||
return ResponseEntity.ok(orderService.saveNew(order) != null);
|
||||
}
|
||||
|
||||
@RequestMapping(path = ORDER_BASE, method = RequestMethod.DELETE, produces = "application/json")
|
||||
@DeleteMapping
|
||||
public ResponseEntity<Boolean> delete(HttpServletRequest request,
|
||||
@RequestParam(value = PARAM_ID) Long orderId) {
|
||||
logRequest(request);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
|
||||
package de.htwsaar.webshop.controller;
|
||||
|
||||
import de.htwsaar.webshop.model.ReviewModel;
|
||||
@@ -5,8 +6,13 @@ import de.htwsaar.webshop.repository.entities.Review;
|
||||
import de.htwsaar.webshop.service.ArticleService;
|
||||
import de.htwsaar.webshop.service.ReviewService;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@@ -19,6 +25,7 @@ import static de.htwsaar.webshop.config.ParameterConfig.*;
|
||||
import static de.htwsaar.webshop.util.LoggerUtil.logRequest;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(value = REVIEW_BASE, produces = "application/json")
|
||||
@Slf4j
|
||||
public class ReviewController {
|
||||
|
||||
@@ -31,69 +38,95 @@ public class ReviewController {
|
||||
this.articleService = articleService;
|
||||
}
|
||||
|
||||
@RequestMapping(path = REVIEW_GET_ALL, method = RequestMethod.GET, produces = "application/json")
|
||||
@GetMapping(path = REVIEW_GET_ALL)
|
||||
public ResponseEntity<List<ReviewModel>> getAll(HttpServletRequest request,
|
||||
@RequestParam(value = PARAM_UUID) UUID uuid) {
|
||||
logRequest(request);
|
||||
List<ReviewModel> review = reviewService.getAllByUUID(uuid).stream().map(reviewService::toModel).toList();
|
||||
if (review.isEmpty()) {
|
||||
List<ReviewModel> reviews = reviewService.getAllByUUID(uuid)
|
||||
.stream()
|
||||
.map(reviewService::toModel)
|
||||
.toList();
|
||||
|
||||
if (reviews.isEmpty()) {
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
return ResponseEntity.ok(review);
|
||||
return ResponseEntity.ok(reviews);
|
||||
}
|
||||
|
||||
@RequestMapping(path = REVIEW_BASE, method = RequestMethod.GET, produces = "application/json")
|
||||
public ResponseEntity<Review> get(HttpServletRequest request,
|
||||
@GetMapping
|
||||
public ResponseEntity<ReviewModel> get(HttpServletRequest request,
|
||||
@RequestParam(value = PARAM_ID) Long reviewId) {
|
||||
logRequest(request);
|
||||
Review review = reviewService.getReviewById(reviewId);
|
||||
|
||||
if (review == null) {
|
||||
log.debug("Review with id {} not found", reviewId);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
return ResponseEntity.ok(review);
|
||||
|
||||
return ResponseEntity.ok(reviewService.toModel(review));
|
||||
}
|
||||
|
||||
@RequestMapping(path = REVIEW_BASE, method = RequestMethod.POST, produces = "application/json")
|
||||
public ResponseEntity<Boolean> add(HttpServletRequest request,
|
||||
@RequestParam(value = PARAM_UUID) UUID uuid,
|
||||
@RequestParam(value = PARAM_RATING) int rating,
|
||||
@RequestBody String review) {
|
||||
@PostMapping
|
||||
public ResponseEntity<ReviewModel> add(HttpServletRequest request,
|
||||
@RequestParam(value = PARAM_UUID) UUID articleUuid,
|
||||
@RequestParam(value = PARAM_RATING)
|
||||
@Min(value = 0, message = "Rating must be at least 0")
|
||||
@Max(value = 10, message = "Rating must be at most 10")
|
||||
int rating,
|
||||
@RequestBody @NotBlank(message = "Review text cannot be empty") String reviewText) {
|
||||
logRequest(request);
|
||||
|
||||
if (uuid == null || articleService.findByUUID(uuid) == null
|
||||
|| rating < 0 || rating > 10) {
|
||||
log.warn("[{}] failed Validation, sending bad request", request.getRequestURI());
|
||||
return ResponseEntity.badRequest().body(false);
|
||||
if (articleService.findByUUID(articleUuid) == null) {
|
||||
log.warn("Article with UUID {} not found for review creation", articleUuid);
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
Review saved = reviewService.save(uuid, rating, review);
|
||||
return ResponseEntity.ok(saved != null);
|
||||
Review savedReview = reviewService.save(articleUuid, rating, reviewText);
|
||||
|
||||
if (savedReview == null) {
|
||||
log.error("Failed to save review for article UUID {}", articleUuid);
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
|
||||
}
|
||||
|
||||
@RequestMapping(path = REVIEW_BASE, method = RequestMethod.PUT, produces = "application/json")
|
||||
public ResponseEntity<Boolean> update(HttpServletRequest request,
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(reviewService.toModel(savedReview));
|
||||
}
|
||||
|
||||
@PutMapping
|
||||
public ResponseEntity<ReviewModel> update(HttpServletRequest request,
|
||||
@RequestParam(value = PARAM_ID) Long reviewId,
|
||||
@RequestBody Review review) {
|
||||
@RequestBody @Valid Review review) {
|
||||
logRequest(request);
|
||||
if (reviewId == null || reviewService.getReviewById(reviewId) == null) {
|
||||
return ResponseEntity.badRequest().body(false);
|
||||
}
|
||||
review.setId(reviewService.getReviewById(reviewId).getId());
|
||||
return ResponseEntity.ok(reviewService.save(review) != null);
|
||||
|
||||
Review existingReview = reviewService.getReviewById(reviewId);
|
||||
if (existingReview == null) {
|
||||
log.warn("Review with id {} not found for update", reviewId);
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
|
||||
@RequestMapping(path = REVIEW_BASE, method = RequestMethod.DELETE, produces = "application/json")
|
||||
public ResponseEntity<Boolean> delete(HttpServletRequest request,
|
||||
// Ensure the ID matches
|
||||
review.setId(reviewId);
|
||||
Review updatedReview = reviewService.save(review);
|
||||
|
||||
if (updatedReview == null) {
|
||||
log.error("Failed to update review with id {}", reviewId);
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
|
||||
}
|
||||
|
||||
return ResponseEntity.ok(reviewService.toModel(updatedReview));
|
||||
}
|
||||
|
||||
@DeleteMapping
|
||||
public ResponseEntity<Void> delete(HttpServletRequest request,
|
||||
@RequestParam(value = PARAM_ID) Long reviewId) {
|
||||
logRequest(request);
|
||||
if (reviewId == null) {
|
||||
log.warn("[{}] got invalid imageId", request.getRequestURI());
|
||||
return ResponseEntity.badRequest().body(false);
|
||||
}
|
||||
if (reviewService.getReviewById(reviewId) != null) {
|
||||
log.warn("[{}] got invalid imageId", request.getRequestURI());
|
||||
return ResponseEntity.badRequest().body(false);
|
||||
|
||||
Review existingReview = reviewService.getReviewById(reviewId);
|
||||
if (existingReview == null) {
|
||||
log.warn("Review with id {} not found for deletion", reviewId);
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
|
||||
reviewService.delete(reviewId);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package de.htwsaar.webshop.controller;
|
||||
|
||||
import de.htwsaar.webshop.model.CatMonthModel;
|
||||
import de.htwsaar.webshop.model.CategoryMonthModel;
|
||||
import de.htwsaar.webshop.model.OrderStatus;
|
||||
import de.htwsaar.webshop.service.SessionService;
|
||||
import de.htwsaar.webshop.service.StatisticsService;
|
||||
@@ -12,7 +12,6 @@ import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
@@ -34,7 +33,7 @@ public class StatisticsController {
|
||||
}
|
||||
|
||||
@RequestMapping(value = STATISTICS_VOLUME, method = RequestMethod.GET, produces = "application/json")
|
||||
public ResponseEntity<CatMonthModel<Integer>> getMonthlySalesVolume(HttpServletRequest request,
|
||||
public ResponseEntity<CategoryMonthModel<Integer>> getMonthlySalesVolume(HttpServletRequest request,
|
||||
@RequestParam(value = PARAM_SESSION) UUID session,
|
||||
@RequestParam(value = PARAM_EMAIL) String email) {
|
||||
logRequest(request);
|
||||
@@ -46,7 +45,7 @@ public class StatisticsController {
|
||||
}
|
||||
|
||||
@RequestMapping(value = STATISTICS_REVENUE, method = RequestMethod.GET, produces = "application/json")
|
||||
public ResponseEntity<CatMonthModel<Integer>> getMonthlyRevenue(HttpServletRequest request,
|
||||
public ResponseEntity<CategoryMonthModel<Integer>> getMonthlyRevenue(HttpServletRequest request,
|
||||
@RequestParam(value = PARAM_SESSION) UUID token,
|
||||
@RequestParam(value = PARAM_EMAIL) String email) {
|
||||
logRequest(request);
|
||||
|
||||
@@ -16,17 +16,10 @@ public class ExpiredSessionDeleteJob {
|
||||
|
||||
private final SessionService sessionService;
|
||||
|
||||
/**
|
||||
* Constructor of the class
|
||||
* @param sessionService used in the class
|
||||
*/
|
||||
public ExpiredSessionDeleteJob(SessionService sessionService) {
|
||||
this.sessionService = sessionService;
|
||||
}
|
||||
|
||||
/**
|
||||
* Method running the job calling the referring service method
|
||||
*/
|
||||
@Scheduled(fixedRate = MILLIS_TO_WEEK)
|
||||
public void runFixedRateTask() {
|
||||
log.info("Deleting expired sessions...");
|
||||
|
||||
@@ -9,6 +9,6 @@ import java.util.Map;
|
||||
@Getter
|
||||
@Setter
|
||||
@AllArgsConstructor
|
||||
public class CatMonthModel<T extends Number> {
|
||||
public class CategoryMonthModel<T extends Number> {
|
||||
Map<String, Map<Long, T>> catMonthMap;
|
||||
}
|
||||
@@ -1,16 +1,14 @@
|
||||
package de.htwsaar.webshop.service;
|
||||
|
||||
import de.htwsaar.webshop.model.CatMonthModel;
|
||||
import de.htwsaar.webshop.model.CategoryMonthModel;
|
||||
import de.htwsaar.webshop.model.OrderStatus;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface StatisticsService {
|
||||
CatMonthModel<Integer> getSalesVolume();
|
||||
CategoryMonthModel<Integer> getSalesVolume();
|
||||
|
||||
CatMonthModel<Integer> getSalesRevenue();
|
||||
CategoryMonthModel<Integer> getSalesRevenue();
|
||||
|
||||
Map<OrderStatus, Integer> getOrderStatus();
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package de.htwsaar.webshop.service.impl;
|
||||
|
||||
import de.htwsaar.webshop.model.ArticleCategory;
|
||||
import de.htwsaar.webshop.model.CatMonthModel;
|
||||
import de.htwsaar.webshop.model.CategoryMonthModel;
|
||||
import de.htwsaar.webshop.model.OrderStatus;
|
||||
import de.htwsaar.webshop.repository.entities.OrderItem;
|
||||
import de.htwsaar.webshop.service.ArticleService;
|
||||
@@ -30,7 +30,7 @@ public class StatisticsServiceImpl implements StatisticsService {
|
||||
}
|
||||
|
||||
//returns Map<unix milli timestamp, Map<Category, T>>
|
||||
private <T extends Number> CatMonthModel<T> getMonthCategoryMap(Function<OrderItem, T> mappingFunction,
|
||||
private <T extends Number> CategoryMonthModel<T> getMonthCategoryMap(Function<OrderItem, T> mappingFunction,
|
||||
BinaryOperator<T> reduceFunction,
|
||||
T defaultValue) {
|
||||
Map<String, Map<Long, T>> map = new TreeMap<>();
|
||||
@@ -49,16 +49,16 @@ public class StatisticsServiceImpl implements StatisticsService {
|
||||
})
|
||||
);
|
||||
});
|
||||
return new CatMonthModel<>(map);
|
||||
return new CategoryMonthModel<>(map);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CatMonthModel<Integer> getSalesVolume() {
|
||||
public CategoryMonthModel<Integer> getSalesVolume() {
|
||||
return getMonthCategoryMap(OrderItem::getAmount, Integer::sum, 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CatMonthModel<Integer> getSalesRevenue() {
|
||||
public CategoryMonthModel<Integer> getSalesRevenue() {
|
||||
return getMonthCategoryMap(item -> item.getArticle().getPrice100(), Integer::sum, 0);
|
||||
}
|
||||
|
||||
|
||||
15
01-frontend/package-lock.json
generated
15
01-frontend/package-lock.json
generated
@@ -4880,21 +4880,6 @@
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/yaml": {
|
||||
"version": "2.8.0",
|
||||
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.0.tgz",
|
||||
"integrity": "sha512-4lLa/EcQCB0cJkyts+FpIRx5G/llPxfP6VQU5KByHEhLxY3IJCH0f0Hy1MHI8sClTvsIb8qwRJ6R/ZdlDJ/leQ==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"yaml": "bin.mjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 14.6"
|
||||
}
|
||||
},
|
||||
"node_modules/yocto-queue": {
|
||||
"version": "0.1.0",
|
||||
"resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
|
||||
|
||||
@@ -132,8 +132,8 @@
|
||||
"salesStatistics": "Sales Statistics",
|
||||
"monthlySalesVolume": "Monthly Sales Volume",
|
||||
"monthlySalesRevenue": "Monthly Sales Revenue in €",
|
||||
"itemVolumeDistribution": "Item Volume Distribution",
|
||||
"itemRevenueDistribution": "Item Revenue Distribution",
|
||||
"itemVolumeDistribution": "Sales Volume Distribution",
|
||||
"itemRevenueDistribution": "Sales Revenue Distribution",
|
||||
"stockFulfillment": "Stock fulfillment",
|
||||
"orderStatus": "Order Status",
|
||||
"ORDERED": "Ordered",
|
||||
|
||||
@@ -14,7 +14,8 @@
|
||||
transition: background-color 300ms cubic-bezier(0.4, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
html, body {
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
|
||||
@@ -1,24 +1,23 @@
|
||||
import {StyledEngineProvider} from '@mui/material/styles';
|
||||
import {QueryClient, QueryClientProvider} from '@tanstack/react-query';
|
||||
import {BrowserRouter, Route, Routes} from 'react-router-dom';
|
||||
import './App.css';
|
||||
import {BasketProvider} from './helper/BasketProvider';
|
||||
import NavBar from './helper/navbar/NavBar';
|
||||
import Account from './pages/Account';
|
||||
import Contact from './pages/Contact';
|
||||
import Home from './pages/Home';
|
||||
import NoPage from './pages/NoPage';
|
||||
import Orders from './pages/Orders';
|
||||
import Payment from './pages/Payment';
|
||||
import Product from './pages/Product';
|
||||
import {CustomThemeProvider} from './theme/ThemeContext';
|
||||
import FSComponents from './pages/FSComponents.tsx';
|
||||
import AdminPanel from './pages/AdminPanel';
|
||||
import {AccountProvider} from './helper/AccountProvider.tsx';
|
||||
import {CookiesProvider} from 'react-cookie';
|
||||
import { StyledEngineProvider } from "@mui/material/styles";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { BrowserRouter, Route, Routes } from "react-router-dom";
|
||||
import "./App.css";
|
||||
import { BasketProvider } from "./helper/BasketProvider";
|
||||
import NavBar from "./helper/navbar/NavBar";
|
||||
import Account from "./pages/Account";
|
||||
import Contact from "./pages/Contact";
|
||||
import Home from "./pages/Home";
|
||||
import NoPage from "./pages/NoPage";
|
||||
import Orders from "./pages/Orders";
|
||||
import Payment from "./pages/Payment";
|
||||
import Product from "./pages/Product";
|
||||
import { CustomThemeProvider } from "./theme/ThemeContext";
|
||||
import FSComponents from "./pages/FSComponents.tsx";
|
||||
import AdminPanel from "./pages/AdminPanel";
|
||||
import { AccountProvider } from "./helper/AccountProvider.tsx";
|
||||
import { CookiesProvider } from "react-cookie";
|
||||
|
||||
export default function App() {
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
return (
|
||||
@@ -37,9 +36,9 @@ export default function App() {
|
||||
<Route path="/checkout" element={<Payment />} />
|
||||
<Route path="/components" element={<FSComponents />} />
|
||||
<Route path="/contact" element={<Contact />} />
|
||||
<Route path='/account' element={<Account/>}/>
|
||||
<Route path='/orders' element={<Orders/>}/>
|
||||
<Route path='/admin' element={<AdminPanel/>}/>
|
||||
<Route path="/account" element={<Account />} />
|
||||
<Route path="/orders" element={<Orders />} />
|
||||
<Route path="/admin" element={<AdminPanel />} />
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
</BasketProvider>
|
||||
@@ -48,5 +47,5 @@ export default function App() {
|
||||
</CustomThemeProvider>
|
||||
</StyledEngineProvider>
|
||||
</QueryClientProvider>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -16,15 +16,14 @@ type AccountType = {
|
||||
|
||||
export default AccountType;
|
||||
|
||||
export type CustomerType =
|
||||
{
|
||||
export type CustomerType = {
|
||||
id: number;
|
||||
name: string;
|
||||
surname: string;
|
||||
address: string;
|
||||
country: string;
|
||||
zip: string;
|
||||
}
|
||||
};
|
||||
|
||||
export type SubmitLogin = {
|
||||
email: string;
|
||||
@@ -40,7 +39,7 @@ export type AdminAccountOperation = {
|
||||
email: string;
|
||||
uuid: string;
|
||||
accountId: number;
|
||||
}
|
||||
};
|
||||
|
||||
export type User = {
|
||||
password: string;
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
export enum OrderStatusEnum {
|
||||
ORDERED = 'ORDERED',
|
||||
IN_PROGRESS = 'IN_PROGRESS',
|
||||
ISSUES = 'ISSUES',
|
||||
DELIVERED = 'DELIVERED',
|
||||
CANCELLED = 'CANCELLED',
|
||||
ORDERED = "ORDERED",
|
||||
IN_PROGRESS = "IN_PROGRESS",
|
||||
ISSUES = "ISSUES",
|
||||
DELIVERED = "DELIVERED",
|
||||
CANCELLED = "CANCELLED",
|
||||
}
|
||||
|
||||
type OrderType = {
|
||||
@@ -17,7 +17,6 @@ type OrderType = {
|
||||
|
||||
export default OrderType;
|
||||
|
||||
|
||||
export type ShippingDetails = {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
|
||||
@@ -15,5 +15,5 @@ i18next
|
||||
},
|
||||
backend: {
|
||||
loadPath: "/locales/{{lng}}/translation.json",
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import {createContext, ReactNode, useContext, useEffect, useState} from "react";
|
||||
import {
|
||||
createContext,
|
||||
ReactNode,
|
||||
useContext,
|
||||
useEffect,
|
||||
useState,
|
||||
} from "react";
|
||||
import { AccountContextType, User } from "../components/Account";
|
||||
import {useCookies} from 'react-cookie';
|
||||
import { useCookies } from "react-cookie";
|
||||
|
||||
const AccountContext = createContext<AccountContextType | undefined>(undefined);
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, {createContext, useContext, useEffect, useState} from 'react';
|
||||
import Item from '../components/Item';
|
||||
import {useCookies} from 'react-cookie';
|
||||
import React, { createContext, useContext, useEffect, useState } from "react";
|
||||
import Item from "../components/Item";
|
||||
import { useCookies } from "react-cookie";
|
||||
|
||||
export interface BasketItem {
|
||||
item: Item;
|
||||
@@ -15,19 +15,23 @@ interface BasketContextType {
|
||||
|
||||
const BasketContext = createContext<BasketContextType | undefined>(undefined);
|
||||
|
||||
export const BasketProvider: React.FC<{ children: React.ReactNode }> = ({children}) => {
|
||||
export const BasketProvider: React.FC<{ children: React.ReactNode }> = ({
|
||||
children,
|
||||
}) => {
|
||||
const [cookies, setCookie] = useCookies(["basket"]);
|
||||
const [basket, setBasket] = useState<BasketItem[]>(cookies.basket || []);
|
||||
|
||||
const addToBasket = (item: Item, quantity: number) => {
|
||||
setBasket((prevBasket) => {
|
||||
const existingItem = prevBasket.find((basketItem) => basketItem.item.uuid === item.uuid);
|
||||
const existingItem = prevBasket.find(
|
||||
(basketItem) => basketItem.item.uuid === item.uuid,
|
||||
);
|
||||
if (existingItem) {
|
||||
// Update quantity if item already exists
|
||||
return prevBasket.map((basketItem) =>
|
||||
basketItem.item.uuid === item.uuid
|
||||
? { ...basketItem, quantity: basketItem.quantity + quantity }
|
||||
: basketItem
|
||||
: basketItem,
|
||||
);
|
||||
}
|
||||
// Add new item to basket
|
||||
@@ -54,7 +58,7 @@ export const BasketProvider: React.FC<{ children: React.ReactNode }> = ({childre
|
||||
export const useBasket = () => {
|
||||
const context = useContext(BasketContext);
|
||||
if (!context) {
|
||||
throw new Error('useBasket must be used within a BasketProvider');
|
||||
throw new Error("useBasket must be used within a BasketProvider");
|
||||
}
|
||||
return context;
|
||||
};
|
||||
@@ -1,13 +1,25 @@
|
||||
import DeleteIcon from "@mui/icons-material/Delete";
|
||||
import EditIcon from "@mui/icons-material/Edit";
|
||||
import { Box, Button, IconButton, Toolbar, useTheme } from "@mui/material";
|
||||
import {DataGrid, GridColDef, GridRowId, GridRowSelectionModel} from "@mui/x-data-grid";
|
||||
import {
|
||||
DataGrid,
|
||||
GridColDef,
|
||||
GridRowId,
|
||||
GridRowSelectionModel,
|
||||
} from "@mui/x-data-grid";
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import AccountType, {AdminAccountOperation, CustomerType} from "../../components/Account";
|
||||
import AccountType, {
|
||||
AdminAccountOperation,
|
||||
CustomerType,
|
||||
} from "../../components/Account";
|
||||
import { useAccount } from "../AccountProvider";
|
||||
import {deleteAccountAdmin, fetchAccounts, updateAccountAdmin} from "../query/Queries";
|
||||
import {
|
||||
deleteAccountAdmin,
|
||||
fetchAccounts,
|
||||
updateAccountAdmin,
|
||||
} from "../query/Queries";
|
||||
import CustomerEditDialog from "./CustomerEditDialog";
|
||||
|
||||
export default function AccountsInfo() {
|
||||
@@ -20,7 +32,7 @@ export default function AccountsInfo() {
|
||||
surname: "",
|
||||
address: "",
|
||||
zip: "",
|
||||
country: ""
|
||||
country: "",
|
||||
});
|
||||
|
||||
async function handleCustomerEdit(account: AccountType) {
|
||||
@@ -35,20 +47,24 @@ export default function AccountsInfo() {
|
||||
|
||||
const { data, refetch } = useQuery({
|
||||
queryKey: ["fetchAccounts", loginData],
|
||||
queryFn: () => fetchAccounts(loginData ? loginData : {
|
||||
queryFn: () =>
|
||||
fetchAccounts(
|
||||
loginData
|
||||
? loginData
|
||||
: {
|
||||
email: "",
|
||||
password: "",
|
||||
session: "",
|
||||
customerId: -1,
|
||||
isAdmin: false
|
||||
}),
|
||||
isAdmin: false,
|
||||
},
|
||||
),
|
||||
retry: 3,
|
||||
retryDelay: 1000,
|
||||
});
|
||||
|
||||
const deleteAccount = useMutation({
|
||||
mutationFn: (user: AdminAccountOperation) =>
|
||||
deleteAccountAdmin(user),
|
||||
mutationFn: (user: AdminAccountOperation) => deleteAccountAdmin(user),
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
@@ -63,60 +79,70 @@ export default function AccountsInfo() {
|
||||
|
||||
const handleDeleteSelected = async () => {
|
||||
selectedRows.forEach(async (rowId) => {
|
||||
let id = rows.find((row) => row.id === rowId)?.id
|
||||
let id = rows.find((row) => row.id === rowId)?.id;
|
||||
if (id === undefined) id = -1;
|
||||
await deleteAccount.mutateAsync({
|
||||
email: loginData?.email || '',
|
||||
uuid: loginData?.session || '',
|
||||
email: loginData?.email || "",
|
||||
uuid: loginData?.session || "",
|
||||
accountId: id,
|
||||
});
|
||||
})
|
||||
});
|
||||
|
||||
setRows(rows.filter((row) => !selectedRows.has(row.id)));
|
||||
};
|
||||
|
||||
const updateAdmin = useMutation({
|
||||
mutationFn: (account: AccountType) =>
|
||||
updateAccountAdmin(account, loginData ? loginData : {
|
||||
updateAccountAdmin(
|
||||
account,
|
||||
loginData
|
||||
? loginData
|
||||
: {
|
||||
email: "",
|
||||
password: "",
|
||||
session: "",
|
||||
customerId: -1,
|
||||
isAdmin: false
|
||||
}),
|
||||
|
||||
isAdmin: false,
|
||||
},
|
||||
),
|
||||
});
|
||||
|
||||
const columns: GridColDef<(typeof rows)[number]>[] = [
|
||||
{field: 'id', headerName: 'ID', width: 60},
|
||||
{ field: "id", headerName: "ID", width: 60 },
|
||||
{
|
||||
field: 'admin',
|
||||
headerName: t('admin'),
|
||||
field: "admin",
|
||||
headerName: t("admin"),
|
||||
type: "boolean",
|
||||
width: 90,
|
||||
editable: true
|
||||
editable: true,
|
||||
},
|
||||
{
|
||||
field: 'email',
|
||||
headerName: t('email'),
|
||||
field: "email",
|
||||
headerName: t("email"),
|
||||
width: 150,
|
||||
editable: false,
|
||||
},
|
||||
{
|
||||
field: 'langI18n',
|
||||
headerName: t('language'),
|
||||
field: "langI18n",
|
||||
headerName: t("language"),
|
||||
width: 150,
|
||||
editable: false,
|
||||
},
|
||||
{ //edit billing information button
|
||||
{
|
||||
//edit billing information button
|
||||
field: "customer",
|
||||
headerName: t('address'),
|
||||
headerName: t("address"),
|
||||
width: 90,
|
||||
sortable: false,
|
||||
disableReorder: true,
|
||||
disableColumnMenu: true,
|
||||
renderCell: params => <IconButton onClick={() => handleCustomerEdit(params.row)}> <EditIcon/> </IconButton>,
|
||||
}
|
||||
renderCell: (params) => (
|
||||
<IconButton onClick={() => handleCustomerEdit(params.row)}>
|
||||
{" "}
|
||||
<EditIcon />{" "}
|
||||
</IconButton>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const [open, setOpen] = useState(false);
|
||||
@@ -132,7 +158,7 @@ export default function AccountsInfo() {
|
||||
className="page-table"
|
||||
sx={{
|
||||
backgroundColor: theme.palette.background.paper,
|
||||
color: theme.palette.text.secondary
|
||||
color: theme.palette.text.secondary,
|
||||
}}
|
||||
>
|
||||
<DataGrid
|
||||
@@ -152,21 +178,23 @@ export default function AccountsInfo() {
|
||||
onClick={handleDeleteSelected}
|
||||
disabled={selectedRows.size === 0}
|
||||
sx={{
|
||||
marginRight: 1
|
||||
marginRight: 1,
|
||||
}}
|
||||
>
|
||||
{t('deleteAccount')}
|
||||
{t("deleteAccount")}
|
||||
</Button>
|
||||
</Toolbar>
|
||||
)
|
||||
),
|
||||
}}
|
||||
showToolbar
|
||||
processRowUpdate={async (updatedRow) => {
|
||||
const originalRow = rows.find(row => row.id === updatedRow.id);
|
||||
const originalRow = rows.find((row) => row.id === updatedRow.id);
|
||||
if (originalRow && originalRow.admin !== updatedRow.admin) {
|
||||
await updateAdmin.mutateAsync(updatedRow);
|
||||
}
|
||||
setRows(rows.map(row => row.id === updatedRow.id ? updatedRow : row));
|
||||
setRows(
|
||||
rows.map((row) => (row.id === updatedRow.id ? updatedRow : row)),
|
||||
);
|
||||
return updatedRow;
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
import {Button, Dialog, DialogActions, DialogContent, DialogTitle, TextField} from "@mui/material";
|
||||
import {
|
||||
Button,
|
||||
Dialog,
|
||||
DialogActions,
|
||||
DialogContent,
|
||||
DialogTitle,
|
||||
TextField,
|
||||
} from "@mui/material";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import React, { useEffect } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -18,9 +25,8 @@ const CustomerEditDialog: React.FC<CustomerDialogProps> = ({
|
||||
onClose,
|
||||
customerData,
|
||||
setCustomerData,
|
||||
onSubmit
|
||||
onSubmit,
|
||||
}) => {
|
||||
|
||||
const { t } = useTranslation();
|
||||
|
||||
useEffect(() => {
|
||||
@@ -33,8 +39,7 @@ const CustomerEditDialog: React.FC<CustomerDialogProps> = ({
|
||||
}, [open]);
|
||||
|
||||
const changeCustomer = useMutation({
|
||||
mutationFn: (customer: CustomerType) =>
|
||||
updateCustomer(customer),
|
||||
mutationFn: (customer: CustomerType) => updateCustomer(customer),
|
||||
});
|
||||
|
||||
const handleSave = async () => {
|
||||
@@ -49,11 +54,11 @@ const CustomerEditDialog: React.FC<CustomerDialogProps> = ({
|
||||
await changeCustomer.mutateAsync(customer);
|
||||
onSubmit(); // Rufe die onSubmit-Funktion auf, um den Dialog zu schließen und die Änderungen zu übernehmen
|
||||
onClose(); // Schließe den Dialog
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onClose={onClose} disableEnforceFocus>
|
||||
<DialogTitle>{t('changeCustomer')}</DialogTitle>
|
||||
<DialogTitle>{t("changeCustomer")}</DialogTitle>
|
||||
<DialogContent>
|
||||
<TextField
|
||||
margin="dense"
|
||||
@@ -61,7 +66,9 @@ const CustomerEditDialog: React.FC<CustomerDialogProps> = ({
|
||||
type="text"
|
||||
fullWidth
|
||||
value={customerData.name}
|
||||
onChange={e => setCustomerData(prev => ({...prev, name: e.target.value}))}
|
||||
onChange={(e) =>
|
||||
setCustomerData((prev) => ({ ...prev, name: e.target.value }))
|
||||
}
|
||||
/>
|
||||
<TextField
|
||||
margin="dense"
|
||||
@@ -69,7 +76,9 @@ const CustomerEditDialog: React.FC<CustomerDialogProps> = ({
|
||||
type="text"
|
||||
fullWidth
|
||||
value={customerData.surname}
|
||||
onChange={e => setCustomerData(prev => ({...prev, surname: e.target.value}))}
|
||||
onChange={(e) =>
|
||||
setCustomerData((prev) => ({ ...prev, surname: e.target.value }))
|
||||
}
|
||||
/>
|
||||
<TextField
|
||||
margin="dense"
|
||||
@@ -77,7 +86,9 @@ const CustomerEditDialog: React.FC<CustomerDialogProps> = ({
|
||||
type="text"
|
||||
fullWidth
|
||||
value={customerData.address}
|
||||
onChange={e => setCustomerData(prev => ({...prev, address: e.target.value}))}
|
||||
onChange={(e) =>
|
||||
setCustomerData((prev) => ({ ...prev, address: e.target.value }))
|
||||
}
|
||||
/>
|
||||
<TextField
|
||||
margin="dense"
|
||||
@@ -85,7 +96,9 @@ const CustomerEditDialog: React.FC<CustomerDialogProps> = ({
|
||||
type="text"
|
||||
fullWidth
|
||||
value={customerData.zip}
|
||||
onChange={e => setCustomerData(prev => ({...prev, zip: e.target.value}))}
|
||||
onChange={(e) =>
|
||||
setCustomerData((prev) => ({ ...prev, zip: e.target.value }))
|
||||
}
|
||||
/>
|
||||
<TextField
|
||||
margin="dense"
|
||||
@@ -93,7 +106,9 @@ const CustomerEditDialog: React.FC<CustomerDialogProps> = ({
|
||||
type="text"
|
||||
fullWidth
|
||||
value={customerData.country}
|
||||
onChange={e => setCustomerData(prev => ({...prev, country: e.target.value}))}
|
||||
onChange={(e) =>
|
||||
setCustomerData((prev) => ({ ...prev, country: e.target.value }))
|
||||
}
|
||||
/>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, {useState} from 'react';
|
||||
import React, { useState } from "react";
|
||||
import {
|
||||
Alert,
|
||||
Box,
|
||||
@@ -10,11 +10,11 @@ import {
|
||||
DialogTitle,
|
||||
IconButton,
|
||||
Typography,
|
||||
} from '@mui/material';
|
||||
import CloudUploadIcon from '@mui/icons-material/CloudUpload';
|
||||
import CloseIcon from '@mui/icons-material/Close';
|
||||
import {useTranslation} from 'react-i18next';
|
||||
import {Item} from '../../components/Item.tsx';
|
||||
} from "@mui/material";
|
||||
import CloudUploadIcon from "@mui/icons-material/CloudUpload";
|
||||
import CloseIcon from "@mui/icons-material/Close";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Item } from "../../components/Item.tsx";
|
||||
|
||||
interface ItemImageDialogProps {
|
||||
open: boolean;
|
||||
@@ -24,7 +24,13 @@ interface ItemImageDialogProps {
|
||||
isFarmStationImage: boolean;
|
||||
}
|
||||
|
||||
export default function ItemImageDialog({open, onClose, item, onSuccess, isFarmStationImage}: ItemImageDialogProps) {
|
||||
export default function ItemImageDialog({
|
||||
open,
|
||||
onClose,
|
||||
item,
|
||||
onSuccess,
|
||||
isFarmStationImage,
|
||||
}: ItemImageDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null);
|
||||
const [preview, setPreview] = useState<string | null>(null);
|
||||
@@ -36,14 +42,14 @@ export default function ItemImageDialog({open, onClose, item, onSuccess, isFarmS
|
||||
const file = event.target.files?.[0];
|
||||
if (file) {
|
||||
// Validate file type
|
||||
if (!file.type.startsWith('image/')) {
|
||||
setError('Please select a valid image file');
|
||||
if (!file.type.startsWith("image/")) {
|
||||
setError("Please select a valid image file");
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate file size (5MB limit)
|
||||
if (file.size > 5 * 1024 * 1024) {
|
||||
setError('File size must be less than 5MB');
|
||||
setError("File size must be less than 5MB");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -65,7 +71,7 @@ export default function ItemImageDialog({open, onClose, item, onSuccess, isFarmS
|
||||
reader.onload = () => {
|
||||
const result = reader.result as string;
|
||||
// Remove the data URL prefix (e.g., "data:image/jpeg;base64,")
|
||||
const base64 = result.split(',')[1];
|
||||
const base64 = result.split(",")[1];
|
||||
resolve(base64);
|
||||
};
|
||||
reader.onerror = reject;
|
||||
@@ -75,7 +81,7 @@ export default function ItemImageDialog({open, onClose, item, onSuccess, isFarmS
|
||||
|
||||
const handleUpload = async () => {
|
||||
if (!selectedFile) {
|
||||
setError('Please select an image file');
|
||||
setError("Please select an image file");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -85,16 +91,23 @@ export default function ItemImageDialog({open, onClose, item, onSuccess, isFarmS
|
||||
try {
|
||||
const base64Image = await convertFileToBase64(selectedFile);
|
||||
|
||||
const response = await fetch((isFarmStationImage ? 'http://localhost:8085/farm' : 'http://localhost:8085/image') + '?uuid=' + item.uuid, {
|
||||
method: 'PUT',
|
||||
const response = await fetch(
|
||||
(isFarmStationImage
|
||||
? "http://localhost:8085/farm"
|
||||
: "http://localhost:8085/image") +
|
||||
"?uuid=" +
|
||||
item.uuid,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: base64Image,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
console.error('Failed to upload image:', await response.text());
|
||||
console.error("Failed to upload image:", await response.text());
|
||||
}
|
||||
|
||||
setSuccess(true);
|
||||
@@ -104,9 +117,8 @@ export default function ItemImageDialog({open, onClose, item, onSuccess, isFarmS
|
||||
setTimeout(() => {
|
||||
handleClose();
|
||||
}, 1500);
|
||||
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to upload image');
|
||||
setError(err instanceof Error ? err.message : "Failed to upload image");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -122,42 +134,45 @@ export default function ItemImageDialog({open, onClose, item, onSuccess, isFarmS
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onClose={handleClose}
|
||||
maxWidth="sm"
|
||||
fullWidth
|
||||
<Dialog open={open} onClose={handleClose} maxWidth="sm" fullWidth>
|
||||
<DialogTitle
|
||||
sx={{
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
<DialogTitle sx={{display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}>
|
||||
{t('uploadImage')} - {item.name}
|
||||
{t("uploadImage")} - {item.name}
|
||||
<IconButton onClick={handleClose} size="small">
|
||||
<CloseIcon />
|
||||
</IconButton>
|
||||
</DialogTitle>
|
||||
|
||||
<DialogContent>
|
||||
<Box sx={{display: 'flex', flexDirection: 'column', gap: 2, py: 1}}>
|
||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 2, py: 1 }}>
|
||||
{/* Item Info */}
|
||||
<Box>
|
||||
<Typography variant="body2" color="textSecondary">
|
||||
{t('item')}: {item.name}
|
||||
{t("item")}: {item.name}
|
||||
</Typography>
|
||||
<Typography variant="body2" color="textSecondary">
|
||||
UUID: {item.uuid}
|
||||
</Typography>
|
||||
<Typography variant="body2" color="error">
|
||||
{t('imageUploadNotice')}
|
||||
{t("imageUploadNotice")}
|
||||
</Typography>
|
||||
{isFarmStationImage && <Typography variant="body2" color="error">
|
||||
{t('imageUploadNoticeFs')}
|
||||
</Typography>}
|
||||
{isFarmStationImage && (
|
||||
<Typography variant="body2" color="error">
|
||||
{t("imageUploadNoticeFs")}
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
{/* File Upload */}
|
||||
<Box>
|
||||
<input
|
||||
accept="image/*"
|
||||
style={{display: 'none'}}
|
||||
style={{ display: "none" }}
|
||||
id="image-upload"
|
||||
type="file"
|
||||
onChange={handleFileSelect}
|
||||
@@ -170,27 +185,28 @@ export default function ItemImageDialog({open, onClose, item, onSuccess, isFarmS
|
||||
fullWidth
|
||||
sx={{ mb: 2 }}
|
||||
>
|
||||
{selectedFile ? selectedFile.name : t('selectImage')}
|
||||
{selectedFile ? selectedFile.name : t("selectImage")}
|
||||
</Button>
|
||||
</label>
|
||||
</Box>
|
||||
|
||||
{/* Image Preview */}
|
||||
{preview && (
|
||||
<Box sx={{textAlign: 'center'}}>
|
||||
<Box sx={{ textAlign: "center" }}>
|
||||
<img
|
||||
src={preview}
|
||||
alt="Preview"
|
||||
style={{
|
||||
maxWidth: '100%',
|
||||
maxHeight: '300px',
|
||||
objectFit: 'contain',
|
||||
border: '1px solid #ddd',
|
||||
borderRadius: '4px',
|
||||
maxWidth: "100%",
|
||||
maxHeight: "300px",
|
||||
objectFit: "contain",
|
||||
border: "1px solid #ddd",
|
||||
borderRadius: "4px",
|
||||
}}
|
||||
/>
|
||||
<Typography variant="caption" display="block" sx={{ mt: 1 }}>
|
||||
{selectedFile?.name} ({(selectedFile?.size || 0 / 1024).toFixed(1)} KB)
|
||||
{selectedFile?.name} (
|
||||
{(selectedFile?.size || 0 / 1024).toFixed(1)} KB)
|
||||
</Typography>
|
||||
</Box>
|
||||
)}
|
||||
@@ -204,16 +220,14 @@ export default function ItemImageDialog({open, onClose, item, onSuccess, isFarmS
|
||||
|
||||
{/* Success Message */}
|
||||
{success && (
|
||||
<Alert severity="success">
|
||||
{t('imageUploadedSuccessfully')}
|
||||
</Alert>
|
||||
<Alert severity="success">{t("imageUploadedSuccessfully")}</Alert>
|
||||
)}
|
||||
</Box>
|
||||
</DialogContent>
|
||||
|
||||
<DialogActions>
|
||||
<Button onClick={handleClose} disabled={loading}>
|
||||
{t('cancel')}
|
||||
{t("cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleUpload}
|
||||
@@ -221,7 +235,7 @@ export default function ItemImageDialog({open, onClose, item, onSuccess, isFarmS
|
||||
disabled={!selectedFile || loading}
|
||||
startIcon={loading ? <CircularProgress size={20} /> : undefined}
|
||||
>
|
||||
{loading ? t('uploading') : t('upload')}
|
||||
{loading ? t("uploading") : t("upload")}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
@@ -3,18 +3,26 @@ import DeleteIcon from "@mui/icons-material/Delete";
|
||||
import EditIcon from "@mui/icons-material/Edit";
|
||||
import { Box, Button, IconButton, Toolbar, useTheme } from "@mui/material";
|
||||
import { Gauge, gaugeClasses } from "@mui/x-charts";
|
||||
import { DataGrid, GridColDef, GridRowId, GridRowSelectionModel } from "@mui/x-data-grid";
|
||||
import {
|
||||
DataGrid,
|
||||
GridColDef,
|
||||
GridRowId,
|
||||
GridRowSelectionModel,
|
||||
} from "@mui/x-data-grid";
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import Item from "../../components/Item";
|
||||
import { mapValueToColor } from "../../util/ColorUtil.tsx";
|
||||
import { useAccount } from "../AccountProvider.tsx";
|
||||
import { deleteItemQuery, fetchItems, updateItemAdmin } from "../query/Queries.tsx";
|
||||
import {
|
||||
deleteItemQuery,
|
||||
fetchItemList,
|
||||
updateItemAdmin,
|
||||
} from "../query/Queries.tsx";
|
||||
import ItemImageDialog from "./ItemImageDialog.tsx";
|
||||
import NewItemDialog from "./NewItemDialog.tsx";
|
||||
|
||||
export default function ItemsInfo() {
|
||||
export default function ItemsInfo({ itemList }: { itemList: Item[] }) {
|
||||
const theme = useTheme();
|
||||
const { t } = useTranslation();
|
||||
|
||||
@@ -26,7 +34,6 @@ export default function ItemsInfo() {
|
||||
const [selectedItem, setSelectedItem] = useState<Item | null>(null);
|
||||
const [isFarmStationImage, setIsFarmStationImage] = useState(false);
|
||||
|
||||
|
||||
function handleImageEdit(item: Item) {
|
||||
setIsFarmStationImage(false);
|
||||
setSelectedItem(item);
|
||||
@@ -41,152 +48,173 @@ export default function ItemsInfo() {
|
||||
console.log("IconEdit", item);
|
||||
}
|
||||
|
||||
|
||||
function handleAddItem() {
|
||||
setNewItemDialog(true);
|
||||
}
|
||||
|
||||
const { user: loginData } = useAccount();
|
||||
|
||||
const { data } = useQuery({
|
||||
queryKey: ["fetchItems", loginData],
|
||||
queryFn: () => fetchItems(),
|
||||
retry: 3,
|
||||
retryDelay: 1000,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
setRows(data);
|
||||
if (itemList) {
|
||||
setRows(itemList);
|
||||
}
|
||||
}, [data]);
|
||||
}, [itemList]);
|
||||
|
||||
const handleSelectionChange = (newSelection: GridRowSelectionModel) => {
|
||||
setSelectedRows(newSelection.ids);
|
||||
};
|
||||
|
||||
const deleteItem = useMutation({
|
||||
mutationFn: (uuid: string) =>
|
||||
deleteItemQuery(uuid),
|
||||
mutationFn: (uuid: string) => deleteItemQuery(uuid),
|
||||
});
|
||||
|
||||
const handleDeleteSelected = async () => {
|
||||
await Promise.all(
|
||||
Array.from(selectedRows).map(async (row) => {
|
||||
await deleteItem.mutateAsync(rows.find(item => item.id === row)?.uuid || "");
|
||||
})
|
||||
await deleteItem.mutateAsync(
|
||||
rows.find((item) => item.id === row)?.uuid || "",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
setRows(rows.filter((row) => !selectedRows.has(row.id)));
|
||||
};
|
||||
|
||||
const updateItem = useMutation({
|
||||
mutationFn: (item: Item) =>
|
||||
updateItemAdmin(item),
|
||||
|
||||
mutationFn: (item: Item) => updateItemAdmin(item),
|
||||
});
|
||||
|
||||
const handleRowUpdate = async (updatedRow: Item) => {
|
||||
setRows(rows.map(row => row.id === updatedRow.id ? updatedRow : row));
|
||||
setRows(rows.map((row) => (row.id === updatedRow.id ? updatedRow : row)));
|
||||
await updateItem.mutateAsync(updatedRow);
|
||||
return updatedRow;
|
||||
}
|
||||
};
|
||||
|
||||
const columns: GridColDef<(typeof rows)[number]>[] = [
|
||||
{ field: 'id', headerName: 'ID', width: 60 },
|
||||
{ field: "id", headerName: "ID", width: 60 },
|
||||
{
|
||||
field: 'uuid',
|
||||
headerName: t('uuid'),
|
||||
field: "uuid",
|
||||
headerName: t("uuid"),
|
||||
type: "string",
|
||||
width: 120,
|
||||
editable: false
|
||||
editable: false,
|
||||
},
|
||||
{
|
||||
field: 'name',
|
||||
headerName: t('name'),
|
||||
field: "name",
|
||||
headerName: t("name"),
|
||||
width: 200,
|
||||
editable: true,
|
||||
},
|
||||
{
|
||||
field: 'category',
|
||||
headerName: t('category'),
|
||||
field: "category",
|
||||
headerName: t("category"),
|
||||
width: 150,
|
||||
editable: true,
|
||||
valueFormatter: (val) => t(val),
|
||||
},
|
||||
{
|
||||
field: 'description',
|
||||
headerName: t('description'),
|
||||
field: "description",
|
||||
headerName: t("description"),
|
||||
width: 150,
|
||||
editable: true,
|
||||
},
|
||||
{
|
||||
field: 'price100',
|
||||
headerName: t('price100€'),
|
||||
field: "price100",
|
||||
headerName: t("price100€"),
|
||||
width: 100,
|
||||
editable: true,
|
||||
type: 'number',
|
||||
type: "number",
|
||||
valueFormatter: (val) => (val / 100).toFixed(2),
|
||||
},
|
||||
{
|
||||
field: 'discount100',
|
||||
headerName: t('discount100'),
|
||||
field: "discount100",
|
||||
headerName: t("discount100"),
|
||||
width: 120,
|
||||
editable: true,
|
||||
type: 'number'
|
||||
type: "number",
|
||||
},
|
||||
{
|
||||
field: 'stock',
|
||||
headerName: t('stock'),
|
||||
field: "stock",
|
||||
headerName: t("stock"),
|
||||
width: 100,
|
||||
editable: true,
|
||||
type: 'number',
|
||||
renderCell: params => <Gauge value={Math.min(params.row.stock, params.row.stockExpected)} valueMin={0}
|
||||
valueMax={params.row.stockExpected} startAngle={-90} endAngle={90} sx={{
|
||||
type: "number",
|
||||
renderCell: (params) => (
|
||||
<Gauge
|
||||
value={Math.min(params.row.stock, params.row.stockExpected)}
|
||||
valueMin={0}
|
||||
valueMax={params.row.stockExpected}
|
||||
startAngle={-90}
|
||||
endAngle={90}
|
||||
sx={{
|
||||
[`& .${gaugeClasses.valueArc}`]: {
|
||||
fill: () => {
|
||||
return mapValueToColor(0, params.row.stockExpected, params.row.stock)
|
||||
return mapValueToColor(
|
||||
0,
|
||||
params.row.stockExpected,
|
||||
params.row.stock,
|
||||
);
|
||||
},
|
||||
},
|
||||
}} text={() => `${params.row.stock}`} />
|
||||
}}
|
||||
text={() => `${params.row.stock}`}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
field: 'rating',
|
||||
headerName: t('rating'),
|
||||
field: "rating",
|
||||
headerName: t("rating"),
|
||||
width: 100,
|
||||
editable: false, //the rating is averaged from ratings
|
||||
type: 'number',
|
||||
renderCell: params => <Gauge value={Math.min(params.row.rating, 10)} valueMin={0} valueMax={10}
|
||||
startAngle={-90} endAngle={90} sx={{
|
||||
type: "number",
|
||||
renderCell: (params) => (
|
||||
<Gauge
|
||||
value={Math.min(params.row.rating, 10)}
|
||||
valueMin={0}
|
||||
valueMax={10}
|
||||
startAngle={-90}
|
||||
endAngle={90}
|
||||
sx={{
|
||||
[`& .${gaugeClasses.valueArc}`]: {
|
||||
fill: () => {
|
||||
return mapValueToColor(0, 10, params.row.rating)
|
||||
return mapValueToColor(0, 10, params.row.rating);
|
||||
},
|
||||
},
|
||||
}} text={() => `${params.row.rating.toFixed(2)}`} />
|
||||
}}
|
||||
text={() => `${params.row.rating.toFixed(2)}`}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
field: "actualPrice",
|
||||
headerName: t('actualPrice'),
|
||||
headerName: t("actualPrice"),
|
||||
width: 90,
|
||||
editable: false,
|
||||
valueGetter: (_, row) => (row.price100 / 100 * ((100 - row.discount100) / 100)).toFixed(2)
|
||||
valueGetter: (_, row) =>
|
||||
((row.price100 / 100) * ((100 - row.discount100) / 100)).toFixed(2),
|
||||
},
|
||||
{
|
||||
field: 'images',
|
||||
headerName: t('images'),
|
||||
field: "images",
|
||||
headerName: t("images"),
|
||||
width: 90,
|
||||
editable: false,
|
||||
renderCell: params => <IconButton onClick={() => handleImageEdit(params.row)}> <EditIcon /> </IconButton>,
|
||||
renderCell: (params) => (
|
||||
<IconButton onClick={() => handleImageEdit(params.row)}>
|
||||
{" "}
|
||||
<EditIcon />{" "}
|
||||
</IconButton>
|
||||
),
|
||||
},
|
||||
{
|
||||
field: 'farmImage',
|
||||
headerName: t('fsImage'),
|
||||
field: "farmImage",
|
||||
headerName: t("fsImage"),
|
||||
width: 90,
|
||||
editable: false,
|
||||
renderCell: params => <IconButton onClick={() => handleFarmImageEdit(params.row)}> <EditIcon />
|
||||
</IconButton>,
|
||||
}
|
||||
renderCell: (params) => (
|
||||
<IconButton onClick={() => handleFarmImageEdit(params.row)}>
|
||||
{" "}
|
||||
<EditIcon />
|
||||
</IconButton>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
@@ -194,7 +222,7 @@ export default function ItemsInfo() {
|
||||
className="page-table"
|
||||
sx={{
|
||||
backgroundColor: theme.palette.background.paper,
|
||||
color: theme.palette.text.secondary
|
||||
color: theme.palette.text.secondary,
|
||||
}}
|
||||
>
|
||||
<DataGrid
|
||||
@@ -214,10 +242,10 @@ export default function ItemsInfo() {
|
||||
onClick={handleDeleteSelected}
|
||||
disabled={selectedRows.size === 0}
|
||||
sx={{
|
||||
marginRight: 1
|
||||
marginRight: 1,
|
||||
}}
|
||||
>
|
||||
{t('deleteProduct')}
|
||||
{t("deleteProduct")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="contained"
|
||||
@@ -225,13 +253,13 @@ export default function ItemsInfo() {
|
||||
startIcon={<AddIcon />}
|
||||
onClick={handleAddItem}
|
||||
sx={{
|
||||
marginRight: 1
|
||||
marginRight: 1,
|
||||
}}
|
||||
>
|
||||
{t('addProduct')}
|
||||
{t("addProduct")}
|
||||
</Button>
|
||||
</Toolbar>
|
||||
)
|
||||
),
|
||||
}}
|
||||
showToolbar
|
||||
processRowUpdate={handleRowUpdate}
|
||||
@@ -243,7 +271,7 @@ export default function ItemsInfo() {
|
||||
item={selectedItem}
|
||||
onSuccess={() => {
|
||||
// Refresh data or update UI
|
||||
console.log('Image uploaded successfully');
|
||||
console.log("Image uploaded successfully");
|
||||
}}
|
||||
isFarmStationImage={isFarmStationImage}
|
||||
/>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import CloseIcon from '@mui/icons-material/Close';
|
||||
import CloseIcon from "@mui/icons-material/Close";
|
||||
import {
|
||||
Alert,
|
||||
Box,
|
||||
@@ -8,13 +8,13 @@ import {
|
||||
DialogContent,
|
||||
DialogTitle,
|
||||
IconButton,
|
||||
TextField
|
||||
} from '@mui/material';
|
||||
import {useMutation} from '@tanstack/react-query';
|
||||
import {useState} from 'react';
|
||||
import {useTranslation} from 'react-i18next';
|
||||
import {Item} from '../../components/Item';
|
||||
import {submitItem} from '../query/Queries';
|
||||
TextField,
|
||||
} from "@mui/material";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Item } from "../../components/Item";
|
||||
import { submitItem } from "../query/Queries";
|
||||
|
||||
interface NewItemDialogProps {
|
||||
open: boolean;
|
||||
@@ -51,8 +51,7 @@ export default function NewItemDialog({open, onClose}: NewItemDialogProps) {
|
||||
};
|
||||
|
||||
const saveItem = useMutation({
|
||||
mutationFn: (item: Item) =>
|
||||
submitItem(item),
|
||||
mutationFn: (item: Item) => submitItem(item),
|
||||
});
|
||||
|
||||
const handleSave = async () => {
|
||||
@@ -60,28 +59,29 @@ export default function NewItemDialog({open, onClose}: NewItemDialogProps) {
|
||||
setError(null);
|
||||
setSuccess(false);
|
||||
|
||||
await saveItem.mutateAsync(item)
|
||||
await saveItem.mutateAsync(item);
|
||||
|
||||
onClose(); // Close the dialog after saving
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onClose={handleClose}
|
||||
maxWidth="sm"
|
||||
fullWidth
|
||||
<Dialog open={open} onClose={handleClose} maxWidth="sm" fullWidth>
|
||||
<DialogTitle
|
||||
sx={{
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
<DialogTitle sx={{display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}>
|
||||
{t('createNewItem')}
|
||||
{t("createNewItem")}
|
||||
<IconButton onClick={handleClose} size="small">
|
||||
<CloseIcon />
|
||||
</IconButton>
|
||||
</DialogTitle>
|
||||
|
||||
<DialogContent>
|
||||
<Box sx={{display: 'flex', flexDirection: 'column', gap: 2, py: 1}}>
|
||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 2, py: 1 }}>
|
||||
{/* Name, Kategorie, Beschreibung, Preis, Rabatt, Bestand, Bestand erwartet */}
|
||||
<TextField
|
||||
label={t("name")}
|
||||
@@ -110,7 +110,7 @@ export default function NewItemDialog({open, onClose}: NewItemDialogProps) {
|
||||
value={item.price100}
|
||||
onChange={handleChange}
|
||||
fullWidth
|
||||
type='number'
|
||||
type="number"
|
||||
/>
|
||||
<TextField
|
||||
label={t("discount100")}
|
||||
@@ -118,7 +118,7 @@ export default function NewItemDialog({open, onClose}: NewItemDialogProps) {
|
||||
value={item.discount100}
|
||||
onChange={handleChange}
|
||||
fullWidth
|
||||
type='number'
|
||||
type="number"
|
||||
/>
|
||||
<TextField
|
||||
label={t("stockExpected")}
|
||||
@@ -126,7 +126,7 @@ export default function NewItemDialog({open, onClose}: NewItemDialogProps) {
|
||||
value={item.stockExpected}
|
||||
onChange={handleChange}
|
||||
fullWidth
|
||||
type='number'
|
||||
type="number"
|
||||
/>
|
||||
<TextField
|
||||
label={t("stock")}
|
||||
@@ -134,7 +134,7 @@ export default function NewItemDialog({open, onClose}: NewItemDialogProps) {
|
||||
value={item.stock}
|
||||
onChange={handleChange}
|
||||
fullWidth
|
||||
type='number'
|
||||
type="number"
|
||||
/>
|
||||
|
||||
{/* Error Message */}
|
||||
@@ -146,19 +146,17 @@ export default function NewItemDialog({open, onClose}: NewItemDialogProps) {
|
||||
|
||||
{/* Success Message */}
|
||||
{success && (
|
||||
<Alert severity="success">
|
||||
{t('itemCreatedSuccessfully')}
|
||||
</Alert>
|
||||
<Alert severity="success">{t("itemCreatedSuccessfully")}</Alert>
|
||||
)}
|
||||
</Box>
|
||||
</DialogContent>
|
||||
|
||||
<DialogActions>
|
||||
<Button onClick={handleSave} disabled={loading}>
|
||||
{t('save')}
|
||||
{t("save")}
|
||||
</Button>
|
||||
<Button onClick={handleClose} disabled={loading}>
|
||||
{t('cancel')}
|
||||
{t("cancel")}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
@@ -12,16 +12,17 @@ import {
|
||||
Snackbar,
|
||||
Stack,
|
||||
Typography,
|
||||
useTheme
|
||||
useTheme,
|
||||
} from "@mui/material";
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import React, { PropsWithChildren, useState } from "react";
|
||||
import {DndProvider, useDrag, useDrop} from 'react-dnd';
|
||||
import {HTML5Backend} from 'react-dnd-html5-backend';
|
||||
import { DndProvider, useDrag, useDrop } from "react-dnd";
|
||||
import { HTML5Backend } from "react-dnd-html5-backend";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import OrderType, { OrderPatch, OrderStatusEnum } from "../../components/Order";
|
||||
import { useAccount } from "../AccountProvider";
|
||||
import { fetchOrdersAdmin, orderPatch } from "../query/Queries";
|
||||
import Item from "../../components/Item";
|
||||
|
||||
// The order in which the statuses are displayed
|
||||
const statusOrder: OrderStatusEnum[] = [
|
||||
@@ -29,16 +30,17 @@ const statusOrder: OrderStatusEnum[] = [
|
||||
OrderStatusEnum.ISSUES,
|
||||
OrderStatusEnum.ORDERED,
|
||||
OrderStatusEnum.IN_PROGRESS,
|
||||
OrderStatusEnum.DELIVERED
|
||||
OrderStatusEnum.DELIVERED,
|
||||
];
|
||||
|
||||
|
||||
const OrderCard: React.FC<{ order: OrderType; onClick: () => void }> = ({order, onClick}) => {
|
||||
|
||||
const OrderCard: React.FC<{ order: OrderType; onClick: () => void }> = ({
|
||||
order,
|
||||
onClick,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const [{ isDragging }, drag] = useDrag(() => ({
|
||||
type: 'order',
|
||||
type: "order",
|
||||
item: { id: order.id },
|
||||
collect: (monitor) => ({
|
||||
isDragging: !!monitor.isDragging(),
|
||||
@@ -47,18 +49,21 @@ const OrderCard: React.FC<{ order: OrderType; onClick: () => void }> = ({order,
|
||||
|
||||
return (
|
||||
<div ref={drag} style={{ opacity: isDragging ? 0.5 : 1, marginBottom: 8 }}>
|
||||
<Card elevation={4} sx={{
|
||||
m: 1
|
||||
}}>
|
||||
<Card
|
||||
elevation={4}
|
||||
sx={{
|
||||
m: 1,
|
||||
}}
|
||||
>
|
||||
<CardContent onClick={onClick}>
|
||||
<Typography gutterBottom variant="h5" component="div">
|
||||
Order: {order.id}
|
||||
</Typography>
|
||||
<Typography>
|
||||
{t('date') + ": " + new Date(order.time).toUTCString()}
|
||||
{t("date") + ": " + new Date(order.time).toUTCString()}
|
||||
</Typography>
|
||||
<Typography>
|
||||
{t('total') + ": " + (order.total / 100).toFixed(2) + " €"}
|
||||
{t("total") + ": " + (order.total / 100).toFixed(2) + " €"}
|
||||
</Typography>
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -66,16 +71,17 @@ const OrderCard: React.FC<{ order: OrderType; onClick: () => void }> = ({order,
|
||||
);
|
||||
};
|
||||
|
||||
const Column: React.FC<PropsWithChildren<{
|
||||
const Column: React.FC<
|
||||
PropsWithChildren<{
|
||||
status: OrderStatusEnum;
|
||||
onDrop: (id: number, status: OrderStatusEnum) => void
|
||||
}>> = ({status, onDrop, children}) => {
|
||||
|
||||
onDrop: (id: number, status: OrderStatusEnum) => void;
|
||||
}>
|
||||
> = ({ status, onDrop, children }) => {
|
||||
const { t } = useTranslation();
|
||||
const theme = useTheme();
|
||||
|
||||
const [{ isOver }, drop] = useDrop(() => ({
|
||||
accept: 'order',
|
||||
accept: "order",
|
||||
drop: (item: { id: number }) => onDrop(item.id, status),
|
||||
collect: (monitor) => ({
|
||||
isOver: !!monitor.isOver(),
|
||||
@@ -83,93 +89,102 @@ const Column: React.FC<PropsWithChildren<{
|
||||
}));
|
||||
|
||||
return (
|
||||
<div ref={drop} style={{
|
||||
<div
|
||||
ref={drop}
|
||||
style={{
|
||||
flex: 1,
|
||||
backgroundColor: isOver ? theme.palette.background.paper : 'transparent',
|
||||
backgroundColor: isOver
|
||||
? theme.palette.background.paper
|
||||
: "transparent",
|
||||
minWidth: 300,
|
||||
maxWidth: 400
|
||||
}}>
|
||||
<Card sx={{
|
||||
minHeight: '100%',
|
||||
maxWidth: 400,
|
||||
}}
|
||||
>
|
||||
<Card
|
||||
sx={{
|
||||
minHeight: "100%",
|
||||
marginTop: 2,
|
||||
marginLeft: 1,
|
||||
height: '80vh',
|
||||
display: 'flex',
|
||||
flexDirection: 'column'
|
||||
}} elevation={1}>
|
||||
<CardContent sx={{
|
||||
height: "80vh",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
}}
|
||||
elevation={1}
|
||||
>
|
||||
<CardContent
|
||||
sx={{
|
||||
flex: 1,
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
overflowY: 'auto',
|
||||
height: '100%',
|
||||
}}>
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
overflowY: "auto",
|
||||
height: "100%",
|
||||
}}
|
||||
>
|
||||
<Typography variant="h6">{t(status)}</Typography>
|
||||
<div style={{flex: 1, overflowY: 'auto'}}>
|
||||
{children}
|
||||
</div>
|
||||
<div style={{ flex: 1, overflowY: "auto" }}>{children}</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const EditOrder: React.FC<{ open: boolean; order: OrderType | null; onClose: () => void }> = ({
|
||||
open,
|
||||
order,
|
||||
onClose
|
||||
}) => {
|
||||
|
||||
const EditOrder: React.FC<{
|
||||
open: boolean;
|
||||
order: OrderType | null;
|
||||
articleNameMapping: (uuid: string) => string;
|
||||
onClose: () => void;
|
||||
}> = ({ open, order, articleNameMapping, onClose }) => {
|
||||
const { t } = useTranslation();
|
||||
if (order === null)
|
||||
return "";
|
||||
if (order === null) return "";
|
||||
return (
|
||||
<Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
|
||||
<DialogTitle>
|
||||
{`${t(order.status)} #${order?.id}`}
|
||||
</DialogTitle>
|
||||
<DialogTitle>{`${t(order.status)} #${order?.id}`}</DialogTitle>
|
||||
<DialogContent dividers>
|
||||
{order && (
|
||||
<Stack spacing={2}>
|
||||
<Typography
|
||||
variant="subtitle1">{`${t('orderDate')}: ${new Date(order.time).toDateString()}`}</Typography>
|
||||
<Typography variant="subtitle1">{`${t("orderDate")}: ${new Date(order.time).toDateString()}`}</Typography>
|
||||
<Divider />
|
||||
<Typography variant="subtitle2">{t('orderedItems')}:</Typography>
|
||||
<Typography variant="subtitle2">{t("orderedItems")}:</Typography>
|
||||
<List dense>
|
||||
{order.orderItems.map((item, idx) => (
|
||||
<ListItemText
|
||||
key={idx}
|
||||
primary={`${item.article} x${item.amount}`}
|
||||
primary={`${item.amount}x ${articleNameMapping(item.article)}`}
|
||||
/>
|
||||
))}
|
||||
</List>
|
||||
<Divider />
|
||||
<Typography variant="h6">{`${t('sum')}: ${(order.total / 100).toFixed(2)} €`}</Typography>
|
||||
<Typography variant="h6">{`${t("sum")}: ${(order.total / 100).toFixed(2)} €`}</Typography>
|
||||
</Stack>
|
||||
)}
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={onClose}>{t('close')}</Button>
|
||||
<Button onClick={onClose}>{t("close")}</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default function OrdersInfo() {
|
||||
export default function OrdersInfo({ itemList }: { itemList: Item[] }) {
|
||||
const [editOrder, setEditOrder] = useState<OrderType | null>(null);
|
||||
const [openSnackbar, setOpenSnackbar] = useState(false);
|
||||
|
||||
const { user: loginData } = useAccount();
|
||||
|
||||
const {data, refetch, isLoading} = useQuery({
|
||||
const { data, refetch, isLoading } = useQuery<OrderType[]>({
|
||||
queryKey: ["fetchOrdersAdmin", loginData],
|
||||
queryFn: () => fetchOrdersAdmin(loginData ? loginData : {
|
||||
queryFn: () =>
|
||||
fetchOrdersAdmin(
|
||||
loginData
|
||||
? loginData
|
||||
: {
|
||||
email: "",
|
||||
password: "",
|
||||
session: "",
|
||||
customerId: -1,
|
||||
isAdmin: false
|
||||
}),
|
||||
isAdmin: false,
|
||||
},
|
||||
),
|
||||
retry: 3,
|
||||
retryDelay: 1000,
|
||||
});
|
||||
@@ -179,9 +194,7 @@ export default function OrdersInfo() {
|
||||
orderPatch({ id: order.id, status: order.status }),
|
||||
});
|
||||
|
||||
|
||||
const handleDrop = async (id: number, status: OrderStatusEnum) => {
|
||||
|
||||
const currentOrders = data ?? [];
|
||||
const obj = currentOrders.find((o) => o.id === id);
|
||||
if (!obj) {
|
||||
@@ -202,9 +215,13 @@ export default function OrdersInfo() {
|
||||
return <div>Lade Bestellungen...</div>;
|
||||
}
|
||||
|
||||
if (!itemList) {
|
||||
return <div>itemlist empty</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<DndProvider backend={HTML5Backend}>
|
||||
<div style={{display: 'flex', gap: 10, minHeight: '90%'}}>
|
||||
<div style={{ display: "flex", gap: 10, minHeight: "90%" }}>
|
||||
{statusOrder.map((status) => (
|
||||
<Column key={status} status={status} onDrop={handleDrop}>
|
||||
{data
|
||||
@@ -218,6 +235,9 @@ export default function OrdersInfo() {
|
||||
<EditOrder
|
||||
open={!!editOrder}
|
||||
order={editOrder}
|
||||
articleNameMapping={(uuid: string) => {
|
||||
return itemList.find((item) => item.uuid == uuid)?.name || uuid;
|
||||
}}
|
||||
onClose={() => setEditOrder(null)}
|
||||
/>
|
||||
<Snackbar
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
import { Box, Typography, useTheme } from "@mui/material";
|
||||
import {BarChart} from '@mui/x-charts/BarChart';
|
||||
import {PieChart} from '@mui/x-charts/PieChart';
|
||||
import {BarSeriesType} from '@mui/x-charts'
|
||||
import { BarChart } from "@mui/x-charts/BarChart";
|
||||
import { PieChart } from "@mui/x-charts/PieChart";
|
||||
import { BarSeriesType } from "@mui/x-charts";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import {fetchOrderStatus, fetchStatisticsRevenue, fetchStatisticsVolume, fetchStockPercent} from "../query/Queries.tsx";
|
||||
import {
|
||||
fetchOrderStatus,
|
||||
fetchStatisticsRevenue,
|
||||
fetchStatisticsVolume,
|
||||
fetchStockPercent,
|
||||
} from "../query/Queries.tsx";
|
||||
import { useAccount } from "../AccountProvider.tsx";
|
||||
import { getColorFromPercent } from "../../util/ColorUtil.tsx";
|
||||
|
||||
@@ -18,143 +23,168 @@ export default function StatisticsInfo() {
|
||||
const [totalVolume, setTotalVolume] = useState([]);
|
||||
|
||||
const [monthlyRevenue, setMonthlyRevenue] = useState<BarSeriesType[]>([]);
|
||||
const [monthlyRevenueXaxis, setMonthlyRevenueXaxis] = useState([{data: []}]);
|
||||
const [monthlyRevenueXaxis, setMonthlyRevenueXaxis] = useState([
|
||||
{ data: [] },
|
||||
]);
|
||||
const [totalRevenue, setTotalRevenue] = useState([]);
|
||||
|
||||
const [orderStatus, setOrderStatus] = useState([]);
|
||||
|
||||
const [stockPercent, setStockPercent] = useState([]);
|
||||
|
||||
|
||||
const { user: loginData } = useAccount();
|
||||
|
||||
|
||||
const { data: dataVolume } = useQuery({
|
||||
queryKey: ["fetchStatisticsVolume", loginData],
|
||||
queryFn: () => fetchStatisticsVolume(loginData ? loginData : {
|
||||
queryFn: () =>
|
||||
fetchStatisticsVolume(
|
||||
loginData
|
||||
? loginData
|
||||
: {
|
||||
email: "",
|
||||
password: "",
|
||||
session: "",
|
||||
customerId: -1,
|
||||
isAdmin: false
|
||||
}),
|
||||
isAdmin: false,
|
||||
},
|
||||
),
|
||||
retry: 0,
|
||||
retryDelay: 0,
|
||||
});
|
||||
|
||||
const { data: dataRevenue } = useQuery({
|
||||
queryKey: ["fetchStatisticsRevenue", loginData],
|
||||
queryFn: () => fetchStatisticsRevenue(loginData ? loginData : {
|
||||
queryFn: () =>
|
||||
fetchStatisticsRevenue(
|
||||
loginData
|
||||
? loginData
|
||||
: {
|
||||
email: "",
|
||||
password: "",
|
||||
session: "",
|
||||
customerId: -1,
|
||||
isAdmin: false
|
||||
}),
|
||||
isAdmin: false,
|
||||
},
|
||||
),
|
||||
retry: 0,
|
||||
retryDelay: 0,
|
||||
});
|
||||
|
||||
const { data: dataOrderStatus } = useQuery({
|
||||
queryKey: ["fetchOrderStatus", loginData],
|
||||
queryFn: () => fetchOrderStatus(loginData ? loginData : {
|
||||
queryFn: () =>
|
||||
fetchOrderStatus(
|
||||
loginData
|
||||
? loginData
|
||||
: {
|
||||
email: "",
|
||||
password: "",
|
||||
session: "",
|
||||
customerId: -1,
|
||||
isAdmin: false
|
||||
}),
|
||||
isAdmin: false,
|
||||
},
|
||||
),
|
||||
retry: 0,
|
||||
retryDelay: 0,
|
||||
});
|
||||
|
||||
const { data: dataStockPercent } = useQuery({
|
||||
queryKey: ["fetchStockPercent", loginData],
|
||||
queryFn: () => fetchStockPercent(loginData ? loginData : {
|
||||
queryFn: () =>
|
||||
fetchStockPercent(
|
||||
loginData
|
||||
? loginData
|
||||
: {
|
||||
email: "",
|
||||
password: "",
|
||||
session: "",
|
||||
customerId: -1,
|
||||
isAdmin: false
|
||||
}),
|
||||
isAdmin: false,
|
||||
},
|
||||
),
|
||||
retry: 0,
|
||||
retryDelay: 0,
|
||||
});
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
if (dataVolume) {
|
||||
const cmm = []
|
||||
const cmmx = monthlyVolumeXaxis
|
||||
const tv = []
|
||||
let i = 0
|
||||
const cmm = [];
|
||||
const cmmx = monthlyVolumeXaxis;
|
||||
const tv = [];
|
||||
let i = 0;
|
||||
for (const cat in dataVolume.catMonthMap) {
|
||||
for (const timestamp in dataVolume.catMonthMap[cat]) {
|
||||
const date = new Date(parseInt(timestamp))
|
||||
const formattedDate = date.getFullYear() + "-" + String(date.getMonth() + 1).padStart(2, '0')
|
||||
const date = new Date(parseInt(timestamp));
|
||||
const formattedDate =
|
||||
date.getFullYear() +
|
||||
"-" +
|
||||
String(date.getMonth() + 1).padStart(2, "0");
|
||||
if (!cmmx[0].data.includes(formattedDate)) {
|
||||
cmmx[0].data.push(formattedDate);
|
||||
}
|
||||
const datapoint = dataVolume.catMonthMap[cat][timestamp]
|
||||
const datapoint = dataVolume.catMonthMap[cat][timestamp];
|
||||
if (cmm.length == i) {
|
||||
cmm.push({id: i, data: [], label: t(cat), type: "bar"})
|
||||
cmm.push({ id: i, data: [], label: t(cat), type: "bar" });
|
||||
}
|
||||
cmm[i].data.push(datapoint)
|
||||
cmm[i].data.push(datapoint);
|
||||
|
||||
if (tv.length == i) {
|
||||
tv.push({id: i, value: 0, label: t(cat)})
|
||||
tv.push({ id: i, value: 0, label: t(cat) });
|
||||
}
|
||||
tv[i].value += datapoint
|
||||
tv[i].value += datapoint;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
|
||||
setMonthlyVolume(cmm)
|
||||
setMonthlyVolumeXaxis(cmmx)
|
||||
setTotalVolume(tv)
|
||||
setMonthlyVolume(cmm);
|
||||
setMonthlyVolumeXaxis(cmmx);
|
||||
setTotalVolume(tv);
|
||||
}
|
||||
}, [dataVolume]);
|
||||
|
||||
useEffect(() => {
|
||||
if (dataRevenue) {
|
||||
const cmm = []
|
||||
const cmmx = monthlyRevenueXaxis
|
||||
const tv = []
|
||||
let i = 0
|
||||
const cmm = [];
|
||||
const cmmx = monthlyRevenueXaxis;
|
||||
const tv = [];
|
||||
let i = 0;
|
||||
for (const cat in dataRevenue.catMonthMap) {
|
||||
for (const timestamp in dataRevenue.catMonthMap[cat]) {
|
||||
const date = new Date(parseInt(timestamp))
|
||||
const formattedDate = date.getFullYear() + "-" + String(date.getMonth() + 1).padStart(2, '0')
|
||||
const date = new Date(parseInt(timestamp));
|
||||
const formattedDate =
|
||||
date.getFullYear() +
|
||||
"-" +
|
||||
String(date.getMonth() + 1).padStart(2, "0");
|
||||
if (!cmmx[0].data.includes(formattedDate)) {
|
||||
cmmx[0].data.push(formattedDate);
|
||||
}
|
||||
const datapoint = dataRevenue.catMonthMap[cat][timestamp] / 100
|
||||
const datapoint = dataRevenue.catMonthMap[cat][timestamp] / 100;
|
||||
if (cmm.length == i) {
|
||||
cmm.push({id: i, data: [], label: t(cat), type: "bar"})
|
||||
cmm.push({ id: i, data: [], label: t(cat), type: "bar" });
|
||||
}
|
||||
cmm[i].data.push(datapoint)
|
||||
cmm[i].data.push(datapoint);
|
||||
|
||||
if (tv.length == i) {
|
||||
tv.push({id: i, value: 0, label: t(cat)})
|
||||
tv.push({ id: i, value: 0, label: t(cat) });
|
||||
}
|
||||
tv[i].value += datapoint
|
||||
tv[i].value += datapoint;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
|
||||
setMonthlyRevenue(cmm)
|
||||
setMonthlyRevenueXaxis(cmmx)
|
||||
setTotalRevenue(tv)
|
||||
setMonthlyRevenue(cmm);
|
||||
setMonthlyRevenueXaxis(cmmx);
|
||||
setTotalRevenue(tv);
|
||||
}
|
||||
}, [dataRevenue, monthlyRevenueXaxis, t]);
|
||||
|
||||
useEffect(() => {
|
||||
if (dataOrderStatus) {
|
||||
const orderStatus = []
|
||||
const orderStatus = [];
|
||||
for (const status in dataOrderStatus) {
|
||||
orderStatus.push({value: dataOrderStatus[status], label: t(status)})
|
||||
orderStatus.push({ value: dataOrderStatus[status], label: t(status) });
|
||||
}
|
||||
setOrderStatus(orderStatus)
|
||||
setOrderStatus(orderStatus);
|
||||
}
|
||||
}, [dataOrderStatus, t]);
|
||||
|
||||
@@ -164,33 +194,36 @@ export default function StatisticsInfo() {
|
||||
}
|
||||
|
||||
if (dataStockPercent) {
|
||||
const stockPercent = []
|
||||
let i = 0
|
||||
const stockPercent = [];
|
||||
let i = 0;
|
||||
for (let x = 0; x < 10; x++) {
|
||||
stockPercent.push({
|
||||
value: 0,
|
||||
label: generateName(String(x * 10)),
|
||||
color: getColorFromPercent(String(x * 10))
|
||||
color: getColorFromPercent(String(x * 10)),
|
||||
});
|
||||
}
|
||||
for (const cat in dataStockPercent) {
|
||||
for (const percent in dataStockPercent[cat]) {
|
||||
let index = stockPercent.findIndex((entry) => entry.label == generateName(percent))
|
||||
const datapoint = dataStockPercent[cat][percent]
|
||||
let index = stockPercent.findIndex(
|
||||
(entry) => entry.label == generateName(percent),
|
||||
);
|
||||
const datapoint = dataStockPercent[cat][percent];
|
||||
if (index === -1) {
|
||||
index = stockPercent.push({
|
||||
index =
|
||||
stockPercent.push({
|
||||
value: 0,
|
||||
label: generateName(percent),
|
||||
color: getColorFromPercent(percent)
|
||||
}) - 1
|
||||
color: getColorFromPercent(percent),
|
||||
}) - 1;
|
||||
}
|
||||
stockPercent[index].value += datapoint
|
||||
stockPercent[index].value += datapoint;
|
||||
}
|
||||
i++
|
||||
i++;
|
||||
}
|
||||
setStockPercent(stockPercent)
|
||||
setStockPercent(stockPercent);
|
||||
}
|
||||
}, [dataStockPercent])
|
||||
}, [dataStockPercent]);
|
||||
|
||||
return (
|
||||
<Box className="" sx={{ color: theme.palette.text.primary }}>
|
||||
@@ -224,11 +257,17 @@ export default function StatisticsInfo() {
|
||||
{t("itemVolumeDistribution")}
|
||||
</Typography>
|
||||
<PieChart
|
||||
series={[{
|
||||
series={[
|
||||
{
|
||||
data: totalVolume,
|
||||
highlightScope: {fade: 'global', highlight: 'item'},
|
||||
faded: {innerRadius: 30, additionalRadius: -30, color: 'gray'},
|
||||
}]}
|
||||
highlightScope: { fade: "global", highlight: "item" },
|
||||
faded: {
|
||||
innerRadius: 30,
|
||||
additionalRadius: -30,
|
||||
color: "gray",
|
||||
},
|
||||
},
|
||||
]}
|
||||
width={200}
|
||||
height={200}
|
||||
/>
|
||||
@@ -239,11 +278,13 @@ export default function StatisticsInfo() {
|
||||
{t("itemRevenueDistribution")}
|
||||
</Typography>
|
||||
<PieChart
|
||||
series={[{
|
||||
series={[
|
||||
{
|
||||
data: totalRevenue,
|
||||
highlightScope: {fade: 'global', highlight: 'item'},
|
||||
valueFormatter: (v) => (v ? `${v.value}€` : '-'),
|
||||
}]}
|
||||
highlightScope: { fade: "global", highlight: "item" },
|
||||
valueFormatter: (v) => (v ? `${v.value}€` : "-"),
|
||||
},
|
||||
]}
|
||||
width={200}
|
||||
height={200}
|
||||
/>
|
||||
@@ -253,14 +294,16 @@ export default function StatisticsInfo() {
|
||||
{t("stockFulfillment")}
|
||||
</Typography>
|
||||
<PieChart
|
||||
series={[{
|
||||
series={[
|
||||
{
|
||||
data: stockPercent,
|
||||
innerRadius: 10,
|
||||
outerRadius: 85,
|
||||
cornerRadius: 5,
|
||||
paddingAngle: 2,
|
||||
valueFormatter: (v) => (v ? `${v.value}%` : '-'),
|
||||
}]}
|
||||
valueFormatter: (v) => (v ? `${v.value}%` : "-"),
|
||||
},
|
||||
]}
|
||||
width={200}
|
||||
height={200}
|
||||
hideLegend
|
||||
@@ -271,15 +314,21 @@ export default function StatisticsInfo() {
|
||||
{t("orderStatus")}
|
||||
</Typography>
|
||||
<PieChart
|
||||
series={[{
|
||||
series={[
|
||||
{
|
||||
data: orderStatus,
|
||||
innerRadius: 20,
|
||||
outerRadius: 70,
|
||||
cornerRadius: 5,
|
||||
paddingAngle: 1,
|
||||
highlightScope: {fade: 'global', highlight: 'item'},
|
||||
faded: {innerRadius: 30, additionalRadius: -10, color: 'gray'},
|
||||
}]}
|
||||
highlightScope: { fade: "global", highlight: "item" },
|
||||
faded: {
|
||||
innerRadius: 30,
|
||||
additionalRadius: -10,
|
||||
color: "gray",
|
||||
},
|
||||
},
|
||||
]}
|
||||
height={200}
|
||||
width={200}
|
||||
/>
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
import {FormControl, FormControlLabel, FormLabel, Radio, RadioGroup, Rating, useTheme,} from "@mui/material";
|
||||
import {
|
||||
FormControl,
|
||||
FormControlLabel,
|
||||
FormLabel,
|
||||
Radio,
|
||||
RadioGroup,
|
||||
Rating,
|
||||
useTheme,
|
||||
} from "@mui/material";
|
||||
import React from "react";
|
||||
|
||||
type FilterItemOption = {
|
||||
|
||||
@@ -1,16 +1,25 @@
|
||||
import { AddShoppingCart } from "@mui/icons-material";
|
||||
import {Box, Card, CardActionArea, CardContent, CardMedia, IconButton, Paper, Rating, Typography} from "@mui/material";
|
||||
import {
|
||||
Box,
|
||||
Card,
|
||||
CardActionArea,
|
||||
CardContent,
|
||||
CardMedia,
|
||||
IconButton,
|
||||
Paper,
|
||||
Rating,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import { useState } from "react";
|
||||
import {useTranslation} from 'react-i18next';
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import ItemWithImage from "../../components/Item";
|
||||
import { useBasket } from "../BasketProvider";
|
||||
import "../helper.css";
|
||||
|
||||
export default function ItemCard({ item }: { item: ItemWithImage }) {
|
||||
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate()
|
||||
const navigate = useNavigate();
|
||||
const { addToBasket } = useBasket();
|
||||
|
||||
const handleAddToCart = () => {
|
||||
@@ -20,17 +29,33 @@ export default function ItemCard({item}: { item: ItemWithImage }) {
|
||||
|
||||
const handleClick = () => {
|
||||
navigate(`/product/${item.id}`, { state: { item } });
|
||||
}
|
||||
const [imageUrl, setImageUrl] = useState<string>(item.image || "/src/assets/default.jpg"); // Fallback-Bild
|
||||
};
|
||||
const [imageUrl, setImageUrl] = useState<string>(
|
||||
item.image || "/src/assets/default.jpg",
|
||||
); // Fallback-Bild
|
||||
|
||||
if (imageUrl !== "/src/assets/default.jpg" && !imageUrl.startsWith("data:image/")) {
|
||||
if (
|
||||
imageUrl !== "/src/assets/default.jpg" &&
|
||||
!imageUrl.startsWith("data:image/")
|
||||
) {
|
||||
setImageUrl("data:image/jpeg;base64," + imageUrl);
|
||||
}
|
||||
|
||||
return (
|
||||
<Paper elevation={4}>
|
||||
<Card sx={{height: "100%", width: "100%"}}>
|
||||
<CardActionArea onClick={handleClick} sx={{height: "100%"}} component="div">
|
||||
<Card
|
||||
sx={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
height: "100%",
|
||||
width: "100%",
|
||||
}}
|
||||
>
|
||||
<CardActionArea
|
||||
onClick={handleClick}
|
||||
sx={{ height: "100%", width: "100%" }}
|
||||
component="div"
|
||||
>
|
||||
<CardMedia
|
||||
component="img"
|
||||
height="140"
|
||||
@@ -45,22 +70,57 @@ export default function ItemCard({item}: { item: ItemWithImage }) {
|
||||
maxHeight: "100%", // Begrenze die maximale Höhe auf den Container
|
||||
}}
|
||||
/>
|
||||
<CardContent>
|
||||
<CardContent
|
||||
sx={{ display: "flex", flexDirection: "column", flexGrow: 1 }}
|
||||
>
|
||||
<Typography gutterBottom variant="h5" component="div">
|
||||
{item.name}
|
||||
</Typography>
|
||||
<Rating name="half-rating" readOnly defaultValue={item.rating / 2} precision={0.5}/>
|
||||
<Box sx={{display: "flex", justifyContent: "space-between", alignItems: "flex-end"}}>
|
||||
<Typography variant="body2" sx={{color: 'text.secondary'}} className="item-description">
|
||||
{(item.price100 / 100 * (1 - item.discount100 / 100)).toFixed(2)} €
|
||||
<Box
|
||||
sx={{
|
||||
mt: "auto",
|
||||
display: "flex",
|
||||
flexGrow: 1,
|
||||
flexDirection: "column",
|
||||
}}
|
||||
>
|
||||
<Rating
|
||||
name="half-rating"
|
||||
readOnly
|
||||
defaultValue={item.rating / 2}
|
||||
precision={0.5}
|
||||
/>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "flex-end",
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
variant="body2"
|
||||
sx={{ color: "text.secondary" }}
|
||||
className="item-description"
|
||||
>
|
||||
{(
|
||||
(item.price100 / 100) *
|
||||
(1 - item.discount100 / 100)
|
||||
).toFixed(2)}{" "}
|
||||
€
|
||||
</Typography>
|
||||
{item.discount100 == 0 ? <></> :
|
||||
<Typography variant="body2" sx={{color: 'red'}} className="item-description">
|
||||
{(- item.discount100)}%
|
||||
{item.discount100 == 0 ? (
|
||||
<></>
|
||||
) : (
|
||||
<Typography
|
||||
variant="body2"
|
||||
sx={{ color: "red" }}
|
||||
className="item-description"
|
||||
>
|
||||
{-item.discount100}%
|
||||
</Typography>
|
||||
}
|
||||
)}
|
||||
<IconButton
|
||||
aria-label={t('addToCart')}
|
||||
aria-label={t("addToCart")}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
handleAddToCart();
|
||||
@@ -71,21 +131,20 @@ export default function ItemCard({item}: { item: ItemWithImage }) {
|
||||
</Box>
|
||||
|
||||
{item.stock > 10 ? (
|
||||
<Typography variant="body2">
|
||||
{t('inStock')}
|
||||
</Typography>
|
||||
<Typography variant="body2">{t("inStock")}</Typography>
|
||||
) : item.stock > 0 ? (
|
||||
<Typography variant="body2" sx={{color: 'orange'}}>
|
||||
{t('almostSoldOut')}
|
||||
<Typography variant="body2" sx={{ color: "orange" }}>
|
||||
{t("almostSoldOut")}
|
||||
</Typography>
|
||||
) : (
|
||||
<Typography variant="body2" sx={{color: 'red'}}>
|
||||
{t('outOfStock')}
|
||||
<Typography variant="body2" sx={{ color: "red" }}>
|
||||
{t("outOfStock")}
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
</CardContent>
|
||||
</CardActionArea>
|
||||
</Card>
|
||||
</Paper>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -8,7 +8,11 @@ type PriceSliderProps = {
|
||||
onChange?: (range: [number, number]) => void;
|
||||
};
|
||||
|
||||
export default function PriceSlider({min = 0, max = 10000, onChange}: PriceSliderProps) {
|
||||
export default function PriceSlider({
|
||||
min = 0,
|
||||
max = 10000,
|
||||
onChange,
|
||||
}: PriceSliderProps) {
|
||||
const { t } = useTranslation();
|
||||
const theme = useTheme();
|
||||
|
||||
@@ -25,7 +29,10 @@ export default function PriceSlider({min = 0, max = 10000, onChange}: PriceSlide
|
||||
}
|
||||
};
|
||||
|
||||
const handleCommitted = (_: Event | SyntheticEvent<Element, Event>, newValue: number | number[]) => {
|
||||
const handleCommitted = (
|
||||
_: Event | SyntheticEvent<Element, Event>,
|
||||
newValue: number | number[],
|
||||
) => {
|
||||
if (Array.isArray(newValue)) {
|
||||
onChange?.([newValue[0], newValue[1]]);
|
||||
}
|
||||
@@ -58,7 +65,7 @@ export default function PriceSlider({min = 0, max = 10000, onChange}: PriceSlide
|
||||
step={1}
|
||||
sx={{
|
||||
color: "#0fd13f",
|
||||
'& .MuiSlider-valueLabel': {
|
||||
"& .MuiSlider-valueLabel": {
|
||||
color: theme.palette.text.primary,
|
||||
},
|
||||
}}
|
||||
|
||||
@@ -1,4 +1,13 @@
|
||||
import {Box, Button, Dialog, DialogActions, DialogContent, DialogTitle, Link, TextField} from "@mui/material";
|
||||
import {
|
||||
Box,
|
||||
Button,
|
||||
Dialog,
|
||||
DialogActions,
|
||||
DialogContent,
|
||||
DialogTitle,
|
||||
Link,
|
||||
TextField,
|
||||
} from "@mui/material";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import i18next from "i18next";
|
||||
import React, { useEffect, useState } from "react";
|
||||
@@ -12,11 +21,22 @@ type LoginDialogProps = {
|
||||
onClose: () => void;
|
||||
onSubmit: () => void; // Funktion, die aufgerufen wird, wenn der Login erfolgreich ist
|
||||
loginData: { email: string; password: string };
|
||||
setLoginData: React.Dispatch<React.SetStateAction<{ email: string; password: string, customerId: number }>>;
|
||||
setLoginData: React.Dispatch<
|
||||
React.SetStateAction<{
|
||||
email: string;
|
||||
password: string;
|
||||
customerId: number;
|
||||
}>
|
||||
>;
|
||||
};
|
||||
|
||||
const LoginDialog: React.FC<LoginDialogProps> = ({open, onClose, loginData, setLoginData, onSubmit}) => {
|
||||
|
||||
const LoginDialog: React.FC<LoginDialogProps> = ({
|
||||
open,
|
||||
onClose,
|
||||
loginData,
|
||||
setLoginData,
|
||||
onSubmit,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const { login } = useAccount();
|
||||
const [showRegister, setShowRegister] = useState(false);
|
||||
@@ -24,9 +44,16 @@ const LoginDialog: React.FC<LoginDialogProps> = ({open, onClose, loginData, setL
|
||||
email: "",
|
||||
password: "",
|
||||
id: 0,
|
||||
customer: {id: 0, name: "", surname: "", address: "", country: "", zip: ""},
|
||||
customer: {
|
||||
id: 0,
|
||||
name: "",
|
||||
surname: "",
|
||||
address: "",
|
||||
country: "",
|
||||
zip: "",
|
||||
},
|
||||
langI18n: i18next.language,
|
||||
admin: false
|
||||
admin: false,
|
||||
});
|
||||
const [showErrorRegister, setShowErrorRegister] = useState(false); // Neuer Zustand für die Anzeige der Fehlermeldung
|
||||
const [showErrorLogin, setShowErrorLogin] = useState(false); // Neuer Zustand für die Anzeige der Login-Fehlermeldung
|
||||
@@ -40,9 +67,12 @@ const LoginDialog: React.FC<LoginDialogProps> = ({open, onClose, loginData, setL
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
|
||||
// useQuery für Login
|
||||
const {refetch: refetchLogin, isLoading: isLoadingLogin, error: errorLogin} = useQuery({
|
||||
const {
|
||||
refetch: refetchLogin,
|
||||
isLoading: isLoadingLogin,
|
||||
error: errorLogin,
|
||||
} = useQuery({
|
||||
queryKey: ["submitLogin", loginData],
|
||||
queryFn: () => submitLogin(loginData),
|
||||
retry: 0,
|
||||
@@ -59,7 +89,11 @@ const LoginDialog: React.FC<LoginDialogProps> = ({open, onClose, loginData, setL
|
||||
});
|
||||
|
||||
// useQuery für Registrierung
|
||||
const {refetch: refetchRegister, isLoading: isLoadingRegister, error: errorRegister} = useQuery({
|
||||
const {
|
||||
refetch: refetchRegister,
|
||||
isLoading: isLoadingRegister,
|
||||
error: errorRegister,
|
||||
} = useQuery({
|
||||
queryKey: ["submitRegister", registerData],
|
||||
queryFn: () => submitRegister(registerData),
|
||||
retry: 0,
|
||||
@@ -86,7 +120,7 @@ const LoginDialog: React.FC<LoginDialogProps> = ({open, onClose, loginData, setL
|
||||
password: customerData.password,
|
||||
customerId: customerData.customer.id, // Setze die customerId aus den Account-Daten
|
||||
session: session, // Setze die Session aus der Login-Antwort
|
||||
isAdmin: customerData.admin
|
||||
isAdmin: customerData.admin,
|
||||
};
|
||||
login(user);
|
||||
setShowRegister(false); // Zurück zum Login wechseln
|
||||
@@ -114,14 +148,17 @@ const LoginDialog: React.FC<LoginDialogProps> = ({open, onClose, loginData, setL
|
||||
|
||||
return (
|
||||
<Dialog open={open} onClose={handleClose} disableEnforceFocus>
|
||||
<form onSubmit={e => {
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (showRegister) {
|
||||
handleLogin();
|
||||
} else {
|
||||
handleRegister();
|
||||
}
|
||||
}} noValidate>
|
||||
}}
|
||||
noValidate
|
||||
>
|
||||
<DialogTitle>{showRegister ? t("register") : t("login")}</DialogTitle>
|
||||
<DialogContent>
|
||||
<TextField
|
||||
@@ -130,9 +167,9 @@ const LoginDialog: React.FC<LoginDialogProps> = ({open, onClose, loginData, setL
|
||||
type="email"
|
||||
fullWidth
|
||||
value={showRegister ? registerData.email : loginData.email}
|
||||
onChange={e => {
|
||||
setLoginData(prev => ({...prev, email: e.target.value}));
|
||||
setRegisterData(prev => ({...prev, email: e.target.value}))
|
||||
onChange={(e) => {
|
||||
setLoginData((prev) => ({ ...prev, email: e.target.value }));
|
||||
setRegisterData((prev) => ({ ...prev, email: e.target.value }));
|
||||
}}
|
||||
/>
|
||||
<TextField
|
||||
@@ -141,12 +178,15 @@ const LoginDialog: React.FC<LoginDialogProps> = ({open, onClose, loginData, setL
|
||||
type="password"
|
||||
fullWidth
|
||||
value={showRegister ? registerData.password : loginData.password}
|
||||
onChange={e => {
|
||||
setLoginData(prev => ({...prev, password: e.target.value}))
|
||||
setRegisterData(prev => ({...prev, password: e.target.value}))
|
||||
onChange={(e) => {
|
||||
setLoginData((prev) => ({ ...prev, password: e.target.value }));
|
||||
setRegisterData((prev) => ({
|
||||
...prev,
|
||||
password: e.target.value,
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
{showRegister &&
|
||||
{showRegister && (
|
||||
<>
|
||||
<TextField
|
||||
margin="dense"
|
||||
@@ -154,10 +194,12 @@ const LoginDialog: React.FC<LoginDialogProps> = ({open, onClose, loginData, setL
|
||||
type="text"
|
||||
fullWidth
|
||||
value={registerData.customer.name}
|
||||
onChange={e => setRegisterData(prev => ({
|
||||
onChange={(e) =>
|
||||
setRegisterData((prev) => ({
|
||||
...prev,
|
||||
customer: { ...prev.customer, name: e.target.value },
|
||||
}))}
|
||||
}))
|
||||
}
|
||||
/>
|
||||
<TextField
|
||||
margin="dense"
|
||||
@@ -165,10 +207,12 @@ const LoginDialog: React.FC<LoginDialogProps> = ({open, onClose, loginData, setL
|
||||
type="text"
|
||||
fullWidth
|
||||
value={registerData.customer.surname}
|
||||
onChange={e => setRegisterData(prev => ({
|
||||
onChange={(e) =>
|
||||
setRegisterData((prev) => ({
|
||||
...prev,
|
||||
customer: { ...prev.customer, surname: e.target.value },
|
||||
}))}
|
||||
}))
|
||||
}
|
||||
/>
|
||||
<TextField
|
||||
margin="dense"
|
||||
@@ -176,10 +220,12 @@ const LoginDialog: React.FC<LoginDialogProps> = ({open, onClose, loginData, setL
|
||||
type="text"
|
||||
fullWidth
|
||||
value={registerData.customer.address}
|
||||
onChange={e => setRegisterData(prev => ({
|
||||
onChange={(e) =>
|
||||
setRegisterData((prev) => ({
|
||||
...prev,
|
||||
customer: { ...prev.customer, address: e.target.value },
|
||||
}))}
|
||||
}))
|
||||
}
|
||||
/>
|
||||
<TextField
|
||||
margin="dense"
|
||||
@@ -187,10 +233,12 @@ const LoginDialog: React.FC<LoginDialogProps> = ({open, onClose, loginData, setL
|
||||
type="text"
|
||||
fullWidth
|
||||
value={registerData.customer.country}
|
||||
onChange={e => setRegisterData(prev => ({
|
||||
onChange={(e) =>
|
||||
setRegisterData((prev) => ({
|
||||
...prev,
|
||||
customer: { ...prev.customer, country: e.target.value },
|
||||
}))}
|
||||
}))
|
||||
}
|
||||
/>
|
||||
<TextField
|
||||
margin="dense"
|
||||
@@ -198,13 +246,15 @@ const LoginDialog: React.FC<LoginDialogProps> = ({open, onClose, loginData, setL
|
||||
type="text"
|
||||
fullWidth
|
||||
value={registerData.customer.zip}
|
||||
onChange={e => setRegisterData(prev => ({
|
||||
onChange={(e) =>
|
||||
setRegisterData((prev) => ({
|
||||
...prev,
|
||||
customer: { ...prev.customer, zip: e.target.value },
|
||||
}))}
|
||||
}))
|
||||
}
|
||||
/>
|
||||
</>
|
||||
}
|
||||
)}
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={handleClose}>{t("cancel")}</Button>
|
||||
@@ -225,7 +275,7 @@ const LoginDialog: React.FC<LoginDialogProps> = ({open, onClose, loginData, setL
|
||||
<Box color="error.main">{t("registerFailed")}</Box>
|
||||
)}
|
||||
{showRegister ? (
|
||||
<Box sx={{width: '100%', textAlign: 'center', pb: 2}}>
|
||||
<Box sx={{ width: "100%", textAlign: "center", pb: 2 }}>
|
||||
<Link
|
||||
component="button"
|
||||
variant="body2"
|
||||
@@ -237,7 +287,7 @@ const LoginDialog: React.FC<LoginDialogProps> = ({open, onClose, loginData, setL
|
||||
</Link>
|
||||
</Box>
|
||||
) : (
|
||||
<Box sx={{width: '100%', textAlign: 'center', pb: 2}}>
|
||||
<Box sx={{ width: "100%", textAlign: "center", pb: 2 }}>
|
||||
<Link
|
||||
component="button"
|
||||
variant="body2"
|
||||
|
||||
@@ -61,9 +61,9 @@
|
||||
|
||||
/* Typography styles */
|
||||
.navbar-typography {
|
||||
font-family: 'monospace';
|
||||
font-family: "monospace";
|
||||
font-weight: 700;
|
||||
letter-spacing: .3rem;
|
||||
letter-spacing: 0.3rem;
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
@@ -1,76 +1,79 @@
|
||||
import MenuIcon from '@mui/icons-material/Menu';
|
||||
import SearchIcon from '@mui/icons-material/Search';
|
||||
import {Autocomplete, Badge, TextField} from '@mui/material';
|
||||
import AppBar from '@mui/material/AppBar';
|
||||
import Avatar from '@mui/material/Avatar';
|
||||
import Box from '@mui/material/Box';
|
||||
import Button from '@mui/material/Button';
|
||||
import IconButton from '@mui/material/IconButton';
|
||||
import Menu from '@mui/material/Menu';
|
||||
import MenuItem from '@mui/material/MenuItem';
|
||||
import Toolbar from '@mui/material/Toolbar';
|
||||
import Tooltip from '@mui/material/Tooltip';
|
||||
import Typography from '@mui/material/Typography';
|
||||
import {useQuery} from '@tanstack/react-query';
|
||||
import * as React from 'react';
|
||||
import {useTranslation} from 'react-i18next';
|
||||
import {useNavigate} from 'react-router-dom';
|
||||
import Item from '../../components/Item';
|
||||
import ThemeToggle from '../../theme/ThemeToggle';
|
||||
import {useAccount} from '../AccountProvider';
|
||||
import {fetchItemList} from '../query/Queries';
|
||||
import LoginDialog from './LoginDialog';
|
||||
import './NavBar.css';
|
||||
import {useBasket} from '../BasketProvider';
|
||||
import logo from '../../assets/logo/Blume-logo.png';
|
||||
|
||||
import MenuIcon from "@mui/icons-material/Menu";
|
||||
import SearchIcon from "@mui/icons-material/Search";
|
||||
import { Autocomplete, Badge, TextField } from "@mui/material";
|
||||
import AppBar from "@mui/material/AppBar";
|
||||
import Avatar from "@mui/material/Avatar";
|
||||
import Box from "@mui/material/Box";
|
||||
import Button from "@mui/material/Button";
|
||||
import IconButton from "@mui/material/IconButton";
|
||||
import Menu from "@mui/material/Menu";
|
||||
import MenuItem from "@mui/material/MenuItem";
|
||||
import Toolbar from "@mui/material/Toolbar";
|
||||
import Tooltip from "@mui/material/Tooltip";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import * as React from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import Item from "../../components/Item";
|
||||
import ThemeToggle from "../../theme/ThemeToggle";
|
||||
import { useAccount } from "../AccountProvider";
|
||||
import { fetchItemList } from "../query/Queries";
|
||||
import LoginDialog from "./LoginDialog";
|
||||
import "./NavBar.css";
|
||||
import { useBasket } from "../BasketProvider";
|
||||
import logo from "../../assets/logo/Blume-logo.png";
|
||||
|
||||
export default function NavBar() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const [anchorElNav, setAnchorElNav] = React.useState<null | HTMLElement>(null);
|
||||
const [anchorElUser, setAnchorElUser] = React.useState<null | HTMLElement>(null);
|
||||
const [avatarName, setAvatarName] = React.useState<string>(''); // Für Avatar-Tooltip
|
||||
const [anchorElNav, setAnchorElNav] = React.useState<null | HTMLElement>(
|
||||
null,
|
||||
);
|
||||
const [anchorElUser, setAnchorElUser] = React.useState<null | HTMLElement>(
|
||||
null,
|
||||
);
|
||||
const [avatarName, setAvatarName] = React.useState<string>(""); // Für Avatar-Tooltip
|
||||
|
||||
const { user, logout } = useAccount();
|
||||
|
||||
const { basket } = useBasket();
|
||||
|
||||
const totalQuantity = basket?.reduce((sum, item) => sum + item.quantity, 0) ?? 0;
|
||||
|
||||
const totalQuantity =
|
||||
basket?.reduce((sum, item) => sum + item.quantity, 0) ?? 0;
|
||||
|
||||
const [loginOpen, setLoginOpen] = React.useState(false);
|
||||
const [loginData, setLoginData] = React.useState({password: '', email: '', customerId: 0});
|
||||
|
||||
const [loginData, setLoginData] = React.useState({
|
||||
password: "",
|
||||
email: "",
|
||||
customerId: 0,
|
||||
});
|
||||
|
||||
const [itemNames, setItemNames] = React.useState<string[]>([]); // Für Autocomplete
|
||||
|
||||
const pageKeys = ['components', 'checkout', 'contact', 'admin'];
|
||||
const pageKeys = ["components", "checkout", "contact", "admin"];
|
||||
|
||||
const filteredPages = pageKeys
|
||||
.filter(key => {
|
||||
.filter((key) => {
|
||||
if (key === "admin") {
|
||||
return user?.isAdmin === true; // nur Admins sehen Admin-Seite
|
||||
}
|
||||
return true; // alle anderen Seiten immer anzeigen
|
||||
})
|
||||
.map(key => ({key, label: t(key)}));
|
||||
|
||||
.map((key) => ({ key, label: t(key) }));
|
||||
|
||||
const settings = user
|
||||
? [
|
||||
{
|
||||
key: 'email',
|
||||
label: `${t('loggedInAs')}: ${user.email}`,
|
||||
disabled: true // wir nutzen dieses Flag gleich zur Erkennung
|
||||
key: "email",
|
||||
label: `${t("loggedInAs")}: ${user.email}`,
|
||||
disabled: true, // wir nutzen dieses Flag gleich zur Erkennung
|
||||
},
|
||||
{key: 'account', label: t('account')},
|
||||
{key: 'orders', label: t('orders')},
|
||||
{key: 'logout', label: t('logout')}
|
||||
{ key: "account", label: t("account") },
|
||||
{ key: "orders", label: t("orders") },
|
||||
{ key: "logout", label: t("logout") },
|
||||
]
|
||||
: [
|
||||
{key: 'login', label: t('login')}
|
||||
];
|
||||
: [{ key: "login", label: t("login") }];
|
||||
|
||||
const handleOpenNavMenu = (event: React.MouseEvent<HTMLElement>) => {
|
||||
setAnchorElNav(event.currentTarget);
|
||||
@@ -87,18 +90,18 @@ export default function NavBar() {
|
||||
|
||||
const handleCloseUserMenu = (link: string) => {
|
||||
setAnchorElUser(null);
|
||||
if (link === 'login') {
|
||||
if (link === "login") {
|
||||
setLoginOpen(true);
|
||||
} else if (link === 'logout') {
|
||||
} else if (link === "logout") {
|
||||
logout();
|
||||
if (
|
||||
location.pathname.startsWith('/account') ||
|
||||
location.pathname.startsWith('/orders')
|
||||
location.pathname.startsWith("/account") ||
|
||||
location.pathname.startsWith("/orders")
|
||||
) {
|
||||
navigate('/');
|
||||
navigate("/");
|
||||
}
|
||||
} else {
|
||||
navigate(`/${link.toLowerCase()}`)
|
||||
navigate(`/${link.toLowerCase()}`);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -106,7 +109,6 @@ export default function NavBar() {
|
||||
setLoginOpen(false);
|
||||
};
|
||||
|
||||
|
||||
// useQuery, um die Item-Namen zu laden
|
||||
const { data: items = [] } = useQuery<Item[]>({
|
||||
queryKey: ["fetchItemList"],
|
||||
@@ -124,12 +126,11 @@ export default function NavBar() {
|
||||
setAvatarName(user.email.toUpperCase());
|
||||
}
|
||||
if (!user) {
|
||||
setAvatarName('');
|
||||
setAvatarName("");
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
const handleSearch = (_: React.SyntheticEvent, value: string | null) => {
|
||||
|
||||
if (!value) {
|
||||
// Wenn der Suchwert leer ist, navigiere zur Homepage ohne Suchparameter
|
||||
navigate("/");
|
||||
@@ -145,9 +146,9 @@ export default function NavBar() {
|
||||
<Toolbar
|
||||
disableGutters
|
||||
sx={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center', // <--- HIER hinzugefügt
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center", // <--- HIER hinzugefügt
|
||||
px: 3,
|
||||
minHeight: { xs: 56, sm: 64 }, // optional: Standardhöhe für bessere Zentrierung
|
||||
}}
|
||||
@@ -157,14 +158,19 @@ export default function NavBar() {
|
||||
src={logo}
|
||||
alt="Logo"
|
||||
className="navbar-logo"
|
||||
style={{ display: "block", height: 40, marginRight: 12, objectFit: "contain" }} // optional: Höhe anpassen
|
||||
onClick={() => navigate('/')}
|
||||
style={{
|
||||
display: "block",
|
||||
height: 40,
|
||||
marginRight: 12,
|
||||
objectFit: "contain",
|
||||
}} // optional: Höhe anpassen
|
||||
onClick={() => navigate("/")}
|
||||
/>
|
||||
<Typography
|
||||
variant="h6"
|
||||
noWrap
|
||||
component="a"
|
||||
onClick={() => navigate('/')}
|
||||
onClick={() => navigate("/")}
|
||||
sx={{
|
||||
fontFamily: "monospace",
|
||||
fontWeight: 700,
|
||||
@@ -174,28 +180,32 @@ export default function NavBar() {
|
||||
display: "flex",
|
||||
alignItems: "center", // <--- HIER hinzugefügt
|
||||
height: "100%", // optional
|
||||
":hover": {
|
||||
color: "#fff1d8ff",
|
||||
},
|
||||
}}
|
||||
>
|
||||
Digitaler Produktionsshop
|
||||
</Typography>
|
||||
|
||||
</Box>
|
||||
|
||||
<Box sx={{
|
||||
<Box
|
||||
sx={{
|
||||
flexGrow: 1,
|
||||
display: "flex",
|
||||
justifyContent: "center",
|
||||
alignItems: "center", // <--- HIER hinzugefügt
|
||||
px: 3,
|
||||
zIndex: 100000
|
||||
}}>
|
||||
zIndex: 100000,
|
||||
}}
|
||||
>
|
||||
<Autocomplete
|
||||
sx={{
|
||||
flexGrow: 1,
|
||||
minWidth: "150px",
|
||||
maxWidth: "600px",
|
||||
display: "flex",
|
||||
alignItems: "center" // <--- HIER hinzugefügt
|
||||
alignItems: "center", // <--- HIER hinzugefügt
|
||||
}}
|
||||
freeSolo
|
||||
options={itemNames}
|
||||
@@ -211,20 +221,20 @@ export default function NavBar() {
|
||||
),
|
||||
}}
|
||||
sx={{
|
||||
'& .MuiOutlinedInput-root': {
|
||||
'& fieldset': {
|
||||
borderColor: 'white',
|
||||
borderWidth: '1px',
|
||||
"& .MuiOutlinedInput-root": {
|
||||
"& fieldset": {
|
||||
borderColor: "white",
|
||||
borderWidth: "1px",
|
||||
},
|
||||
'&:hover fieldset': {
|
||||
borderColor: 'white',
|
||||
"&:hover fieldset": {
|
||||
borderColor: "white",
|
||||
},
|
||||
'&.Mui-focused fieldset': {
|
||||
borderColor: 'white',
|
||||
"&.Mui-focused fieldset": {
|
||||
borderColor: "white",
|
||||
},
|
||||
},
|
||||
input: {
|
||||
color: 'white',
|
||||
color: "white",
|
||||
},
|
||||
}}
|
||||
/>
|
||||
@@ -232,10 +242,17 @@ export default function NavBar() {
|
||||
/>
|
||||
</Box>
|
||||
|
||||
<Box sx={{display: "flex", alignItems: "center", gap: 2, marginLeft: 'auto'}}>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 2,
|
||||
marginLeft: "auto",
|
||||
}}
|
||||
>
|
||||
<Box sx={{ display: { xs: "none", md: "flex" }, gap: 2 }}>
|
||||
{filteredPages.map(({ key, label }) => {
|
||||
if (key === 'checkout') {
|
||||
if (key === "checkout") {
|
||||
return (
|
||||
<Button
|
||||
key={key}
|
||||
@@ -269,7 +286,7 @@ export default function NavBar() {
|
||||
<Box sx={{ display: { xs: "flex", md: "none" } }}>
|
||||
<IconButton
|
||||
size="large"
|
||||
aria-label={t('menu')}
|
||||
aria-label={t("menu")}
|
||||
onClick={handleOpenNavMenu}
|
||||
color="inherit"
|
||||
>
|
||||
@@ -291,7 +308,7 @@ export default function NavBar() {
|
||||
</Box>
|
||||
|
||||
<ThemeToggle />
|
||||
<Tooltip title={t('openSettings')} placement='bottom-end'>
|
||||
<Tooltip title={t("openSettings")} placement="bottom-end">
|
||||
<IconButton onClick={handleOpenUserMenu} sx={{ p: 0 }}>
|
||||
<Avatar alt={avatarName} src="/static/images/avatar/2.jpg" />
|
||||
</IconButton>
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
SnackbarCloseReason,
|
||||
Stack,
|
||||
TextField,
|
||||
Typography
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -20,12 +20,13 @@ import Item from "../../components/Item";
|
||||
import { useBasket } from "../BasketProvider";
|
||||
|
||||
export default function ProductInfo({ item }: { item: Item }) {
|
||||
|
||||
const { t } = useTranslation();
|
||||
const [quantity, setQuantity] = useState<number>(1);
|
||||
const [open, setOpen] = useState<boolean>(false);
|
||||
const [imageDimensions, setImageDimensions] = useState({width: 0, height: 0});
|
||||
|
||||
const [imageDimensions, setImageDimensions] = useState({
|
||||
width: 0,
|
||||
height: 0,
|
||||
});
|
||||
|
||||
const { addToBasket } = useBasket();
|
||||
|
||||
@@ -33,7 +34,7 @@ export default function ProductInfo({item}: { item: Item }) {
|
||||
_: React.SyntheticEvent | Event,
|
||||
reason?: SnackbarCloseReason,
|
||||
) => {
|
||||
if (reason === 'clickaway') {
|
||||
if (reason === "clickaway") {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -44,7 +45,7 @@ export default function ProductInfo({item}: { item: Item }) {
|
||||
<React.Fragment>
|
||||
<IconButton
|
||||
size="small"
|
||||
aria-label={t('close')}
|
||||
aria-label={t("close")}
|
||||
color="inherit"
|
||||
onClick={handleClose}
|
||||
>
|
||||
@@ -53,7 +54,6 @@ export default function ProductInfo({item}: { item: Item }) {
|
||||
</React.Fragment>
|
||||
);
|
||||
|
||||
|
||||
const handleAddToCart = () => {
|
||||
addToBasket(item, quantity);
|
||||
setOpen(true);
|
||||
@@ -72,13 +72,15 @@ export default function ProductInfo({item}: { item: Item }) {
|
||||
useEffect(() => {
|
||||
const fetchImage = async () => {
|
||||
try {
|
||||
const response = await fetch(`http://localhost:8085/image?uuid=${item.uuid}`);
|
||||
const response = await fetch(
|
||||
`http://localhost:8085/image?uuid=${item.uuid}`,
|
||||
);
|
||||
let data = await response.text();
|
||||
if (data.length == 0) {
|
||||
console.error("Got emtpy picture for article ", item.uuid);
|
||||
}
|
||||
if (!data.startsWith("data:image/")) {
|
||||
data = "data:image/jpeg;base64," + data
|
||||
data = "data:image/jpeg;base64," + data;
|
||||
}
|
||||
setImageUrl(data);
|
||||
} catch (error) {
|
||||
@@ -93,7 +95,10 @@ export default function ProductInfo({item}: { item: Item }) {
|
||||
<Grid container spacing={4}>
|
||||
{/* Left Column - Image */}
|
||||
|
||||
<Card elevation={2} sx={{width: '100%', maxWidth: 400, display: 'inherit'}}>
|
||||
<Card
|
||||
elevation={2}
|
||||
sx={{ width: "100%", maxWidth: 400, display: "inherit" }}
|
||||
>
|
||||
<Box
|
||||
component="img"
|
||||
src={imageUrl}
|
||||
@@ -103,16 +108,18 @@ export default function ProductInfo({item}: { item: Item }) {
|
||||
event.currentTarget.src = "/src/assets/default.jpg"; // Standardbild setzen
|
||||
}}
|
||||
sx={{
|
||||
maxWidth: imageDimensions.width > imageDimensions.height ? "100%" : "auto",
|
||||
maxHeight: imageDimensions.height >= imageDimensions.width ? 400 : "auto",
|
||||
maxWidth:
|
||||
imageDimensions.width > imageDimensions.height ? "100%" : "auto",
|
||||
maxHeight:
|
||||
imageDimensions.height >= imageDimensions.width ? 400 : "auto",
|
||||
width: "auto",
|
||||
height: "auto",
|
||||
objectFit: "contain",
|
||||
margin: "auto",
|
||||
}}
|
||||
/>
|
||||
</Card>
|
||||
|
||||
|
||||
{/* Right Column - Product Details */}
|
||||
|
||||
<Stack spacing={3}>
|
||||
@@ -123,8 +130,7 @@ export default function ProductInfo({item}: { item: Item }) {
|
||||
<Box display="flex" alignItems="center" gap={1}>
|
||||
<Rating value={item.rating / 2} precision={0.5} readOnly />
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
{item.rating > 0 ? `(${item.rating / 2} / 5)` : t('noRatingsYet')}
|
||||
|
||||
{item.rating > 0 ? `(${item.rating / 2} / 5)` : t("noRatingsYet")}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
@@ -137,7 +143,7 @@ export default function ProductInfo({item}: { item: Item }) {
|
||||
<Typography
|
||||
variant="h6"
|
||||
color="text.secondary"
|
||||
sx={{textDecoration: 'line-through'}}
|
||||
sx={{ textDecoration: "line-through" }}
|
||||
>
|
||||
{(item.price100 / 100).toFixed(2)} €
|
||||
</Typography>
|
||||
@@ -156,21 +162,24 @@ export default function ProductInfo({item}: { item: Item }) {
|
||||
|
||||
<Box>
|
||||
{item.stock > 10 ? (
|
||||
<Alert severity="success" variant='outlined'>
|
||||
{t('inStock')} ({item.stock} {t('available')})
|
||||
<Alert severity="success" variant="outlined">
|
||||
{t("inStock")} ({item.stock} {t("available")})
|
||||
</Alert>
|
||||
) : item.stock > 0 ? (
|
||||
<Alert severity="warning"
|
||||
variant='outlined'>{t('almostSoldOut')} ({item.stock} {t('available')})</Alert>
|
||||
<Alert severity="warning" variant="outlined">
|
||||
{t("almostSoldOut")} ({item.stock} {t("available")})
|
||||
</Alert>
|
||||
) : (
|
||||
<Alert severity="error" variant='filled'>{t('outOfStock')}</Alert>
|
||||
<Alert severity="error" variant="filled">
|
||||
{t("outOfStock")}
|
||||
</Alert>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<Stack direction="row" spacing={2} alignItems="center">
|
||||
<TextField
|
||||
type="number"
|
||||
label={t('quantity')}
|
||||
label={t("quantity")}
|
||||
value={quantity}
|
||||
onChange={(e) => setQuantity(Math.max(1, parseInt(e.target.value)))}
|
||||
InputProps={{ inputProps: { min: 1, max: item.stock } }}
|
||||
@@ -184,26 +193,24 @@ export default function ProductInfo({item}: { item: Item }) {
|
||||
disabled={item.stock <= 0}
|
||||
fullWidth
|
||||
>
|
||||
{t('addToCart')}
|
||||
{t("addToCart")}
|
||||
</Button>
|
||||
</Stack>
|
||||
|
||||
<Box sx={{ mt: 2 }}>
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
<LocalShipping sx={{mr: 1, verticalAlign: 'middle'}}/>
|
||||
{t('freeShipping')}
|
||||
<LocalShipping sx={{ mr: 1, verticalAlign: "middle" }} />
|
||||
{t("freeShipping")}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
</Stack>
|
||||
<Snackbar
|
||||
open={open}
|
||||
autoHideDuration={3000}
|
||||
onClose={handleClose}
|
||||
message={t('addedToCart')}
|
||||
message={t("addedToCart")}
|
||||
action={action}
|
||||
/>
|
||||
|
||||
</Grid>
|
||||
);
|
||||
}
|
||||
@@ -1,13 +1,20 @@
|
||||
import {Card, CardActionArea, CardContent, Paper, Rating, Typography, useTheme} from "@mui/material";
|
||||
import {
|
||||
Card,
|
||||
CardActionArea,
|
||||
CardContent,
|
||||
Paper,
|
||||
Rating,
|
||||
Typography,
|
||||
useTheme,
|
||||
} from "@mui/material";
|
||||
import RatingType from "../../components/Rating";
|
||||
import {useTranslation} from 'react-i18next';
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
export default function RatingCard(ratingType: RatingType) {
|
||||
const { t } = useTranslation();
|
||||
const theme = useTheme(); // Zugriff auf Light/Dark-Mode
|
||||
|
||||
const handleClick = () => {
|
||||
};
|
||||
const handleClick = () => {};
|
||||
|
||||
return (
|
||||
<Paper
|
||||
@@ -15,7 +22,7 @@ export default function RatingCard(ratingType: RatingType) {
|
||||
sx={{
|
||||
backgroundColor: theme.palette.background.paper,
|
||||
color: theme.palette.text.primary,
|
||||
mb: 3
|
||||
mb: 3,
|
||||
}}
|
||||
>
|
||||
<Card
|
||||
@@ -31,7 +38,8 @@ export default function RatingCard(ratingType: RatingType) {
|
||||
component="div"
|
||||
sx={{ color: theme.palette.text.primary }}
|
||||
>
|
||||
{t('ratingFrom')} {new Date(ratingType.timestamp).toLocaleDateString('de-DE')}
|
||||
{t("ratingFrom")}{" "}
|
||||
{new Date(ratingType.timestamp).toLocaleDateString("de-DE")}
|
||||
</Typography>
|
||||
|
||||
<Rating
|
||||
|
||||
@@ -8,12 +8,12 @@ import {
|
||||
SnackbarCloseReason,
|
||||
TextField,
|
||||
Typography,
|
||||
useTheme
|
||||
useTheme,
|
||||
} from "@mui/material";
|
||||
import { Close } from "@mui/icons-material";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import React, { useMemo, useState } from "react";
|
||||
import {useTranslation} from 'react-i18next';
|
||||
import { useTranslation } from "react-i18next";
|
||||
import RatingType from "../../components/Rating";
|
||||
import { fetchRatingList, submitRating } from "../query/Queries";
|
||||
import RatingCard from "./RatingCard";
|
||||
@@ -48,7 +48,7 @@ export default function Ratings({itemId}: { itemId: string }) {
|
||||
|
||||
const handleClose = (
|
||||
_: React.SyntheticEvent | Event,
|
||||
reason?: SnackbarCloseReason
|
||||
reason?: SnackbarCloseReason,
|
||||
) => {
|
||||
if (reason === "clickaway") return;
|
||||
setOpen(false);
|
||||
@@ -79,7 +79,10 @@ export default function Ratings({itemId}: { itemId: string }) {
|
||||
const getRatings = () => {
|
||||
if (ratings.length === 0) {
|
||||
return (
|
||||
<Typography variant="body1" sx={{color: theme.palette.text.secondary}}>
|
||||
<Typography
|
||||
variant="body1"
|
||||
sx={{ color: theme.palette.text.secondary }}
|
||||
>
|
||||
{t("noRatingsYet")}
|
||||
</Typography>
|
||||
);
|
||||
@@ -95,7 +98,10 @@ export default function Ratings({itemId}: { itemId: string }) {
|
||||
<Divider sx={{ backgroundColor: theme.palette.divider, my: 3 }} />
|
||||
|
||||
<Box sx={{ mb: 4 }}>
|
||||
<Typography variant="h5" sx={{color: theme.palette.text.primary, mb: 2}}>
|
||||
<Typography
|
||||
variant="h5"
|
||||
sx={{ color: theme.palette.text.primary, mb: 2 }}
|
||||
>
|
||||
{t("rateThisProduct")}:
|
||||
</Typography>
|
||||
|
||||
@@ -117,20 +123,20 @@ export default function Ratings({itemId}: { itemId: string }) {
|
||||
mb: 2,
|
||||
backgroundColor: theme.palette.background.paper,
|
||||
color: theme.palette.text.primary,
|
||||
'& .MuiInputBase-input': {
|
||||
"& .MuiInputBase-input": {
|
||||
color: theme.palette.text.primary,
|
||||
},
|
||||
'& label': {
|
||||
"& label": {
|
||||
color: theme.palette.text.secondary,
|
||||
},
|
||||
'& .MuiOutlinedInput-root': {
|
||||
'& fieldset': {
|
||||
"& .MuiOutlinedInput-root": {
|
||||
"& fieldset": {
|
||||
borderColor: theme.palette.divider,
|
||||
},
|
||||
'&:hover fieldset': {
|
||||
"&:hover fieldset": {
|
||||
borderColor: theme.palette.text.primary,
|
||||
},
|
||||
'&.Mui-focused fieldset': {
|
||||
"&.Mui-focused fieldset": {
|
||||
borderColor: theme.palette.primary.main,
|
||||
},
|
||||
},
|
||||
@@ -150,9 +156,7 @@ export default function Ratings({itemId}: { itemId: string }) {
|
||||
|
||||
<Divider sx={{ backgroundColor: theme.palette.divider, my: 3 }} />
|
||||
|
||||
<Box>
|
||||
{getRatings()}
|
||||
</Box>
|
||||
<Box>{getRatings()}</Box>
|
||||
|
||||
<Snackbar
|
||||
open={open}
|
||||
|
||||
@@ -1,110 +1,129 @@
|
||||
// api/queries.js
|
||||
|
||||
import AccountType, {AdminAccountOperation, CustomerType, SubmitLogin, User} from "../../components/Account";
|
||||
import AccountType, {
|
||||
AdminAccountOperation,
|
||||
CustomerType,
|
||||
SubmitLogin,
|
||||
User,
|
||||
} from "../../components/Account";
|
||||
import OrderType, { OrderPatch } from "../../components/Order";
|
||||
import RatingSubmitType from "../../components/RatingSubmit";
|
||||
import { Item, ItemWithFSImage } from "../../components/Item";
|
||||
|
||||
export const fetchItemList = async () => {
|
||||
const response = await fetch('http://localhost:8085/article/all');
|
||||
const response = await fetch("http://localhost:8085/article/all");
|
||||
if (!response.ok) {
|
||||
throw new Error('Fehler beim Laden der Items');
|
||||
throw new Error("Fehler beim Laden der Items");
|
||||
}
|
||||
const data = await response.json();
|
||||
return data;
|
||||
};
|
||||
|
||||
export const fetchItemListWithImage = async () => {
|
||||
const response = await fetch('http://localhost:8085/article/all/image');
|
||||
const response = await fetch("http://localhost:8085/article/all/image");
|
||||
if (!response.ok) {
|
||||
throw new Error('Fehler beim Laden der Items');
|
||||
throw new Error("Fehler beim Laden der Items");
|
||||
}
|
||||
const data = await response.json();
|
||||
return data;
|
||||
};
|
||||
|
||||
export const submitRating = async (ratingData: RatingSubmitType) => {
|
||||
const response = await fetch('http://localhost:8085/review?uuid=' + ratingData.articleId + '&rating=' + ratingData.rating * 2, {
|
||||
method: 'POST',
|
||||
const response = await fetch(
|
||||
"http://localhost:8085/review?uuid=" +
|
||||
ratingData.articleId +
|
||||
"&rating=" +
|
||||
ratingData.rating * 2,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
'Content-Type': 'text/plain',
|
||||
"Content-Type": "text/plain",
|
||||
},
|
||||
body: ratingData.content,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Fehler beim Senden der Bewertung');
|
||||
throw new Error("Fehler beim Senden der Bewertung");
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return data;
|
||||
}
|
||||
};
|
||||
|
||||
export const fetchRatingList = async (itemId: string) => {
|
||||
const response = await fetch('http://localhost:8085/review/all?uuid=' + itemId);
|
||||
const response = await fetch(
|
||||
"http://localhost:8085/review/all?uuid=" + itemId,
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error('Fehler beim Laden der Items');
|
||||
throw new Error("Fehler beim Laden der Items");
|
||||
}
|
||||
const data = await response.json();
|
||||
return data;
|
||||
};
|
||||
|
||||
export const submitOrder = async (data: OrderType) => {
|
||||
const response = await fetch('http://localhost:8085/order', {
|
||||
method: 'POST',
|
||||
const response = await fetch("http://localhost:8085/order", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Fehler beim Senden der Bestellung');
|
||||
throw new Error("Fehler beim Senden der Bestellung");
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
}
|
||||
};
|
||||
|
||||
export const submitAccount = async (data: AccountType) => {
|
||||
const response = await fetch('http://localhost:8085/account', {
|
||||
method: 'POST',
|
||||
const response = await fetch("http://localhost:8085/account", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Fehler beim Senden des Accounts');
|
||||
throw new Error("Fehler beim Senden des Accounts");
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
}
|
||||
};
|
||||
|
||||
export const submitCustomer = async (data: CustomerType) => {
|
||||
const response = await fetch('http://localhost:8085/customer', {
|
||||
method: 'POST',
|
||||
const response = await fetch("http://localhost:8085/customer", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Fehler beim Senden des Accounts');
|
||||
throw new Error("Fehler beim Senden des Accounts");
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
}
|
||||
};
|
||||
|
||||
export const submitLogin = async (loginData: SubmitLogin) => {
|
||||
const response = await fetch("http://localhost:8085/session?email=" + loginData.email + "&password=" + loginData.password, {
|
||||
const response = await fetch(
|
||||
"http://localhost:8085/session?email=" +
|
||||
loginData.email +
|
||||
"&password=" +
|
||||
loginData.password,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(loginData),
|
||||
});
|
||||
},
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error("Login failed");
|
||||
}
|
||||
@@ -112,7 +131,12 @@ export const submitLogin = async (loginData: SubmitLogin) => {
|
||||
};
|
||||
|
||||
export const fetchAccount = async (loginData: SubmitLogin) => {
|
||||
const response = await fetch("http://localhost:8085/account?email=" + loginData.email + "&password=" + loginData.password);
|
||||
const response = await fetch(
|
||||
"http://localhost:8085/account?email=" +
|
||||
loginData.email +
|
||||
"&password=" +
|
||||
loginData.password,
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error("Login failed");
|
||||
}
|
||||
@@ -134,61 +158,79 @@ export const submitRegister = async (registerData: AccountType) => {
|
||||
};
|
||||
|
||||
export const fetchCustomer = async (userId: number) => {
|
||||
const response = await fetch('http://localhost:8085/customer?id=' + userId);
|
||||
const response = await fetch("http://localhost:8085/customer?id=" + userId);
|
||||
if (!response.ok) {
|
||||
throw new Error('Fehler beim Laden des Customers');
|
||||
throw new Error("Fehler beim Laden des Customers");
|
||||
}
|
||||
const data = await response.json();
|
||||
return data;
|
||||
};
|
||||
|
||||
export const deleteAccount = async (user: User) => {
|
||||
const response = await fetch('http://localhost:8085/account?email=' + user.email + '&password=' + user.password, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
const response = await fetch(
|
||||
"http://localhost:8085/account?email=" +
|
||||
user.email +
|
||||
"&password=" +
|
||||
user.password,
|
||||
{
|
||||
method: "DELETE",
|
||||
},
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error('Fehler beim Löschen des Accounts');
|
||||
throw new Error("Fehler beim Löschen des Accounts");
|
||||
}
|
||||
return await response.json();
|
||||
};
|
||||
|
||||
export const deleteAccountAdmin = async (operation: AdminAccountOperation) => {
|
||||
const response = await fetch('http://localhost:8085/account/admin?email=' + operation.email + '&uuid=' + operation.uuid + '&id=' + operation.accountId, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
const response = await fetch(
|
||||
"http://localhost:8085/account/admin?email=" +
|
||||
operation.email +
|
||||
"&uuid=" +
|
||||
operation.uuid +
|
||||
"&id=" +
|
||||
operation.accountId,
|
||||
{
|
||||
method: "DELETE",
|
||||
},
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error('Fehler beim Löschen des Accounts');
|
||||
throw new Error("Fehler beim Löschen des Accounts");
|
||||
}
|
||||
return await response.json();
|
||||
};
|
||||
|
||||
export const fetchOrders = async (customerId: number) => {
|
||||
const response = await fetch('http://localhost:8085/order/all?customerId=' + customerId);
|
||||
const response = await fetch(
|
||||
"http://localhost:8085/order/all?customerId=" + customerId,
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error('Fehler beim Laden des Customers');
|
||||
throw new Error("Fehler beim Laden des Customers");
|
||||
}
|
||||
const data = await response.json();
|
||||
return data;
|
||||
};
|
||||
|
||||
export const fetchAccounts = async (loginData: User) => {
|
||||
const response = await fetch("http://localhost:8085/account/all?email=" + loginData.email + "&session=" + loginData.session);
|
||||
const response = await fetch(
|
||||
"http://localhost:8085/account/all?email=" +
|
||||
loginData.email +
|
||||
"&session=" +
|
||||
loginData.session,
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error("Login failed");
|
||||
}
|
||||
return response.json();
|
||||
};
|
||||
|
||||
export const fetchItems = async () => { //TODO: remove and use above
|
||||
const response = await fetch("http://localhost:8085/article/all");
|
||||
if (!response.ok) {
|
||||
throw new Error("fetching items failed");
|
||||
}
|
||||
return response.json();
|
||||
};
|
||||
|
||||
export const fetchStatisticsVolume = async (loginData: User) => {
|
||||
const response = await fetch("http://localhost:8085/statistics/volume?email=" + loginData.email + "&session=" + loginData.session);
|
||||
const response = await fetch(
|
||||
"http://localhost:8085/statistics/volume?email=" +
|
||||
loginData.email +
|
||||
"&session=" +
|
||||
loginData.session,
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error("fetching satistics Volume failed");
|
||||
}
|
||||
@@ -196,7 +238,12 @@ export const fetchStatisticsVolume = async (loginData: User) => {
|
||||
};
|
||||
|
||||
export const fetchStatisticsRevenue = async (loginData: User) => {
|
||||
const response = await fetch("http://localhost:8085/statistics/revenue?email=" + loginData.email + "&session=" + loginData.session);
|
||||
const response = await fetch(
|
||||
"http://localhost:8085/statistics/revenue?email=" +
|
||||
loginData.email +
|
||||
"&session=" +
|
||||
loginData.session,
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error("fetching satistics Revenue failed");
|
||||
}
|
||||
@@ -204,23 +251,28 @@ export const fetchStatisticsRevenue = async (loginData: User) => {
|
||||
};
|
||||
|
||||
export const editAccount = async (customer: CustomerType) => {
|
||||
const response = await fetch('http://localhost:8085/customer?id=' + customer.id, {
|
||||
method: 'PUT',
|
||||
const response = await fetch(
|
||||
"http://localhost:8085/customer?id=" + customer.id,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(customer),
|
||||
});
|
||||
},
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error('Fehler beim Löschen des Accounts');
|
||||
throw new Error("Fehler beim Löschen des Accounts");
|
||||
}
|
||||
return await response.json();
|
||||
};
|
||||
|
||||
export const orderPatch = async (order: OrderPatch) => {
|
||||
const response = await fetch("http://localhost:8085/order?id=" + order.id + "&status=" + order.status, {
|
||||
const response = await fetch(
|
||||
"http://localhost:8085/order?id=" + order.id + "&status=" + order.status,
|
||||
{
|
||||
method: "PATCH",
|
||||
}
|
||||
},
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error("Order patch failed");
|
||||
@@ -229,7 +281,12 @@ export const orderPatch = async (order: OrderPatch) => {
|
||||
};
|
||||
|
||||
export const fetchOrderStatus = async (loginData: User) => {
|
||||
const response = await fetch("http://localhost:8085/statistics/orderstatus?email=" + loginData.email + "&session=" + loginData.session);
|
||||
const response = await fetch(
|
||||
"http://localhost:8085/statistics/orderstatus?email=" +
|
||||
loginData.email +
|
||||
"&session=" +
|
||||
loginData.session,
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error("fetching order status failed");
|
||||
}
|
||||
@@ -237,16 +294,25 @@ export const fetchOrderStatus = async (loginData: User) => {
|
||||
};
|
||||
|
||||
export const fetchStockPercent = async (loginData: User) => {
|
||||
const response = await fetch("http://localhost:8085/statistics/stockpercent?email=" + loginData.email + "&session=" + loginData.session);
|
||||
const response = await fetch(
|
||||
"http://localhost:8085/statistics/stockpercent?email=" +
|
||||
loginData.email +
|
||||
"&session=" +
|
||||
loginData.session,
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error("fetching stock% failed");
|
||||
}
|
||||
return response.json();
|
||||
};
|
||||
|
||||
|
||||
export const fetchOrdersAdmin = async (loginData: User) => {
|
||||
const response = await fetch("http://localhost:8085/order/all/all?email=" + loginData.email + "&session=" + loginData.session);
|
||||
const response = await fetch(
|
||||
"http://localhost:8085/order/all/all?email=" +
|
||||
loginData.email +
|
||||
"&session=" +
|
||||
loginData.session,
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error("fetching admin orders failed");
|
||||
}
|
||||
@@ -254,25 +320,29 @@ export const fetchOrdersAdmin = async (loginData: User) => {
|
||||
};
|
||||
|
||||
export const updateCustomer = async (customer: CustomerType) => {
|
||||
const response = await fetch('http://localhost:8085/customer?id=' + customer.id, {
|
||||
method: 'PUT',
|
||||
const response = await fetch(
|
||||
"http://localhost:8085/customer?id=" + customer.id,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(customer),
|
||||
});
|
||||
},
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error('Fehler beim Ändern des Customers');
|
||||
throw new Error("Fehler beim Ändern des Customers");
|
||||
}
|
||||
return await response.json();
|
||||
}
|
||||
};
|
||||
|
||||
export const fetchFarmingStationItemList = async (): Promise<ItemWithFSImage[]> => {
|
||||
const response = await fetch('http://localhost:8085/farm/articles');
|
||||
if (!response.ok)
|
||||
throw new Error('Failed to fetch items');
|
||||
export const fetchFarmingStationItemList = async (): Promise<
|
||||
ItemWithFSImage[]
|
||||
> => {
|
||||
const response = await fetch("http://localhost:8085/farm/articles");
|
||||
if (!response.ok) throw new Error("Failed to fetch items");
|
||||
return response.json();
|
||||
}
|
||||
};
|
||||
|
||||
export const submitItem = async (item: Item) => {
|
||||
const response = await fetch("http://localhost:8085/article", {
|
||||
@@ -290,7 +360,7 @@ export const submitItem = async (item: Item) => {
|
||||
|
||||
export const deleteItemQuery = async (uuid: string) => {
|
||||
const response = await fetch("http://localhost:8085/article?uuid=" + uuid, {
|
||||
method: "DELETE"
|
||||
method: "DELETE",
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error("Login failed");
|
||||
@@ -299,25 +369,38 @@ export const deleteItemQuery = async (uuid: string) => {
|
||||
};
|
||||
|
||||
export const updateAccountAdmin = async (account: AccountType, user: User) => {
|
||||
const response = await fetch('http://localhost:8085/account/admin?email=' + user.email + "&uuid=" + user.session + "&id=" + account.id + "&admin=" + account.admin, {
|
||||
method: 'POST',
|
||||
});
|
||||
const response = await fetch(
|
||||
"http://localhost:8085/account/admin?email=" +
|
||||
user.email +
|
||||
"&uuid=" +
|
||||
user.session +
|
||||
"&id=" +
|
||||
account.id +
|
||||
"&admin=" +
|
||||
account.admin,
|
||||
{
|
||||
method: "POST",
|
||||
},
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error('Fehler beim Ändern des Customers');
|
||||
throw new Error("Fehler beim Ändern des Customers");
|
||||
}
|
||||
return await response.json();
|
||||
}
|
||||
};
|
||||
|
||||
export const updateItemAdmin = async (item: Item) => {
|
||||
const response = await fetch('http://localhost:8085/article?uuid=' + item.uuid, {
|
||||
method: 'PUT',
|
||||
const response = await fetch(
|
||||
"http://localhost:8085/article?uuid=" + item.uuid,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(item),
|
||||
});
|
||||
},
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error('Fehler beim Ändern des Items');
|
||||
throw new Error("Fehler beim Ändern des Items");
|
||||
}
|
||||
return await response.json();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import './components/i18n/i18n';
|
||||
import {StrictMode} from 'react';
|
||||
import {createRoot} from 'react-dom/client';
|
||||
import './index.css';
|
||||
import App from './App.tsx';
|
||||
import "./components/i18n/i18n";
|
||||
import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import "./index.css";
|
||||
import App from "./App.tsx";
|
||||
|
||||
const rootElement = document.getElementById('root');
|
||||
const rootElement = document.getElementById("root");
|
||||
if (!rootElement) throw new Error("Root element not found");
|
||||
|
||||
const root = createRoot(rootElement);
|
||||
root.render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>
|
||||
</StrictMode>,
|
||||
);
|
||||
@@ -17,7 +17,11 @@ import {useTranslation} from "react-i18next";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { CustomerType, User } from "../components/Account";
|
||||
import { useAccount } from "../helper/AccountProvider";
|
||||
import {deleteAccount, editAccount, fetchCustomer} from "../helper/query/Queries";
|
||||
import {
|
||||
deleteAccount,
|
||||
editAccount,
|
||||
fetchCustomer,
|
||||
} from "../helper/query/Queries";
|
||||
import "./pages.css";
|
||||
|
||||
export default function Account() {
|
||||
@@ -34,13 +38,15 @@ export default function Account() {
|
||||
id: userData?.customerId || 0,
|
||||
});
|
||||
|
||||
const [userDataState, setUserDataState] = useState<User>(userData || {
|
||||
const [userDataState, setUserDataState] = useState<User>(
|
||||
userData || {
|
||||
password: "",
|
||||
email: "",
|
||||
customerId: 0,
|
||||
session: "",
|
||||
isAdmin: false,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (userData?.customerId) {
|
||||
@@ -138,7 +144,10 @@ export default function Account() {
|
||||
className="page-background page-background-center"
|
||||
sx={{ minHeight: "100vh", justifyContent: "flex-start", pt: 4 }}
|
||||
>
|
||||
<Paper elevation={3} sx={{p: 4, maxWidth: 500, width: "100%", mx: "auto"}}>
|
||||
<Paper
|
||||
elevation={3}
|
||||
sx={{ p: 4, maxWidth: 500, width: "100%", mx: "auto" }}
|
||||
>
|
||||
<Typography variant="h4" gutterBottom>
|
||||
{t("myAccount")}
|
||||
</Typography>
|
||||
@@ -191,7 +200,11 @@ export default function Account() {
|
||||
<Button variant="contained" color="primary" onClick={handleSave}>
|
||||
{t("save")}
|
||||
</Button>
|
||||
<Button variant="outlined" color="secondary" onClick={handleCancel}>
|
||||
<Button
|
||||
variant="outlined"
|
||||
color="secondary"
|
||||
onClick={handleCancel}
|
||||
>
|
||||
{t("cancel")}
|
||||
</Button>
|
||||
</>
|
||||
|
||||
@@ -1,11 +1,28 @@
|
||||
import {AccountCircle, Category, QueryStats, ReceiptLong,} from "@mui/icons-material";
|
||||
import {Box, List, ListItem, ListItemButton, ListItemIcon, ListItemText, useTheme,} from "@mui/material";
|
||||
import {
|
||||
AccountCircle,
|
||||
Category,
|
||||
QueryStats,
|
||||
ReceiptLong,
|
||||
} from "@mui/icons-material";
|
||||
import {
|
||||
Box,
|
||||
List,
|
||||
ListItem,
|
||||
ListItemButton,
|
||||
ListItemIcon,
|
||||
ListItemText,
|
||||
useTheme,
|
||||
} from "@mui/material";
|
||||
import { fetchItemList } from "../helper/query/Queries.tsx";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useAccount } from "../helper/AccountProvider.tsx";
|
||||
import AccountsInfo from "../helper/adminpanel/AccountsInfo";
|
||||
import ItemInfo from "../helper/adminpanel/ItemsInfo";
|
||||
import OrdersInfo from "../helper/adminpanel/OrdersInfo";
|
||||
import StatisticsInfo from "../helper/adminpanel/StatisticsInfo";
|
||||
import Item from "../components/Item";
|
||||
|
||||
export default function AdminPanel() {
|
||||
const { t } = useTranslation();
|
||||
@@ -16,16 +33,25 @@ export default function AdminPanel() {
|
||||
setInfoStatus(path);
|
||||
};
|
||||
|
||||
const renderContent = () => {
|
||||
const { user: loginData } = useAccount();
|
||||
|
||||
const { data: itemList, isLoading } = useQuery<Item[]>({
|
||||
queryKey: ["fetchItemList", loginData],
|
||||
queryFn: () => fetchItemList(),
|
||||
retry: 3,
|
||||
retryDelay: 1000,
|
||||
});
|
||||
|
||||
const renderContent = (itemList: Item[]) => {
|
||||
switch (infoStatus) {
|
||||
case "statistics":
|
||||
return <StatisticsInfo />;
|
||||
case "orders":
|
||||
return <OrdersInfo/>;
|
||||
return <OrdersInfo itemList={itemList} />;
|
||||
case "accounts":
|
||||
return <AccountsInfo />;
|
||||
case "items":
|
||||
return <ItemInfo/>;
|
||||
return <ItemInfo itemList={itemList} />;
|
||||
default:
|
||||
return <StatisticsInfo />;
|
||||
}
|
||||
@@ -45,7 +71,8 @@ export default function AdminPanel() {
|
||||
style={{
|
||||
color: theme.palette.text.primary,
|
||||
backgroundColor: theme.palette.background.paper,
|
||||
}}>
|
||||
}}
|
||||
>
|
||||
{/* Sidebar */}
|
||||
<Box className="sidebar">
|
||||
<nav aria-label={t("mainAdminMenu")}>
|
||||
@@ -63,8 +90,11 @@ export default function AdminPanel() {
|
||||
"&:hover": {
|
||||
bgcolor: theme.palette.action.hover,
|
||||
},
|
||||
}}>
|
||||
<ListItemIcon sx={{color: "inherit"}}>{item.icon}</ListItemIcon>
|
||||
}}
|
||||
>
|
||||
<ListItemIcon sx={{ color: "inherit" }}>
|
||||
{item.icon}
|
||||
</ListItemIcon>
|
||||
<ListItemText primary={item.label} />
|
||||
</ListItemButton>
|
||||
</ListItem>
|
||||
@@ -74,7 +104,7 @@ export default function AdminPanel() {
|
||||
</Box>
|
||||
|
||||
{/* Content */}
|
||||
<Box className="page-background">{renderContent()}</Box>
|
||||
<Box className="page-background">{renderContent(itemList)}</Box>
|
||||
</div>
|
||||
</Box>
|
||||
);
|
||||
|
||||
@@ -4,87 +4,126 @@ import "./pages.css";
|
||||
export default function Impressum() {
|
||||
return (
|
||||
<Box className="impressum-container">
|
||||
<Typography variant="h4" sx={{color: 'text.primary', mb: 2}}>
|
||||
<Typography variant="h4" sx={{ color: "text.primary", mb: 2 }}>
|
||||
Impressum
|
||||
</Typography>
|
||||
|
||||
<Typography variant="body1" sx={{color: 'text.primary', mb: 4}}>
|
||||
Hochschule für Technik und Wirtschaft<br/>
|
||||
des Saarlandes<br/>
|
||||
Goebenstraße 40<br/>
|
||||
66117 Saarbrücken<br/><br/>
|
||||
<Typography variant="body1" sx={{ color: "text.primary", mb: 4 }}>
|
||||
Hochschule für Technik und Wirtschaft
|
||||
<br />
|
||||
des Saarlandes
|
||||
<br />
|
||||
Goebenstraße 40
|
||||
<br />
|
||||
66117 Saarbrücken
|
||||
<br />
|
||||
<br />
|
||||
Telefon: (0681) 58 67 - 0<br />
|
||||
Telefax: (0681) 58 67 - 122<br/>
|
||||
E-Mail: info@htwsaar.de<br/><br/>
|
||||
Aufsichtsbehörde:<br/>
|
||||
Telefax: (0681) 58 67 - 122
|
||||
<br />
|
||||
E-Mail: info@htwsaar.de
|
||||
<br />
|
||||
<br />
|
||||
Aufsichtsbehörde:
|
||||
<br />
|
||||
Ministerium der Finanzen und für Wissenschaft des Saarlandes
|
||||
</Typography>
|
||||
|
||||
<Divider className="contact-divider" />
|
||||
|
||||
<Typography variant="h5" sx={{color: 'text.primary', mt: 4, mb: 2}}>
|
||||
<Typography variant="h5" sx={{ color: "text.primary", mt: 4, mb: 2 }}>
|
||||
Datenschutzerklärung
|
||||
</Typography>
|
||||
|
||||
<Typography variant="body1" sx={{color: 'text.primary', mb: 2}}>
|
||||
<Typography variant="body1" sx={{ color: "text.primary", mb: 2 }}>
|
||||
Personenbezogene Daten (nachfolgend zumeist nur „Daten“ genannt) ...
|
||||
</Typography>
|
||||
|
||||
<Typography variant="body1" sx={{color: 'text.primary', mb: 2}}>
|
||||
Gemäß Art. 4 Ziffer 1. der Verordnung (EU) 2016/679, also der Datenschutz-Grundverordnung ...
|
||||
<Typography variant="body1" sx={{ color: "text.primary", mb: 2 }}>
|
||||
Gemäß Art. 4 Ziffer 1. der Verordnung (EU) 2016/679, also der
|
||||
Datenschutz-Grundverordnung ...
|
||||
</Typography>
|
||||
|
||||
<Typography variant="body1" sx={{color: 'text.primary', mb: 2}}>
|
||||
Unsere Datenschutzerklärung ist wie folgt gegliedert:<br/>
|
||||
I. Informationen über uns als Verantwortliche<br/>
|
||||
II. Rechte der Nutzer und Betroffenen<br/>
|
||||
<Typography variant="body1" sx={{ color: "text.primary", mb: 2 }}>
|
||||
Unsere Datenschutzerklärung ist wie folgt gegliedert:
|
||||
<br />
|
||||
I. Informationen über uns als Verantwortliche
|
||||
<br />
|
||||
II. Rechte der Nutzer und Betroffenen
|
||||
<br />
|
||||
III. Informationen zur Datenverarbeitung
|
||||
</Typography>
|
||||
|
||||
<Typography variant="h6" sx={{color: 'text.primary', mt: 4, mb: 1}}>
|
||||
<Typography variant="h6" sx={{ color: "text.primary", mt: 4, mb: 1 }}>
|
||||
I. Informationen über uns als Verantwortliche
|
||||
</Typography>
|
||||
|
||||
<Typography variant="body1" sx={{color: 'text.primary', mb: 2}}>
|
||||
<Typography variant="body1" sx={{ color: "text.primary", mb: 2 }}>
|
||||
Verantwortlicher Anbieter dieses Internetauftritts ...
|
||||
</Typography>
|
||||
|
||||
<Typography variant="h6" sx={{color: 'text.primary', mt: 4, mb: 1}}>
|
||||
<Typography variant="h6" sx={{ color: "text.primary", mt: 4, mb: 1 }}>
|
||||
II. Rechte der Nutzer und Betroffenen
|
||||
</Typography>
|
||||
|
||||
<Typography variant="body1" sx={{color: 'text.primary', mb: 2}}>
|
||||
Mit Blick auf die nachfolgend noch näher beschriebene Datenverarbeitung haben die Nutzer und Betroffenen
|
||||
...
|
||||
<Typography variant="body1" sx={{ color: "text.primary", mb: 2 }}>
|
||||
Mit Blick auf die nachfolgend noch näher beschriebene Datenverarbeitung
|
||||
haben die Nutzer und Betroffenen ...
|
||||
</Typography>
|
||||
|
||||
<Box component="ul" sx={{listStyle: 'none', p: 0, m: 0}}>
|
||||
<li><Typography variant="body2" sx={{color: 'text.primary', mb: 0.5}}> • Auskunft über die verarbeiteten
|
||||
Daten (Art. 15 DSGVO)</Typography></li>
|
||||
<li><Typography variant="body2" sx={{color: 'text.primary', mb: 0.5}}> • Berichtigung unrichtiger Daten
|
||||
(Art. 16 DSGVO)</Typography></li>
|
||||
<li><Typography variant="body2" sx={{color: 'text.primary', mb: 0.5}}> • Löschung der Daten (Art. 17
|
||||
DSGVO)</Typography></li>
|
||||
<li><Typography variant="body2" sx={{color: 'text.primary', mb: 0.5}}> • Einschränkung der Verarbeitung
|
||||
(Art. 18 DSGVO)</Typography></li>
|
||||
<li><Typography variant="body2" sx={{color: 'text.primary', mb: 0.5}}> • Datenübertragbarkeit (Art. 20
|
||||
DSGVO)</Typography></li>
|
||||
<Box component="ul" sx={{ listStyle: "none", p: 0, m: 0 }}>
|
||||
<li>
|
||||
<Typography variant="body2" sx={{ color: "text.primary", mb: 0.5 }}>
|
||||
{" "}
|
||||
• Auskunft über die verarbeiteten Daten (Art. 15 DSGVO)
|
||||
</Typography>
|
||||
</li>
|
||||
<li>
|
||||
<Typography variant="body2" sx={{ color: "text.primary", mb: 0.5 }}>
|
||||
{" "}
|
||||
• Berichtigung unrichtiger Daten (Art. 16 DSGVO)
|
||||
</Typography>
|
||||
</li>
|
||||
<li>
|
||||
<Typography variant="body2" sx={{ color: "text.primary", mb: 0.5 }}>
|
||||
{" "}
|
||||
• Löschung der Daten (Art. 17 DSGVO)
|
||||
</Typography>
|
||||
</li>
|
||||
<li>
|
||||
<Typography variant="body2" sx={{ color: "text.primary", mb: 0.5 }}>
|
||||
{" "}
|
||||
• Einschränkung der Verarbeitung (Art. 18 DSGVO)
|
||||
</Typography>
|
||||
</li>
|
||||
<li>
|
||||
<Typography variant="body2" sx={{ color: "text.primary", mb: 0.5 }}>
|
||||
{" "}
|
||||
• Datenübertragbarkeit (Art. 20 DSGVO)
|
||||
</Typography>
|
||||
</li>
|
||||
</Box>
|
||||
|
||||
<Typography variant="h6" sx={{color: 'text.primary', mt: 4, mb: 1}}>
|
||||
<Typography variant="h6" sx={{ color: "text.primary", mt: 4, mb: 1 }}>
|
||||
III. Informationen zur Datenverarbeitung
|
||||
</Typography>
|
||||
|
||||
<Typography variant="body1" sx={{color: 'text.primary', mb: 2}}>
|
||||
<Typography variant="body1" sx={{ color: "text.primary", mb: 2 }}>
|
||||
Ihre bei Nutzung unseres Internetauftritts verarbeiteten Daten ...
|
||||
</Typography>
|
||||
|
||||
{/* Du kannst einfach alle weiteren Absätze so fortsetzen – copy & paste,
|
||||
jeweils in: <Typography variant="body1" sx={{ color: 'text.primary' }}>…</Typography> */}
|
||||
|
||||
<Typography variant="body2" sx={{color: 'text.primary', mt: 4}}>
|
||||
Mehr Infos unter: <a href="https://www.cloudflare.com/privacypolicy/" target="_blank"
|
||||
rel="noopener noreferrer">CloudFlare Datenschutzerklärung</a>
|
||||
<Typography variant="body2" sx={{ color: "text.primary", mt: 4 }}>
|
||||
Mehr Infos unter:{" "}
|
||||
<a
|
||||
href="https://www.cloudflare.com/privacypolicy/"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
CloudFlare Datenschutzerklärung
|
||||
</a>
|
||||
</Typography>
|
||||
</Box>
|
||||
);
|
||||
|
||||
@@ -4,13 +4,13 @@ import {useState} from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useBasket } from "../helper/BasketProvider";
|
||||
import ItemCard from "../helper/homepage/ItemCard";
|
||||
import AddShoppingCartIcon from '@mui/icons-material/AddShoppingCart';
|
||||
import AddShoppingCartIcon from "@mui/icons-material/AddShoppingCart";
|
||||
|
||||
import farmingStation from '../assets/fscomponents/fs_components_0.png';
|
||||
import farmingStation from "../assets/fscomponents/fs_components_0.png";
|
||||
import { ItemWithFSImage } from "../components/Item";
|
||||
import { fetchFarmingStationItemList } from "../helper/query/Queries";
|
||||
|
||||
"../components/Item";
|
||||
("../components/Item");
|
||||
|
||||
export default function FSComponents() {
|
||||
const { t } = useTranslation();
|
||||
@@ -19,11 +19,26 @@ export default function FSComponents() {
|
||||
const [hoverIndex, setHoverIndex] = useState<number | null>(null);
|
||||
|
||||
// Sehr sehr dummer Weg das zu machen, aber wird später noch refactored
|
||||
const wantedIds = ["60", "67", "68", "69", "70", "71", "72", "73", "74", "75"];
|
||||
const wantedIds = [
|
||||
"60",
|
||||
"67",
|
||||
"68",
|
||||
"69",
|
||||
"70",
|
||||
"71",
|
||||
"72",
|
||||
"73",
|
||||
"74",
|
||||
"75",
|
||||
];
|
||||
|
||||
// Daten mit react-query laden
|
||||
const {data = [], isLoading, error} = useQuery<ItemWithFSImage[]>({
|
||||
queryKey: ['fetchFarmingStationItemList'],
|
||||
const {
|
||||
data = [],
|
||||
isLoading,
|
||||
error,
|
||||
} = useQuery<ItemWithFSImage[]>({
|
||||
queryKey: ["fetchFarmingStationItemList"],
|
||||
queryFn: fetchFarmingStationItemList,
|
||||
retry: 3,
|
||||
retryDelay: 1000,
|
||||
@@ -31,37 +46,51 @@ export default function FSComponents() {
|
||||
|
||||
// Button-Funktion: alle gefilterten Items in den Warenkorb packen
|
||||
const handleAddAllToCart = () => {
|
||||
data.forEach(item => {
|
||||
data.forEach((item) => {
|
||||
addToBasket(item, 1);
|
||||
});
|
||||
};
|
||||
|
||||
if (isLoading) return <Typography>{t('loading')}</Typography>;
|
||||
if (error) return <Typography color="error">{t('errorLoadingItems')}</Typography>;
|
||||
if (isLoading) return <Typography>{t("loading")}</Typography>;
|
||||
if (error)
|
||||
return <Typography color="error">{t("errorLoadingItems")}</Typography>;
|
||||
|
||||
return (
|
||||
<Box sx={{width: '100%', display: 'flex', maxWidth: 1600, mx: 'auto', pt: 2, height: '100vh'}}>
|
||||
<Box
|
||||
sx={{
|
||||
width: "100%",
|
||||
display: "flex",
|
||||
maxWidth: 1600,
|
||||
mx: "auto",
|
||||
pt: 2,
|
||||
height: "100vh",
|
||||
}}
|
||||
>
|
||||
{/* Bild links */}
|
||||
<Box sx={{
|
||||
width: 'auto',
|
||||
height: '90vh',
|
||||
position: 'sticky',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
<Box
|
||||
sx={{
|
||||
width: "auto",
|
||||
height: "90vh",
|
||||
position: "sticky",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
padding: 2,
|
||||
overflow: 'hidden',
|
||||
}}>
|
||||
overflow: "hidden",
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
component="img"
|
||||
src={hoverIndex !== null ? data[hoverIndex].farmImage : farmingStation}
|
||||
alt={t('componentsFarmingStation')}
|
||||
src={
|
||||
hoverIndex !== null ? data[hoverIndex].farmImage : farmingStation
|
||||
}
|
||||
alt={t("componentsFarmingStation")}
|
||||
sx={{
|
||||
width: '100%',
|
||||
height: 'auto',
|
||||
maxHeight: '80vh',
|
||||
objectFit: 'contain',
|
||||
width: "100%",
|
||||
height: "auto",
|
||||
maxHeight: "80vh",
|
||||
objectFit: "contain",
|
||||
borderRadius: 2,
|
||||
border: `4px solid ${theme.palette.primary.main}`,
|
||||
marginBottom: 2,
|
||||
@@ -73,20 +102,27 @@ export default function FSComponents() {
|
||||
startIcon={<AddShoppingCartIcon />}
|
||||
onClick={handleAddAllToCart}
|
||||
>
|
||||
{t('addAllToCart')}
|
||||
{t("addAllToCart")}
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
{/* Items rechts */}
|
||||
<Box sx={{
|
||||
width: '60%',
|
||||
height: '90vh',
|
||||
overflowY: 'auto',
|
||||
<Box
|
||||
sx={{
|
||||
width: "60%",
|
||||
height: "90vh",
|
||||
overflowY: "auto",
|
||||
padding: 2,
|
||||
}}>
|
||||
}}
|
||||
>
|
||||
<Box mb={2}>
|
||||
<Typography variant="h4" align="center" gutterBottom sx={{color: 'text.primary'}}>
|
||||
{t('componentsFarmingStation')}
|
||||
<Typography
|
||||
variant="h4"
|
||||
align="center"
|
||||
gutterBottom
|
||||
sx={{ color: "text.primary" }}
|
||||
>
|
||||
{t("componentsFarmingStation")}
|
||||
</Typography>
|
||||
</Box>
|
||||
<Box className="cardgrid">
|
||||
|
||||
@@ -7,38 +7,40 @@ import ItemWithImage from "../components/Item";
|
||||
import FilterItem from "../helper/homepage/FilterItem";
|
||||
import ItemCard from "../helper/homepage/ItemCard";
|
||||
import PriceSlider from "../helper/homepage/PriceSlider";
|
||||
import {fetchItemListWithImage} from '../helper/query/Queries';
|
||||
import { fetchItemListWithImage } from "../helper/query/Queries";
|
||||
import "./pages.css"; // Import der CSS-Datei
|
||||
|
||||
export default function Home() {
|
||||
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const theme = useTheme();
|
||||
const [searchQuery, setSearchQuery] = useState<string | null>(null);
|
||||
|
||||
const categoriesFilter = useMemo(() => [
|
||||
const categoriesFilter = useMemo(
|
||||
() => [
|
||||
{ value: "", label: t("allCategories") },
|
||||
{ value: "Seeds", label: t("seeds") },
|
||||
{ value: "GardenSupplies", label: t("gardenSupplies") },
|
||||
{ value: "TechnicalComponents", label: t("technicalComponents") },
|
||||
{value: "Other", label: t("other")}
|
||||
], [t]);
|
||||
{ value: "Other", label: t("other") },
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
const ratingFilter = [
|
||||
{value: "", label: t('allRatings')},
|
||||
...[5, 4, 3, 2, 1].map(value => ({
|
||||
{ value: "", label: t("allRatings") },
|
||||
...[5, 4, 3, 2, 1].map((value) => ({
|
||||
value: value.toString(),
|
||||
label: value.toString()
|
||||
}))
|
||||
label: value.toString(),
|
||||
})),
|
||||
];
|
||||
|
||||
const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
|
||||
const [selectedRating, setSelectedRating] = useState<string | null>(null);
|
||||
|
||||
const { data = [], isLoading } = useQuery<ItemWithImage[]>({
|
||||
queryKey: ['fetchItemListWithImage'],
|
||||
queryKey: ["fetchItemListWithImage"],
|
||||
queryFn: fetchItemListWithImage,
|
||||
retry: 3, // Versucht es 3-mal erneut
|
||||
retryDelay: 1000, // Wartezeit zwischen den Versuchen (in ms)
|
||||
@@ -47,10 +49,12 @@ export default function Home() {
|
||||
const items: ItemWithImage[] = useMemo(() => data || [], [data]);
|
||||
|
||||
const discountedPrices = items.map(
|
||||
(item) => item.price100 * (1 - item.discount100 / 100)
|
||||
(item) => item.price100 * (1 - item.discount100 / 100),
|
||||
);
|
||||
const minPrice = discountedPrices.length > 0 ? Math.min(...discountedPrices) : 0;
|
||||
const maxPrice = discountedPrices.length > 0 ? Math.max(...discountedPrices) : 1000;
|
||||
const minPrice =
|
||||
discountedPrices.length > 0 ? Math.min(...discountedPrices) : 0;
|
||||
const maxPrice =
|
||||
discountedPrices.length > 0 ? Math.max(...discountedPrices) : 1000;
|
||||
const [priceRange, setPriceRange] = useState<[number, number]>([
|
||||
minPrice,
|
||||
maxPrice,
|
||||
@@ -72,7 +76,9 @@ export default function Home() {
|
||||
return items
|
||||
.filter((item) => {
|
||||
const discountedPrice = item.price100 * (1 - item.discount100 / 100);
|
||||
return discountedPrice >= priceRange[0] && discountedPrice <= priceRange[1];
|
||||
return (
|
||||
discountedPrice >= priceRange[0] && discountedPrice <= priceRange[1]
|
||||
);
|
||||
})
|
||||
.filter((item) => {
|
||||
if (!selectedCategory) return true;
|
||||
@@ -81,16 +87,14 @@ export default function Home() {
|
||||
.filter((item) => {
|
||||
if (!selectedRating) return true;
|
||||
const rating = item.rating;
|
||||
return rating >= (Number(selectedRating) * 2);
|
||||
return rating >= Number(selectedRating) * 2;
|
||||
})
|
||||
.filter((item) => {
|
||||
if (!searchQuery) return true;
|
||||
return (item.name.toLowerCase().includes(searchQuery.toLowerCase())
|
||||
);
|
||||
return item.name.toLowerCase().includes(searchQuery.toLowerCase());
|
||||
});
|
||||
}, [items, priceRange, selectedCategory, selectedRating, searchQuery]);
|
||||
|
||||
|
||||
// Lese die Suchanfrage aus der URL
|
||||
useEffect(() => {
|
||||
const params = new URLSearchParams(location.search);
|
||||
@@ -98,7 +102,6 @@ export default function Home() {
|
||||
setSearchQuery(query);
|
||||
}, [location.search]);
|
||||
|
||||
|
||||
// Container Ref
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
@@ -157,7 +160,7 @@ export default function Home() {
|
||||
}}
|
||||
/>
|
||||
<FilterItem
|
||||
filterName={t("rating")}
|
||||
filterName={t("ratingFrom")}
|
||||
filterItems={ratingFilter}
|
||||
value={selectedRating}
|
||||
onChange={handleRatingChange}
|
||||
@@ -167,8 +170,9 @@ export default function Home() {
|
||||
className="home-page-background"
|
||||
style={{ backgroundColor: theme.palette.homepage }}
|
||||
>
|
||||
{isLoading && t('loading')}
|
||||
{!isLoading && <main
|
||||
{isLoading && t("loading")}
|
||||
{!isLoading && (
|
||||
<main
|
||||
className="page-background page-background-center"
|
||||
ref={containerRef}
|
||||
>
|
||||
@@ -180,7 +184,7 @@ export default function Home() {
|
||||
sx={{
|
||||
bgcolor: theme.palette.error.main,
|
||||
color: theme.palette.getContrastText(
|
||||
theme.palette.error.main
|
||||
theme.palette.error.main,
|
||||
),
|
||||
width: "100%",
|
||||
justifyContent: "center",
|
||||
@@ -189,12 +193,13 @@ export default function Home() {
|
||||
{t("noItemsFound")}
|
||||
</Alert>
|
||||
) : (
|
||||
filteredItems.map(item => (
|
||||
filteredItems.map((item) => (
|
||||
<ItemCard key={item.id} item={item} />
|
||||
))
|
||||
)}
|
||||
</Box>
|
||||
</main>}
|
||||
</main>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -4,7 +4,6 @@ import "./pages.css";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
export default function NoPage() {
|
||||
|
||||
const theme = useTheme();
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
@@ -22,10 +21,10 @@ export default function NoPage() {
|
||||
404
|
||||
</Typography>
|
||||
<Typography variant="h5" className="no-page-subtitle">
|
||||
{t('pageDoesNotExist')}
|
||||
{t("pageDoesNotExist")}
|
||||
</Typography>
|
||||
<Typography variant="body1" className="no-page-description">
|
||||
{t('wrongTurn')}
|
||||
{t("wrongTurn")}
|
||||
</Typography>
|
||||
<Button
|
||||
variant="contained"
|
||||
@@ -34,7 +33,7 @@ export default function NoPage() {
|
||||
className="no-page-button"
|
||||
onClick={handleGoHome}
|
||||
>
|
||||
{t('backToHome')}
|
||||
{t("backToHome")}
|
||||
</Button>
|
||||
</Box>
|
||||
);
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
Stack,
|
||||
Tab,
|
||||
Tabs,
|
||||
Typography
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useEffect, useState } from "react";
|
||||
@@ -24,13 +24,12 @@ import {useAccount} from "../helper/AccountProvider";
|
||||
import { fetchOrders, orderPatch } from "../helper/query/Queries";
|
||||
|
||||
export default function Orders() {
|
||||
|
||||
const { user } = useAccount();
|
||||
const [orders, setOrders] = useState<OrderType[]>([])
|
||||
const [orders, setOrders] = useState<OrderType[]>([]);
|
||||
|
||||
const { data: accountOrders, refetch } = useQuery<OrderType[]>({
|
||||
queryKey: ['fetchOrders', user?.customerId], // Hier sollte die tatsächliche Kunden-ID verwendet werden
|
||||
queryFn: () => user ? fetchOrders(user.customerId) : Promise.resolve([]), // Simulierte API-Antwort
|
||||
queryKey: ["fetchOrders", user?.customerId], // Hier sollte die tatsächliche Kunden-ID verwendet werden
|
||||
queryFn: () => (user ? fetchOrders(user.customerId) : Promise.resolve([])), // Simulierte API-Antwort
|
||||
enabled: !!user, // Nur ausführen, wenn user existiert
|
||||
retry: 3, // Versucht es 3-mal erneut
|
||||
retryDelay: 1000, // Wartezeit zwischen den Versuchen (in ms)
|
||||
@@ -46,15 +45,31 @@ export default function Orders() {
|
||||
const [tab, setTab] = useState(0);
|
||||
const [selectedOrder, setSelectedOrder] = useState<OrderType | null>(null);
|
||||
|
||||
const activeOrders = orders.filter(o => o.status === OrderStatusEnum.ISSUES || o.status === OrderStatusEnum.IN_PROGRESS || o.status === OrderStatusEnum.ORDERED);
|
||||
const inactiveOrders = orders.filter(o => o.status === OrderStatusEnum.CANCELLED || o.status === OrderStatusEnum.DELIVERED);
|
||||
|
||||
const handleTabChange = (_: React.SyntheticEvent, newValue: number) => setTab(newValue);
|
||||
const activeOrders = orders.filter(
|
||||
(o) =>
|
||||
o.status === OrderStatusEnum.ISSUES ||
|
||||
o.status === OrderStatusEnum.IN_PROGRESS ||
|
||||
o.status === OrderStatusEnum.ORDERED,
|
||||
);
|
||||
const inactiveOrders = orders.filter(
|
||||
(o) =>
|
||||
o.status === OrderStatusEnum.CANCELLED ||
|
||||
o.status === OrderStatusEnum.DELIVERED,
|
||||
);
|
||||
|
||||
const handleTabChange = (_: React.SyntheticEvent, newValue: number) =>
|
||||
setTab(newValue);
|
||||
|
||||
const { refetch: cancleOrder } = useQuery({
|
||||
queryKey: ["orderPatch", {id: selectedOrder?.id || -1, status: OrderStatusEnum.CANCELLED}],
|
||||
queryFn: () => orderPatch({id: selectedOrder?.id || -1, status: OrderStatusEnum.CANCELLED}),
|
||||
queryKey: [
|
||||
"orderPatch",
|
||||
{ id: selectedOrder?.id || -1, status: OrderStatusEnum.CANCELLED },
|
||||
],
|
||||
queryFn: () =>
|
||||
orderPatch({
|
||||
id: selectedOrder?.id || -1,
|
||||
status: OrderStatusEnum.CANCELLED,
|
||||
}),
|
||||
retry: 0,
|
||||
retryDelay: 1000,
|
||||
enabled: false,
|
||||
@@ -67,59 +82,79 @@ export default function Orders() {
|
||||
};
|
||||
|
||||
return (
|
||||
<Box className="page-background page-background-center" sx={{minHeight: "100vh", pt: 4}}>
|
||||
<Paper elevation={3} sx={{p: 4, maxWidth: 700, width: "100%", mx: "auto"}}>
|
||||
<Box
|
||||
className="page-background page-background-center"
|
||||
sx={{ minHeight: "100vh", pt: 4 }}
|
||||
>
|
||||
<Paper
|
||||
elevation={3}
|
||||
sx={{ p: 4, maxWidth: 700, width: "100%", mx: "auto" }}
|
||||
>
|
||||
<Typography variant="h4" gutterBottom>
|
||||
{t('myOrders')}
|
||||
{t("myOrders")}
|
||||
</Typography>
|
||||
<Tabs value={tab} onChange={handleTabChange} sx={{ mb: 3 }}>
|
||||
<Tab label={t('active')}/>
|
||||
<Tab label={t('previous')}/>
|
||||
<Tab label={t("active")} />
|
||||
<Tab label={t("previous")} />
|
||||
</Tabs>
|
||||
<Divider sx={{ mb: 2 }} />
|
||||
{tab === 0 ? (
|
||||
activeOrders.length > 0 ? (
|
||||
<List>
|
||||
{activeOrders.map(order => (
|
||||
<ListItemButton key={order.id} onClick={() => setSelectedOrder(order)}>
|
||||
{activeOrders.map((order) => (
|
||||
<ListItemButton
|
||||
key={order.id}
|
||||
onClick={() => setSelectedOrder(order)}
|
||||
>
|
||||
<ListItemText
|
||||
primary={`${t('order')} #${order.id} • ${order.status} • ${new Date(order.time).toUTCString()}`}
|
||||
secondary={`${t('sum')}: ${(order.total / 100).toFixed(2)} € • ${order.orderItems.length} ${t('items')}`}
|
||||
primary={`${t("order")} #${order.id} • ${order.status} • ${new Date(order.time).toUTCString()}`}
|
||||
secondary={`${t("sum")}: ${(order.total / 100).toFixed(2)} € • ${order.orderItems.length} ${t("items")}`}
|
||||
/>
|
||||
</ListItemButton>
|
||||
))}
|
||||
</List>
|
||||
) : (
|
||||
<Typography color="text.secondary">{t('noActiveOrders')}</Typography>
|
||||
<Typography color="text.secondary">
|
||||
{t("noActiveOrders")}
|
||||
</Typography>
|
||||
)
|
||||
) : (
|
||||
inactiveOrders.length > 0 ? (
|
||||
) : inactiveOrders.length > 0 ? (
|
||||
<List>
|
||||
{inactiveOrders.map(order => (
|
||||
<ListItemButton key={order.id} onClick={() => setSelectedOrder(order)}>
|
||||
{inactiveOrders.map((order) => (
|
||||
<ListItemButton
|
||||
key={order.id}
|
||||
onClick={() => setSelectedOrder(order)}
|
||||
>
|
||||
<ListItemText
|
||||
primary={`${t('order')} #${order.id} • ${order.status} • ${new Date(order.time).toUTCString()}`}
|
||||
secondary={`${t('sum')}: ${(order.total / 100).toFixed(2)} € • ${order.orderItems.length} ${t('items')}`}
|
||||
primary={`${t("order")} #${order.id} • ${order.status} • ${new Date(order.time).toUTCString()}`}
|
||||
secondary={`${t("sum")}: ${(order.total / 100).toFixed(2)} € • ${order.orderItems.length} ${t("items")}`}
|
||||
/>
|
||||
</ListItemButton>
|
||||
))}
|
||||
</List>
|
||||
) : (
|
||||
<Typography color="text.secondary">{t('noPreviousOrders')}</Typography>
|
||||
)
|
||||
<Typography color="text.secondary">
|
||||
{t("noPreviousOrders")}
|
||||
</Typography>
|
||||
)}
|
||||
|
||||
<Dialog open={!!selectedOrder} onClose={() => setSelectedOrder(null)} maxWidth="sm" fullWidth>
|
||||
<Dialog
|
||||
open={!!selectedOrder}
|
||||
onClose={() => setSelectedOrder(null)}
|
||||
maxWidth="sm"
|
||||
fullWidth
|
||||
>
|
||||
<DialogTitle>
|
||||
{`${selectedOrder?.status === OrderStatusEnum.IN_PROGRESS ? t('activeOrder') : t('previousOrder')} #${selectedOrder?.id}`}
|
||||
{`${selectedOrder?.status === OrderStatusEnum.IN_PROGRESS ? t("activeOrder") : t("previousOrder")} #${selectedOrder?.id}`}
|
||||
</DialogTitle>
|
||||
<DialogContent dividers>
|
||||
{selectedOrder && (
|
||||
<Stack spacing={2}>
|
||||
<Typography
|
||||
variant="subtitle1">{`${t('orderDate')}: ${new Date(selectedOrder.time).toUTCString()}`}</Typography>
|
||||
<Typography variant="subtitle1">{`${t("orderDate")}: ${new Date(selectedOrder.time).toUTCString()}`}</Typography>
|
||||
<Divider />
|
||||
<Typography variant="subtitle2">{t('orderedItems')}:</Typography>
|
||||
<Typography variant="subtitle2">
|
||||
{t("orderedItems")}:
|
||||
</Typography>
|
||||
<List dense>
|
||||
{selectedOrder.orderItems.map((item, idx) => (
|
||||
<ListItemText
|
||||
@@ -129,18 +164,19 @@ export default function Orders() {
|
||||
))}
|
||||
</List>
|
||||
<Divider />
|
||||
<Typography
|
||||
variant="h6">{`${t('sum')}: ${(selectedOrder.total / 100).toFixed(2)} €`}</Typography>
|
||||
<Typography variant="h6">{`${t("sum")}: ${(selectedOrder.total / 100).toFixed(2)} €`}</Typography>
|
||||
</Stack>
|
||||
)}
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
{(selectedOrder?.status === OrderStatusEnum.ISSUES || selectedOrder?.status === OrderStatusEnum.IN_PROGRESS || selectedOrder?.status === OrderStatusEnum.ORDERED) && (
|
||||
{(selectedOrder?.status === OrderStatusEnum.ISSUES ||
|
||||
selectedOrder?.status === OrderStatusEnum.IN_PROGRESS ||
|
||||
selectedOrder?.status === OrderStatusEnum.ORDERED) && (
|
||||
<Button color="error" onClick={() => handleCancelOrder()}>
|
||||
{t('cancelOrder')}
|
||||
{t("cancelOrder")}
|
||||
</Button>
|
||||
)}
|
||||
<Button onClick={() => setSelectedOrder(null)}>{t('close')}</Button>
|
||||
<Button onClick={() => setSelectedOrder(null)}>{t("close")}</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
</Paper>
|
||||
|
||||
@@ -13,28 +13,35 @@ import {
|
||||
StepLabel,
|
||||
Stepper,
|
||||
TextField,
|
||||
Typography
|
||||
} from '@mui/material';
|
||||
import {useMutation, useQuery} from '@tanstack/react-query';
|
||||
import {TFunction} from 'i18next';
|
||||
import React, {useEffect, useState} from 'react';
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import { TFunction } from "i18next";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {useNavigate} from 'react-router-dom';
|
||||
import {CustomerType} from '../components/Account';
|
||||
import Item from '../components/Item';
|
||||
import OrderType, {OrderStatusEnum} from '../components/Order';
|
||||
import {useAccount} from '../helper/AccountProvider';
|
||||
import {BasketItem, useBasket} from '../helper/BasketProvider';
|
||||
import {fetchCustomer, submitCustomer, submitOrder} from '../helper/query/Queries';
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { CustomerType } from "../components/Account";
|
||||
import Item from "../components/Item";
|
||||
import OrderType, { OrderStatusEnum } from "../components/Order";
|
||||
import { useAccount } from "../helper/AccountProvider";
|
||||
import { BasketItem, useBasket } from "../helper/BasketProvider";
|
||||
import {
|
||||
fetchCustomer,
|
||||
submitCustomer,
|
||||
submitOrder,
|
||||
} from "../helper/query/Queries";
|
||||
|
||||
function getDiscountedPrice(item: Item): number {
|
||||
return (item.price100 / 100 * (100 - item.discount100) / 100);
|
||||
return ((item.price100 / 100) * (100 - item.discount100)) / 100;
|
||||
}
|
||||
|
||||
function generateBasket(t: TFunction<"translation", undefined>, basket: BasketItem[]) {
|
||||
function generateBasket(
|
||||
t: TFunction<"translation", undefined>,
|
||||
basket: BasketItem[],
|
||||
) {
|
||||
return basket.length === 0 ? (
|
||||
<Typography color="error" sx={{ my: 2 }}>
|
||||
{t('basketEmpty')}
|
||||
{t("basketEmpty")}
|
||||
</Typography>
|
||||
) : (
|
||||
<List>
|
||||
@@ -46,40 +53,59 @@ function generateBasket(t: TFunction<"translation", undefined>, basket: BasketIt
|
||||
/>
|
||||
|
||||
<div className="rightBound">
|
||||
{`${(item.quantity * getDiscountedPrice(item.item)).toFixed(2)} €`}<br/>
|
||||
{item.item.discount100 > 0 ? <a className='rightBound red'>{-item.item.discount100}%</a> : ""}
|
||||
{`${(item.quantity * getDiscountedPrice(item.item)).toFixed(2)} €`}
|
||||
<br />
|
||||
{item.item.discount100 > 0 ? (
|
||||
<a className="rightBound red">{-item.item.discount100}%</a>
|
||||
) : (
|
||||
""
|
||||
)}
|
||||
</div>
|
||||
</ListItem>
|
||||
))}
|
||||
</List>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function generateTotal(t: TFunction<"translation", undefined>, basket: BasketItem[]) {
|
||||
return basket.length === 0 ? "" :
|
||||
<div className='rightBound'>
|
||||
{t('total') + ": " + basket.map((item) => item.quantity * getDiscountedPrice(item.item))
|
||||
.reduce((prev: number, cur: number) => prev + cur, 0).toFixed(2) + ` €`}
|
||||
function generateTotal(
|
||||
t: TFunction<"translation", undefined>,
|
||||
basket: BasketItem[],
|
||||
) {
|
||||
return basket.length === 0 ? (
|
||||
""
|
||||
) : (
|
||||
<div className="rightBound">
|
||||
{t("total") +
|
||||
": " +
|
||||
basket
|
||||
.map((item) => item.quantity * getDiscountedPrice(item.item))
|
||||
.reduce((prev: number, cur: number) => prev + cur, 0)
|
||||
.toFixed(2) +
|
||||
` €`}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Payment() {
|
||||
|
||||
|
||||
const { t } = useTranslation();
|
||||
const { basket, clearBasket } = useBasket();
|
||||
const navigator = useNavigate();
|
||||
const [activeStep, setActiveStep] = useState(0);
|
||||
const [shippingDetails, setShippingDetails] = useState<CustomerType>({
|
||||
id: 0, // This will be set by the backend or user data
|
||||
name: '',
|
||||
surname: '',
|
||||
address: '',
|
||||
zip: '',
|
||||
country: 'Deutschland',
|
||||
name: "",
|
||||
surname: "",
|
||||
address: "",
|
||||
zip: "",
|
||||
country: "Deutschland",
|
||||
});
|
||||
const [orderNumber, setOrderNumber] = useState<string | null>(null);
|
||||
const steps = [t('reviewCart'), t('shippingDetails'), t('payment'), t('orderSummary')];
|
||||
const steps = [
|
||||
t("reviewCart"),
|
||||
t("shippingDetails"),
|
||||
t("payment"),
|
||||
t("orderSummary"),
|
||||
];
|
||||
const { user } = useAccount();
|
||||
|
||||
const submitOrderData: OrderType = {
|
||||
@@ -87,12 +113,15 @@ export default function Payment() {
|
||||
customerId: user ? user.customerId : 0, // Use user ID if logged in, otherwise 0
|
||||
time: Date.now(),
|
||||
status: OrderStatusEnum.ORDERED, // Initial status when order is placed
|
||||
orderItems: basket.map(item => ({
|
||||
orderItems: basket.map((item) => ({
|
||||
id: item.item.id,
|
||||
amount: item.quantity,
|
||||
article: item.item.uuid, // Assuming UUID is the identifier for the item
|
||||
})),
|
||||
total: basket.reduce((total, item) => total + (item.quantity * getDiscountedPrice(item.item)), 0),
|
||||
total: basket.reduce(
|
||||
(total, item) => total + item.quantity * getDiscountedPrice(item.item),
|
||||
0,
|
||||
),
|
||||
};
|
||||
|
||||
const { refetch: refetchCustomer } = useQuery({
|
||||
@@ -104,15 +133,13 @@ export default function Payment() {
|
||||
});
|
||||
|
||||
const showAlert = () => {
|
||||
return <Alert>
|
||||
//TODO:
|
||||
</Alert>
|
||||
return <Alert>//TODO:</Alert>;
|
||||
};
|
||||
|
||||
const { refetch: customerData } = useQuery<CustomerType>({
|
||||
queryKey: ['fetchCustomer', user?.customerId],
|
||||
queryKey: ["fetchCustomer", user?.customerId],
|
||||
queryFn: () => fetchCustomer(user?.customerId || 0), // Funktion zum Abrufen der Kundendaten
|
||||
enabled: false
|
||||
enabled: false,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
@@ -130,7 +157,6 @@ export default function Payment() {
|
||||
fetchShippingDetails();
|
||||
}, [user, customerData]);
|
||||
|
||||
|
||||
// Verwende useMutation statt useQuery für submitOrder
|
||||
const { mutateAsync: submitOrderMutation } = useMutation({
|
||||
mutationFn: (orderData: OrderType) => submitOrder(orderData),
|
||||
@@ -188,11 +214,11 @@ export default function Payment() {
|
||||
// Hilfsfunktion prüfen, ob alle Pflichtfelder ausgefüllt sind
|
||||
const isShippingDetailsValid = () => {
|
||||
return (
|
||||
shippingDetails.name.trim() !== '' &&
|
||||
shippingDetails.surname.trim() !== '' &&
|
||||
shippingDetails.address.trim() !== '' &&
|
||||
shippingDetails.zip.trim() !== '' &&
|
||||
shippingDetails.country.trim() !== ''
|
||||
shippingDetails.name.trim() !== "" &&
|
||||
shippingDetails.surname.trim() !== "" &&
|
||||
shippingDetails.address.trim() !== "" &&
|
||||
shippingDetails.zip.trim() !== "" &&
|
||||
shippingDetails.country.trim() !== ""
|
||||
);
|
||||
};
|
||||
|
||||
@@ -202,13 +228,17 @@ export default function Payment() {
|
||||
return (
|
||||
<Box>
|
||||
<Typography variant="h6" gutterBottom>
|
||||
{t('reviewCart')}
|
||||
{t("reviewCart")}
|
||||
</Typography>
|
||||
{generateBasket(t, basket)}
|
||||
<Divider sx={{ my: 2 }} />
|
||||
<Button variant="outlined" color="error" onClick={handleClearBasket}
|
||||
disabled={basket.length === 0}>
|
||||
{t('clearCart')}
|
||||
<Button
|
||||
variant="outlined"
|
||||
color="error"
|
||||
onClick={handleClearBasket}
|
||||
disabled={basket.length === 0}
|
||||
>
|
||||
{t("clearCart")}
|
||||
</Button>
|
||||
{generateTotal(t, basket)}
|
||||
</Box>
|
||||
@@ -217,13 +247,12 @@ export default function Payment() {
|
||||
return (
|
||||
<Box>
|
||||
<Typography variant="h6" gutterBottom>
|
||||
{t('shippingDetails')}
|
||||
{t("shippingDetails")}
|
||||
</Typography>
|
||||
<Grid container spacing={2}>
|
||||
|
||||
<TextField
|
||||
fullWidth
|
||||
label={t('firstName')}
|
||||
label={t("firstName")}
|
||||
name="name"
|
||||
value={shippingDetails.name}
|
||||
onChange={handleInputChange}
|
||||
@@ -232,7 +261,7 @@ export default function Payment() {
|
||||
|
||||
<TextField
|
||||
fullWidth
|
||||
label={t('lastName')}
|
||||
label={t("lastName")}
|
||||
name="surname"
|
||||
value={shippingDetails.surname}
|
||||
onChange={handleInputChange}
|
||||
@@ -241,7 +270,7 @@ export default function Payment() {
|
||||
|
||||
<TextField
|
||||
fullWidth
|
||||
label={t('address')}
|
||||
label={t("address")}
|
||||
name="address"
|
||||
value={shippingDetails.address}
|
||||
onChange={handleInputChange}
|
||||
@@ -250,7 +279,7 @@ export default function Payment() {
|
||||
|
||||
<TextField
|
||||
fullWidth
|
||||
label={t('postalCode')}
|
||||
label={t("postalCode")}
|
||||
name="zip"
|
||||
value={shippingDetails.zip}
|
||||
onChange={handleInputChange}
|
||||
@@ -259,7 +288,7 @@ export default function Payment() {
|
||||
|
||||
<TextField
|
||||
fullWidth
|
||||
label={t('country')}
|
||||
label={t("country")}
|
||||
name="country"
|
||||
value={shippingDetails.country}
|
||||
onChange={handleInputChange}
|
||||
@@ -272,34 +301,35 @@ export default function Payment() {
|
||||
return (
|
||||
<Box>
|
||||
<Typography variant="h6" gutterBottom>
|
||||
{t('payment')}
|
||||
</Typography>
|
||||
<Typography variant="body1">
|
||||
{t('paymentNotAvailable')}
|
||||
{t("payment")}
|
||||
</Typography>
|
||||
<Typography variant="body1">{t("paymentNotAvailable")}</Typography>
|
||||
</Box>
|
||||
);
|
||||
case 3:
|
||||
return (
|
||||
<Box>
|
||||
<Typography variant="h6" gutterBottom>
|
||||
{t('orderSummary')}
|
||||
{t("orderSummary")}
|
||||
</Typography>
|
||||
<Typography variant="body1" gutterBottom>
|
||||
{t('thanksForOrder')}
|
||||
{t("thanksForOrder")}
|
||||
</Typography>
|
||||
<Typography variant="body2" gutterBottom>
|
||||
{t('yourOrderNumber')}: <strong>{orderNumber}</strong>
|
||||
{t("yourOrderNumber")}: <strong>{orderNumber}</strong>
|
||||
</Typography>
|
||||
<Divider sx={{ my: 2 }} />
|
||||
<Typography variant="h6">{t('shippingDetails')}:</Typography>
|
||||
<Typography variant="h6">{t("shippingDetails")}:</Typography>
|
||||
<Typography variant="body2">
|
||||
{shippingDetails.name} {shippingDetails.surname}<br/>
|
||||
{shippingDetails.address}<br/>
|
||||
{shippingDetails.zip} {shippingDetails.country}<br/>
|
||||
{shippingDetails.name} {shippingDetails.surname}
|
||||
<br />
|
||||
{shippingDetails.address}
|
||||
<br />
|
||||
{shippingDetails.zip} {shippingDetails.country}
|
||||
<br />
|
||||
</Typography>
|
||||
<Divider sx={{ my: 2 }} />
|
||||
<Typography variant="h6">{t('orderedItems')}:</Typography>
|
||||
<Typography variant="h6">{t("orderedItems")}:</Typography>
|
||||
{generateBasket(t, basket)}
|
||||
<Divider sx={{ my: 2 }} />
|
||||
{generateTotal(t, basket)}
|
||||
@@ -317,13 +347,13 @@ export default function Payment() {
|
||||
maxWidth="md"
|
||||
sx={{
|
||||
py: 4,
|
||||
maxHeight: '90vh',
|
||||
overflowY: 'auto'
|
||||
maxHeight: "90vh",
|
||||
overflowY: "auto",
|
||||
}}
|
||||
>
|
||||
<Paper elevation={3} sx={{ p: 4 }}>
|
||||
<Typography variant="h4" align="center" gutterBottom>
|
||||
{t('completeYourOrder')}
|
||||
{t("completeYourOrder")}
|
||||
</Typography>
|
||||
<Stepper activeStep={activeStep} alternativeLabel>
|
||||
{steps.map((label) => (
|
||||
@@ -333,13 +363,13 @@ export default function Payment() {
|
||||
))}
|
||||
</Stepper>
|
||||
<Box sx={{ mt: 4 }}>{renderStepContent(activeStep)}</Box>
|
||||
<Box sx={{display: 'flex', justifyContent: 'space-between', mt: 4}}>
|
||||
<Box sx={{ display: "flex", justifyContent: "space-between", mt: 4 }}>
|
||||
<Button
|
||||
disabled={activeStep === 0}
|
||||
onClick={handleBack}
|
||||
variant="outlined"
|
||||
>
|
||||
{t('back')}
|
||||
{t("back")}
|
||||
</Button>
|
||||
{activeStep === steps.length - 1 ? (
|
||||
<Button
|
||||
@@ -347,10 +377,10 @@ export default function Payment() {
|
||||
color="primary"
|
||||
onClick={() => {
|
||||
handleClearBasket();
|
||||
navigator('/');
|
||||
navigator("/");
|
||||
}}
|
||||
>
|
||||
{t('finish')}
|
||||
{t("finish")}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
@@ -362,7 +392,7 @@ export default function Payment() {
|
||||
(activeStep === 1 && !isShippingDetailsValid())
|
||||
}
|
||||
>
|
||||
{activeStep === steps.length - 2 ? t('placeOrder') : t('next')}
|
||||
{activeStep === steps.length - 2 ? t("placeOrder") : t("next")}
|
||||
</Button>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import {Box, Button, Container, Divider, Typography} from '@mui/material';
|
||||
import {useLocation, useNavigate} from 'react-router-dom';
|
||||
import Item from '../components/Item';
|
||||
import ProductInfo from '../helper/productpage/ProductInfo';
|
||||
import Ratings from '../helper/productpage/Ratings';
|
||||
import { Box, Button, Container, Divider, Typography } from "@mui/material";
|
||||
import { useLocation, useNavigate } from "react-router-dom";
|
||||
import Item from "../components/Item";
|
||||
import ProductInfo from "../helper/productpage/ProductInfo";
|
||||
import Ratings from "../helper/productpage/Ratings";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {useTheme} from '@mui/material/styles';
|
||||
import { useTheme } from "@mui/material/styles";
|
||||
|
||||
export default function Product() {
|
||||
const { t } = useTranslation();
|
||||
@@ -22,32 +22,28 @@ export default function Product() {
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
height: '100vh',
|
||||
textAlign: 'center',
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
height: "100vh",
|
||||
textAlign: "center",
|
||||
backgroundColor: theme.palette.background.default,
|
||||
color: theme.palette.text.primary,
|
||||
gap: '2rem',
|
||||
overflow: 'auto',
|
||||
gap: "2rem",
|
||||
overflow: "auto",
|
||||
px: 2,
|
||||
}}
|
||||
>
|
||||
<Typography variant="h1">
|
||||
{t('productNotFound')}
|
||||
</Typography>
|
||||
<Typography variant="h5">
|
||||
{t('productDoesNotExist')}
|
||||
</Typography>
|
||||
<Typography variant="h1">{t("productNotFound")}</Typography>
|
||||
<Typography variant="h5">{t("productDoesNotExist")}</Typography>
|
||||
<Button
|
||||
variant="contained"
|
||||
color="primary"
|
||||
size="large"
|
||||
onClick={handleGoHome}
|
||||
>
|
||||
{t('backToHome')}
|
||||
{t("backToHome")}
|
||||
</Button>
|
||||
</Box>
|
||||
);
|
||||
@@ -58,8 +54,8 @@ export default function Product() {
|
||||
sx={{
|
||||
backgroundColor: theme.palette.background.default,
|
||||
color: theme.palette.text.primary,
|
||||
height: '100vh',
|
||||
overflow: 'auto',
|
||||
height: "100vh",
|
||||
overflow: "auto",
|
||||
pt: 4,
|
||||
pb: 10,
|
||||
}}
|
||||
@@ -75,7 +71,7 @@ export default function Product() {
|
||||
variant="body2"
|
||||
sx={{ color: theme.palette.text.secondary, mb: 1 }}
|
||||
>
|
||||
{t('articleNumber')}: {item.uuid}
|
||||
{t("articleNumber")}: {item.uuid}
|
||||
</Typography>
|
||||
|
||||
<Typography
|
||||
@@ -89,4 +85,4 @@ export default function Product() {
|
||||
</Container>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -150,7 +150,7 @@
|
||||
}
|
||||
|
||||
.sidebar-filter {
|
||||
margin: 30px
|
||||
margin: 30px;
|
||||
}
|
||||
|
||||
.no-results {
|
||||
@@ -166,5 +166,5 @@
|
||||
}
|
||||
|
||||
.red {
|
||||
color: #F00;
|
||||
color: #f00;
|
||||
}
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
'use client';
|
||||
import React, {createContext, ReactNode, useContext, useEffect, useState} from 'react';
|
||||
import {createTheme, ThemeProvider} from '@mui/material/styles';
|
||||
import {CssBaseline, GlobalStyles} from '@mui/material';
|
||||
import useMediaQuery from '@mui/material/useMediaQuery';
|
||||
"use client";
|
||||
import React, {
|
||||
createContext,
|
||||
ReactNode,
|
||||
useContext,
|
||||
useEffect,
|
||||
useState,
|
||||
} from "react";
|
||||
import { createTheme, ThemeProvider } from "@mui/material/styles";
|
||||
import { CssBaseline, GlobalStyles } from "@mui/material";
|
||||
import useMediaQuery from "@mui/material/useMediaQuery";
|
||||
|
||||
type ThemeMode = 'light' | 'dark';
|
||||
type ThemeMode = "light" | "dark";
|
||||
|
||||
interface ThemeContextType {
|
||||
mode: ThemeMode;
|
||||
@@ -12,9 +18,8 @@ interface ThemeContextType {
|
||||
}
|
||||
|
||||
const ThemeContext = createContext<ThemeContextType>({
|
||||
mode: 'light',
|
||||
toggleMode: () => {
|
||||
},
|
||||
mode: "light",
|
||||
toggleMode: () => {},
|
||||
});
|
||||
|
||||
export const useThemeMode = () => useContext(ThemeContext);
|
||||
@@ -23,47 +28,54 @@ interface CustomThemeProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export const CustomThemeProvider: React.FC<CustomThemeProviderProps> = ({children}) => {
|
||||
export const CustomThemeProvider: React.FC<CustomThemeProviderProps> = ({
|
||||
children,
|
||||
}) => {
|
||||
// SSR-sichere System-Präferenz-Erkennung
|
||||
const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)', {noSsr: true});
|
||||
const prefersDarkMode = useMediaQuery("(prefers-color-scheme: dark)", {
|
||||
noSsr: true,
|
||||
});
|
||||
|
||||
// SSR-sichere Initialisierung
|
||||
const [mode, setMode] = useState<ThemeMode>('light');
|
||||
const [mode, setMode] = useState<ThemeMode>("light");
|
||||
const [mounted, setMounted] = useState(false);
|
||||
|
||||
// Nach dem ersten Render ausführen (SSR-sicher)
|
||||
useEffect(() => {
|
||||
setMounted(true);
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
const savedMode = localStorage.getItem('themeMode') as ThemeMode;
|
||||
if (savedMode === 'light' || savedMode === 'dark') {
|
||||
if (typeof window !== "undefined") {
|
||||
const savedMode = localStorage.getItem("themeMode") as ThemeMode;
|
||||
if (savedMode === "light" || savedMode === "dark") {
|
||||
setMode(savedMode);
|
||||
} else {
|
||||
setMode(prefersDarkMode ? 'dark' : 'light');
|
||||
setMode(prefersDarkMode ? "dark" : "light");
|
||||
}
|
||||
}
|
||||
}, [prefersDarkMode]);
|
||||
|
||||
// Mode in localStorage speichern
|
||||
useEffect(() => {
|
||||
if (mounted && typeof window !== 'undefined') {
|
||||
localStorage.setItem('themeMode', mode);
|
||||
if (mounted && typeof window !== "undefined") {
|
||||
localStorage.setItem("themeMode", mode);
|
||||
}
|
||||
}, [mode, mounted]);
|
||||
|
||||
// Browser-only DOM-Manipulation
|
||||
useEffect(() => {
|
||||
if (mounted && typeof window !== 'undefined') {
|
||||
const backgroundColor = mode === 'dark' ? '#121212' : '#fafafa';
|
||||
if (mounted && typeof window !== "undefined") {
|
||||
const backgroundColor = mode === "dark" ? "#121212" : "#fafafa";
|
||||
|
||||
// Warten bis DOM geladen ist
|
||||
const updateBackground = () => {
|
||||
document.documentElement.style.setProperty('--background-color', backgroundColor);
|
||||
document.documentElement.style.setProperty(
|
||||
"--background-color",
|
||||
backgroundColor,
|
||||
);
|
||||
document.documentElement.style.backgroundColor = backgroundColor;
|
||||
document.body.style.backgroundColor = backgroundColor;
|
||||
|
||||
const root = document.getElementById('root');
|
||||
const root = document.getElementById("root");
|
||||
if (root) {
|
||||
root.style.backgroundColor = backgroundColor;
|
||||
}
|
||||
@@ -80,46 +92,52 @@ export const CustomThemeProvider: React.FC<CustomThemeProviderProps> = ({childre
|
||||
}, [mode, mounted]);
|
||||
|
||||
const toggleMode = () => {
|
||||
setMode(prevMode => prevMode === 'light' ? 'dark' : 'light');
|
||||
setMode((prevMode) => (prevMode === "light" ? "dark" : "light"));
|
||||
};
|
||||
|
||||
// Theme basierend auf Mode erstellen
|
||||
const theme = React.useMemo(() =>
|
||||
const theme = React.useMemo(
|
||||
() =>
|
||||
createTheme({
|
||||
palette: {
|
||||
mode,
|
||||
primary: {
|
||||
main: '#0fd13f', // Grüne NavBar
|
||||
light: mode === 'dark' ? '#4caf50' : '#42a5f5',
|
||||
dark: mode === 'dark' ? '#388e3c' : '#1565c0',
|
||||
contrastText: '#fff',
|
||||
main: "#0fd13f", // Grüne NavBar
|
||||
light: mode === "dark" ? "#4caf50" : "#42a5f5",
|
||||
dark: mode === "dark" ? "#388e3c" : "#1565c0",
|
||||
contrastText: "#fff",
|
||||
},
|
||||
secondary: {
|
||||
main: mode === 'dark' ? '#bb86fc' : '#9c27b0',
|
||||
light: mode === 'dark' ? '#d7aefb' : '#ba68c8',
|
||||
dark: mode === 'dark' ? '#985eff' : '#7b1fa2',
|
||||
contrastText: '#fff',
|
||||
main: mode === "dark" ? "#bb86fc" : "#9c27b0",
|
||||
light: mode === "dark" ? "#d7aefb" : "#ba68c8",
|
||||
dark: mode === "dark" ? "#985eff" : "#7b1fa2",
|
||||
contrastText: "#fff",
|
||||
},
|
||||
background: {
|
||||
default: mode === 'dark' ? '#121212' : '#fafafa',
|
||||
paper: mode === 'dark' ? '#1e1e1e' : '#ffffff',
|
||||
default: mode === "dark" ? "#121212" : "#fafafa",
|
||||
paper: mode === "dark" ? "#1e1e1e" : "#ffffff",
|
||||
},
|
||||
text: {
|
||||
primary: mode === 'dark' ? '#ffffff' : '#000000',
|
||||
secondary: mode === 'dark' ? 'rgba(255, 255, 255, 0.7)' : 'rgba(0, 0, 0, 0.6)',
|
||||
primary: mode === "dark" ? "#ffffff" : "#000000",
|
||||
secondary:
|
||||
mode === "dark"
|
||||
? "rgba(255, 255, 255, 0.7)"
|
||||
: "rgba(0, 0, 0, 0.6)",
|
||||
},
|
||||
homepage: mode === 'dark' ? '#1e1e1e' : '#f4f4f4',
|
||||
homepage: mode === "dark" ? "#1e1e1e" : "#f4f4f4",
|
||||
},
|
||||
components: {
|
||||
MuiCssBaseline: {
|
||||
styleOverrides: {
|
||||
html: {
|
||||
backgroundColor: `${mode === 'dark' ? '#121212' : '#fafafa'} !important`,
|
||||
transition: 'background-color 300ms cubic-bezier(0.4, 0, 0.2, 1)',
|
||||
backgroundColor: `${mode === "dark" ? "#121212" : "#fafafa"} !important`,
|
||||
transition:
|
||||
"background-color 300ms cubic-bezier(0.4, 0, 0.2, 1)",
|
||||
},
|
||||
body: {
|
||||
backgroundColor: `${mode === 'dark' ? '#121212' : '#fafafa'} !important`,
|
||||
transition: 'background-color 300ms cubic-bezier(0.4, 0, 0.2, 1)',
|
||||
backgroundColor: `${mode === "dark" ? "#121212" : "#fafafa"} !important`,
|
||||
transition:
|
||||
"background-color 300ms cubic-bezier(0.4, 0, 0.2, 1)",
|
||||
margin: 0,
|
||||
},
|
||||
},
|
||||
@@ -127,37 +145,38 @@ export const CustomThemeProvider: React.FC<CustomThemeProviderProps> = ({childre
|
||||
MuiAppBar: {
|
||||
styleOverrides: {
|
||||
colorPrimary: {
|
||||
backgroundColor: mode === 'dark' ? '#388e3c' : '#0fd13f',
|
||||
color: '#ffffff',
|
||||
backgroundColor: mode === "dark" ? "#388e3c" : "#0fd13f",
|
||||
color: "#ffffff",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
[mode]
|
||||
[mode],
|
||||
);
|
||||
|
||||
// Aggressive GlobalStyles mit CSS-Variablen
|
||||
const globalStyles = mounted ? (
|
||||
<GlobalStyles
|
||||
styles={{
|
||||
':root': {
|
||||
'--background-color': mode === 'dark' ? '#121212' : '#fafafa',
|
||||
'--text-color': mode === 'dark' ? '#ffffff' : '#000000',
|
||||
":root": {
|
||||
"--background-color": mode === "dark" ? "#121212" : "#fafafa",
|
||||
"--text-color": mode === "dark" ? "#ffffff" : "#000000",
|
||||
},
|
||||
'*': {
|
||||
boxSizing: 'border-box',
|
||||
"*": {
|
||||
boxSizing: "border-box",
|
||||
},
|
||||
'html, body, #root': {
|
||||
"html, body, #root": {
|
||||
backgroundColor: `var(--background-color) !important`,
|
||||
color: `var(--text-color) !important`,
|
||||
transition: 'background-color 300ms cubic-bezier(0.4, 0, 0.2, 1), color 300ms cubic-bezier(0.4, 0, 0.2, 1)',
|
||||
transition:
|
||||
"background-color 300ms cubic-bezier(0.4, 0, 0.2, 1), color 300ms cubic-bezier(0.4, 0, 0.2, 1)",
|
||||
margin: 0,
|
||||
padding: 0,
|
||||
minHeight: '100vh',
|
||||
minHeight: "100vh",
|
||||
},
|
||||
'div, section, main, article': {
|
||||
backgroundColor: 'transparent',
|
||||
"div, section, main, article": {
|
||||
backgroundColor: "transparent",
|
||||
},
|
||||
}}
|
||||
/>
|
||||
@@ -166,7 +185,7 @@ export const CustomThemeProvider: React.FC<CustomThemeProviderProps> = ({childre
|
||||
// SSR-Fallback während mounted = false
|
||||
if (!mounted) {
|
||||
return (
|
||||
<ThemeProvider theme={createTheme({palette: {mode: 'light'}})}>
|
||||
<ThemeProvider theme={createTheme({ palette: { mode: "light" } })}>
|
||||
<CssBaseline />
|
||||
{children}
|
||||
</ThemeProvider>
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// theme/ThemeToggle.tsx
|
||||
import React from 'react';
|
||||
import {IconButton, Tooltip} from '@mui/material';
|
||||
import {Brightness4, Brightness7} from '@mui/icons-material';
|
||||
import {useThemeMode} from './ThemeContext';
|
||||
import React from "react";
|
||||
import { IconButton, Tooltip } from "@mui/material";
|
||||
import { Brightness4, Brightness7 } from "@mui/icons-material";
|
||||
import { useThemeMode } from "./ThemeContext";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
const ThemeToggle: React.FC = () => {
|
||||
@@ -10,19 +10,18 @@ const ThemeToggle: React.FC = () => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Tooltip title={mode === 'dark' ? t('lightMode') : t('darkMode')}>
|
||||
|
||||
<Tooltip title={mode === "dark" ? t("lightMode") : t("darkMode")}>
|
||||
<IconButton
|
||||
onClick={toggleMode}
|
||||
color="inherit"
|
||||
sx={{
|
||||
transition: 'transform 0.2s',
|
||||
'&:hover': {
|
||||
transform: 'scale(1.1)',
|
||||
transition: "transform 0.2s",
|
||||
"&:hover": {
|
||||
transform: "scale(1.1)",
|
||||
},
|
||||
}}
|
||||
>
|
||||
{mode === 'dark' ? <Brightness7/> : <Brightness4/>}
|
||||
{mode === "dark" ? <Brightness7 /> : <Brightness4 />}
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
);
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import '@mui/material/styles';
|
||||
import "@mui/material/styles";
|
||||
|
||||
declare module '@mui/material/styles' {
|
||||
declare module "@mui/material/styles" {
|
||||
interface Palette {
|
||||
tertiary: Palette['primary'];
|
||||
tertiary: Palette["primary"];
|
||||
homepage: string;
|
||||
}
|
||||
|
||||
interface PaletteOptions {
|
||||
tertiary?: PaletteOptions['primary'];
|
||||
tertiary?: PaletteOptions["primary"];
|
||||
homepage?: string;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,51 +1,51 @@
|
||||
import {createTheme} from '@mui/material/styles';
|
||||
import './theme-augmentation.d.ts'; // Falls vorhanden
|
||||
import { createTheme } from "@mui/material/styles";
|
||||
import "./theme-augmentation.d.ts"; // Falls vorhanden
|
||||
|
||||
export const darkmode = createTheme({
|
||||
palette: {
|
||||
primary: {
|
||||
main: '#0fd13f', // Grüne Standardfarbe
|
||||
light: '#42a5f5',
|
||||
dark: '#15650',
|
||||
contrastText: '#fff',
|
||||
main: "#0fd13f", // Grüne Standardfarbe
|
||||
light: "#42a5f5",
|
||||
dark: "#15650",
|
||||
contrastText: "#fff",
|
||||
},
|
||||
secondary: {
|
||||
main: '#9c27b0',
|
||||
light: '#ba68c8',
|
||||
dark: '#7b1fa2',
|
||||
contrastText: '#fff',
|
||||
main: "#9c27b0",
|
||||
light: "#ba68c8",
|
||||
dark: "#7b1fa2",
|
||||
contrastText: "#fff",
|
||||
},
|
||||
error: {
|
||||
main: '#f44336',
|
||||
light: '#e57373',
|
||||
dark: '#d32f2f',
|
||||
contrastText: '#fff',
|
||||
main: "#f44336",
|
||||
light: "#e57373",
|
||||
dark: "#d32f2f",
|
||||
contrastText: "#fff",
|
||||
},
|
||||
warning: {
|
||||
main: '#ed6c02',
|
||||
light: '#ff9800',
|
||||
dark: '#e65100',
|
||||
contrastText: '#fff',
|
||||
main: "#ed6c02",
|
||||
light: "#ff9800",
|
||||
dark: "#e65100",
|
||||
contrastText: "#fff",
|
||||
},
|
||||
info: {
|
||||
main: '#0288d1',
|
||||
light: '#03a9f4',
|
||||
dark: '#01579b',
|
||||
contrastText: '#fff',
|
||||
main: "#0288d1",
|
||||
light: "#03a9f4",
|
||||
dark: "#01579b",
|
||||
contrastText: "#fff",
|
||||
},
|
||||
success: {
|
||||
main: '#2e7d32',
|
||||
light: '#4caf50',
|
||||
dark: '#1b5e20',
|
||||
contrastText: '#fff',
|
||||
main: "#2e7d32",
|
||||
light: "#4caf50",
|
||||
dark: "#1b5e20",
|
||||
contrastText: "#fff",
|
||||
},
|
||||
background: {
|
||||
default: '#fafafa',
|
||||
paper: '#ffffff',
|
||||
default: "#fafafa",
|
||||
paper: "#ffffff",
|
||||
},
|
||||
text: {
|
||||
primary: '#000000',
|
||||
secondary: 'rgba(0, 0, 0, 0.6)',
|
||||
primary: "#000000",
|
||||
secondary: "rgba(0, 0, 0, 0.6)",
|
||||
},
|
||||
},
|
||||
// Sanfte Übergänge
|
||||
@@ -60,10 +60,10 @@ export const darkmode = createTheme({
|
||||
leavingScreen: 195,
|
||||
},
|
||||
easing: {
|
||||
easeInOut: 'cubic-bezier(0.4, 0, 0.2, 1)',
|
||||
easeOut: 'cubic-bezier(0.0, 0, 0.2, 1)',
|
||||
easeIn: 'cubic-bezier(0.4, 0, 1, 1)',
|
||||
sharp: 'cubic-bezier(0.4, 0, 0.6, 1)',
|
||||
easeInOut: "cubic-bezier(0.4, 0, 0.2, 1)",
|
||||
easeOut: "cubic-bezier(0.0, 0, 0.2, 1)",
|
||||
easeIn: "cubic-bezier(0.4, 0, 1, 1)",
|
||||
sharp: "cubic-bezier(0.4, 0, 0.6, 1)",
|
||||
},
|
||||
},
|
||||
// Verbesserte Komponenten-Overrides
|
||||
@@ -71,20 +71,20 @@ export const darkmode = createTheme({
|
||||
MuiCssBaseline: {
|
||||
styleOverrides: {
|
||||
body: {
|
||||
backgroundColor: '#fafafa',
|
||||
transition: 'background-color 300ms cubic-bezier(0.4, 0, 0.2, 1)',
|
||||
backgroundColor: "#fafafa",
|
||||
transition: "background-color 300ms cubic-bezier(0.4, 0, 0.2, 1)",
|
||||
},
|
||||
html: {
|
||||
backgroundColor: '#fafafa',
|
||||
transition: 'background-color 300ms cubic-bezier(0.4, 0, 0.2, 1)',
|
||||
backgroundColor: "#fafafa",
|
||||
transition: "background-color 300ms cubic-bezier(0.4, 0, 0.2, 1)",
|
||||
},
|
||||
},
|
||||
},
|
||||
MuiAppBar: {
|
||||
styleOverrides: {
|
||||
colorPrimary: {
|
||||
backgroundColor: '#0fd13f', // Grüne NavBar
|
||||
color: '#ffffff',
|
||||
backgroundColor: "#0fd13f", // Grüne NavBar
|
||||
color: "#ffffff",
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -92,13 +92,13 @@ export const darkmode = createTheme({
|
||||
styleOverrides: {
|
||||
root: {
|
||||
borderRadius: 8,
|
||||
textTransform: 'none', // Entfernt automatische Großschreibung
|
||||
textTransform: "none", // Entfernt automatische Großschreibung
|
||||
fontWeight: 600,
|
||||
},
|
||||
contained: {
|
||||
boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
|
||||
'&:hover': {
|
||||
boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
|
||||
boxShadow: "0 2px 8px rgba(0,0,0,0.1)",
|
||||
"&:hover": {
|
||||
boxShadow: "0 4px 12px rgba(0,0,0,0.15)",
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -107,10 +107,10 @@ export const darkmode = createTheme({
|
||||
styleOverrides: {
|
||||
root: {
|
||||
borderRadius: 12,
|
||||
boxShadow: '0 2px 12px rgba(0,0,0,0.08)',
|
||||
transition: 'box-shadow 300ms cubic-bezier(0.4, 0, 0.2, 1)',
|
||||
'&:hover': {
|
||||
boxShadow: '0 4px 20px rgba(0,0,0,0.12)',
|
||||
boxShadow: "0 2px 12px rgba(0,0,0,0.08)",
|
||||
transition: "box-shadow 300ms cubic-bezier(0.4, 0, 0.2, 1)",
|
||||
"&:hover": {
|
||||
boxShadow: "0 4px 20px rgba(0,0,0,0.12)",
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -118,7 +118,7 @@ export const darkmode = createTheme({
|
||||
MuiTextField: {
|
||||
styleOverrides: {
|
||||
root: {
|
||||
'& .MuiOutlinedInput-root': {
|
||||
"& .MuiOutlinedInput-root": {
|
||||
borderRadius: 8,
|
||||
},
|
||||
},
|
||||
@@ -137,10 +137,10 @@ export const darkmode = createTheme({
|
||||
borderRadius: 8,
|
||||
},
|
||||
elevation1: {
|
||||
boxShadow: '0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24)',
|
||||
boxShadow: "0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24)",
|
||||
},
|
||||
elevation2: {
|
||||
boxShadow: '0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23)',
|
||||
boxShadow: "0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23)",
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -150,45 +150,45 @@ export const darkmode = createTheme({
|
||||
fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
|
||||
h1: {
|
||||
fontWeight: 700,
|
||||
fontSize: '2.5rem',
|
||||
fontSize: "2.5rem",
|
||||
lineHeight: 1.2,
|
||||
},
|
||||
h2: {
|
||||
fontWeight: 600,
|
||||
fontSize: '2rem',
|
||||
fontSize: "2rem",
|
||||
lineHeight: 1.3,
|
||||
},
|
||||
h3: {
|
||||
fontWeight: 600,
|
||||
fontSize: '1.75rem',
|
||||
fontSize: "1.75rem",
|
||||
lineHeight: 1.3,
|
||||
},
|
||||
h4: {
|
||||
fontWeight: 600,
|
||||
fontSize: '1.5rem',
|
||||
fontSize: "1.5rem",
|
||||
lineHeight: 1.4,
|
||||
},
|
||||
h5: {
|
||||
fontWeight: 600,
|
||||
fontSize: '1.25rem',
|
||||
fontSize: "1.25rem",
|
||||
lineHeight: 1.4,
|
||||
},
|
||||
h6: {
|
||||
fontWeight: 600,
|
||||
fontSize: '1rem',
|
||||
fontSize: "1rem",
|
||||
lineHeight: 1.4,
|
||||
},
|
||||
body1: {
|
||||
fontSize: '1rem',
|
||||
fontSize: "1rem",
|
||||
lineHeight: 1.5,
|
||||
},
|
||||
body2: {
|
||||
fontSize: '0.875rem',
|
||||
fontSize: "0.875rem",
|
||||
lineHeight: 1.4,
|
||||
},
|
||||
button: {
|
||||
fontWeight: 600,
|
||||
textTransform: 'none',
|
||||
textTransform: "none",
|
||||
},
|
||||
},
|
||||
// Benutzerdefinierte Breakpoints
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
export function mapValueToColor(minVal: number, maxVal: number, actualVal: number): string {
|
||||
export function mapValueToColor(
|
||||
minVal: number,
|
||||
maxVal: number,
|
||||
actualVal: number,
|
||||
): string {
|
||||
const clamped = Math.min(Math.max(actualVal, minVal), maxVal);
|
||||
|
||||
// Calculate interpolation ratio (0-1)
|
||||
const ratio = maxVal !== minVal
|
||||
? (clamped - minVal) / (maxVal - minVal)
|
||||
: 0;
|
||||
const ratio = maxVal !== minVal ? (clamped - minVal) / (maxVal - minVal) : 0;
|
||||
return hsvDegToHex(120 * ratio); //120° is green, 0° is red
|
||||
}
|
||||
|
||||
export function getColorFromPercent(percent: string): string {
|
||||
let perc = Number(percent) / 100
|
||||
let perc = Number(percent) / 100;
|
||||
if (perc > 1) {
|
||||
perc = 2.5;
|
||||
}
|
||||
@@ -20,7 +22,7 @@ export function hsvDegToHex(h: number): string {
|
||||
h = Math.max(0, Math.min(360, h));
|
||||
|
||||
const c = 1;
|
||||
const x = (1 - Math.abs(((h / 60) % 2) - 1));
|
||||
const x = 1 - Math.abs(((h / 60) % 2) - 1);
|
||||
|
||||
let r, g, b;
|
||||
if (h < 60) {
|
||||
@@ -50,9 +52,15 @@ export function hsvDegToHex(h: number): string {
|
||||
}
|
||||
|
||||
// scale to 0-255
|
||||
const rHex = Math.round(r * 255).toString(16).padStart(2, '0');
|
||||
const gHex = Math.round(g * 255).toString(16).padStart(2, '0');
|
||||
const bHex = Math.round(b * 255).toString(16).padStart(2, '0');
|
||||
const rHex = Math.round(r * 255)
|
||||
.toString(16)
|
||||
.padStart(2, "0");
|
||||
const gHex = Math.round(g * 255)
|
||||
.toString(16)
|
||||
.padStart(2, "0");
|
||||
const bHex = Math.round(b * 255)
|
||||
.toString(16)
|
||||
.padStart(2, "0");
|
||||
|
||||
return `#${rHex}${gHex}${bHex}`;
|
||||
}
|
||||
|
||||
13
start.sh
13
start.sh
@@ -1,16 +1,16 @@
|
||||
#!/bin/sh
|
||||
|
||||
LANG="C"
|
||||
|
||||
cleanup() {
|
||||
trap - INT EXIT TERM
|
||||
echo "[DPS] Cleaning up..."
|
||||
pkill $backend_pid # pkill because subshells
|
||||
pkill $frontend_pid
|
||||
pgrep -P "$backend_pid" | xargs kill -TERM > /dev/null 2>&1
|
||||
pgrep -P "$frontend_pid" | xargs kill -TERM > /dev/null 2>&1
|
||||
echo "[DPS] Cleaned up..."
|
||||
exit
|
||||
}
|
||||
|
||||
# Trap INT (Ctrl+C)
|
||||
trap cleanup INT
|
||||
trap cleanup INT EXIT TERM
|
||||
echo "[DPS] trapped"
|
||||
|
||||
cd ./00-backend
|
||||
@@ -25,4 +25,5 @@ echo "[DPS] Frontend started with PID $frontend_pid"
|
||||
|
||||
echo "[DPS] Ctrl+C to stop"
|
||||
# Wait for cleanup
|
||||
wait
|
||||
wait $backend_pid
|
||||
wait $frontend_pid
|
||||
|
||||
Reference in New Issue
Block a user