This commit is contained in:
Andreas Wilms
2025-09-08 18:30:35 +02:00
commit f12cc8b2ce
130 changed files with 16911 additions and 0 deletions

137
README.md Normal file
View File

@@ -0,0 +1,137 @@
# 🖨️ PrintAuftrag - Automated Personalization & Production System
A system that automates repetitive business processes, digitizes workflows, reduces mistakes and costs, and provides an easy-to-use, universally accessible web UI.
---
## 💡 What It Does
- **Automates** repetitive and time-consuming business processes
- **Digitizes** order-to-production workflows
- **Reduces mistakes and costs** by eliminating manual steps and standardizing outputs
- **Accessible everywhere** via a simple and intuitive web interface
---
## 👥 Who Uses It
This system is in production at **Wolga-Kreativ**, a company specializing in personalized products such as:
- Lunch boxes
- T-shirts
- Candles
- Other custom items (primarily for children)
These are sold across multiple platforms: **Amazon**, **Etsy**, and **Shopify**.
> 🧑‍💻 Im the developer and operator of this system, affiliated with Wolga-Kreativ as the owners son.
---
## 🔁 High-Level Pipeline
1. 📦 Orders are captured from sales channels and aggregated via **Billbee**
2. 🔄 The system pulls order data from Billbee using its API
3. 🖼️ Personalized product images are generated based on order data
4. 🖨️ Production-ready print files are created for each specific machine
5. 📤 Files are sent to production for manufacturing and packaging
6. 📬 At day's end, production sends a report → system updates statuses → customers are notified via all sales channels
---
## ✅ Key Benefits
- 🚀 Faster processing and turnaround
_Saves up to two full-time employees during peak seasons_
- ❌ Fewer manual errors and misprints
- 🎯 Consistent, machine-ready print files
- 📍 Centralized tracking and cross-channel customer notifications
---
## 🧰 Tech Stack
- **Backend:** Spring Boot, PostgreSQL
- **Frontend:** Next.js, TypeScript, Tailwind CSS
- **Image Generation:** Python
- **Containerization:** Docker
- **Hosting:** Self-hosted on internal server
---
## 🧩 System Components
### 🖼️ Image Generator
#### Problem
Designs were originally made manually in tools like **CorelDraw** or **Photoshop**—unsuitable for automated large-scale personalization.
Each personalized product had to be manually edited and exported—a slow, error-prone process, especially with over **150+ orders/day** during peak season.
#### Solution
- Designs are transformed into **SVG templates** with embedded bitmaps
- Stored in the database
- A standalone **Python** program takes prefiltered order data from Billbee and generates the images automatically
**Technology:** Python
---
### 🖨️ Print File Generator
#### Problem
Different machines, product types, and practices require specific print file formats.
Manual import and layout of each image is time-consuming and inconsistent.
#### Solution
- Web UI allows users to configure **print templates**
- Templates are saved to the database
- Backend (Spring Boot) generates the correct print files automatically when processing orders
**Technologies:** Java, Spring Boot, HTML5, TypeScript, Tailwind, Next.js
---
### 🔄 Sales Channel Update
#### Problem
After production, each order had to be manually marked as shipped and customers notified—labor-intensive and slow.
#### Solution
- End-of-day production sheet is automatically read
- Order statuses are updated via API
- Notifications are sent to customers through **Billbee**
**Technologies:** TypeScript, Next.js
---
## 🔮 Future Work
- 🔗 Integrate the Python image generator into the core server workflow
- ⚙️ Improve system automation with deeper **Billbee API** usage
- 📈 Extend with more processes
---
## 🖼️ Screenshots
### 🎨 Web View Print Templates
![Template View 1](/doc/img/template_view_1.jpg)
_Template configuration interface View 1_
![Template View 2](/doc/img/template_view_2.jpg)
_Template configuration interface View 2_
---
### 🔁 Abstract Visualization System Flow
![System Flow Diagram](/doc/img/system_flow.png)
_High-level overview of the automated order-to-production pipeline_

14
api/Dockerfile Normal file
View File

@@ -0,0 +1,14 @@
# Use an official OpenJDK runtime as a parent image
FROM openjdk:21-jdk-slim
# Set the working directory inside the container
WORKDIR /app
# Copy the application's JAR file into the container
COPY target/*.jar app.jar
# Expose the port your Spring Boot application runs on
EXPOSE 8080
# Run the JAR file
ENTRYPOINT ["java", "-jar", "app.jar"]

259
api/mvnw vendored Executable file
View File

@@ -0,0 +1,259 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version 3.3.2
#
# Optional ENV vars
# -----------------
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
# MVNW_REPOURL - repo url base for downloading maven distribution
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
# ----------------------------------------------------------------------------
set -euf
[ "${MVNW_VERBOSE-}" != debug ] || set -x
# OS specific support.
native_path() { printf %s\\n "$1"; }
case "$(uname)" in
CYGWIN* | MINGW*)
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
native_path() { cygpath --path --windows "$1"; }
;;
esac
# set JAVACMD and JAVACCMD
set_java_home() {
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
if [ -n "${JAVA_HOME-}" ]; then
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
JAVACCMD="$JAVA_HOME/jre/sh/javac"
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACCMD="$JAVA_HOME/bin/javac"
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
return 1
fi
fi
else
JAVACMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v java
)" || :
JAVACCMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v javac
)" || :
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
return 1
fi
fi
}
# hash string like Java String::hashCode
hash_string() {
str="${1:-}" h=0
while [ -n "$str" ]; do
char="${str%"${str#?}"}"
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
str="${str#?}"
done
printf %x\\n $h
}
verbose() { :; }
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
die() {
printf %s\\n "$1" >&2
exit 1
}
trim() {
# MWRAPPER-139:
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
# Needed for removing poorly interpreted newline sequences when running in more
# exotic environments such as mingw bash on Windows.
printf "%s" "${1}" | tr -d '[:space:]'
}
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
while IFS="=" read -r key value; do
case "${key-}" in
distributionUrl) distributionUrl=$(trim "${value-}") ;;
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
esac
done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties"
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties"
case "${distributionUrl##*/}" in
maven-mvnd-*bin.*)
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
*)
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
distributionPlatform=linux-amd64
;;
esac
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
;;
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
esac
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
distributionUrlName="${distributionUrl##*/}"
distributionUrlNameMain="${distributionUrlName%.*}"
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
exec_maven() {
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
}
if [ -d "$MAVEN_HOME" ]; then
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
exec_maven "$@"
fi
case "${distributionUrl-}" in
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
esac
# prepare tmp dir
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
trap clean HUP INT TERM EXIT
else
die "cannot create temp dir"
fi
mkdir -p -- "${MAVEN_HOME%/*}"
# Download and Install Apache Maven
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
verbose "Downloading from: $distributionUrl"
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
# select .zip or .tar.gz
if ! command -v unzip >/dev/null; then
distributionUrl="${distributionUrl%.zip}.tar.gz"
distributionUrlName="${distributionUrl##*/}"
fi
# verbose opt
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
# normalize http auth
case "${MVNW_PASSWORD:+has-password}" in
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
esac
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
verbose "Found wget ... using wget"
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
verbose "Found curl ... using curl"
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
elif set_java_home; then
verbose "Falling back to use Java to download"
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
cat >"$javaSource" <<-END
public class Downloader extends java.net.Authenticator
{
protected java.net.PasswordAuthentication getPasswordAuthentication()
{
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
}
public static void main( String[] args ) throws Exception
{
setDefault( new Downloader() );
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
}
}
END
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
verbose " - Compiling Downloader.java ..."
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
verbose " - Running Downloader.java ..."
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
fi
# If specified, validate the SHA-256 sum of the Maven distribution zip file
if [ -n "${distributionSha256Sum-}" ]; then
distributionSha256Result=false
if [ "$MVN_CMD" = mvnd.sh ]; then
echo "Checksum validation is not supported for maven-mvnd." >&2
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
elif command -v sha256sum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then
distributionSha256Result=true
fi
elif command -v shasum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
distributionSha256Result=true
fi
else
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
fi
if [ $distributionSha256Result = false ]; then
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
exit 1
fi
fi
# unzip and move
if command -v unzip >/dev/null; then
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
else
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
fi
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url"
mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
clean || :
exec_maven "$@"

149
api/mvnw.cmd vendored Normal file
View File

@@ -0,0 +1,149 @@
<# : batch portion
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.3.2
@REM
@REM Optional ENV vars
@REM MVNW_REPOURL - repo url base for downloading maven distribution
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
@REM ----------------------------------------------------------------------------
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
@SET __MVNW_CMD__=
@SET __MVNW_ERROR__=
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
@SET PSModulePath=
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
)
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
@SET __MVNW_PSMODULEP_SAVE=
@SET __MVNW_ARG0_NAME__=
@SET MVNW_USERNAME=
@SET MVNW_PASSWORD=
@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*)
@echo Cannot start maven from wrapper >&2 && exit /b 1
@GOTO :EOF
: end batch / begin powershell #>
$ErrorActionPreference = "Stop"
if ($env:MVNW_VERBOSE -eq "true") {
$VerbosePreference = "Continue"
}
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
if (!$distributionUrl) {
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
}
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
"maven-mvnd-*" {
$USE_MVND = $true
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
$MVN_CMD = "mvnd.cmd"
break
}
default {
$USE_MVND = $false
$MVN_CMD = $script -replace '^mvnw','mvn'
break
}
}
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
if ($env:MVNW_REPOURL) {
$MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" }
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')"
}
$distributionUrlName = $distributionUrl -replace '^.*/',''
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain"
if ($env:MAVEN_USER_HOME) {
$MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain"
}
$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
exit $?
}
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
}
# prepare tmp dir
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
trap {
if ($TMP_DOWNLOAD_DIR.Exists) {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
}
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
# Download and Install Apache Maven
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
Write-Verbose "Downloading from: $distributionUrl"
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
$webclient = New-Object System.Net.WebClient
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
# If specified, validate the SHA-256 sum of the Maven distribution zip file
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
if ($distributionSha256Sum) {
if ($USE_MVND) {
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
}
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
}
}
# unzip and move
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null
try {
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
} catch {
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
Write-Error "fail to move MAVEN_HOME"
}
} finally {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"

96
api/pom.xml Normal file
View File

@@ -0,0 +1,96 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.4.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.server</groupId>
<artifactId>api</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>api</name>
<description>API Server</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>21</java.version>
<itext.version>9.1.0</itext.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.5.2.Final</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.2.224</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-core</artifactId>
<version>${itext.version}</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>bouncy-castle-adapter</artifactId>
<version>${itext.version}</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.7.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,12 @@
package com.server.api;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ApiApplication {
public static void main(String[] args) {
SpringApplication.run(ApiApplication.class, args);
}
}

View File

@@ -0,0 +1,29 @@
package com.server.api.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry
.addMapping("/**") // Erlaubt alle Endpunkte
.allowedOrigins(
"http://localhost:3050",
"http://nextjs-app:3050",
"https://erp.wolga-kreativ.de") // Erlaubt Anfragen von Next.js
.allowedMethods(
"GET", "POST", "PUT", "DELETE", "OPTIONS") // Erlaubt spezifische HTTP-Methoden
.allowedHeaders("*") // Erlaubt alle Header
.allowCredentials(true); // Erlaubt Cookies/Authentifizierung
}
};
}
}

View File

@@ -0,0 +1,35 @@
package com.server.api.controller;
import com.server.api.models.User;
import com.server.api.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/auth")
public class AuthController {
@Autowired private AuthService authService;
@PostMapping("/signup")
public ResponseEntity<String> signup(@RequestBody User user){
if (authService.signUp(user)){
return ResponseEntity.ok("SignUp successful!");
}else{
return ResponseEntity.status(400).body("SignUp failed. Please try again.");
}
}
@PostMapping("/signin")
public ResponseEntity<String> signin(@RequestBody User user){
if (authService.signIn(user)){
return ResponseEntity.ok("SignIn successful!");
}else{
return ResponseEntity.status(400).body("SignIn failed. Please try again.");
}
}
}

View File

@@ -0,0 +1,144 @@
// filepath:
// /Users/andre/Desktop/api/src/main/java/com/server/api/controller/VorlageFlaechendruckController.java
package com.server.api.controller;
import com.server.api.controller.dto.RollendruckGenReqDto;
import com.server.api.models.VorlageFlaechendruck;
import com.server.api.service.flaechendruck.VorlageFlaechendruckService;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import com.server.api.service.flaechendruck.VorlagenFlaechendruckPDFGeneratorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/vorlageFlaechendruck")
public class VorlageFlaechendruckController {
@Autowired private VorlageFlaechendruckService vorlageFlaechendruckService;
@Autowired private VorlagenFlaechendruckPDFGeneratorService vorlagenPDFGeneratorService;
@PostMapping("/createWithCoordinates")
public ResponseEntity<String> createVorlageWithCoordinates(
@RequestBody VorlageFlaechendruck vorlage) {
vorlageFlaechendruckService.saveVorlageWithCoordinates(vorlage);
return ResponseEntity.ok("Vorlage successfully created with coordinates.");
}
@PostMapping("/alterVorlage")
public ResponseEntity<?> alterVorlage(@RequestBody VorlageFlaechendruck vorlage){
vorlageFlaechendruckService.alterVorlage(vorlage);
return ResponseEntity.ok("Vorlage successfully created with coordinates.");
}
@GetMapping("/getAllFlaechendruckVorlagen")
public List<VorlageFlaechendruck> getAllFlaechendruckVorlagen() {
return vorlageFlaechendruckService.getAllVorlagen();
}
@DeleteMapping("/delete/{id}")
public void deleteVorlageFlaechendruck(@PathVariable Long id) {
vorlageFlaechendruckService.deleteVorlageFlaechendruck(id);
}
@PostMapping(value = "/generate", consumes = "application/json")
public ResponseEntity<?> uploadFiles(@RequestBody RollendruckGenReqDto rollendruckGenReqDto) {
List<String> vorlageIds = rollendruckGenReqDto.getVorlageIds();
String rootDir = rollendruckGenReqDto.getRootDirectory();
String OUTPUT_DIR = String.valueOf((long) (Math.random() * 9_000_000_000L) + 1_000_000_000L)+"/";
Path output = Paths.get(OUTPUT_DIR);
// Ensure the directory path exists before checking it
if (Files.exists(output)) {
try {
deleteDirectoryRecursively(output);
}catch (Exception e) {
}
}
String sharedFolder = null;
String next_url = null;
try {
sharedFolder = System.getenv("SHARED_FOLDER");
next_url = System.getenv("NEXT_SERVER_URL");
if (sharedFolder == null || sharedFolder.isEmpty()) {
sharedFolder = "../frontend/public";
}
if (next_url == null || next_url.isEmpty()) {
next_url = "http://localhost:3050";
}
String uploadPath = sharedFolder + "/" + rootDir + "/";
File dir = new File(uploadPath);
if (!dir.exists() && !dir.isDirectory()) {
throw new Exception("Ordner "+rootDir+" mit Bildern fehlt!");
}
for (String vorlageId : vorlageIds) {
System.out.println("Wird generiert: " + vorlageId);
vorlagenPDFGeneratorService.generateFlaechendruckPDFs(
Long.parseLong(vorlageId), OUTPUT_DIR, uploadPath);
}
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
try {
// move final output folder to shared folder
Path outputDir = output;
Path sharedOutputDir = Paths.get(sharedFolder + "/" + rootDir + "/output");
// delete shared output folder if it exists
if (Files.exists(sharedOutputDir)) {
deleteDirectoryRecursively(sharedOutputDir);
}
Files.walk(outputDir)
.forEach(
source -> {
try {
Path destination = sharedOutputDir.resolve(outputDir.relativize(source));
Files.createDirectories(destination.getParent());
Files.copy(source, destination);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
// Output-Ordner löschen
deleteDirectoryRecursively(output);
return ResponseEntity.status(HttpStatus.OK).build();
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
private void deleteDirectoryRecursively(Path path) throws IOException {
if (Files.exists(path)) {
Files.walk(path)
.sorted((a, b) -> b.compareTo(a)) // Dateien zuerst, dann Verzeichnisse
.forEach(
p -> {
try {
Files.delete(p);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
}
}
}

View File

@@ -0,0 +1,161 @@
package com.server.api.controller;
import com.server.api.controller.dto.RollendruckGenReqDto;
import com.server.api.models.RollenDruckDupliArtikel;
import com.server.api.models.VorlageRollendruck;
import com.server.api.service.rollendruck.VorlageRollendruckService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.server.api.service.rollendruck.VorlageRollendruckPDFGeneratorService;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
@RestController
@RequestMapping("/VorlageRollenDruck")
public class VorlageRollendruckController {
@Autowired private VorlageRollendruckService vorlageRollendruckService;
@Autowired private VorlageRollendruckPDFGeneratorService vorlagenPDFGeneratorService;
@PostMapping("/createRollenDruckVorlage")
public ResponseEntity<String> createVorlageWithCoordinates(
@RequestBody VorlageRollendruck vorlage) {
vorlageRollendruckService.createRollendruckVorlage(vorlage);
return ResponseEntity.ok("Vorlage Rollendruck successfully created.");
}
@GetMapping("/getAllRollendruckVorlagen")
public List<VorlageRollendruck> getAllRollendruckVorlagen() {
// Get all rollendruck templates
return vorlageRollendruckService.getAllVorlagen();
}
@PostMapping("/alterVorlage")
public ResponseEntity<?> alterVorlage(@RequestBody VorlageRollendruck vorlage) {
vorlageRollendruckService.alterVorlage(vorlage);
return ResponseEntity.ok("Vorlage successfully created with coordinates.");
}
@DeleteMapping("/delete/{id}")
public void deleteVorlageRollendruck(@PathVariable Long id) {
vorlageRollendruckService.deleteVorlageRollendruck(id);
}
@PostMapping(value = "/generate", consumes = "application/json")
public ResponseEntity<?> uploadFiles(@RequestBody RollendruckGenReqDto rollendruckGenReqDto) {
List<String> vorlageIds = rollendruckGenReqDto.getVorlageIds();
String rootDir = rollendruckGenReqDto.getRootDirectory();
String OUTPUT_DIR = String.valueOf((long) (Math.random() * 9_000_000_000L) + 1_000_000_000L)+"/";
Path output = Paths.get(OUTPUT_DIR);
// Ensure the directory path exists before checking it
if (Files.exists(output)) {
try {
deleteDirectoryRecursively(output);
}catch (Exception e) {
}
}
String sharedFolder = null;
String next_url = null;
try {
sharedFolder = System.getenv("SHARED_FOLDER");
next_url = System.getenv("NEXT_SERVER_URL");
if (sharedFolder == null || sharedFolder.isEmpty()) {
sharedFolder = "../frontend/public";
}
if (next_url == null || next_url.isEmpty()) {
next_url = "http://localhost:3050";
}
String uploadPath = sharedFolder + "/" + rootDir + "/";
File dir = new File(uploadPath);
if (!dir.exists() && !dir.isDirectory()) {
throw new Exception("Ordner "+rootDir+" mit Bildern fehlt!");
}
for (String vorlageId : vorlageIds) {
System.out.println("Wird generiert: " + vorlageId);
vorlagenPDFGeneratorService.generatePdf(
Long.parseLong(vorlageId), OUTPUT_DIR, uploadPath);
}
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
try {
// move final output folder to shared folder
Path outputDir = output;
Path sharedOutputDir = Paths.get(sharedFolder + "/" + rootDir + "/output");
// delete shared output folder if it exists
if (Files.exists(sharedOutputDir)) {
deleteDirectoryRecursively(sharedOutputDir);
}
Files.walk(outputDir)
.forEach(
source -> {
try {
Path destination = sharedOutputDir.resolve(outputDir.relativize(source));
Files.createDirectories(destination.getParent());
Files.copy(source, destination);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
// Output-Ordner löschen
deleteDirectoryRecursively(output);
return ResponseEntity.status(HttpStatus.OK).build();
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
@PostMapping("/addDupliArtikel")
public ResponseEntity<?> addDupliArtikel(@RequestBody RollenDruckDupliArtikel artikel) {
vorlageRollendruckService.addDupliArtikel(artikel);
return ResponseEntity.ok("Vorlage successfully created with coordinates.");
}
@GetMapping("/getAllDupliArtikel")
public List<RollenDruckDupliArtikel> getAllDupliArtikel() {
return vorlageRollendruckService.getAllDupliArtikel();
}
@DeleteMapping("deleteDupli/{id}")
public void deleteDupli(@PathVariable Long id){
vorlageRollendruckService.deleteDupliArtikel(id);
}
private void deleteDirectoryRecursively(Path path) throws IOException {
if (Files.exists(path)) {
Files.walk(path)
.sorted((a, b) -> b.compareTo(a)) // Dateien zuerst, dann Verzeichnisse
.forEach(
p -> {
try {
Files.delete(p);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
}
}
}

View File

@@ -0,0 +1,26 @@
package com.server.api.controller.dto;
import java.util.List;
public class RollendruckGenReqDto {
private List<String> vorlageIds;
private String rootDirectory;
// Getter und Setter
public List<String> getVorlageIds() {
return vorlageIds;
}
public void setVorlageIds(List<String> vorlageIds) {
this.vorlageIds = vorlageIds;
}
public String getRootDirectory() {
return rootDirectory;
}
public void setRootDirectory(String rootDirectory) {
this.rootDirectory = rootDirectory;
}
}

View File

@@ -0,0 +1,68 @@
package com.server.api.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
@Entity
@Table(name = "coordinates")
public class Coordinates {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long coordinate_id;
@ManyToOne
@JoinColumn(name = "flaechendruck_id", nullable = false)
@JsonIgnore
private VorlageFlaechendruck vorlage;
private Double x;
private Double y;
private Double rotation;
// Getter und Setter
public Long getId() {
return coordinate_id;
}
public void setId(Long id) {
this.coordinate_id = id;
}
public VorlageFlaechendruck getVorlage() {
return vorlage;
}
public void setVorlage(VorlageFlaechendruck vorlage) {
this.vorlage = vorlage;
}
public Double getX() {
return x;
}
public void setX(Double x) {
this.x = x;
}
public Double getY() {
return y;
}
public void setY(Double y) {
this.y = y;
}
public Double getRotation() {
return rotation;
}
public void setRotation(Double rotation) {
this.rotation = rotation;
}
}

View File

@@ -0,0 +1,24 @@
package com.server.api.models;
import jakarta.persistence.*;
@Entity
@Table(name = "RollenDruckDupliArtikel")
public class RollenDruckDupliArtikel {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String product_type;
public void setProduct_type(String product_type) {
this.product_type = product_type;
}
public String getProduct_type() {
return product_type;
}
public Long getId() {
return id;
}
}

View File

@@ -0,0 +1,31 @@
package com.server.api.models;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "users")
public class User {
@Id
private String name;
private String password;
public void setName(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword() {
return password;
}
}

View File

@@ -0,0 +1,75 @@
package com.server.api.models;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
import java.util.List;
@Entity
@Table(name = "vorlageFlaechendruck")
public class VorlageFlaechendruck {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long flaechendruck_id;
private String printer;
private String product_type;
private Float height;
private Float width;
@OneToMany(mappedBy = "coordinate_id")
private List<Coordinates> coordinates;
// Getter und Setter
public String getPrinter() {
return printer;
}
public void setPrinter(String printer) {
this.printer = printer;
}
public Long getId() {
return flaechendruck_id;
}
public void setId(Long id) {
this.flaechendruck_id = id;
}
public String getProduct_type() {
return product_type;
}
public void setProduct_type(String product_type) {
this.product_type = product_type;
}
public Float getHeight() {
return height;
}
public void setHeight(Float height) {
this.height = height;
}
public Float getWidth() {
return width;
}
public void setWidth(Float width) {
this.width = width;
}
public List<Coordinates> getCoordinates() {
return coordinates;
}
public void setCoordinates(List<Coordinates> coordinates) {
this.coordinates = coordinates;
}
}

View File

@@ -0,0 +1,60 @@
package com.server.api.models;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.persistence.*;
@Entity
@Table(name = "vorlageRollendruck")
public class VorlageRollendruck {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String printer;
private Float height;
private Float width;
private String articleTypes;
// Getter and Setter
public String getArticleTypes() {
return articleTypes;
}
public void setArticleTypes(String articleTypes) {
this.articleTypes = articleTypes;
}
// Getter und Setter
public String getPrinter() {
return printer;
}
public void setPrinter(String printer) {
this.printer = printer;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Float getHeight() {
return height;
}
public void setHeight(Float height) {
this.height = height;
}
public Float getWidth() {
return width;
}
public void setWidth(Float width) {
this.width = width;
}
}

View File

@@ -0,0 +1,19 @@
package com.server.api.repository;
import com.server.api.models.User;
import com.server.api.models.VorlageRollendruck;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface AuthRepository extends JpaRepository<User, Long> {
@Query("SELECT u FROM User u WHERE u.name = :name")
User findByName(@Param("name") String name);
}

View File

@@ -0,0 +1,15 @@
// filepath:
// /Users/andre/Desktop/PrintAuftrag/api/src/main/java/com/server/api/repository/CoordinatesRepository.java
package com.server.api.repository;
import com.server.api.models.Coordinates;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface CoordinatesRepository extends JpaRepository<Coordinates, Long> {
void deleteByVorlageId(Long vorlageId); // Diese Methode hinzufügen
List<Coordinates> findAllByVorlageId(Long vorlageId);
}

View File

@@ -0,0 +1,10 @@
package com.server.api.repository;
import com.server.api.models.RollenDruckDupliArtikel;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface RollenDruckDupliRepository extends JpaRepository<RollenDruckDupliArtikel, Long> {
}

View File

@@ -0,0 +1,10 @@
// filepath:
// /Users/andre/Desktop/api/src/main/java/com/server/api/repository/VorlagenFlaechendruckRepository.java
package com.server.api.repository;
import com.server.api.models.VorlageFlaechendruck;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface VorlageFlaechendruckRepository extends JpaRepository<VorlageFlaechendruck, Long> {}

View File

@@ -0,0 +1,15 @@
package com.server.api.repository;
import com.server.api.models.VorlageRollendruck;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface VorlageRollendruckRepository extends JpaRepository<VorlageRollendruck, Long> {
@Query("SELECT v FROM VorlageRollendruck v")
List<VorlageRollendruck> getAllVorlagenRollendruck();
}

View File

@@ -0,0 +1,61 @@
package com.server.api.service;
import com.server.api.models.User;
import com.server.api.repository.AuthRepository;
import com.server.api.utils.HashUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class AuthService {
private static final Logger logger = LoggerFactory.getLogger(AuthService.class);
@Autowired
private AuthRepository authRepository;
public boolean signUp(User user) {
try {
// Validate user object (you can implement your own validation logic)
if (user == null || user.getName() == null || user.getPassword() == null) {
throw new IllegalArgumentException("User or required fields cannot be null");
}
// Hash password
user.setPassword(HashUtil.hash(user.getPassword()));
// Save the user to the repository
authRepository.save(user);
return true;
} catch (Exception e) {
logger.error("Error during sign up: ", e); // Log the exception
return false;
}
}
public boolean signIn(User user) {
if (user == null || user.getName() == null || user.getPassword() == null) {
return false;
}
try {
Optional<User> maybe = Optional.ofNullable(authRepository.findByName(user.getName()));
if (maybe.isEmpty()) return false;
User stored = maybe.get();
// Hash das eingegebene Passwort und vergleiche mit gespeichertem Hash
String hashedInput = HashUtil.hash(user.getPassword());
return hashedInput.equals(stored.getPassword());
} catch (Exception e) {
logger.error("Error during sign in: ", e);
return false;
}
}
}

View File

@@ -0,0 +1,102 @@
package com.server.api.service.flaechendruck;
import com.server.api.models.Coordinates;
import com.server.api.models.VorlageFlaechendruck;
import com.server.api.repository.CoordinatesRepository;
import com.server.api.repository.VorlageFlaechendruckRepository;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class VorlageFlaechendruckService {
@Autowired private VorlageFlaechendruckRepository vorlageFlaechendruckRepository;
@Autowired private CoordinatesRepository coordinatesRepository;
@Transactional
public void deleteVorlageFlaechendruck(Long id) {
coordinatesRepository.deleteByVorlageId(id);
vorlageFlaechendruckRepository.deleteById(id);
}
public void saveVorlageWithCoordinates(VorlageFlaechendruck vorlageDTO) {
// Erstellen der VorlageFlaechendruck-Entität
VorlageFlaechendruck vorlage = new VorlageFlaechendruck();
vorlage.setPrinter(vorlageDTO.getPrinter());
vorlage.setProduct_type(vorlageDTO.getProduct_type());
vorlage.setHeight(vorlageDTO.getHeight());
vorlage.setWidth(vorlageDTO.getWidth());
// Speichern der VorlageFlaechendruck-Entität
VorlageFlaechendruck savedVorlage = vorlageFlaechendruckRepository.save(vorlage);
// Speichern der zugehörigen Coordinates
for (Coordinates coordinate : vorlageDTO.getCoordinates()) {
coordinate.setVorlage(savedVorlage); // Fremdschlüssel setzen
coordinatesRepository.save(coordinate);
}
}
public void alterVorlage(VorlageFlaechendruck vorlage){
VorlageFlaechendruck vorlageInDB = vorlageFlaechendruckRepository.findById(vorlage.getId()).get();
vorlageInDB.setPrinter(vorlage.getPrinter());
vorlageInDB.setProduct_type(vorlage.getProduct_type());
vorlageInDB.setHeight(vorlage.getHeight());
vorlageInDB.setWidth(vorlage.getWidth());
List<Coordinates> coordinates = coordinatesRepository.findAll();
List<Coordinates> coordinatesToDelete = new ArrayList<>();
for (Coordinates coordinate : coordinates) {
if (coordinate.getVorlage().getId() == vorlageInDB.getId()) {
coordinatesToDelete.add(coordinate);
}
}
coordinatesRepository.deleteAll(coordinatesToDelete);
for (Coordinates coordinate : vorlage.getCoordinates()) {
coordinate.setVorlage(vorlageInDB); // Fremdschlüssel setzen
coordinatesRepository.save(coordinate);
}
vorlageFlaechendruckRepository.save(vorlageInDB);
}
public List<VorlageFlaechendruck> getAllVorlagen() {
List<VorlageFlaechendruck> vorlagen = vorlageFlaechendruckRepository.findAll();
List<Coordinates> coordinates = coordinatesRepository.findAll();
List<VorlageFlaechendruck> vorlagenWithCoordinates = new ArrayList<>();
for (VorlageFlaechendruck vorlage : vorlagen) {
List<Coordinates> vorlageCoordinates = new ArrayList<>();
for (Coordinates coordinate : coordinates) {
if (coordinate.getVorlage().getId() == vorlage.getId()) {
vorlageCoordinates.add(coordinate);
}
}
vorlage.setCoordinates(vorlageCoordinates);
vorlagenWithCoordinates.add(vorlage);
}
return vorlagenWithCoordinates;
}
public VorlageFlaechendruck getVorlageById(long id) {
VorlageFlaechendruck vorlage = vorlageFlaechendruckRepository.findById(id).get();
List<Coordinates> coordinates = coordinatesRepository.findAll();
List<Coordinates> vorlageCoordinates = new ArrayList<>();
for (Coordinates coordinate : coordinates) {
if (coordinate.getVorlage().getId() == vorlage.getId()) {
vorlageCoordinates.add(coordinate);
}
}
vorlage.setCoordinates(vorlageCoordinates);
return vorlage;
}
}

View File

@@ -0,0 +1,330 @@
package com.server.api.service.flaechendruck;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import com.server.api.models.Coordinates;
import com.server.api.models.VorlageFlaechendruck;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Stream;
import javax.imageio.ImageIO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class VorlagenFlaechendruckPDFGeneratorService {
@Autowired
private VorlageFlaechendruckService vorlageFlaechendruckService;
public void generateFlaechendruckPDFs(long vorlageId, String outputDir, String uploadDir)
throws Exception {
VorlageFlaechendruck vorlage = vorlageFlaechendruckService.getVorlageById(vorlageId);
String imagePath = uploadDir;
Path outputFolder = Paths.get(outputDir);
if (!Files.exists(outputFolder)) {
Files.createDirectories(outputFolder);
}
PdfGenerator pdfGenerator = new PdfGenerator(imagePath, outputDir);
pdfGenerator.generatePdf(vorlage);
}
public class PdfGenerator {
private String imagePath;
private String pdfPath;
public class Article {
private String imagePath;
private String color;
private String productType;
public Article(String imagePath, String color, String productType) {
this.imagePath = imagePath;
this.color = color;
this.productType = productType;
}
public String getImagePath() {
return imagePath;
}
public String getColor() {
return color;
}
public String getProductType() {
return productType;
}
}
public class ColorCount {
private String color;
private int count;
public ColorCount(String color, int count) {
this.color = color;
this.count = count;
}
public String getColor() {
return color;
}
public int getCount() {
return count;
}
public void incrementCount() {
this.count++;
}
public void decrementCount() {
this.count--;
}
}
public PdfGenerator(String imagePath, String pdfPath) {
this.imagePath = imagePath;
this.pdfPath = pdfPath;
}
public void generatePdf(VorlageFlaechendruck vorlage) throws Exception {
// Bild hinzufügen
File folder = new File(imagePath);
File[] files = folder.listFiles();
files = getAllFilePaths(imagePath);
// delete hidden files beginning with .
files = Arrays.stream(files).filter(file -> !file.getName().startsWith(".")).toArray(File[]::new);
// only keep files with the correct product type
files = Arrays.stream(files)
.filter(file -> file.getName().startsWith(vorlage.getProduct_type().toLowerCase()))
.toArray(File[]::new);
// Sort files by color
Article[] articles = createArticlesOrder(files, vorlage.getCoordinates().size());
Coordinates[] coordinates = vorlage.getCoordinates().toArray(new Coordinates[0]);
float height = vorlage.getHeight();
float width = vorlage.getWidth();
int count = 0;
for (int i = 0; i < articles.length; i += coordinates.length) {
count++;
ArrayList<ColorCount> colorCounts = new ArrayList<>();
float pointsPerMm = 2.83465f;
try (PdfWriter writer = new PdfWriter(pdfPath + count + ".pdf");
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(
pdf, new PageSize(width * pointsPerMm, height * pointsPerMm))) {
for (int j = 0; j < coordinates.length; j++) {
if (i + j >= articles.length) {
break;
}
boolean found = false;
for (ColorCount colorCount : colorCounts) {
if (colorCount.getColor().equals(articles[i + j].getColor())) {
colorCount.incrementCount();
found = true;
break;
}
}
if (!found) {
colorCounts.add(new ColorCount(articles[i + j].getColor(), 1));
}
String imagePathTemp = articles[i + j].getImagePath();
ImageData imageData = ImageDataFactory.create(imagePathTemp);
Image image = new Image(imageData);
double x = coordinates[j].getX() * pointsPerMm;
double y = coordinates[j].getY() * pointsPerMm;
double rotation = coordinates[j].getRotation();
float[] imageSize = getImageSize(imagePathTemp);
float imageWidth = pixelsToMm(imageSize[0]);
float imageHeight = pixelsToMm(imageSize[1]);
if (rotation != 0) {
image.setRotationAngle(Math.toRadians(rotation));
// Swap width and height if the image is rotated
}
image.scaleToFit(imageWidth * pointsPerMm, imageHeight * pointsPerMm);
// Adjust x and y to center the image at the given coordinates
if (rotation != 0) {
float temp = imageWidth;
imageWidth = imageHeight;
imageHeight = temp;
}
double adjustedX = x - (imageWidth * pointsPerMm) / 2;
double adjustedY = y - (imageHeight * pointsPerMm) / 2;
image.setFixedPosition((float) adjustedX, (float) adjustedY);
document.add(image);
}
}
String saveName = compressString(colorCounts, articles[0].getProductType());
// Datei umbenennen
String tempFileName = pdfPath + count + ".pdf";
File tempFile = new File(tempFileName);
File renamedFile = new File(pdfPath + count + ". " + saveName + ".pdf");
if (!tempFile.renameTo(renamedFile)) {
throw new Exception("Internal Server Error");
}
}
}
private Article[] createArticlesOrder(File[] files, int cors_len) throws Exception {
ArrayList<Article> articles = new ArrayList<>();
ArrayList<ColorCount> colorCounts = new ArrayList<>();
for (int i = 0; i < files.length; i++) {
articles.add(getArticleProperties(files[i].getAbsolutePath()));
boolean found = false;
for (ColorCount colorCount : colorCounts) {
if (colorCount.getColor().equals(articles.get(i).getColor())) {
colorCount.incrementCount();
found = true;
break;
}
}
if (!found) {
colorCounts.add(new ColorCount(articles.get(i).getColor(), 1));
}
}
ArrayList<Article> sortedArticles = new ArrayList<>();
int index = 0;
while (index < colorCounts.size()) {
if (colorCounts.get(index).getCount() >= cors_len) {
int num_added = 0;
ArrayList<Article> removeArticles = new ArrayList<>();
for (Article artc : articles) {
if (artc.getColor().equals(colorCounts.get(index).getColor())) {
sortedArticles.add(artc);
removeArticles.add(artc);
colorCounts.get(index).decrementCount();
num_added++;
}
if (num_added >= cors_len) {
break;
}
}
articles.removeAll(removeArticles);
} else {
index++;
}
}
// sort articles by color
articles.sort((a, b) -> a.getColor().compareTo(b.getColor()));
for (Article artc : articles) {
sortedArticles.add(artc);
}
// transform ArrayList to Array
Article[] sortedArticlesArray = new Article[sortedArticles.size()];
for (int i = 0; i < sortedArticles.size(); i++) {
sortedArticlesArray[i] = sortedArticles.get(i);
}
return sortedArticlesArray;
}
private File[] getAllFilePaths(String directoryPath) throws Exception {
try (Stream<Path> paths = Files.walk(Paths.get(directoryPath))) {
return paths
.filter(Files::isRegularFile) // Behalte nur reguläre Dateien (keine Verzeichnisse)
.map(Path::toFile) // Konvertiere Path zu File
.toArray(File[]::new); // Sammle die Ergebnisse in ein Array
}
}
private String compressString(ArrayList<ColorCount> colorCounts, String productType) {
StringBuilder result = new StringBuilder();
for (ColorCount colorCount : colorCounts) {
result.append(colorCount.getCount()); // Häufigkeit
result.append(productType); // Produkttyp
result.append(" ");
result.append(colorCount.getColor()); // Farbe
result.append(" ");
}
// Entferne das letzte Leerzeichen
if (result.length() > 0) {
result.setLength(result.length() - 1);
}
return result.toString();
}
private Article getArticleProperties(String imagePath) throws Exception {
String filename = new File(imagePath).getName();
String farben = "abcdefghijklmnopqrstuvwxyz";
String productType = "";
int i = 0;
while (true) {
if (Character.isDigit(filename.charAt(i))) {
break;
}
productType += filename.charAt(i);
i++;
}
while (true) {
if (!Character.isDigit(filename.charAt(i))) {
break;
}
i++;
}
String color = String.valueOf(filename.charAt(i));
// for colors with two letters
if (farben.indexOf(filename.charAt(i + 1)) != -1) {
color += String.valueOf(filename.charAt(i + 1));
}
// Prüfe, ob der Buchstabe in der Liste der Farben enthalten ist
if (farben.indexOf(color) == -1 && color.length() != 2) {
throw new Exception("Nicht alle Bilder enthalten Farbbuchstaben!");
}
return new Article(imagePath, color, productType);
}
private float[] getImageSize(String imagePath) {
try {
BufferedImage image = ImageIO.read(new File(imagePath));
return new float[] { image.getWidth(), image.getHeight() };
} catch (Exception e) {
return new float[] { 0, 0 };
}
}
private float pixelsToMm(float pixels) {
float dpi = 300;
return pixels / dpi * 25.4f;
}
}
}

View File

@@ -0,0 +1,398 @@
package com.server.api.service.rollendruck;
import java.io.File;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Stream;
import javax.imageio.ImageIO;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.element.Paragraph;
import com.server.api.models.VorlageRollendruck;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import java.util.List;
import java.awt.image.BufferedImage;
@Service
public class VorlageRollendruckPDFGeneratorService {
final float pointsPerMm = 2.83464567f;
final float numberPointsForMm = 28.3465f;
@Autowired VorlageRollendruckService vorlageRollendruckService;
private static class ImageObject {
float x1;
float y1;
float x2;
float y2;
String imageGroup;
boolean isRotated;
String imagePath;
public ImageObject(float x1, float y1, float x2, float y2, String imageGroup, boolean isRotated,
String imagePath) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.imageGroup = imageGroup;
this.isRotated = isRotated;
this.imagePath = imagePath;
}
public float getX1() {
return x1;
}
public float getY1() {
return y1;
}
public float getX2() {
return x2;
}
public float getY2() {
return y2;
}
public boolean isRotated() {
return isRotated;
}
public String getImagePath() {
return imagePath;
}
}
private static class ImageGroup {
String name;
List<String> images;
float size;
public ImageGroup(String name) {
this.name = name;
this.images = new ArrayList<>();
}
public String getName() {
return name;
}
public List<String> getImages() {
return images;
}
public float getSize() {
return size;
}
public void setSize(float size) {
this.size = size;
}
}
private class Surface {
float height;
float width;
List<ImageObject> placedImages;
public Surface(float height, float width) {
this.height = height;
this.width = width;
this.placedImages = new ArrayList<>();
}
private List<String> placeImageGroup(List<String> imagePaths, float width, float height, String imageGroupName) throws MalformedURLException {
List<String> notPlacedImages = new ArrayList<>();
float cursor_x = 0;
float cursor_y = height * pointsPerMm;
for (String singleImagePath : imagePaths) {
ImageData imageData = ImageDataFactory.create(singleImagePath);
Image image = new Image(imageData);
float[] imageSize = getImageSize(singleImagePath);
float imageWidth = pixelsToMm(imageSize[0]);
float imageHeight = pixelsToMm(imageSize[1]);
image.scaleToFit(imageWidth * pointsPerMm, imageHeight * pointsPerMm);
boolean foundFreePos = false;
boolean isRotated = false;
float abstand = numberPointsForMm * pointsPerMm;
float updated_x = 0;
float updated_y = 0;
boolean isEndOfPage = false;
while (!foundFreePos) {
// cursor runs through the whole page
if (cursor_x + 1 > width * pointsPerMm) {
cursor_x = 0;
if (cursor_y - 1 < 0) {
isEndOfPage = true;
break;
} else {
cursor_y -= 1;
}
} else {
cursor_x += 1;
}
// check if cursor is not on an image
if (isOverlap(cursor_x, imageWidth, cursor_y - imageHeight * pointsPerMm, imageHeight)) {
continue;
}
updated_x = cursor_x + abstand;
updated_y = cursor_y - imageHeight * pointsPerMm - abstand;
boolean isLeftNeighbourOverlap = false;
for (ImageObject placedImage : placedImages) {
if(placedImage.y1 < cursor_y && placedImage.y2 > updated_y && placedImage.x2 >= cursor_x - 30 && placedImage.x1 < cursor_x - 30){
isLeftNeighbourOverlap = true;
break;
}
}
if (isLeftNeighbourOverlap) {
continue;
}
if (isOverlap(updated_x, imageWidth, updated_y, imageHeight)) {
continue;
}
if (updated_x + imageWidth * pointsPerMm < width * pointsPerMm
&& updated_y> 0) {
foundFreePos = true;
}
}
if (isEndOfPage) {
notPlacedImages.add(singleImagePath);
continue;
}
if (isRotated) {
placedImages.add(new ImageObject(updated_x, updated_y,
updated_x + imageHeight * pointsPerMm,
updated_y + imageWidth * pointsPerMm, imageGroupName, true, singleImagePath));
image.setFixedPosition(updated_x, updated_y);
image.setRotationAngle(Math.toRadians(90));
} else {
placedImages.add(new ImageObject(updated_x, updated_y,
updated_x + imageWidth * pointsPerMm,
updated_y + imageHeight * pointsPerMm, imageGroupName, false, singleImagePath));
image.setFixedPosition(updated_x, updated_y);
}
}
return notPlacedImages;
}
private boolean isOverlap(float cursor_x, float imageWidth, float cursor_y, float imageHeight) {
for (ImageObject imageObject : placedImages) {
if (imageObject.getX1() < cursor_x + imageWidth * pointsPerMm
&& imageObject.getX2() > cursor_x
&& imageObject.getY1() < cursor_y + imageHeight * pointsPerMm
&& imageObject.getY2() > cursor_y) {
return true;
}
}
return false;
}
}
public void generatePdf(long vorlageId, String outputDir, String uploadPath) throws Exception {
// get width and height from vorlage
VorlageRollendruck vorlage = vorlageRollendruckService.getVorlageById(vorlageId);
float width = vorlage.getWidth();
float height = vorlage.getHeight();
List<String> articleTypes = splitArticleTypes(vorlage.getArticleTypes());
List<String> dupliStrings = vorlageRollendruckService.getAllDupliStrings();
Path outputFolder = Paths.get(outputDir);
if (!Files.exists(outputFolder)) {
Files.createDirectories(outputFolder);
}
String imagePath = uploadPath;
File folder = new File(imagePath);
File[] files = folder.listFiles();
files = getAllFilePaths(imagePath);
// delete hidden files beginning with .
files = Arrays.stream(getAllFilePaths(imagePath)).filter(file -> !file.getName().startsWith(".")).toArray(File[]::new);
// create subgroups
List<ImageGroup> imageGroups = new ArrayList<>();
for (File file : files) {
String name = file.getName();
int i = 0;
while (i < name.length() && !Character.isDigit(name.charAt(i)) && name.charAt(i) != ' ') {
i++;
}
boolean isGroup = false;
for (ImageGroup imageGroup : imageGroups) {
if (imageGroup.getName().equals(name.substring(0, i).trim())) {
imageGroup.images.add(file.getAbsolutePath());
isGroup = true;
break;
}
}
if (!isGroup) {
String groupName = name.substring(0, i).trim();
ImageGroup imageGroup = new ImageGroup(groupName);
imageGroup.images.add(file.getAbsolutePath());
float[] imageSizes = getImageSize(file.getAbsolutePath());
float imageSize = pixelsToMm(imageSizes[0]) * pixelsToMm(imageSizes[1]);
imageGroup.setSize(imageSize);
imageGroups.add(imageGroup);
}
}
// delete imageGroups that are not in articleTypes
imageGroups.removeIf(imageGroup -> !articleTypes.contains(imageGroup.getName()));
// sort groups by size
imageGroups.sort((g1, g2) -> Float.compare(g2.getSize(), g1.getSize()));
// if imageGroup contains dupliStrings double the entries
for (ImageGroup imageGroup : imageGroups) {
if (dupliStrings.contains(imageGroup.getName())) {
List<String> images = new ArrayList<>(imageGroup.getImages());
for (String image : images) {
imageGroup.getImages().add(image);
}
}
}
List<Surface> surfaces = new ArrayList<>();
surfaces.add(new Surface(height, width));
int surfaceIndex = 0;
for (ImageGroup imageGroup : imageGroups) {
List<String> notPlacedImages = surfaces.get(surfaceIndex).placeImageGroup(imageGroup.getImages(), width, height, imageGroup.getName());
while (!notPlacedImages.isEmpty()) {
surfaces.add(new Surface(height, width));
surfaceIndex++;
notPlacedImages = surfaces.get(surfaceIndex).placeImageGroup(notPlacedImages, width, height, imageGroup.getName());
}
}
int count = 1;
for (Surface surface: surfaces){
try (PdfWriter writer = new PdfWriter(outputDir + count + ". " + vorlage.getPrinter() + " Rollendruck.pdf");
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(
pdf, new PageSize(width * pointsPerMm, height * pointsPerMm))) {
for (ImageObject imageObject : surface.placedImages) {
ImageData imageData = ImageDataFactory.create(imageObject.getImagePath());
Image image = getImage(imageObject, imageData);
// Add image at fixed position
image.setFixedPosition(imageObject.getX1(), imageObject.getY1());
document.add(image);
// Add text under image
String caption = imageObject.getImagePath().substring(imageObject.getImagePath().lastIndexOf("/") + 1);
float textX = ((imageObject.getX2() - imageObject.getX1())/2) + imageObject.getX1() + caption.length()*2; // Centered
float textY = imageObject.getY1() - numberPointsForMm - 10; // Adjust to place below image
PdfDocument pdfDocument = document.getPdfDocument();
PdfCanvas pdfCanvas = new PdfCanvas(pdfDocument.getLastPage());
pdfCanvas.saveState();
// Apply a horizontal mirroring transformation
pdfCanvas.concatMatrix(-1, 0, 0, 1, textX * 2, 0);
Paragraph paragraph = new Paragraph(caption)
.setFontSize(11)
.setFixedPosition(textX, textY, 200);
// Add the mirrored paragraph to the document
document.add(paragraph);
pdfCanvas.restoreState();
}
}
count++;
}
}
private static List<String> splitArticleTypes(String articleTypes) {
if (articleTypes == null || articleTypes.isEmpty()) {
return new ArrayList<>();
}
// Split the string by commas and trim whitespace from each part
articleTypes = articleTypes.replaceAll(" ", ""); // Remove all whitespace
return Arrays.asList(articleTypes.split(","));
}
private static Image getImage(ImageObject imageObject, ImageData imageData) {
Image image = new Image(imageData);
if (imageObject.isRotated()) {
image.setRotationAngle(Math.toRadians(90));
image.setFixedPosition(imageObject.getX1(), imageObject.getY1());
image.scaleToFit(imageObject.getY2() - imageObject.getY1(),
imageObject.getX2() - imageObject.getX1());
} else {
image.setFixedPosition(imageObject.getX1(), imageObject.getY1());
image.scaleToFit(imageObject.getX2() - imageObject.getX1(),
imageObject.getY2() - imageObject.getY1());
}
return image;
}
private File[] getAllFilePaths(String directoryPath) throws Exception {
try (Stream<Path> paths = Files.walk(Paths.get(directoryPath))) {
return paths
.filter(Files::isRegularFile) // Behalte nur reguläre Dateien (keine Verzeichnisse)
.map(Path::toFile) // Konvertiere Path zu File
.toArray(File[]::new); // Sammle die Ergebnisse in ein Array
}
}
private float[] getImageSize(String imagePath) {
try {
BufferedImage image = ImageIO.read(new File(imagePath));
return new float[] { image.getWidth(), image.getHeight() };
} catch (Exception e) {
System.out.println("Error reading image: " + e.getMessage());
}
return new float[] { 0, 0 };
}
private float pixelsToMm(float pixels) {
float dpi = 300;
return pixels / dpi * 25.4f;
}
}

View File

@@ -0,0 +1,79 @@
package com.server.api.service.rollendruck;
import com.server.api.models.RollenDruckDupliArtikel;
import com.server.api.models.VorlageRollendruck;
import com.server.api.repository.RollenDruckDupliRepository;
import com.server.api.repository.VorlageRollendruckRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class VorlageRollendruckService {
@Autowired
private VorlageRollendruckRepository vorlageRollendruckRepository;
@Autowired
private RollenDruckDupliRepository rollenDruckDupliRepository;
public void createRollendruckVorlage(VorlageRollendruck vorlage) {
System.out.println("Das sie die Artiekl "+ vorlage.getArticleTypes());
vorlageRollendruckRepository.save(vorlage);
}
public List<VorlageRollendruck> getAllVorlagen() {
return vorlageRollendruckRepository.getAllVorlagenRollendruck();
}
public void alterVorlage(VorlageRollendruck vorlage) {
VorlageRollendruck vorlageInDB = vorlageRollendruckRepository.findById(vorlage.getId()).orElseThrow(() -> new RuntimeException("Vorlage not found"));
vorlageInDB.setPrinter(vorlage.getPrinter());
vorlageInDB.setHeight(vorlage.getHeight());
vorlageInDB.setWidth(vorlage.getWidth());
vorlageInDB.setArticleTypes(vorlage.getArticleTypes());
vorlageRollendruckRepository.save(vorlageInDB);
}
public void deleteVorlageRollendruck(Long id) {
VorlageRollendruck vorlage = vorlageRollendruckRepository.findById(id)
.orElseThrow(() -> new RuntimeException("Vorlage not found"));
vorlageRollendruckRepository.delete(vorlage);
}
public void addDupliArtikel(RollenDruckDupliArtikel artikel) {
// save the article
rollenDruckDupliRepository.save(artikel);
}
public List<RollenDruckDupliArtikel> getAllDupliArtikel() {
// print all articles
for (RollenDruckDupliArtikel artikel : rollenDruckDupliRepository.findAll()) {
System.out.println(artikel);
}
return rollenDruckDupliRepository.findAll();
}
public void deleteDupliArtikel(Long id) {
RollenDruckDupliArtikel artikel = rollenDruckDupliRepository.findById(id)
.orElseThrow(() -> new RuntimeException("Artikel not found"));
rollenDruckDupliRepository.delete(artikel);
}
public VorlageRollendruck getVorlageById(Long id) {
return vorlageRollendruckRepository.findById(id)
.orElseThrow(() -> new RuntimeException("Vorlage not found"));
}
public List<String> getAllDupliStrings(){
List<RollenDruckDupliArtikel> dupliArtikelList = rollenDruckDupliRepository.findAll();
return dupliArtikelList.stream()
.map(RollenDruckDupliArtikel::getProduct_type)
.toList();
}
}

View File

@@ -0,0 +1,25 @@
package com.server.api.utils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class HashUtil {
public static String hash(String input) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hashBytes = digest.digest(input.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : hashBytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Hashing algorithm not found", e);
}
}
}

View File

@@ -0,0 +1,16 @@
spring.application.name=api
spring.datasource.url=${DB_URL:jdbc:postgresql://localhost:5432/postgres}
spring.datasource.username=${DB_USERNAME:postgres}
spring.datasource.password=${DB_PASSWORD:mysecretpassword}
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.maximum-pool-size=10
spring.datasource.hikari.idle-timeout=30000
spring.datasource.hikari.pool-name=HikariPool-1
spring.datasource.hikari.max-lifetime=1800000
spring.datasource.hikari.connection-timeout=30000
spring.servlet.multipart.enabled=false
spring.profiles.active=development

View File

@@ -0,0 +1,13 @@
package com.server.api;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ApiApplicationTests {
@Test
void contextLoads() {
}
}

View File

@@ -0,0 +1,12 @@
package com.server.api;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class FlaechendruckTests {
@Test
void testRightColorOrdering() {
}
}

Binary file not shown.

18
deploy.sh Executable file
View File

@@ -0,0 +1,18 @@
-#!/bin/bash
# Setze das aktuelle Verzeichnis auf den Speicherort des Skripts
cd "$(dirname "$0")"
#echo "Pull git"
#git pull
echo "Stopping existing Docker containers..."
docker-compose down --remove-orphans
echo "Rebuilding and starting Docker containers..."
docker-compose up --build -d
echo "Clean Docker Var Lib"
docker system prune -a
echo "Done!"

BIN
doc/img/system_flow.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 519 KiB

BIN
doc/img/template_view_1.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 201 KiB

BIN
doc/img/template_view_2.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 208 KiB

64
docker-compose.yml Normal file
View File

@@ -0,0 +1,64 @@
version: "3.8"
services:
springboot-app:
build:
context: ./api
dockerfile: Dockerfile
ports:
- "127.0.0.1:8080:8080"
depends_on:
- postgres-db
environment:
- DB_URL=${DB_URL}
- DB_USERNAME=${DB_USERNAME}
- DB_PASSWORD=${DB_PASSWORD}
- SHARED_FOLDER=/shared
- NEXT_SERVER_URL=${NEXT_SERVER_URL}
volumes:
- /root/storage:/shared
restart: always
networks:
- app-network
postgres-db:
image: postgres:15
container_name: postgres-db
environment:
POSTGRES_DB: ${POSTGRES_DB}
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
ports:
- "127.0.0.1:5432:5432"
volumes:
- .postgres-data:/var/lib/postgresql/data
restart: always
networks:
- app-network
nextjs-app:
build:
context: ./frontend
dockerfile: Dockerfile
ports:
- "127.0.0.1:3050:3050"
working_dir: /app
command: "npm run start"
depends_on:
- springboot-app
environment:
- NEXT_SERVER_API_URL=${NEXT_SERVER_API_URL}
- BILLBEE_PASSWORD=${BILLBEE_PASSWORD}
- BILLBEE_USERNAME=${BILLBEE_USERNAME}
- BILLBEE_API_KEY=${BILLBEE_API_KEY}
- SESSION_SECRET=${SESSION_SECRET}
restart: always
networks:
- app-network
volumes:
postgres-data:
networks:
app-network:
driver: bridge

22
frontend/Dockerfile Normal file
View File

@@ -0,0 +1,22 @@
FROM node:22-alpine
# Set working directory
WORKDIR /app
# Copy package.json und package-lock.json zuerst, um den Cache zu nutzen
COPY package.json package-lock.json ./
# Installiere alle Abhängigkeiten
RUN npm install
# Kopiere den Rest der Anwendung
COPY . .
# Baue die Next.js-Anwendung
RUN npm run build
# Expose the port your Next.js app runs on
EXPOSE 3050
# Start the Next.js server
CMD ["npm", "run", "start"]

View File

@@ -0,0 +1,44 @@
"use server";
//import { promises as fs } from "fs";
const apiUrl = process.env.NEXT_SERVER_API_URL;
//const sharedFolder = process.env.SHARED_FOLDER;
export async function getVorlagen() {
try {
const response = await fetch(
`${apiUrl}/vorlageFlaechendruck/getAllFlaechendruckVorlagen`
);
if (!response.ok) {
console.error("Response status:", response.status);
throw new Error("Failed to fetch vorlagen");
}
return await response.json();
} catch (error) {
console.error("Error fetching vorlagen:", error);
throw new Error("An error occurred while fetching vorlagen.");
}
}
export async function generateFlaechendruck(formData: FormData) {
const vorlageIds = formData.getAll("vorlageIds") as string[];
const requestBody = {
rootDirectory: "Orders",
vorlageIds: vorlageIds,
};
const response = await fetch(`${apiUrl}/vorlageFlaechendruck/generate`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(requestBody),
cache: "no-store",
});
if (!response.ok) {
const body = await response.text().catch(() => null);
const msg = body ? body : `HTTP ${response.status}`;
return { message: msg, status: false };
} else {
return { message: "Erfolgreiche Flächendruckgenerierung!", status: true };
}
}

View File

@@ -0,0 +1,173 @@
"use client";
import { useState, useEffect } from "react";
import { getVorlagen, generateFlaechendruck } from "./action";
import { toast, Bounce } from "react-toastify";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Label } from "@/components/ui/label";
export default function Page() {
const [vorlagen, setVorlagen] = useState<
{ id: number; name: string; printer: string }[]
>([]);
const [selectedVorlagen, setSelectedVorlagen] = useState<number[]>([]);
const [isUploading, setIsUploading] = useState(false); // Zustand für den Upload
// API-Aufruf, um Vorlagen zu laden
useEffect(() => {
async function fetchData() {
try {
const data = await getVorlagen(); // Server-Action aufrufen
setVorlagen(
data.map(
(item: { id: number; product_type: string; printer: string }) => ({
id: item.id,
name: item.product_type,
printer: item.printer,
})
)
);
} catch (err) {
console.error(err);
}
}
fetchData();
}, []);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (selectedVorlagen.length === 0) {
return;
}
const formData = new FormData();
selectedVorlagen.forEach((id) => {
formData.append("vorlageIds", id.toString());
});
setIsUploading(true);
const res = await generateFlaechendruck(formData);
if (res.status) {
toast.success(res.message, {
position: "bottom-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: false,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
transition: Bounce,
});
} else {
toast.error(res.message, {
position: "bottom-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: false,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
transition: Bounce,
});
}
setIsUploading(false);
};
return (
<div className="min-h-screen bg-gray-100 flex items-center justify-center">
<>
<form onSubmit={handleSubmit}>
<Card className="w-[350px]">
<CardHeader>
<CardTitle>Generierung Flächendruck</CardTitle>
<CardDescription>
Wählen sie Vorlagen zur Generierung aus.
</CardDescription>
</CardHeader>
<CardContent>
{!isUploading ? (
<div className="grid w-full items-center gap-4">
<div className="flex flex-col space-y-1.5">
<Label htmlFor="framework" className="mb-4">
Vorlagen
</Label>
<div className="flex flex-col space-y-2">
{vorlagen.map((vorlage) => (
<div
key={vorlage.id}
className="flex items-start space-x-2"
>
<input
type="checkbox"
id={`vorlage-${vorlage.id}`}
value={vorlage.id}
onChange={(e) => {
const id = parseInt(e.target.value, 10);
if (e.target.checked) {
setSelectedVorlagen((prev) => [...prev, id]);
} else {
setSelectedVorlagen((prev) =>
prev.filter((v) => v !== id)
);
}
}}
className="mt-1"
/>
<label
htmlFor={`vorlage-${vorlage.id}`}
className="text-gray-700"
>
Printer: {vorlage.printer} - {vorlage.name}
</label>
</div>
))}
</div>
</div>
</div>
) : (
<div className="flex items-center justify-center w-full h-32">
<div role="status">
<svg
aria-hidden="true"
className="w-20 h-20 text-gray-200 animate-spin dark:text-gray-600 fill-black"
viewBox="0 0 100 101"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z"
fill="currentColor"
/>
<path
d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z"
fill="currentFill"
/>
</svg>
<span className="sr-only">Loading...</span>
</div>
</div>
)}
</CardContent>
<CardFooter className="flex justify-between">
{!isUploading ? <Button type="submit">Start</Button> : null}
</CardFooter>
</Card>
</form>
</>
</div>
);
}

View File

@@ -0,0 +1,45 @@
"use server";
//import { promises as fs } from "fs";
const apiUrl = process.env.NEXT_SERVER_API_URL;
//const sharedFolder = process.env.SHARED_FOLDER;
export async function getVorlagen() {
try {
const response = await fetch(
`${apiUrl}/VorlageRollenDruck/getAllRollendruckVorlagen`
);
if (!response.ok) {
console.error("Response status:", response.status);
throw new Error("Failed to fetch vorlagen");
}
return await response.json();
} catch (error) {
console.error("Error fetching vorlagen:", error);
throw new Error("An error occurred while fetching vorlagen.");
}
}
export async function uploadFiles(formData: FormData) {
const vorlageIds = formData.getAll("vorlageIds") as string[];
// JSON-Daten erstellen
const requestBody = {
rootDirectory: "Rollendruck",
vorlageIds: vorlageIds,
};
const response = await fetch(`${apiUrl}/VorlageRollenDruck/generate`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(requestBody),
cache: "no-store",
});
if (!response.ok) {
const body = await response.text().catch(() => null);
const msg = body ? body : `HTTP ${response.status}`;
return { message: msg, status: false };
} else {
return { message: "Erfolgreiche Rollendruckgenerierung!", status: true };
}
}

View File

@@ -0,0 +1,180 @@
"use client";
import { useState, useEffect } from "react";
import { getVorlagen, uploadFiles } from "./action";
import { toast, Bounce } from "react-toastify";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Label } from "@/components/ui/label";
export default function Page() {
const [vorlagen, setVorlagen] = useState<
{ id: number; printer: string; height: number; width: number }[]
>([]);
const [selectedVorlagen, setSelectedVorlagen] = useState<number[]>([]);
const [isUploading, setIsUploading] = useState(false); // Zustand für den Upload
// API-Aufruf, um Vorlagen zu laden
useEffect(() => {
async function fetchData() {
try {
const data = await getVorlagen(); // Server-Action aufrufen
setVorlagen(
data.map(
(item: {
id: number;
printer: string;
height: number;
width: number;
}) => ({
id: item.id,
printer: item.printer,
height: item.height,
width: item.width,
})
)
);
} catch (err) {
console.error("Error fetching vorlagen:", err);
}
}
fetchData();
}, []);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (selectedVorlagen.length === 0) {
alert("Please select at least one Vorlage before submitting.");
return;
}
const formData = new FormData();
selectedVorlagen.forEach((id) => {
formData.append("vorlageIds", id.toString()); // Fügt die ausgewählten Vorlagen-IDs hinzu
});
setIsUploading(true);
const res = await uploadFiles(formData);
if (res.status) {
toast.success(res.message, {
position: "bottom-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: false,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
transition: Bounce,
});
} else {
toast.error(res.message, {
position: "bottom-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: false,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
transition: Bounce,
});
}
setIsUploading(false);
};
return (
<div className="min-h-screen bg-gray-100 flex items-center justify-center">
<>
<form onSubmit={handleSubmit}>
<Card className="w-[350px]">
<CardHeader>
<CardTitle>Generierung Rollendruck</CardTitle>
<CardDescription>
Wählen sie Vorlagen zur Generierung aus.
</CardDescription>
</CardHeader>
<CardContent>
{!isUploading ? (
<div className="grid w-full items-center gap-4">
<div className="flex flex-col space-y-1.5">
<Label htmlFor="framework" className="mb-4">
Vorlagen
</Label>
<div className="flex flex-col space-y-2">
{vorlagen.map((vorlage) => (
<div
key={vorlage.id}
className="flex items-start space-x-2"
>
<input
type="checkbox"
id={`vorlage-${vorlage.id}`}
value={vorlage.id}
onChange={(e) => {
const id = parseInt(e.target.value, 10);
if (e.target.checked) {
setSelectedVorlagen((prev) => [...prev, id]);
} else {
setSelectedVorlagen((prev) =>
prev.filter((v) => v !== id)
);
}
}}
className="mt-1"
/>
<label
htmlFor={`vorlage-${vorlage.id}`}
className="text-gray-700"
>
Printer: {vorlage.printer} - {vorlage.height}mm x{" "}
{vorlage.width}mm
</label>
</div>
))}
</div>
</div>
</div>
) : (
<div className="flex items-center justify-center w-full h-32">
<div role="status">
<svg
aria-hidden="true"
className="w-20 h-20 text-gray-200 animate-spin dark:text-gray-600 fill-black"
viewBox="0 0 100 101"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z"
fill="currentColor"
/>
<path
d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z"
fill="currentFill"
/>
</svg>
<span className="sr-only">Loading...</span>
</div>
</div>
)}
</CardContent>
<CardFooter className="flex justify-between">
{!isUploading ? <Button type="submit">Start</Button> : null}
</CardFooter>
</Card>
</form>
</>
</div>
);
}

View File

@@ -0,0 +1,13 @@
import AdminPanelLayout from "@/components/admin-panel/admin-panel-layout";
export default function DashboardLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<AdminPanelLayout>
<main>{children}</main>
</AdminPanelLayout>
);
}

View File

@@ -0,0 +1,14 @@
export default function Page() {
return (
<div className="flex flex-col items-center justify-center min-h-screen bg-gray-100 text-gray-800">
<div className="bg-white shadow-md rounded-lg p-8 max-w-lg text-center">
<h1 className="text-2xl font-bold mb-4 text-gray-900">
Willkommen im Dashboard
</h1>
<h2 className="text-lg text-gray-600">
Navigieren Sie über das Menü auf der linken Seite zu den Anwendungen.
</h2>
</div>
</div>
);
}

View File

@@ -0,0 +1,9 @@
import UploadForm from "@/components/upload-form/page";
export default async function Home() {
return (
<main>
<UploadForm />
</main>
);
}

View File

@@ -0,0 +1,42 @@
"use server";
const apiUrl = process.env.NEXT_SERVER_API_URL;
export async function getTableData() {
try {
const res = await fetch(
`${apiUrl}/vorlageFlaechendruck/getAllFlaechendruckVorlagen`
);
if (!res.ok) {
console.error("Response status:", res.status);
}
const data: {
id: number;
product_type: string;
height: number;
width: number;
printer: string;
coordinates: {
x: number;
y: number;
rotation: number;
}[];
}[] = await res.json();
return data;
} catch (error) {
console.error("Error fetching vorlagen:", error);
throw new Error("An error occurred while fetching vorlagen.");
}
}
export async function deleteVorlageFlaechendruck(id: number) {
const res = await fetch(`${apiUrl}/vorlageFlaechendruck/delete/${id}`, {
method: "DELETE",
});
if (!res.ok) {
throw new Error("Failed to delete item");
}
return;
}

View File

@@ -0,0 +1,83 @@
"use server";
const apiUrl = process.env.NEXT_SERVER_API_URL;
export async function createVorlage(formData: FormData) {
const printer = formData.get("printer") as string;
const product_type = formData.get("product_type") as string;
const height = Number(formData.get("height"));
const width = Number(formData.get("width"));
const coordinatesJson = formData.get("coordinates") as string;
const coordinates = JSON.parse(coordinatesJson);
const payload = {
printer,
product_type,
height,
width,
coordinates,
};
try {
const response = await fetch(
`${apiUrl}/vorlageFlaechendruck/createWithCoordinates`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
cache: "no-store",
}
);
if (!response.ok) {
console.error("Response status:", response.status);
throw new Error("Failed to submit form");
}
} catch (error) {
console.error("Error submitting form:", error);
throw new Error("An error occurred while submitting the form.");
}
}
export async function alterVorlage(formData: FormData) {
const id = Number(formData.get("id"));
const printer = formData.get("printer") as string;
const product_type = formData.get("product_type") as string;
const height = Number(formData.get("height"));
const width = Number(formData.get("width"));
const coordinatesJson = formData.get("coordinates") as string;
const coordinates = JSON.parse(coordinatesJson);
const payload = {
id,
printer,
product_type,
height,
width,
coordinates,
};
try {
const response = await fetch(
`${apiUrl}/vorlageFlaechendruck/alterVorlage`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
cache: "no-store",
}
);
if (!response.ok) {
console.error("Response status:", response.status);
throw new Error("Failed to submit form");
}
} catch (error) {
console.error("Error submitting form:", error);
throw new Error("An error occurred while submitting the form.");
}
}

View File

@@ -0,0 +1,276 @@
"use Client";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { z } from "zod"
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Separator } from "@/components/ui/separator";
import { Plus } from "lucide-react";
import { useFieldArray } from "react-hook-form";
import { createVorlage } from "./action";
import { useState } from "react";
export default function AddDialog({ onNewEntry }: { onNewEntry: () => void }) {
const [open, setOpen] = useState(false)
const formSchema = z.object({
Drucker: z.string().min(1, {
message: "Druckername muss mindestens 2 Zeichen lang sein.",
}),
Artikeltyp: z.string().min(1, {
message: "Artikeltyp muss mindestens 2 Zeichen lang sein.",
}),
Höhe: z.preprocess(
(value) => (typeof value === "string" ? parseFloat(value) : value),
z.number({
invalid_type_error: "Höhe muss eine gültige Zahl sein. Bspw. 1.5 .",
}).min(1, {
message: "Höhe muss mindestens 1 sein.",
})
),
Breite: z.preprocess(
(value) => (typeof value === "string" ? parseFloat(value) : value),
z.number({
invalid_type_error: "Breite muss eine gültige Zahl sein. Bspw. 1.5 .",
}).min(1, {
message: "Breite muss mindestens 1 sein.",
})
),
Koordinaten: z.array(
z.object({
x: z.preprocess(
(value) => (typeof value === "string" ? parseFloat(value) : value),
z.number().min(0, {
message: "X-Koordinate muss mindestens 0 sein.",
})
),
y: z.preprocess(
(value) => (typeof value === "string" ? parseFloat(value) : value),
z.number().min(0, {
message: "Y-Koordinate muss mindestens 0 sein.",
})
),
rotation: z.preprocess(
(value) => (typeof value === "string" ? parseFloat(value) : value),
z.number().min(0, {
message: "Rotation muss mindestens 0 sein.",
})
),
})
).min(1, {
message: "Es muss mindestens eine Koordinate angegeben werden.",
}),
});
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
Drucker: "",
Artikeltyp: "",
Höhe: 0,
Breite: 0,
Koordinaten: [{ x: 0, y: 0, rotation: 0 }],
},
});
const { fields, append, remove } = useFieldArray({
control: form.control,
name: "Koordinaten",
});
async function onSubmit(values: z.infer<typeof formSchema>) {
const formData = new FormData();
formData.append("printer", values.Drucker);
formData.append("product_type", values.Artikeltyp);
formData.append("height", values.Höhe.toString());
formData.append("width", values.Breite.toString());
formData.append("coordinates", JSON.stringify(values.Koordinaten));
try {
await createVorlage(formData);
setOpen(false);
form.reset();
onNewEntry();
}
catch (error) {
console.error("Error submitting form:", error);
throw new Error("An error occurred while submitting the form.");
}
}
return (
<div>
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button variant="outline" className="mt-2 mb-2 border-green-700 text-green-700">
Vorlage hinzufügen
</Button>
</DialogTrigger>
<DialogContent className="max-w-screen-lg max-h-screen overflow-y-auto">
<DialogHeader>
<DialogTitle className="mb-8">Vorlage hinzufügen</DialogTitle>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
<FormField
control={form.control}
name="Drucker"
render={({ field }) => (
<FormItem>
<FormLabel>Drucker Name</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<DialogDescription>
Der Name des Druckers, auf dem die Vorlage gedruckt wird.
</DialogDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="Artikeltyp"
render={({ field }) => (
<FormItem>
<FormLabel>Artikel Typ</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<DialogDescription>
Der Name des Artikels, der auf der Vorlage gedruckt wird.
</DialogDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="Höhe"
render={({ field }) => (
<FormItem>
<FormLabel>Höhe</FormLabel>
<FormControl>
<Input type="number" step="any" {...field} />
</FormControl>
<FormDescription>
Die Höhe der Vorlage in Millimeter.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="Breite"
render={({ field }) => (
<FormItem>
<FormLabel>Breite</FormLabel>
<FormControl>
<Input type="number" step="any" {...field} />
</FormControl>
<FormDescription>
Die Breite der Vorlage in Millimeter.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<div className="max-h-64 overflow-y-auto">
<FormLabel className="mb-4">Koordinaten:</FormLabel>
<Separator />
{fields.map((field, index) => (
<div key={field.id} className="space-y-4">
<FormField
control={form.control}
name={`Koordinaten.${index}.x`}
render={({ field }) => (
<FormItem className="mt-4">
<FormLabel>X-Koordinate</FormLabel>
<FormControl>
<Input type="number" step="any" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name={`Koordinaten.${index}.y`}
render={({ field }) => (
<FormItem>
<FormLabel>Y-Koordinate</FormLabel>
<FormControl>
<Input type="number" step="any" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name={`Koordinaten.${index}.rotation`}
render={({ field }) => (
<FormItem>
<FormLabel>Rotation</FormLabel>
<FormControl>
<Input type="number" step="any" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button
type="button"
variant="destructive"
onClick={() => remove(index)}
>
Entfernen
</Button>
<Separator className="mt-4" />
</div>
))}
<Button
type="button"
variant="outline"
onClick={() => append({ x: 0, y: 0, rotation: 0 })}
className="mt-4"
>
<Plus />
</Button>
</div>
<Button type="submit">
Hinzufügen
</Button>
</form>
</Form>
</DialogHeader>
</DialogContent>
</Dialog>
</div>
);
}

View File

@@ -0,0 +1,294 @@
"use Client";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { z } from "zod"
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Separator } from "@/components/ui/separator";
import { Plus } from "lucide-react";
import { useFieldArray } from "react-hook-form";
import { alterVorlage } from "./action";
import { useState } from "react";
type TableData = {
id: number;
product_type: string;
height: number;
width: number;
printer: string;
coordinates: { x: number; y: number; rotation: number }[];
};
type AlterDialogProps = {
onNewEntry: () => void;
data: TableData;
};
export default function AlterDialog({ onNewEntry, data }: AlterDialogProps) {
const [open, setOpen] = useState(false)
const formSchema = z.object({
Drucker: z.string().min(1, {
message: "Druckername muss mindestens 2 Zeichen lang sein.",
}),
Artikeltyp: z.string().min(1, {
message: "Artikeltyp muss mindestens 2 Zeichen lang sein.",
}),
Höhe: z.preprocess(
(value) => (typeof value === "string" ? parseFloat(value) : value),
z.number({
invalid_type_error: "Höhe muss eine gültige Zahl sein. Bspw. 1.5 .",
}).min(1, {
message: "Höhe muss mindestens 1 sein.",
})
),
Breite: z.preprocess(
(value) => (typeof value === "string" ? parseFloat(value) : value),
z.number({
invalid_type_error: "Breite muss eine gültige Zahl sein. Bspw. 1.5 .",
}).min(1, {
message: "Breite muss mindestens 1 sein.",
})
),
Koordinaten: z.array(
z.object({
x: z.preprocess(
(value) => (typeof value === "string" ? parseFloat(value) : value),
z.number().min(0, {
message: "X-Koordinate muss mindestens 0 sein.",
})
),
y: z.preprocess(
(value) => (typeof value === "string" ? parseFloat(value) : value),
z.number().min(0, {
message: "Y-Koordinate muss mindestens 0 sein.",
})
),
rotation: z.preprocess(
(value) => (typeof value === "string" ? parseFloat(value) : value),
z.number().min(0, {
message: "Rotation muss mindestens 0 sein.",
})
),
})
).min(1, {
message: "Es muss mindestens eine Koordinate angegeben werden.",
}),
});
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
Drucker: data.printer,
Artikeltyp: data.product_type,
Höhe: data.height,
Breite: data.width,
Koordinaten: data.coordinates.map((coord) => ({
x: coord.x,
y: coord.y,
rotation: coord.rotation,
})),
},
});
const { fields, append, remove } = useFieldArray({
control: form.control,
name: "Koordinaten",
});
async function onSubmit(values: z.infer<typeof formSchema>) {
const formData = new FormData();
formData.append("id", data.id.toString());
formData.append("printer", values.Drucker);
formData.append("product_type", values.Artikeltyp);
formData.append("height", values.Höhe.toString());
formData.append("width", values.Breite.toString());
formData.append("coordinates", JSON.stringify(values.Koordinaten));
try {
await alterVorlage(formData);
setOpen(false);
form.reset();
onNewEntry();
}
catch (error) {
console.error("Error submitting form:", error);
throw new Error("An error occurred while submitting the form.");
}
}
return (
<div>
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button variant="ghost" className="font-normal pl-2">
Vorlage bearbeiten
</Button>
</DialogTrigger>
<DialogContent className="max-w-screen-lg max-h-screen overflow-y-auto">
<DialogHeader>
<DialogTitle className="mb-8">Vorlage bearbeiten</DialogTitle>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
<FormField
control={form.control}
name="Drucker"
render={({ field }) => (
<FormItem>
<FormLabel>Drucker Name</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<DialogDescription>
Der Name des Druckers, auf dem die Vorlage gedruckt wird.
</DialogDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="Artikeltyp"
render={({ field }) => (
<FormItem>
<FormLabel>Artikel Typ</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<DialogDescription>
Der Name des Artikels, der auf der Vorlage gedruckt wird.
</DialogDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="Höhe"
render={({ field }) => (
<FormItem>
<FormLabel>Höhe</FormLabel>
<FormControl>
<Input type="number" step="any" {...field} />
</FormControl>
<FormDescription>
Die Höhe der Vorlage in Millimeter.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="Breite"
render={({ field }) => (
<FormItem>
<FormLabel>Breite</FormLabel>
<FormControl>
<Input type="number" step="any" {...field} />
</FormControl>
<FormDescription>
Die Breite der Vorlage in Millimeter.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<div className="max-h-64 overflow-y-auto">
<FormLabel className="mb-4">Koordinaten:</FormLabel>
<Separator />
{fields.map((field, index) => (
<div key={field.id} className="space-y-4">
<FormField
control={form.control}
name={`Koordinaten.${index}.x`}
render={({ field }) => (
<FormItem className="mt-4">
<FormLabel>X-Koordinate</FormLabel>
<FormControl>
<Input type="number" step="any" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name={`Koordinaten.${index}.y`}
render={({ field }) => (
<FormItem>
<FormLabel>Y-Koordinate</FormLabel>
<FormControl>
<Input type="number" step="any" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name={`Koordinaten.${index}.rotation`}
render={({ field }) => (
<FormItem>
<FormLabel>Rotation</FormLabel>
<FormControl>
<Input type="number" step="any" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button
type="button"
variant="destructive"
onClick={() => remove(index)}
>
Entfernen
</Button>
<Separator className="mt-4" />
</div>
))}
<Button
type="button"
variant="outline"
onClick={() => append({ x: 0, y: 0, rotation: 0 })}
className="mt-4"
>
<Plus />
</Button>
</div>
<Button type="submit">
Änderungen speichern
</Button>
</form>
</Form>
</DialogHeader>
</DialogContent>
</Dialog>
</div>
);
}

View File

@@ -0,0 +1,199 @@
"use client";
import { useEffect, useState } from "react";
import { Ellipsis } from "lucide-react"
import { getTableData, deleteVorlageFlaechendruck } from "./action";
import {
Table,
TableBody,
TableCaption,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
import AddDialog from "./components/addDialog";
import AlterDialog from "./components/alterDialog";
type TableData = {
id: number;
product_type: string;
height: number;
width: number;
printer: string;
coordinates: { x: number; y: number; rotation: number }[];
};
export default function Page() {
const [data, setData] = useState<TableData[]>([]);
useEffect(() => {
async function fetchData() {
try {
const result = await getTableData();
setData(result);
} catch (error) {
console.error("Fehler beim Laden der Daten:", error);
}
}
fetchData();
}, []);
const handleNewEntry = async () => {
try {
const result = await getTableData(); // Daten erneut abrufen
setData(result); // Tabelle aktualisieren
} catch (error) {
console.error("Fehler beim Aktualisieren der Daten:", error);
}
};
const deleteEntry = async (id: number) => {
try {
await deleteVorlageFlaechendruck(id);
await handleNewEntry();
}
catch (error) {
console.error("Fehler beim Löschen der Daten:", error);
}
};
return (
<div className="min-h-screen bg-gray-50 p-6">
<div className="max-w-5xl mx-auto">
{/* Table Section */}
<Table className="bg-white shadow-md border border-gray-300">
<TableCaption>Vorlagen Flächendruck</TableCaption>
<TableHeader>
<TableRow>
<TableHead className="w-[100px]">Drucker</TableHead>
<TableHead>Artikel Typ</TableHead>
<TableHead>Höhe</TableHead>
<TableHead>Breite</TableHead>
<TableHead>Koordinaten</TableHead>
<TableHead className="text-right">
<AddDialog onNewEntry={handleNewEntry} />
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{data.map((item) => (
<TableRow key={item.id}>
<TableCell>{item.printer}</TableCell>
<TableCell>{item.product_type}</TableCell>
<TableCell>{item.height}</TableCell>
<TableCell >{item.width}</TableCell>
<TableCell>
<Dialog>
<DialogTrigger asChild>
<Button variant="outline">Anzeigen</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Koordinaten</DialogTitle>
<DialogDescription>
Hier sind die Koordinaten für die ausgewählte Vorlage. X und Y Werte in Millimetern.
</DialogDescription>
</DialogHeader>
<Table>
<TableCaption>Koordinaten Tabelle</TableCaption>
<TableHeader>
<TableRow>
<TableHead>X</TableHead>
<TableHead>Y</TableHead>
<TableHead className="text-right">Rotation</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{item.coordinates.map((coordi) => (
<TableRow key={crypto.randomUUID()}>
<TableCell>{coordi.x}</TableCell>
<TableCell>{coordi.y}</TableCell>
<TableCell className="text-right">{coordi.rotation}°</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</DialogContent>
</Dialog>
</TableCell>
<TableCell className="text-right">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon">
<Ellipsis />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<AlterDialog onNewEntry={handleNewEntry} data={item} />
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive">
<AlertDialog>
<AlertDialogTrigger
onClick={(event) => {
event.stopPropagation(); // Verhindert das Schließen des Dropdown-Menüs
}}
>
Eintrag Löschen
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Sind Sie sich sicher?</AlertDialogTitle>
<AlertDialogDescription>
Diese Aktion ist permanent und kann nicht rückgängig gemacht werden.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Abbrechen</AlertDialogCancel>
<AlertDialogAction
onClick={() => {
deleteEntry(item.id); // Eintrag löschen
}}
>
Löschen
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
</div>
);
}

View File

@@ -0,0 +1,69 @@
"use server";
const apiUrl = process.env.NEXT_SERVER_API_URL;
export async function getTableData() {
try {
const res = await fetch(
`${apiUrl}/VorlageRollenDruck/getAllRollendruckVorlagen`
);
if (!res.ok) {
console.error("Response status:", res.status);
}
const data: {
id: number;
height: number;
width: number;
printer: string;
articleTypes: string;
}[] = await res.json();
return data;
} catch (error) {
console.error("Error fetching vorlagen:", error);
throw new Error("An error occurred while fetching vorlagen.");
}
}
export async function deleteVorlageRollendruck(id: number) {
const res = await fetch(`${apiUrl}/VorlageRollenDruck/delete/${id}`, {
method: "DELETE",
});
if (!res.ok) {
throw new Error("Failed to delete item");
}
return;
}
export async function getTableDataDupli() {
try {
const res = await fetch(
`${apiUrl}/VorlageRollenDruck/getAllDupliArtikel`
);
if (!res.ok) {
console.error("Response status:", res.status);
}
const data: {
id: number;
product_type: string;
}[] = await res.json();
return data;
} catch (error) {
console.error("Error fetching vorlagen:", error);
throw new Error("An error occurred while fetching vorlagen.");
}
}
export async function deleteDupliEntry(id: number) {
const res = await fetch(`${apiUrl}/VorlageRollenDruck/deleteDupli/${id}`, {
method: "DELETE",
});
if (!res.ok) {
throw new Error("Failed to delete item");
}
return;
}

View File

@@ -0,0 +1,107 @@
"use server";
const apiUrl = process.env.NEXT_SERVER_API_URL;
export async function createVorlage(formData: FormData) {
const printer = formData.get("printer") as string;
const height = Number(formData.get("height"));
const width = Number(formData.get("width"));
const articleTypes = formData.get("articleTypes") as string;
const payload = {
printer,
height,
width,
articleTypes
};
try {
const response = await fetch(
`${apiUrl}/VorlageRollenDruck/createRollenDruckVorlage`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
cache: "no-store",
}
);
if (!response.ok) {
console.error("Response status:", response.status);
throw new Error("Failed to submit form");
}
} catch (error) {
console.error("Error submitting form:", error);
throw new Error("An error occurred while submitting the form.");
}
}
export async function alterVorlage(formData: FormData) {
const id = Number(formData.get("id"));
const printer = formData.get("printer") as string;
const height = Number(formData.get("height"));
const width = Number(formData.get("width"));
const articleTypes = formData.get("articleTypes") as string;
const payload = {
id,
printer,
height,
width,
articleTypes
};
try {
const response = await fetch(
`${apiUrl}/VorlageRollenDruck/alterVorlage`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
cache: "no-store",
}
);
if (!response.ok) {
console.error("Response status:", response.status);
throw new Error("Failed to submit form");
}
} catch (error) {
console.error("Error submitting form:", error);
throw new Error("An error occurred while submitting the form.");
}
}
export async function addDupliArtikel(fromData: FormData) {
const artikelTyp = fromData.get("ArtikelTyp") as string;
const payload = {
product_type: artikelTyp,
};
try {
const response = await fetch(
`${apiUrl}/VorlageRollenDruck/addDupliArtikel`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
cache: "no-store",
}
);
if (!response.ok) {
console.error("Response status:", response.status);
throw new Error("Failed to submit form");
}
} catch (error) {
console.error("Error submitting form:", error);
throw new Error("An error occurred while submitting the form.");
}
}

View File

@@ -0,0 +1,177 @@
"use Client";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { z } from "zod"
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { createVorlage } from "./action";
import { useState } from "react";
export default function AddDialog({ onNewEntry }: { onNewEntry: () => void }) {
const [open, setOpen] = useState(false)
const formSchema = z.object({
Drucker: z.string().min(1, {
message: "Druckername muss mindestens 2 Zeichen lang sein.",
}),
Höhe: z.preprocess(
(value) => (typeof value === "string" ? parseFloat(value) : value),
z.number({
invalid_type_error: "Höhe muss eine gültige Zahl sein. Bspw. 1.5 .",
}).min(1, {
message: "Höhe muss mindestens 1 sein.",
})
),
Breite: z.preprocess(
(value) => (typeof value === "string" ? parseFloat(value) : value),
z.number({
invalid_type_error: "Breite muss eine gültige Zahl sein. Bspw. 1.5 .",
}).min(1, {
message: "Breite muss mindestens 1 sein.",
})
),
ArtikelTypen: z
.string()
.regex(/^(\s*\w+\s*)(,\s*\w+\s*)*$/, {
message: "Bitte geben Sie eine durch Kommas getrennte Liste ein (z.B. te, bs, s, s, s)",
}),
});
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
Drucker: "",
Höhe: 0,
Breite: 0,
ArtikelTypen: "",
},
});
async function onSubmit(values: z.infer<typeof formSchema>) {
const formData = new FormData();
formData.append("printer", values.Drucker);
formData.append("height", values.Höhe.toString());
formData.append("width", values.Breite.toString());
formData.append("articleTypes", values.ArtikelTypen);
try {
await createVorlage(formData);
setOpen(false);
form.reset();
onNewEntry();
}
catch (error) {
console.error("Error submitting form:", error);
throw new Error("An error occurred while submitting the form.");
}
}
return (
<div>
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button variant="outline" className="mt-2 mb-2 border-green-700 text-green-700">
Vorlage hinzufügen
</Button>
</DialogTrigger>
<DialogContent className="max-w-screen-lg max-h-screen overflow-y-auto">
<DialogHeader>
<DialogTitle className="mb-8">Vorlage hinzufügen</DialogTitle>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
<FormField
control={form.control}
name="Drucker"
render={({ field }) => (
<FormItem>
<FormLabel>Drucker Name</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<DialogDescription>
Der Name des Druckers, auf dem die Vorlage gedruckt wird.
</DialogDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="Höhe"
render={({ field }) => (
<FormItem>
<FormLabel>Höhe</FormLabel>
<FormControl>
<Input type="number" step="any" {...field} />
</FormControl>
<FormDescription>
Die Höhe der Vorlage in Millimeter.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="Breite"
render={({ field }) => (
<FormItem>
<FormLabel>Breite</FormLabel>
<FormControl>
<Input type="number" step="any" {...field} />
</FormControl>
<FormDescription>
Die Breite der Vorlage in Millimeter.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="ArtikelTypen"
render={({ field }) => (
<FormItem>
<FormLabel>Artikel Typen</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormDescription>
Geben Sie die Artikeltypen als durch Kommas getrennte Liste ein (z.B. te, bs, s, s, s).
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit">
Hinzufügen
</Button>
</form>
</Form>
</DialogHeader>
</DialogContent>
</Dialog>
</div>
);
}

View File

@@ -0,0 +1,99 @@
"use Client";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { z } from "zod"
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import {addDupliArtikel} from "./action";
import { useState } from "react";
import {Plus} from "lucide-react";
export default function AddDialog({ onNewEntry }: { onNewEntry: () => void }) {
const [open, setOpen] = useState(false)
const formSchema = z.object({
ArtikelTyp: z.string().min(1, {
message: "Druckername muss mindestens 2 Zeichen lang sein.",
}),
});
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
ArtikelTyp: "",
},
});
async function onSubmit(values: z.infer<typeof formSchema>) {
const formData = new FormData();
formData.append("ArtikelTyp", values.ArtikelTyp);
try {
await addDupliArtikel(formData);
setOpen(false);
form.reset();
onNewEntry();
}
catch (error) {
console.error("Error submitting form:", error);
throw new Error("An error occurred while submitting the form.");
}
}
return (
<div>
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button variant={"outline"} className="border-green-700 text-green-700 mt-2 mb-2" ><Plus /></Button>
</DialogTrigger>
<DialogContent className="max-w-screen-lg max-h-screen overflow-y-auto">
<DialogHeader>
<DialogTitle className="mb-8">ArtikelTyp hinzufügen</DialogTitle>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
<FormField
control={form.control}
name="ArtikelTyp"
render={({ field }) => (
<FormItem>
<FormLabel>ArtikelTyp</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<DialogDescription>
Der Typ des Artikels, der dupliziert gedruckt werden soll.
</DialogDescription>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit">
Hinzufügen
</Button>
</form>
</Form>
</DialogHeader>
</DialogContent>
</Dialog>
</div>
);
}

View File

@@ -0,0 +1,190 @@
"use Client";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { z } from "zod"
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { alterVorlage } from "./action";
import { useState } from "react";
type TableData = {
id: number;
printer: string;
height: number;
width: number;
articleTypes: string;
};
type AlterDialogProps = {
onNewEntry: () => void;
data: TableData;
};
export default function AlterDialog({ onNewEntry, data }: AlterDialogProps) {
const [open, setOpen] = useState(false)
const formSchema = z.object({
Drucker: z.string().min(1, {
message: "Druckername muss mindestens 2 Zeichen lang sein.",
}),
Höhe: z.preprocess(
(value) => (typeof value === "string" ? parseFloat(value) : value),
z.number({
invalid_type_error: "Höhe muss eine gültige Zahl sein. Bspw. 1.5 .",
}).min(1, {
message: "Höhe muss mindestens 1 sein.",
})
),
Breite: z.preprocess(
(value) => (typeof value === "string" ? parseFloat(value) : value),
z.number({
invalid_type_error: "Breite muss eine gültige Zahl sein. Bspw. 1.5 .",
}).min(1, {
message: "Breite muss mindestens 1 sein.",
})
),
ArtikelTypen: z
.string()
.regex(/^(\s*\w+\s*)(,\s*\w+\s*)*$/, {
message: "Bitte geben Sie eine durch Kommas getrennte Liste ein (z.B. te, bs, s, s, s)",
}),
});
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
Drucker: data.printer,
Höhe: data.height,
Breite: data.width,
ArtikelTypen: data.articleTypes,
},
});
async function onSubmit(values: z.infer<typeof formSchema>) {
const formData = new FormData();
formData.append("id", data.id.toString());
formData.append("printer", values.Drucker);
formData.append("height", values.Höhe.toString());
formData.append("width", values.Breite.toString());
formData.append("articleTypes", values.ArtikelTypen);
try {
await alterVorlage(formData);
setOpen(false);
form.reset();
onNewEntry();
}
catch (error) {
console.error("Error submitting form:", error);
throw new Error("An error occurred while submitting the form.");
}
}
return (
<div>
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button variant="ghost" className="font-normal pl-2">
Vorlage bearbeiten
</Button>
</DialogTrigger>
<DialogContent className="max-w-screen-lg max-h-screen overflow-y-auto">
<DialogHeader>
<DialogTitle className="mb-8">Vorlage bearbeiten</DialogTitle>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
<FormField
control={form.control}
name="Drucker"
render={({ field }) => (
<FormItem>
<FormLabel>Drucker Name</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<DialogDescription>
Der Name des Druckers, auf dem die Vorlage gedruckt wird.
</DialogDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="Höhe"
render={({ field }) => (
<FormItem>
<FormLabel>Höhe</FormLabel>
<FormControl>
<Input type="number" step="any" {...field} />
</FormControl>
<FormDescription>
Die Höhe der Vorlage in Millimeter.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="Breite"
render={({ field }) => (
<FormItem>
<FormLabel>Breite</FormLabel>
<FormControl>
<Input type="number" step="any" {...field} />
</FormControl>
<FormDescription>
Die Breite der Vorlage in Millimeter.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="ArtikelTypen"
render={({ field }) => (
<FormItem>
<FormLabel>Artikel Typen</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormDescription>
Geben Sie eine durch Kommas getrennte Liste von Artikeltypen ein (z.B. te, bs, s, s, s).
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit">
Änderungen speichern
</Button>
</form>
</Form>
</DialogHeader>
</DialogContent>
</Dialog>
</div>
);
}

View File

@@ -0,0 +1,227 @@
"use client";
import { useEffect, useState } from "react";
import { Ellipsis } from "lucide-react"
import { getTableData, deleteVorlageRollendruck, getTableDataDupli, deleteDupliEntry } from "./action";
import {
Table,
TableBody,
TableCaption,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"
import { Button } from "@/components/ui/button"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import AddDialog from "./components/addDialog";
import AlterDialog from "./components/alterDialog";
import AddDialogDupli from "./components/addDialogDupli";
type TableData = {
id: number;
printer: string;
height: number;
width: number;
articleTypes: string;
};
export default function Page() {
const [data, setData] = useState<TableData[]>([]);
const [dupliData, setDupliData] = useState<{ id: number; product_type: string }[]>([]);
useEffect(() => {
async function fetchData() {
try {
const result = await getTableData();
setData(result || []);
const dupliResult = await getTableDataDupli();
setDupliData(Array.isArray(dupliResult) ? dupliResult : []);
} catch (error) {
console.error("Fehler beim Laden der Daten:", error);
}
}
fetchData();
}, []);
const handleNewEntry = async () => {
try {
const result = await getTableData(); // Daten erneut abrufen
setData(result); // Tabelle aktualisieren
} catch (error) {
console.error("Fehler beim Aktualisieren der Daten:", error);
}
};
const handleNewEntry2 = async () => {
try {
const result = await getTableDataDupli(); // Daten erneut abrufen
setDupliData(result) // Tabelle aktualisieren
} catch (error) {
console.error("Fehler beim Aktualisieren der Daten:", error);
}
};
const deleteEntry = async (id: number) => {
try {
await deleteVorlageRollendruck(id);
await handleNewEntry();
}
catch (error) {
console.error("Fehler beim Löschen der Daten:", error);
}
};
const deleteEntryDupli = async (id: number) => {
try {
await deleteDupliEntry(id);
await handleNewEntry2();
}
catch (error) {
console.error("Fehler beim Löschen der Daten:", error);
}
}
return (
<div className="min-h-screen bg-gray-50 p-6">
<div className="flex w-full max-w-6xl mx-auto gap-2">
<div className="w-1/3 flex-shrink-0">
<Table className="bg-white shadow-md border border-gray-300">
<TableCaption>Artikel für Duplizierung</TableCaption>
<TableHeader>
<TableRow>
<TableHead className="w-[100px]">Artikel Typ</TableHead>
<TableHead className="text-right">
<AddDialogDupli onNewEntry={handleNewEntry2} />
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{dupliData.map((item) => (
<TableRow key={item.id}>
<TableCell>{item.product_type}</TableCell>
<TableCell className="text-right">
<Button onClick={() => {
deleteEntryDupli(item.id); // Eintrag löschen
}} variant={"outline"} className="border-red-700 text-red-700 h-6">Entfernen</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
<div className="flex-1">
<Table className="bg-white shadow-md border border-gray-300">
<TableCaption>Vorlagen Rollendruck</TableCaption>
<TableHeader>
<TableRow>
<TableHead className="w-[100px]">Drucker</TableHead>
<TableHead>Höhe</TableHead>
<TableHead>Breite</TableHead>
<TableHead>Artikel Typen</TableHead>
<TableHead className="text-right">
<AddDialog onNewEntry={handleNewEntry} />
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{data.map((item) => (
<TableRow key={item.id}>
<TableCell>{item.printer}</TableCell>
<TableCell>{item.height}</TableCell>
<TableCell>{item.width}</TableCell>
<TableCell>
<Dialog>
<DialogTrigger asChild>
<Button variant="outline">Anzeigen</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Artikel Typen</DialogTitle>
<DialogDescription>
Hier sind die Artikel Typen gelistet, die von der Vorlage unterstützt werden.
</DialogDescription>
</DialogHeader>
{item.articleTypes}
</DialogContent>
</Dialog>
</TableCell>
<TableCell className="text-right">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon">
<Ellipsis />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<AlterDialog onNewEntry={handleNewEntry} data={item} />
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive">
<AlertDialog>
<AlertDialogTrigger
onClick={(event) => {
event.stopPropagation(); // Verhindert das Schließen des Dropdown-Menüs
}}
>
Eintrag Löschen
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Sind Sie sich sicher?</AlertDialogTitle>
<AlertDialogDescription>
Diese Aktion ist permanent und kann nicht rückgängig gemacht werden.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Abbrechen</AlertDialogCancel>
<AlertDialogAction
onClick={() => {
deleteEntry(item.id); // Eintrag löschen
}}
>
Löschen
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
</div>
</div>
);
}

BIN
frontend/app/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

122
frontend/app/globals.css Normal file
View File

@@ -0,0 +1,122 @@
@import "tailwindcss";
@import "tw-animate-css";
@custom-variant dark (&:is(.dark *));
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
--color-destructive: var(--destructive);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
--color-card: var(--card);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
}
:root {
--radius: 0.625rem;
--background: oklch(1 0 0);
--foreground: oklch(0.147 0.004 49.25);
--card: oklch(1 0 0);
--card-foreground: oklch(0.147 0.004 49.25);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.147 0.004 49.25);
--primary: oklch(0.216 0.006 56.043);
--primary-foreground: oklch(0.985 0.001 106.423);
--secondary: oklch(0.97 0.001 106.424);
--secondary-foreground: oklch(0.216 0.006 56.043);
--muted: oklch(0.97 0.001 106.424);
--muted-foreground: oklch(0.553 0.013 58.071);
--accent: oklch(0.97 0.001 106.424);
--accent-foreground: oklch(0.216 0.006 56.043);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.923 0.003 48.717);
--input: oklch(0.923 0.003 48.717);
--ring: oklch(0.709 0.01 56.259);
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
--sidebar: oklch(0.985 0.001 106.423);
--sidebar-foreground: oklch(0.147 0.004 49.25);
--sidebar-primary: oklch(0.216 0.006 56.043);
--sidebar-primary-foreground: oklch(0.985 0.001 106.423);
--sidebar-accent: oklch(0.97 0.001 106.424);
--sidebar-accent-foreground: oklch(0.216 0.006 56.043);
--sidebar-border: oklch(0.923 0.003 48.717);
--sidebar-ring: oklch(0.709 0.01 56.259);
}
.dark {
--background: oklch(0.147 0.004 49.25);
--foreground: oklch(0.985 0.001 106.423);
--card: oklch(0.216 0.006 56.043);
--card-foreground: oklch(0.985 0.001 106.423);
--popover: oklch(0.216 0.006 56.043);
--popover-foreground: oklch(0.985 0.001 106.423);
--primary: oklch(0.923 0.003 48.717);
--primary-foreground: oklch(0.216 0.006 56.043);
--secondary: oklch(0.268 0.007 34.298);
--secondary-foreground: oklch(0.985 0.001 106.423);
--muted: oklch(0.268 0.007 34.298);
--muted-foreground: oklch(0.709 0.01 56.259);
--accent: oklch(0.268 0.007 34.298);
--accent-foreground: oklch(0.985 0.001 106.423);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.553 0.013 58.071);
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.216 0.006 56.043);
--sidebar-foreground: oklch(0.985 0.001 106.423);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0.001 106.423);
--sidebar-accent: oklch(0.268 0.007 34.298);
--sidebar-accent-foreground: oklch(0.985 0.001 106.423);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.553 0.013 58.071);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
}

49
frontend/app/layout.tsx Normal file
View File

@@ -0,0 +1,49 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import { ToastContainer, Bounce } from "react-toastify";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "ERP - Wolga Kreativ",
description: "Wolga ERP",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en" suppressHydrationWarning>
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
<ToastContainer
position="bottom-right"
autoClose={5000}
hideProgressBar={false}
newestOnTop={false}
closeOnClick={false}
rtl={false}
pauseOnFocusLoss
draggable
pauseOnHover
theme="light"
transition={Bounce}
/>
{children}
</body>
</html>
);
}

View File

@@ -0,0 +1,9 @@
import SignInPage from "@/components/auth/signin-form";
export default function Page() {
return (
<>
<SignInPage></SignInPage>
</>
);
}

21
frontend/components.json Normal file
View File

@@ -0,0 +1,21 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "",
"css": "app/globals.css",
"baseColor": "stone",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}

View File

@@ -0,0 +1,15 @@
"use server";
const apiUrl = process.env.NEXT_SERVER_API_URL;
export async function deleteVorlageFlaechendruck(id: number) {
const res = await fetch(`${apiUrl}/vorlageFlaechendruck/delete/${id}`, {
method: "DELETE",
});
if (!res.ok) {
throw new Error("Failed to delete item");
}
return;
}

View File

@@ -0,0 +1,46 @@
"use client";
import { Footer } from "@/components/admin-panel/footer";
import { Sidebar } from "@/components/admin-panel/sidebar";
import { useSidebar } from "@/hooks/use-sidebar";
import { useStore } from "@/hooks/use-store";
import { cn } from "@/lib/utils";
export default function AdminPanelLayout({
children
}: {
children: React.ReactNode;
}) {
const sidebar = useStore(useSidebar, (x) => x);
if (!sidebar) return null;
const { getOpenState, settings } = sidebar;
return (
<>
<Sidebar />
<main
className={cn(
"min-h-[calc(100vh_-_56px)] bg-zinc-50 dark:bg-zinc-900 transition-[margin-left] ease-in-out duration-300",
!settings.disabled
? getOpenState()
? "ml-0 lg:ml-72" // Sidebar geöffnet
: "ml-0 lg:ml-[90px]" // Sidebar minimiert
: "ml-0" // Sidebar deaktiviert
)}
>
{children}
</main>
<footer
className={cn(
"transition-[margin-left] ease-in-out duration-300",
!settings.disabled
? getOpenState()
? "ml-0 lg:ml-72"
: "ml-0 lg:ml-[90px]"
: "ml-0"
)}
>
<Footer />
</footer>
</>
);
}

View File

@@ -0,0 +1,189 @@
"use client";
import Link from "next/link";
import { useState } from "react";
import { ChevronDown, Dot, LucideIcon } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { DropdownMenuArrow } from "@radix-ui/react-dropdown-menu";
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger
} from "@/components/ui/collapsible";
import {
Tooltip,
TooltipTrigger,
TooltipContent,
TooltipProvider
} from "@/components/ui/tooltip";
import {
DropdownMenu,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuSeparator
} from "@/components/ui/dropdown-menu";
import { usePathname } from "next/navigation";
type Submenu = {
href: string;
label: string;
active?: boolean;
};
interface CollapseMenuButtonProps {
icon: LucideIcon;
label: string;
active: boolean;
submenus: Submenu[];
isOpen: boolean | undefined;
}
export function CollapseMenuButton({
icon: Icon,
label,
submenus,
isOpen
}: CollapseMenuButtonProps) {
const pathname = usePathname();
const isSubmenuActive = submenus.some((submenu) =>
submenu.active === undefined ? submenu.href === pathname : submenu.active
);
const [isCollapsed, setIsCollapsed] = useState<boolean>(isSubmenuActive);
return isOpen ? (
<Collapsible
open={isCollapsed}
onOpenChange={setIsCollapsed}
className="w-full"
>
<CollapsibleTrigger
className="[&[data-state=open]>div>div>svg]:rotate-180 mb-1"
asChild
>
<Button
variant={isSubmenuActive ? "secondary" : "ghost"}
className="w-full justify-start h-10"
>
<div className="w-full items-center flex justify-between">
<div className="flex items-center">
<span className="mr-4">
<Icon size={18} />
</span>
<p
className={cn(
"max-w-[150px] truncate",
isOpen
? "translate-x-0 opacity-100"
: "-translate-x-96 opacity-0"
)}
>
{label}
</p>
</div>
<div
className={cn(
"whitespace-nowrap",
isOpen
? "translate-x-0 opacity-100"
: "-translate-x-96 opacity-0"
)}
>
<ChevronDown
size={18}
className="transition-transform duration-200"
/>
</div>
</div>
</Button>
</CollapsibleTrigger>
<CollapsibleContent className="overflow-hidden data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down">
{submenus.map(({ href, label, active }, index) => (
<Button
key={index}
variant={
(active === undefined && pathname === href) || active
? "secondary"
: "ghost"
}
className="w-full justify-start h-10 mb-1"
asChild
>
<Link href={href}>
<span className="mr-4 ml-2">
<Dot size={18} />
</span>
<p
className={cn(
"max-w-[170px] truncate",
isOpen
? "translate-x-0 opacity-100"
: "-translate-x-96 opacity-0"
)}
>
{label}
</p>
</Link>
</Button>
))}
</CollapsibleContent>
</Collapsible>
) : (
<DropdownMenu>
<TooltipProvider disableHoverableContent>
<Tooltip delayDuration={100}>
<TooltipTrigger asChild>
<DropdownMenuTrigger asChild>
<Button
variant={isSubmenuActive ? "secondary" : "ghost"}
className="w-full justify-start h-10 mb-1"
>
<div className="w-full items-center flex justify-between">
<div className="flex items-center">
<span className={cn(isOpen === false ? "" : "mr-4")}>
<Icon size={18} />
</span>
<p
className={cn(
"max-w-[200px] truncate",
isOpen === false ? "opacity-0" : "opacity-100"
)}
>
{label}
</p>
</div>
</div>
</Button>
</DropdownMenuTrigger>
</TooltipTrigger>
<TooltipContent side="right" align="start" alignOffset={2}>
{label}
</TooltipContent>
</Tooltip>
</TooltipProvider>
<DropdownMenuContent side="right" sideOffset={25} align="start">
<DropdownMenuLabel className="max-w-[190px] truncate">
{label}
</DropdownMenuLabel>
<DropdownMenuSeparator />
{submenus.map(({ href, label, active }, index) => (
<DropdownMenuItem key={index} asChild>
<Link
className={`cursor-pointer ${
((active === undefined && pathname === href) || active) &&
"bg-secondary"
}`}
href={href}
>
<p className="max-w-[180px] truncate">{label}</p>
</Link>
</DropdownMenuItem>
))}
<DropdownMenuArrow className="fill-border" />
</DropdownMenuContent>
</DropdownMenu>
);
}

View File

@@ -0,0 +1,15 @@
import { Navbar } from "@/components/admin-panel/navbar";
interface ContentLayoutProps {
title: string;
children: React.ReactNode;
}
export function ContentLayout({ title, children }: ContentLayoutProps) {
return (
<div>
<Navbar title={title} />
<div className="container pt-8 pb-8 px-4 sm:px-8">{children}</div>
</div>
);
}

View File

@@ -0,0 +1,12 @@
export function Footer() {
return (
<div className="z-20 w-full bg-background/95 shadow backdrop-blur supports-[backdrop-filter]:bg-background/60">
<div className="mx-4 md:mx-8 flex h-14 items-center">
<p className="text-xs md:text-sm leading-loose text-muted-foreground text-left">
Built by{" "}
Andreas Wilms
</p>
</div>
</div>
);
}

View File

@@ -0,0 +1,155 @@
"use client";
import Link from "next/link";
import { Ellipsis, LogOut } from "lucide-react";
import { usePathname, useRouter } from "next/navigation";
import { cn } from "@/lib/utils";
import { getMenuList } from "@/lib/menu-list";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import { CollapseMenuButton } from "@/components/admin-panel/collapse-menu-button";
import {
Tooltip,
TooltipTrigger,
TooltipContent,
TooltipProvider,
} from "@/components/ui/tooltip";
import { logout } from "@/lib/session";
interface MenuProps {
isOpen: boolean | undefined;
}
export function Menu({ isOpen }: MenuProps) {
const pathname = usePathname();
const menuList = getMenuList(pathname);
const router = useRouter();
async function handleLogOut() {
await logout();
router.push("/login");
}
return (
<ScrollArea className="[&>div>div[style]]:!block">
<nav className="mt-8 h-full w-full">
<ul className="flex flex-col min-h-[calc(100vh-48px-36px-16px-32px)] lg:min-h-[calc(100vh-32px-40px-32px)] items-start space-y-1 px-2">
{menuList.map(({ groupLabel, menus }, index) => (
<li className={cn("w-full", groupLabel ? "pt-5" : "")} key={index}>
{(isOpen && groupLabel) || isOpen === undefined ? (
<p className="text-sm font-medium text-muted-foreground px-4 pb-2 max-w-[248px] truncate">
{groupLabel}
</p>
) : !isOpen && isOpen !== undefined && groupLabel ? (
<TooltipProvider>
<Tooltip delayDuration={100}>
<TooltipTrigger className="w-full">
<div className="w-full flex justify-center items-center">
<Ellipsis className="h-5 w-5" />
</div>
</TooltipTrigger>
<TooltipContent side="right">
<p>{groupLabel}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
) : (
<p className="pb-2"></p>
)}
{menus.map(
({ href, label, icon: Icon, active, submenus }, index) =>
!submenus || submenus.length === 0 ? (
<div className="w-full" key={index}>
<TooltipProvider disableHoverableContent>
<Tooltip delayDuration={100}>
<TooltipTrigger asChild>
<Button
variant={
(active === undefined &&
pathname.startsWith(href)) ||
active
? "secondary"
: "ghost"
}
className="w-full justify-start h-10 mb-1"
asChild
>
<Link href={href}>
<span
className={cn(isOpen === false ? "" : "mr-4")}
>
<Icon size={18} />
</span>
<p
className={cn(
"max-w-[200px] truncate",
isOpen === false
? "-translate-x-96 opacity-0"
: "translate-x-0 opacity-100"
)}
>
{label}
</p>
</Link>
</Button>
</TooltipTrigger>
{isOpen === false && (
<TooltipContent side="right">
{label}
</TooltipContent>
)}
</Tooltip>
</TooltipProvider>
</div>
) : (
<div className="w-full" key={index}>
<CollapseMenuButton
icon={Icon}
label={label}
active={
active === undefined
? pathname.startsWith(href)
: active
}
submenus={submenus}
isOpen={isOpen}
/>
</div>
)
)}
</li>
))}
<li className="w-full grow flex items-end">
<TooltipProvider disableHoverableContent>
<Tooltip delayDuration={100}>
<TooltipTrigger asChild>
<Button
onClick={handleLogOut}
variant="outline"
className="w-full justify-center h-10 mt-5"
>
<span className={cn(isOpen === false ? "" : "mr-4")}>
<LogOut size={18} />
</span>
<p
className={cn(
"whitespace-nowrap",
isOpen === false ? "opacity-0 hidden" : "opacity-100"
)}
>
Abmelden
</p>
</Button>
</TooltipTrigger>
{isOpen === false && (
<TooltipContent side="right">Sign out</TooltipContent>
)}
</Tooltip>
</TooltipProvider>
</li>
</ul>
</nav>
</ScrollArea>
);
}

View File

@@ -0,0 +1,24 @@
import { ModeToggle } from "@/components/mode-toggle";
import { UserNav } from "@/components/admin-panel/user-nav";
import { SheetMenu } from "@/components/admin-panel/sheet-menu";
interface NavbarProps {
title: string;
}
export function Navbar({ title }: NavbarProps) {
return (
<header className="sticky top-0 z-10 w-full bg-background/95 shadow backdrop-blur supports-[backdrop-filter]:bg-background/60 dark:shadow-secondary">
<div className="mx-4 sm:mx-8 flex h-14 items-center">
<div className="flex items-center space-x-4 lg:space-x-0">
<SheetMenu />
<h1 className="font-bold">{title}</h1>
</div>
<div className="flex flex-1 items-center justify-end">
<ModeToggle />
<UserNav />
</div>
</div>
</header>
);
}

View File

@@ -0,0 +1,39 @@
import Link from "next/link";
import { MenuIcon, PanelsTopLeft } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Menu } from "@/components/admin-panel/menu";
import {
Sheet,
SheetHeader,
SheetContent,
SheetTrigger,
SheetTitle
} from "@/components/ui/sheet";
export function SheetMenu() {
return (
<Sheet>
<SheetTrigger className="lg:hidden" asChild>
<Button className="h-8" variant="outline" size="icon">
<MenuIcon size={20} />
</Button>
</SheetTrigger>
<SheetContent className="sm:w-72 px-3 h-full flex flex-col" side="left">
<SheetHeader>
<Button
className="flex justify-center items-center pb-2 pt-1"
variant="link"
asChild
>
<Link href="/dashboard" className="flex items-center gap-2">
<PanelsTopLeft className="w-6 h-6 mr-1" />
<SheetTitle className="font-bold text-lg">Brand</SheetTitle>
</Link>
</Button>
</SheetHeader>
<Menu isOpen />
</SheetContent>
</Sheet>
);
}

View File

@@ -0,0 +1,29 @@
import { ChevronLeft } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
interface SidebarToggleProps {
isOpen: boolean | undefined;
setIsOpen?: () => void;
}
export function SidebarToggle({ isOpen, setIsOpen }: SidebarToggleProps) {
return (
<div className="invisible lg:visible absolute top-[12px] -right-[16px] z-20">
<Button
onClick={() => setIsOpen?.()}
className="rounded-md w-8 h-8"
variant="outline"
size="icon"
>
<ChevronLeft
className={cn(
"h-4 w-4 transition-transform ease-in-out duration-700",
isOpen === false ? "rotate-180" : "rotate-0"
)}
/>
</Button>
</div>
);
}

View File

@@ -0,0 +1,55 @@
"use client";
import { Menu } from "@/components/admin-panel/menu";
import { SidebarToggle } from "@/components/admin-panel/sidebar-toggle";
import { Button } from "@/components/ui/button";
import { useSidebar } from "@/hooks/use-sidebar";
import { useStore } from "@/hooks/use-store";
import { cn } from "@/lib/utils";
import { PanelsTopLeft } from "lucide-react";
import Link from "next/link";
export function Sidebar() {
const sidebar = useStore(useSidebar, (x) => x);
if (!sidebar) return null;
const { isOpen, toggleOpen, getOpenState, setIsHover, settings } = sidebar;
return (
<aside
className={cn(
"fixed top-0 left-0 z-20 h-screen -translate-x-full lg:translate-x-0 transition-[width] ease-in-out duration-300",
!getOpenState() ? "w-[90px]" : "w-72",
settings.disabled && "hidden"
)}
>
<SidebarToggle isOpen={isOpen} setIsOpen={toggleOpen} />
<div
onMouseEnter={() => setIsHover(true)}
onMouseLeave={() => setIsHover(false)}
className="relative h-full flex flex-col px-3 py-4 overflow-y-auto shadow-md dark:shadow-zinc-800"
>
<Button
className={cn(
"transition-transform ease-in-out duration-300 mb-1",
!getOpenState() ? "translate-x-1" : "translate-x-0"
)}
variant="link"
asChild
>
<Link href="/" className="flex items-center gap-2">
<PanelsTopLeft className="w-6 h-6 mr-1" />
<h1
className={cn(
"font-bold text-lg whitespace-nowrap transition-[transform,opacity,display] ease-in-out duration-300",
!getOpenState()
? "-translate-x-96 opacity-0 hidden"
: "translate-x-0 opacity-100"
)}
>
ERP
</h1>
</Link>
</Button>
<Menu isOpen={getOpenState()} />
</div>
</aside>
);
}

View File

@@ -0,0 +1,78 @@
"use client";
import Link from "next/link";
import { LayoutGrid, LogOut, User } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
TooltipProvider,
} from "@/components/ui/tooltip";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
export function UserNav() {
return (
<DropdownMenu>
<TooltipProvider disableHoverableContent>
<Tooltip delayDuration={100}>
<TooltipTrigger asChild>
<DropdownMenuTrigger asChild>
<Button
variant="outline"
className="relative h-8 w-8 rounded-full"
>
<Avatar className="h-8 w-8">
<AvatarImage src="#" alt="Avatar" />
<AvatarFallback className="bg-transparent">JD</AvatarFallback>
</Avatar>
</Button>
</DropdownMenuTrigger>
</TooltipTrigger>
<TooltipContent side="bottom">Profile</TooltipContent>
</Tooltip>
</TooltipProvider>
<DropdownMenuContent className="w-56" align="end" forceMount>
<DropdownMenuLabel className="font-normal">
<div className="flex flex-col space-y-1">
<p className="text-sm font-medium leading-none">John Doe</p>
<p className="text-xs leading-none text-muted-foreground">
johndoe@example.com
</p>
</div>
</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuGroup>
<DropdownMenuItem className="hover:cursor-pointer" asChild>
<Link href="/dashboard" className="flex items-center">
<LayoutGrid className="w-4 h-4 mr-3 text-muted-foreground" />
Dashboard
</Link>
</DropdownMenuItem>
<DropdownMenuItem className="hover:cursor-pointer" asChild>
<Link href="/account" className="flex items-center">
<User className="w-4 h-4 mr-3 text-muted-foreground" />
Account
</Link>
</DropdownMenuItem>
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuItem className="hover:cursor-pointer" onClick={() => {}}>
<LogOut className="w-4 h-4 mr-3 text-muted-foreground" />
Sign out
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
}

View File

@@ -0,0 +1,78 @@
"use server";
import { SignupFormSchema, FormState } from "../../lib/definitions";
import { login } from "@/lib/session";
const apiUrl = process.env.NEXT_SERVER_API_URL;
export async function signup(state: FormState, formData: FormData) {
// Validate form fields
const validatedFields = SignupFormSchema.safeParse({
name: formData.get("name"),
password: formData.get("password"),
});
// If any form fields are invalid, return early
if (!validatedFields.success) {
return {
errors: validatedFields.error.flatten().fieldErrors,
};
}
// Call the provider or db to create a user...
const name = formData.get("name") as string;
const password = formData.get("password") as string;
const payload = {
name,
password,
};
try {
const response = await fetch(`${apiUrl}/auth/signup`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
cache: "no-store",
});
if (!response.ok) {
console.error("Response status:", response.status);
throw new Error("Failed to submit form");
} else {
}
} catch (error) {
console.error("Error submitting form:", error);
throw new Error("An error occurred while submitting the form.");
}
}
export async function signin(name: string, password: string) {
const payload = {
name,
password,
};
try {
const response = await fetch(`${apiUrl}/auth/signin`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
cache: "no-store",
});
if (!response.ok) {
return false;
}
await login(name);
return true;
} catch (error) {
console.error("Error submitting form:", error);
throw new Error("An error occurred while submitting the form.");
}
}

View File

@@ -0,0 +1,117 @@
"use client";
import { useForm } from "react-hook-form";
import { signin } from "./actions"; // optional: remove if you use your own API
import {
Card,
CardContent,
CardFooter,
CardHeader,
CardTitle,
CardDescription,
} from "@/components/ui/card";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { toast, Bounce } from "react-toastify";
import { useRouter } from "next/navigation";
type FormData = {
name: string;
password: string;
};
export default function SignInPage() {
const { register, handleSubmit, formState } = useForm<FormData>({
mode: "onSubmit",
});
const router = useRouter();
async function onSubmit(data: FormData) {
// Example with next-auth credential sign in (optional)
// If you use your own API, replace this block with a fetch to /api/auth/signin
const res = await signin(data.name, data.password);
if (res) {
router.push("/dashboard");
} else {
toast.error("Falsche Anmeldedaten!", {
position: "bottom-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: false,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
transition: Bounce,
});
}
}
return (
<div className="min-h-screen flex items-center justify-center bg-slate-50 p-4">
<Card className="w-full max-w-md">
<CardHeader>
<CardTitle>Anmelden</CardTitle>
<CardDescription>
Nutze deinen Namen und Passwort zum anmelden.
</CardDescription>
</CardHeader>
<CardContent>
<form
id="signin-form"
onSubmit={handleSubmit(onSubmit)}
className="space-y-4"
>
<div>
<Label htmlFor="name">Name</Label>
<Input
id="name"
placeholder="Dein Name"
suppressHydrationWarning={true}
{...register("name", { required: "Name is required" })}
aria-invalid={Boolean(formState.errors.name)}
/>
{formState.errors.name && (
<p className="text-sm text-red-600 mt-1">
{formState.errors.name.message}
</p>
)}
</div>
<div>
<Label htmlFor="password">Password</Label>
<Input
id="password"
type="password"
placeholder="Dein Passwort"
suppressHydrationWarning={true}
{...register("password", {
required: "Password is required",
minLength: 4,
})}
aria-invalid={Boolean(formState.errors.password)}
/>
{formState.errors.password && (
<p className="text-sm text-red-600 mt-1">
{formState.errors.password.type === "minLength"
? "Password must be at least 6 characters"
: formState.errors.password.message}
</p>
)}
</div>
</form>
</CardContent>
<CardFooter>
<div className="w-full flex justify-end">
<Button
form="signin-form"
type="submit"
disabled={formState.isSubmitting}
>
{formState.isSubmitting ? "Anmelden..." : "Anmelden"}
</Button>
</div>
</CardFooter>
</Card>
</div>
);
}

View File

@@ -0,0 +1,35 @@
"use client";
import { signup } from "./actions";
import { useActionState } from "react";
export default function SignupForm() {
const [state, action, pending] = useActionState(signup, undefined);
return (
<form action={action}>
<div>
<label htmlFor="name">Name</label>
<input id="name" name="name" placeholder="Name" />
</div>
{state?.errors?.name && <p>{state.errors.name}</p>}
<div>
<label htmlFor="password">Password</label>
<input id="password" name="password" type="password" />
</div>
{state?.errors?.password && (
<div>
<p>Password must:</p>
<ul>
{state.errors.password.map((error) => (
<li key={error}>- {error}</li>
))}
</ul>
</div>
)}
<button disabled={pending} type="submit">
Sign Up
</button>
</form>
);
}

View File

@@ -0,0 +1,36 @@
import Link from "next/link";
export default function Header() {
return (
<header className="bg-gray-900 text-white shadow-md">
<nav className="flex justify-between items-center max-w-7xl mx-auto p-4">
{/* Logo */}
<h1 className="text-2xl font-bold tracking-wide">
<Link href="/" className="hover:text-gray-300">
Print Auftrag
</Link>
</h1>
{/* Navigation Links */}
<ul className="flex space-x-6 text-lg">
<li>
<Link
href="/generateFlaechendruck"
className="hover:text-gray-300 transition-colors duration-200"
>
PDF Generating
</Link>
</li>
<li>
<Link
href="/"
className="hover:text-gray-300 transition-colors duration-200"
>
Vorlagen
</Link>
</li>
</ul>
</nav>
</header>
);
}

View File

@@ -0,0 +1,37 @@
"use client";
import * as React from "react";
import { useTheme } from "next-themes";
import { MoonIcon, SunIcon } from "@radix-ui/react-icons";
import { Button } from "@/components/ui/button";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
TooltipProvider
} from "@/components/ui/tooltip";
export function ModeToggle() {
const { setTheme, theme } = useTheme();
return (
<TooltipProvider disableHoverableContent>
<Tooltip delayDuration={100}>
<TooltipTrigger asChild>
<Button
className="rounded-full w-8 h-8 bg-background mr-2"
variant="outline"
size="icon"
onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
>
<SunIcon className="w-[1.2rem] h-[1.2rem] rotate-90 scale-0 transition-transform ease-in-out duration-500 dark:rotate-0 dark:scale-100" />
<MoonIcon className="absolute w-[1.2rem] h-[1.2rem] rotate-0 scale-1000 transition-transform ease-in-out duration-500 dark:-rotate-90 dark:scale-0" />
<span className="sr-only">Switch Theme</span>
</Button>
</TooltipTrigger>
<TooltipContent side="bottom">Switch Theme</TooltipContent>
</Tooltip>
</TooltipProvider>
);
}

View File

@@ -0,0 +1,8 @@
"use client";
import * as React from "react";
import { ThemeProvider as NextThemesProvider, ThemeProviderProps } from "next-themes";
export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider>;
}

View File

@@ -0,0 +1,87 @@
"use client";
import { deleteVorlageFlaechendruck } from "./action";
export default function Table({
data,
}: {
data: {
id: number;
printer: string;
product_type: string;
height: number;
width: number;
coordinates: {
x: number;
y: number;
rotation: number;
}[];
}[];
}) {
async function onDelete(id: number) {
try {
await deleteVorlageFlaechendruck(id);
window.location.reload();
} catch (error) {
console.error(error);
alert("An error occurred while deleting the item.");
}
}
return (
<div className="p-6 bg-gray-50 min-h-screen">
<div className="overflow-x-auto">
<table className="table-auto border-collapse border border-gray-300 w-full bg-white shadow-md rounded-lg">
<thead>
<tr className="bg-gray-100 text-gray-700">
<th className="border border-gray-300 px-4 py-2">Printer</th>
<th className="border border-gray-300 px-4 py-2">Product Type</th>
<th className="border border-gray-300 px-4 py-2">Height</th>
<th className="border border-gray-300 px-4 py-2">Width</th>
<th className="border border-gray-300 px-4 py-2">Coordinates</th>
<th className="border border-gray-300 px-4 py-2">Actions</th>
</tr>
</thead>
<tbody>
{data.map((item) => (
<tr
key={item.id}
className="hover:bg-gray-50 transition duration-200"
>
<td className="border border-gray-300 px-4 py-2 text-center">
{item.printer}
</td>
<td className="border border-gray-300 px-4 py-2 text-center">
{item.product_type}
</td>
<td className="border border-gray-300 px-4 py-2 text-center">
{item.height}
</td>
<td className="border border-gray-300 px-4 py-2 text-center">
{item.width}
</td>
<td className="border border-gray-300 px-4 py-2 text-center">
<ul className="list-disc list-inside">
{item.coordinates.map((coord, index) => (
<li key={index} className="text-sm text-gray-600">
X: {coord.x}, Y: {coord.y}, Rotation: {coord.rotation}
</li>
))}
</ul>
</td>
<td className="border border-gray-300 px-4 py-2 text-center">
<button
onClick={() => onDelete(item.id)}
className="bg-red-500 text-white px-3 py-1 rounded hover:bg-red-600 transition duration-200"
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}

View File

@@ -0,0 +1,157 @@
"use client"
import * as React from "react"
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
import { cn } from "@/lib/utils"
import { buttonVariants } from "@/components/ui/button"
function AlertDialog({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />
}
function AlertDialogTrigger({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
return (
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
)
}
function AlertDialogPortal({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
return (
<AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
)
}
function AlertDialogOverlay({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
return (
<AlertDialogPrimitive.Overlay
data-slot="alert-dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className
)}
{...props}
/>
)
}
function AlertDialogContent({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Content>) {
return (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
data-slot="alert-dialog-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
className
)}
{...props}
/>
</AlertDialogPortal>
)
}
function AlertDialogHeader({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
)
}
function AlertDialogFooter({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className
)}
{...props}
/>
)
}
function AlertDialogTitle({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
return (
<AlertDialogPrimitive.Title
data-slot="alert-dialog-title"
className={cn("text-lg font-semibold", className)}
{...props}
/>
)
}
function AlertDialogDescription({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
return (
<AlertDialogPrimitive.Description
data-slot="alert-dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
function AlertDialogAction({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Action>) {
return (
<AlertDialogPrimitive.Action
className={cn(buttonVariants(), className)}
{...props}
/>
)
}
function AlertDialogCancel({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel>) {
return (
<AlertDialogPrimitive.Cancel
className={cn(buttonVariants({ variant: "outline" }), className)}
{...props}
/>
)
}
export {
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
}

View File

@@ -0,0 +1,53 @@
"use client"
import * as React from "react"
import * as AvatarPrimitive from "@radix-ui/react-avatar"
import { cn } from "@/lib/utils"
function Avatar({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Root>) {
return (
<AvatarPrimitive.Root
data-slot="avatar"
className={cn(
"relative flex size-8 shrink-0 overflow-hidden rounded-full",
className
)}
{...props}
/>
)
}
function AvatarImage({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
return (
<AvatarPrimitive.Image
data-slot="avatar-image"
className={cn("aspect-square size-full", className)}
{...props}
/>
)
}
function AvatarFallback({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
return (
<AvatarPrimitive.Fallback
data-slot="avatar-fallback"
className={cn(
"bg-muted flex size-full items-center justify-center rounded-full",
className
)}
{...props}
/>
)
}
export { Avatar, AvatarImage, AvatarFallback }

View File

@@ -0,0 +1,59 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
{
variants: {
variant: {
default:
"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
destructive:
"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
ghost:
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2 has-[>svg]:px-3",
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
icon: "size-9",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Button({
className,
variant,
size,
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot : "button"
return (
<Comp
data-slot="button"
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
}
export { Button, buttonVariants }

View File

@@ -0,0 +1,92 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Card({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card"
className={cn(
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
className
)}
{...props}
/>
)
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-header"
className={cn(
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
className
)}
{...props}
/>
)
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-title"
className={cn("leading-none font-semibold", className)}
{...props}
/>
)
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className
)}
{...props}
/>
)
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-content"
className={cn("px-6", className)}
{...props}
/>
)
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-footer"
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
{...props}
/>
)
}
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
}

View File

@@ -0,0 +1,32 @@
"use client"
import * as React from "react"
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
import { CheckIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function Checkbox({
className,
...props
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
return (
<CheckboxPrimitive.Root
data-slot="checkbox"
className={cn(
"peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
>
<CheckboxPrimitive.Indicator
data-slot="checkbox-indicator"
className="flex items-center justify-center text-current transition-none"
>
<CheckIcon className="size-3.5" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
)
}
export { Checkbox }

View File

@@ -0,0 +1,33 @@
"use client"
import * as CollapsiblePrimitive from "@radix-ui/react-collapsible"
function Collapsible({
...props
}: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />
}
function CollapsibleTrigger({
...props
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {
return (
<CollapsiblePrimitive.CollapsibleTrigger
data-slot="collapsible-trigger"
{...props}
/>
)
}
function CollapsibleContent({
...props
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {
return (
<CollapsiblePrimitive.CollapsibleContent
data-slot="collapsible-content"
{...props}
/>
)
}
export { Collapsible, CollapsibleTrigger, CollapsibleContent }

View File

@@ -0,0 +1,135 @@
"use client"
import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { XIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function Dialog({
...props
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
}
function DialogTrigger({
...props
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
}
function DialogPortal({
...props
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
}
function DialogClose({
...props
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
}
function DialogOverlay({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className
)}
{...props}
/>
)
}
function DialogContent({
className,
children,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content>) {
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
className
)}
{...props}
>
{children}
<DialogPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4">
<XIcon />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
)
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
)
}
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className
)}
{...props}
/>
)
}
function DialogTitle({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn("text-lg leading-none font-semibold", className)}
{...props}
/>
)
}
function DialogDescription({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
}

View File

@@ -0,0 +1,257 @@
"use client"
import * as React from "react"
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function DropdownMenu({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
}
function DropdownMenuPortal({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
return (
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
)
}
function DropdownMenuTrigger({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
return (
<DropdownMenuPrimitive.Trigger
data-slot="dropdown-menu-trigger"
{...props}
/>
)
}
function DropdownMenuContent({
className,
sideOffset = 4,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
return (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
data-slot="dropdown-menu-content"
sideOffset={sideOffset}
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
className
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
)
}
function DropdownMenuGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
return (
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
)
}
function DropdownMenuItem({
className,
inset,
variant = "default",
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean
variant?: "default" | "destructive"
}) {
return (
<DropdownMenuPrimitive.Item
data-slot="dropdown-menu-item"
data-inset={inset}
data-variant={variant}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
)
}
function DropdownMenuCheckboxItem({
className,
children,
checked,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
return (
<DropdownMenuPrimitive.CheckboxItem
data-slot="dropdown-menu-checkbox-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
checked={checked}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
)
}
function DropdownMenuRadioGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
return (
<DropdownMenuPrimitive.RadioGroup
data-slot="dropdown-menu-radio-group"
{...props}
/>
)
}
function DropdownMenuRadioItem({
className,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
return (
<DropdownMenuPrimitive.RadioItem
data-slot="dropdown-menu-radio-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CircleIcon className="size-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
)
}
function DropdownMenuLabel({
className,
inset,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean
}) {
return (
<DropdownMenuPrimitive.Label
data-slot="dropdown-menu-label"
data-inset={inset}
className={cn(
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
className
)}
{...props}
/>
)
}
function DropdownMenuSeparator({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
return (
<DropdownMenuPrimitive.Separator
data-slot="dropdown-menu-separator"
className={cn("bg-border -mx-1 my-1 h-px", className)}
{...props}
/>
)
}
function DropdownMenuShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="dropdown-menu-shortcut"
className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest",
className
)}
{...props}
/>
)
}
function DropdownMenuSub({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
}
function DropdownMenuSubTrigger({
className,
inset,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean
}) {
return (
<DropdownMenuPrimitive.SubTrigger
data-slot="dropdown-menu-sub-trigger"
data-inset={inset}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8",
className
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto size-4" />
</DropdownMenuPrimitive.SubTrigger>
)
}
function DropdownMenuSubContent({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
return (
<DropdownMenuPrimitive.SubContent
data-slot="dropdown-menu-sub-content"
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
className
)}
{...props}
/>
)
}
export {
DropdownMenu,
DropdownMenuPortal,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuLabel,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuSub,
DropdownMenuSubTrigger,
DropdownMenuSubContent,
}

View File

@@ -0,0 +1,167 @@
"use client"
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { Slot } from "@radix-ui/react-slot"
import {
Controller,
FormProvider,
useFormContext,
useFormState,
type ControllerProps,
type FieldPath,
type FieldValues,
} from "react-hook-form"
import { cn } from "@/lib/utils"
import { Label } from "@/components/ui/label"
const Form = FormProvider
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
> = {
name: TName
}
const FormFieldContext = React.createContext<FormFieldContextValue>(
{} as FormFieldContextValue
)
const FormField = <
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
>({
...props
}: ControllerProps<TFieldValues, TName>) => {
return (
<FormFieldContext.Provider value={{ name: props.name }}>
<Controller {...props} />
</FormFieldContext.Provider>
)
}
const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext)
const itemContext = React.useContext(FormItemContext)
const { getFieldState } = useFormContext()
const formState = useFormState({ name: fieldContext.name })
const fieldState = getFieldState(fieldContext.name, formState)
if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>")
}
const { id } = itemContext
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
}
}
type FormItemContextValue = {
id: string
}
const FormItemContext = React.createContext<FormItemContextValue>(
{} as FormItemContextValue
)
function FormItem({ className, ...props }: React.ComponentProps<"div">) {
const id = React.useId()
return (
<FormItemContext.Provider value={{ id }}>
<div
data-slot="form-item"
className={cn("grid gap-2", className)}
{...props}
/>
</FormItemContext.Provider>
)
}
function FormLabel({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
const { error, formItemId } = useFormField()
return (
<Label
data-slot="form-label"
data-error={!!error}
className={cn("data-[error=true]:text-destructive", className)}
htmlFor={formItemId}
{...props}
/>
)
}
function FormControl({ ...props }: React.ComponentProps<typeof Slot>) {
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
return (
<Slot
data-slot="form-control"
id={formItemId}
aria-describedby={
!error
? `${formDescriptionId}`
: `${formDescriptionId} ${formMessageId}`
}
aria-invalid={!!error}
{...props}
/>
)
}
function FormDescription({ className, ...props }: React.ComponentProps<"p">) {
const { formDescriptionId } = useFormField()
return (
<p
data-slot="form-description"
id={formDescriptionId}
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
function FormMessage({ className, ...props }: React.ComponentProps<"p">) {
const { error, formMessageId } = useFormField()
const body = error ? String(error?.message ?? "") : props.children
if (!body) {
return null
}
return (
<p
data-slot="form-message"
id={formMessageId}
className={cn("text-destructive text-sm", className)}
{...props}
>
{body}
</p>
)
}
export {
useFormField,
Form,
FormItem,
FormLabel,
FormControl,
FormDescription,
FormMessage,
FormField,
}

View File

@@ -0,0 +1,21 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<input
type={type}
data-slot="input"
className={cn(
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
className
)}
{...props}
/>
)
}
export { Input }

View File

@@ -0,0 +1,24 @@
"use client"
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cn } from "@/lib/utils"
function Label({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
return (
<LabelPrimitive.Root
data-slot="label"
className={cn(
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className
)}
{...props}
/>
)
}
export { Label }

View File

@@ -0,0 +1,58 @@
"use client"
import * as React from "react"
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
import { cn } from "@/lib/utils"
function ScrollArea({
className,
children,
...props
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
return (
<ScrollAreaPrimitive.Root
data-slot="scroll-area"
className={cn("relative", className)}
{...props}
>
<ScrollAreaPrimitive.Viewport
data-slot="scroll-area-viewport"
className="ring-ring/10 dark:ring-ring/20 dark:outline-ring/40 outline-ring/50 size-full rounded-[inherit] transition-[color,box-shadow] focus-visible:ring-4 focus-visible:outline-1"
>
{children}
</ScrollAreaPrimitive.Viewport>
<ScrollBar />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
)
}
function ScrollBar({
className,
orientation = "vertical",
...props
}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {
return (
<ScrollAreaPrimitive.ScrollAreaScrollbar
data-slot="scroll-area-scrollbar"
orientation={orientation}
className={cn(
"flex touch-none p-px transition-colors select-none",
orientation === "vertical" &&
"h-full w-2.5 border-l border-l-transparent",
orientation === "horizontal" &&
"h-2.5 flex-col border-t border-t-transparent",
className
)}
{...props}
>
<ScrollAreaPrimitive.ScrollAreaThumb
data-slot="scroll-area-thumb"
className="bg-border relative flex-1 rounded-full"
/>
</ScrollAreaPrimitive.ScrollAreaScrollbar>
)
}
export { ScrollArea, ScrollBar }

View File

@@ -0,0 +1,185 @@
"use client"
import * as React from "react"
import * as SelectPrimitive from "@radix-ui/react-select"
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function Select({
...props
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
return <SelectPrimitive.Root data-slot="select" {...props} />
}
function SelectGroup({
...props
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
return <SelectPrimitive.Group data-slot="select-group" {...props} />
}
function SelectValue({
...props
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
return <SelectPrimitive.Value data-slot="select-value" {...props} />
}
function SelectTrigger({
className,
size = "default",
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
size?: "sm" | "default"
}) {
return (
<SelectPrimitive.Trigger
data-slot="select-trigger"
data-size={size}
className={cn(
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDownIcon className="size-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
)
}
function SelectContent({
className,
children,
position = "popper",
...props
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
return (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
data-slot="select-content"
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className
)}
position={position}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
)
}
function SelectLabel({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
return (
<SelectPrimitive.Label
data-slot="select-label"
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
{...props}
/>
)
}
function SelectItem({
className,
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
return (
<SelectPrimitive.Item
data-slot="select-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
className
)}
{...props}
>
<span className="absolute right-2 flex size-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
)
}
function SelectSeparator({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
return (
<SelectPrimitive.Separator
data-slot="select-separator"
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
{...props}
/>
)
}
function SelectScrollUpButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
return (
<SelectPrimitive.ScrollUpButton
data-slot="select-scroll-up-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronUpIcon className="size-4" />
</SelectPrimitive.ScrollUpButton>
)
}
function SelectScrollDownButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
return (
<SelectPrimitive.ScrollDownButton
data-slot="select-scroll-down-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronDownIcon className="size-4" />
</SelectPrimitive.ScrollDownButton>
)
}
export {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectScrollDownButton,
SelectScrollUpButton,
SelectSeparator,
SelectTrigger,
SelectValue,
}

View File

@@ -0,0 +1,28 @@
"use client"
import * as React from "react"
import * as SeparatorPrimitive from "@radix-ui/react-separator"
import { cn } from "@/lib/utils"
function Separator({
className,
orientation = "horizontal",
decorative = true,
...props
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
return (
<SeparatorPrimitive.Root
data-slot="separator-root"
decorative={decorative}
orientation={orientation}
className={cn(
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
className
)}
{...props}
/>
)
}
export { Separator }

View File

@@ -0,0 +1,139 @@
"use client"
import * as React from "react"
import * as SheetPrimitive from "@radix-ui/react-dialog"
import { XIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
return <SheetPrimitive.Root data-slot="sheet" {...props} />
}
function SheetTrigger({
...props
}: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />
}
function SheetClose({
...props
}: React.ComponentProps<typeof SheetPrimitive.Close>) {
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />
}
function SheetPortal({
...props
}: React.ComponentProps<typeof SheetPrimitive.Portal>) {
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />
}
function SheetOverlay({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {
return (
<SheetPrimitive.Overlay
data-slot="sheet-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className
)}
{...props}
/>
)
}
function SheetContent({
className,
children,
side = "right",
...props
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
side?: "top" | "right" | "bottom" | "left"
}) {
return (
<SheetPortal>
<SheetOverlay />
<SheetPrimitive.Content
data-slot="sheet-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
side === "right" &&
"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",
side === "left" &&
"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",
side === "top" &&
"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",
side === "bottom" &&
"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",
className
)}
{...props}
>
{children}
<SheetPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none">
<XIcon className="size-4" />
<span className="sr-only">Close</span>
</SheetPrimitive.Close>
</SheetPrimitive.Content>
</SheetPortal>
)
}
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sheet-header"
className={cn("flex flex-col gap-1.5 p-4", className)}
{...props}
/>
)
}
function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sheet-footer"
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
{...props}
/>
)
}
function SheetTitle({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Title>) {
return (
<SheetPrimitive.Title
data-slot="sheet-title"
className={cn("text-foreground font-semibold", className)}
{...props}
/>
)
}
function SheetDescription({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Description>) {
return (
<SheetPrimitive.Description
data-slot="sheet-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
export {
Sheet,
SheetTrigger,
SheetClose,
SheetContent,
SheetHeader,
SheetFooter,
SheetTitle,
SheetDescription,
}

View File

@@ -0,0 +1,726 @@
"use client"
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { VariantProps, cva } from "class-variance-authority"
import { PanelLeftIcon } from "lucide-react"
import { useIsMobile } from "@/hooks/use-mobile"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Separator } from "@/components/ui/separator"
import {
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
} from "@/components/ui/sheet"
import { Skeleton } from "@/components/ui/skeleton"
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip"
const SIDEBAR_COOKIE_NAME = "sidebar_state"
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
const SIDEBAR_WIDTH = "16rem"
const SIDEBAR_WIDTH_MOBILE = "18rem"
const SIDEBAR_WIDTH_ICON = "3rem"
const SIDEBAR_KEYBOARD_SHORTCUT = "b"
type SidebarContextProps = {
state: "expanded" | "collapsed"
open: boolean
setOpen: (open: boolean) => void
openMobile: boolean
setOpenMobile: (open: boolean) => void
isMobile: boolean
toggleSidebar: () => void
}
const SidebarContext = React.createContext<SidebarContextProps | null>(null)
function useSidebar() {
const context = React.useContext(SidebarContext)
if (!context) {
throw new Error("useSidebar must be used within a SidebarProvider.")
}
return context
}
function SidebarProvider({
defaultOpen = true,
open: openProp,
onOpenChange: setOpenProp,
className,
style,
children,
...props
}: React.ComponentProps<"div"> & {
defaultOpen?: boolean
open?: boolean
onOpenChange?: (open: boolean) => void
}) {
const isMobile = useIsMobile()
const [openMobile, setOpenMobile] = React.useState(false)
// This is the internal state of the sidebar.
// We use openProp and setOpenProp for control from outside the component.
const [_open, _setOpen] = React.useState(defaultOpen)
const open = openProp ?? _open
const setOpen = React.useCallback(
(value: boolean | ((value: boolean) => boolean)) => {
const openState = typeof value === "function" ? value(open) : value
if (setOpenProp) {
setOpenProp(openState)
} else {
_setOpen(openState)
}
// This sets the cookie to keep the sidebar state.
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`
},
[setOpenProp, open]
)
// Helper to toggle the sidebar.
const toggleSidebar = React.useCallback(() => {
return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open)
}, [isMobile, setOpen, setOpenMobile])
// Adds a keyboard shortcut to toggle the sidebar.
React.useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (
event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
(event.metaKey || event.ctrlKey)
) {
event.preventDefault()
toggleSidebar()
}
}
window.addEventListener("keydown", handleKeyDown)
return () => window.removeEventListener("keydown", handleKeyDown)
}, [toggleSidebar])
// We add a state so that we can do data-state="expanded" or "collapsed".
// This makes it easier to style the sidebar with Tailwind classes.
const state = open ? "expanded" : "collapsed"
const contextValue = React.useMemo<SidebarContextProps>(
() => ({
state,
open,
setOpen,
isMobile,
openMobile,
setOpenMobile,
toggleSidebar,
}),
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar]
)
return (
<SidebarContext.Provider value={contextValue}>
<TooltipProvider delayDuration={0}>
<div
data-slot="sidebar-wrapper"
style={
{
"--sidebar-width": SIDEBAR_WIDTH,
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
...style,
} as React.CSSProperties
}
className={cn(
"group/sidebar-wrapper has-data-[variant=inset]:bg-sidebar flex min-h-svh w-full",
className
)}
{...props}
>
{children}
</div>
</TooltipProvider>
</SidebarContext.Provider>
)
}
function Sidebar({
side = "left",
variant = "sidebar",
collapsible = "offcanvas",
className,
children,
...props
}: React.ComponentProps<"div"> & {
side?: "left" | "right"
variant?: "sidebar" | "floating" | "inset"
collapsible?: "offcanvas" | "icon" | "none"
}) {
const { isMobile, state, openMobile, setOpenMobile } = useSidebar()
if (collapsible === "none") {
return (
<div
data-slot="sidebar"
className={cn(
"bg-sidebar text-sidebar-foreground flex h-full w-(--sidebar-width) flex-col",
className
)}
{...props}
>
{children}
</div>
)
}
if (isMobile) {
return (
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
<SheetContent
data-sidebar="sidebar"
data-slot="sidebar"
data-mobile="true"
className="bg-sidebar text-sidebar-foreground w-(--sidebar-width) p-0 [&>button]:hidden"
style={
{
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
} as React.CSSProperties
}
side={side}
>
<SheetHeader className="sr-only">
<SheetTitle>Sidebar</SheetTitle>
<SheetDescription>Displays the mobile sidebar.</SheetDescription>
</SheetHeader>
<div className="flex h-full w-full flex-col">{children}</div>
</SheetContent>
</Sheet>
)
}
return (
<div
className="group peer text-sidebar-foreground hidden md:block"
data-state={state}
data-collapsible={state === "collapsed" ? collapsible : ""}
data-variant={variant}
data-side={side}
data-slot="sidebar"
>
{/* This is what handles the sidebar gap on desktop */}
<div
data-slot="sidebar-gap"
className={cn(
"relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",
"group-data-[collapsible=offcanvas]:w-0",
"group-data-[side=right]:rotate-180",
variant === "floating" || variant === "inset"
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon)"
)}
/>
<div
data-slot="sidebar-container"
className={cn(
"fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",
side === "left"
? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
: "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
// Adjust the padding for floating and inset variants.
variant === "floating" || variant === "inset"
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
className
)}
{...props}
>
<div
data-sidebar="sidebar"
data-slot="sidebar-inner"
className="bg-sidebar group-data-[variant=floating]:border-sidebar-border flex h-full w-full flex-col group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:shadow-sm"
>
{children}
</div>
</div>
</div>
)
}
function SidebarTrigger({
className,
onClick,
...props
}: React.ComponentProps<typeof Button>) {
const { toggleSidebar } = useSidebar()
return (
<Button
data-sidebar="trigger"
data-slot="sidebar-trigger"
variant="ghost"
size="icon"
className={cn("size-7", className)}
onClick={(event) => {
onClick?.(event)
toggleSidebar()
}}
{...props}
>
<PanelLeftIcon />
<span className="sr-only">Toggle Sidebar</span>
</Button>
)
}
function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
const { toggleSidebar } = useSidebar()
return (
<button
data-sidebar="rail"
data-slot="sidebar-rail"
aria-label="Toggle Sidebar"
tabIndex={-1}
onClick={toggleSidebar}
title="Toggle Sidebar"
className={cn(
"hover:after:bg-sidebar-border absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] sm:flex",
"in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
"hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full",
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
className
)}
{...props}
/>
)
}
function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
return (
<main
data-slot="sidebar-inset"
className={cn(
"bg-background relative flex w-full flex-1 flex-col",
"md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",
className
)}
{...props}
/>
)
}
function SidebarInput({
className,
...props
}: React.ComponentProps<typeof Input>) {
return (
<Input
data-slot="sidebar-input"
data-sidebar="input"
className={cn("bg-background h-8 w-full shadow-none", className)}
{...props}
/>
)
}
function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-header"
data-sidebar="header"
className={cn("flex flex-col gap-2 p-2", className)}
{...props}
/>
)
}
function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-footer"
data-sidebar="footer"
className={cn("flex flex-col gap-2 p-2", className)}
{...props}
/>
)
}
function SidebarSeparator({
className,
...props
}: React.ComponentProps<typeof Separator>) {
return (
<Separator
data-slot="sidebar-separator"
data-sidebar="separator"
className={cn("bg-sidebar-border mx-2 w-auto", className)}
{...props}
/>
)
}
function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-content"
data-sidebar="content"
className={cn(
"flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
className
)}
{...props}
/>
)
}
function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-group"
data-sidebar="group"
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
{...props}
/>
)
}
function SidebarGroupLabel({
className,
asChild = false,
...props
}: React.ComponentProps<"div"> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "div"
return (
<Comp
data-slot="sidebar-group-label"
data-sidebar="group-label"
className={cn(
"text-sidebar-foreground/70 ring-sidebar-ring flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-hidden transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
className
)}
{...props}
/>
)
}
function SidebarGroupAction({
className,
asChild = false,
...props
}: React.ComponentProps<"button"> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "button"
return (
<Comp
data-slot="sidebar-group-action"
data-sidebar="group-action"
className={cn(
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 md:after:hidden",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
)
}
function SidebarGroupContent({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-group-content"
data-sidebar="group-content"
className={cn("w-full text-sm", className)}
{...props}
/>
)
}
function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
return (
<ul
data-slot="sidebar-menu"
data-sidebar="menu"
className={cn("flex w-full min-w-0 flex-col gap-1", className)}
{...props}
/>
)
}
function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
return (
<li
data-slot="sidebar-menu-item"
data-sidebar="menu-item"
className={cn("group/menu-item relative", className)}
{...props}
/>
)
}
const sidebarMenuButtonVariants = cva(
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-hidden ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
{
variants: {
variant: {
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
outline:
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
},
size: {
default: "h-8 text-sm",
sm: "h-7 text-xs",
lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function SidebarMenuButton({
asChild = false,
isActive = false,
variant = "default",
size = "default",
tooltip,
className,
...props
}: React.ComponentProps<"button"> & {
asChild?: boolean
isActive?: boolean
tooltip?: string | React.ComponentProps<typeof TooltipContent>
} & VariantProps<typeof sidebarMenuButtonVariants>) {
const Comp = asChild ? Slot : "button"
const { isMobile, state } = useSidebar()
const button = (
<Comp
data-slot="sidebar-menu-button"
data-sidebar="menu-button"
data-size={size}
data-active={isActive}
className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
{...props}
/>
)
if (!tooltip) {
return button
}
if (typeof tooltip === "string") {
tooltip = {
children: tooltip,
}
}
return (
<Tooltip>
<TooltipTrigger asChild>{button}</TooltipTrigger>
<TooltipContent
side="right"
align="center"
hidden={state !== "collapsed" || isMobile}
{...tooltip}
/>
</Tooltip>
)
}
function SidebarMenuAction({
className,
asChild = false,
showOnHover = false,
...props
}: React.ComponentProps<"button"> & {
asChild?: boolean
showOnHover?: boolean
}) {
const Comp = asChild ? Slot : "button"
return (
<Comp
data-slot="sidebar-menu-action"
data-sidebar="menu-action"
className={cn(
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground peer-hover/menu-button:text-sidebar-accent-foreground absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 md:after:hidden",
"peer-data-[size=sm]/menu-button:top-1",
"peer-data-[size=default]/menu-button:top-1.5",
"peer-data-[size=lg]/menu-button:top-2.5",
"group-data-[collapsible=icon]:hidden",
showOnHover &&
"peer-data-[active=true]/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 md:opacity-0",
className
)}
{...props}
/>
)
}
function SidebarMenuBadge({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-menu-badge"
data-sidebar="menu-badge"
className={cn(
"text-sidebar-foreground pointer-events-none absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums select-none",
"peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
"peer-data-[size=sm]/menu-button:top-1",
"peer-data-[size=default]/menu-button:top-1.5",
"peer-data-[size=lg]/menu-button:top-2.5",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
)
}
function SidebarMenuSkeleton({
className,
showIcon = false,
...props
}: React.ComponentProps<"div"> & {
showIcon?: boolean
}) {
// Random width between 50 to 90%.
const width = React.useMemo(() => {
return `${Math.floor(Math.random() * 40) + 50}%`
}, [])
return (
<div
data-slot="sidebar-menu-skeleton"
data-sidebar="menu-skeleton"
className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
{...props}
>
{showIcon && (
<Skeleton
className="size-4 rounded-md"
data-sidebar="menu-skeleton-icon"
/>
)}
<Skeleton
className="h-4 max-w-(--skeleton-width) flex-1"
data-sidebar="menu-skeleton-text"
style={
{
"--skeleton-width": width,
} as React.CSSProperties
}
/>
</div>
)
}
function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
return (
<ul
data-slot="sidebar-menu-sub"
data-sidebar="menu-sub"
className={cn(
"border-sidebar-border mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l px-2.5 py-0.5",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
)
}
function SidebarMenuSubItem({
className,
...props
}: React.ComponentProps<"li">) {
return (
<li
data-slot="sidebar-menu-sub-item"
data-sidebar="menu-sub-item"
className={cn("group/menu-sub-item relative", className)}
{...props}
/>
)
}
function SidebarMenuSubButton({
asChild = false,
size = "md",
isActive = false,
className,
...props
}: React.ComponentProps<"a"> & {
asChild?: boolean
size?: "sm" | "md"
isActive?: boolean
}) {
const Comp = asChild ? Slot : "a"
return (
<Comp
data-slot="sidebar-menu-sub-button"
data-sidebar="menu-sub-button"
data-size={size}
data-active={isActive}
className={cn(
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground [&>svg]:text-sidebar-accent-foreground flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 outline-hidden focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
size === "sm" && "text-xs",
size === "md" && "text-sm",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
)
}
export {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarGroupAction,
SidebarGroupContent,
SidebarGroupLabel,
SidebarHeader,
SidebarInput,
SidebarInset,
SidebarMenu,
SidebarMenuAction,
SidebarMenuBadge,
SidebarMenuButton,
SidebarMenuItem,
SidebarMenuSkeleton,
SidebarMenuSub,
SidebarMenuSubButton,
SidebarMenuSubItem,
SidebarProvider,
SidebarRail,
SidebarSeparator,
SidebarTrigger,
useSidebar,
}

View File

@@ -0,0 +1,13 @@
import { cn } from "@/lib/utils"
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="skeleton"
className={cn("bg-accent animate-pulse rounded-md", className)}
{...props}
/>
)
}
export { Skeleton }

View File

@@ -0,0 +1,116 @@
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
function Table({ className, ...props }: React.ComponentProps<"table">) {
return (
<div
data-slot="table-container"
className="relative w-full overflow-x-auto"
>
<table
data-slot="table"
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
)
}
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
return (
<thead
data-slot="table-header"
className={cn("[&_tr]:border-b", className)}
{...props}
/>
)
}
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
return (
<tbody
data-slot="table-body"
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
)
}
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
return (
<tfoot
data-slot="table-footer"
className={cn(
"bg-muted/50 border-t font-medium [&>tr]:last:border-b-0",
className
)}
{...props}
/>
)
}
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
return (
<tr
data-slot="table-row"
className={cn(
"hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",
className
)}
{...props}
/>
)
}
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
return (
<th
data-slot="table-head"
className={cn(
"text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props}
/>
)
}
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
return (
<td
data-slot="table-cell"
className={cn(
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props}
/>
)
}
function TableCaption({
className,
...props
}: React.ComponentProps<"caption">) {
return (
<caption
data-slot="table-caption"
className={cn("text-muted-foreground mt-4 text-sm", className)}
{...props}
/>
)
}
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
}

View File

@@ -0,0 +1,61 @@
"use client"
import * as React from "react"
import * as TooltipPrimitive from "@radix-ui/react-tooltip"
import { cn } from "@/lib/utils"
function TooltipProvider({
delayDuration = 0,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
return (
<TooltipPrimitive.Provider
data-slot="tooltip-provider"
delayDuration={delayDuration}
{...props}
/>
)
}
function Tooltip({
...props
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
return (
<TooltipProvider>
<TooltipPrimitive.Root data-slot="tooltip" {...props} />
</TooltipProvider>
)
}
function TooltipTrigger({
...props
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
}
function TooltipContent({
className,
sideOffset = 0,
children,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
return (
<TooltipPrimitive.Portal>
<TooltipPrimitive.Content
data-slot="tooltip-content"
sideOffset={sideOffset}
className={cn(
"bg-primary text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
className
)}
{...props}
>
{children}
<TooltipPrimitive.Arrow className="bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
</TooltipPrimitive.Content>
</TooltipPrimitive.Portal>
)
}
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }

View File

@@ -0,0 +1,57 @@
"use server";
import { main, OrderData } from "./orderUpdateBillbee";
export async function uploadFile(formData: FormData) {
const file = formData.get("file") as File;
// Check if the file is a CSV
if (!file || (file.type !== "text/csv" && !file.name.endsWith(".csv"))) {
return { message: "Ausgewählte Datei ist keine CSV", status: false };
}
const arrayBuffer = await file.arrayBuffer();
const buffer = new Uint8Array(arrayBuffer);
// Decode the buffer to a string
const decoder: TextDecoder = new TextDecoder("utf-8");
const csvContent: string = decoder.decode(buffer);
// Determine the delimiter (comma or semicolon)
const delimiter = csvContent.includes(";") ? ";" : ",";
// Parse the CSV content using the detected delimiter
const rows: string[][] = csvContent
.split("\n")
.map((row) => row.split(delimiter));
const requiredHeaders = ["Bestellnummer", "Sendungsnummer"];
const headers: string[] = rows[0].map((header) =>
header.trim().replace(/\r/g, "")
);
// Check if CSV containes required Headers
const allHeadersPresent: boolean = requiredHeaders.every((header) =>
headers.includes(header)
);
if (!allHeadersPresent) {
return {
message:
'CSV enthält nicht die notwendigen Header "Bestellnummer" und "Sendungsnummer"',
status: false,
};
}
// Get the indices of the required headers
const indices: number[] = requiredHeaders.map((header) =>
headers.indexOf(header)
);
// Create an array of objects with only the required headers
const filteredData: OrderData[] = rows.slice(1).map((row) => {
const orderData: OrderData = {
Bestellnummer: row[indices[0]] ? row[indices[0]].trim() : null,
Sendungsnummer: row[indices[1]] ? row[indices[1]].trim() : null,
};
return orderData;
});
return { data: await main(filteredData), status: true };
}

View File

@@ -0,0 +1,120 @@
"use server";
const API_KEY = process.env.BILLBEE_API_KEY as string;
const USERNAME = process.env.BILLBEE_USERNAME as string;
const API_PASSWORD = process.env.BILLBEE_PASSWORD as string;
const BASE_URL = "https://api.billbee.io/api/v1";
export interface OrderData {
Bestellnummer: string | null;
Sendungsnummer: string | null;
}
export interface RespError {
orderId: string | null;
error: string;
}
async function addShipment(orderId: string, shippingId: string) {
const url = `${BASE_URL}/orders/${orderId}/shipment`;
const headers: HeadersInit = {
"X-Billbee-Api-Key": API_KEY,
accept: "application/json",
"Content-Type": "application/json",
Authorization: "Basic " + btoa(`${USERNAME}:${API_PASSWORD}`),
};
const payload = {
ShippingId: shippingId,
ShippingProviderId: 6082,
ShipmentType: 0,
};
const response = await fetch(url, {
method: "POST",
headers: headers,
body: JSON.stringify(payload),
credentials: "include", // Include credentials for basic auth
});
if (!response.ok) {
throw new Error(`Error ${response.status}: ${await response.text()}`);
}
// Update order status
const updateUrl = `${BASE_URL}/orders/${orderId}/orderstate`;
const updatePayload = {
NewStateId: 4,
};
const updateResponse = await fetch(updateUrl, {
method: "PUT",
headers: headers,
body: JSON.stringify(updatePayload),
credentials: "include",
});
if (!updateResponse.ok) {
throw new Error(
`Error updating order status ${
updateResponse.status
}: ${await updateResponse.text()}`
);
}
}
async function getByExternalId(externalId: string) {
const url = `${BASE_URL}/orders/findbyextref/${externalId}`;
const headers: HeadersInit = {
"X-Billbee-Api-Key": API_KEY,
accept: "application/json",
Authorization: "Basic " + btoa(`${USERNAME}:${API_PASSWORD}`),
};
const response = await fetch(url, {
method: "GET",
headers: headers,
credentials: "include",
});
if (!response.ok) {
throw new Error(`Error ${response.status}: ${await response.text()}`);
}
return await response.json();
}
async function updateCompleteShipment(orderId: string, shippingId: string) {
const res = await getByExternalId(orderId);
const content = res.Data;
const billbeeId = content.BillBeeOrderId;
await addShipment(billbeeId, shippingId);
}
export async function main(data: OrderData[]) {
const errors: RespError[] = [];
for (const { Bestellnummer, Sendungsnummer } of data) {
if (!Bestellnummer || !Sendungsnummer) {
errors.push({
orderId: Bestellnummer,
error: "Order ID or Shipping ID is None",
});
continue;
}
try {
await updateCompleteShipment(Bestellnummer, Sendungsnummer);
} catch (e) {
const errorMessage = e instanceof Error ? e.message : "Unknown error";
console.error(`Error processing order ${Bestellnummer}: ${errorMessage}`);
errors.push({ orderId: Bestellnummer, error: errorMessage });
}
}
const result = {
successful: data.length - errors.length,
errors: errors,
};
return result;
}

View File

@@ -0,0 +1,145 @@
"use client";
import { useRef, useState } from "react";
import { uploadFile } from "./action";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Card,
CardHeader,
CardTitle,
CardContent,
CardFooter,
} from "@/components/ui/card";
import { RespError } from "./orderUpdateBillbee";
import { toast, Bounce } from "react-toastify";
export default function UploadForm() {
const fileInput = useRef<HTMLInputElement | null>(null);
const [uploadResult, setUploadResult] = useState<{
successful: number;
errors: RespError[];
} | null>(null);
const [isProcessing, setIsProcessing] = useState<true | false>(false);
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault(); // Prevent the default form submission
if (fileInput.current?.files) {
const file = fileInput.current.files[0];
const data = new FormData();
data.append("file", file);
setIsProcessing(true);
const res = await uploadFile(data);
if (res.status && res.data) {
setUploadResult(res.data);
toast.success(res.message, {
position: "bottom-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: false,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
transition: Bounce,
});
} else {
toast.error(res.message, {
position: "bottom-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: false,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
transition: Bounce,
});
}
setIsProcessing(false);
}
};
return (
<div className="flex flex-col items-center justify-center min-h-screen bg-gray-50">
<Card className="w-full max-w-sm mb-4">
{" "}
{/* Added margin-bottom for spacing */}
<CardHeader>
<CardTitle>Lade eine Datei hoch</CardTitle>
</CardHeader>
{!isProcessing ? (
<form onSubmit={handleSubmit} className="flex flex-col gap-4">
<CardContent className="flex flex-col gap-4">
<div className="flex flex-col gap-2">
<Label htmlFor="file">Choose a file</Label>
<Input id="file" type="file" name="file" ref={fileInput} />
</div>
</CardContent>
<CardFooter className="flex justify-end">
<Button type="submit">Submit</Button>
</CardFooter>
</form>
) : (
<div className="flex items-center justify-center w-full h-32">
<div role="status">
<svg
aria-hidden="true"
className="w-20 h-20 text-gray-200 animate-spin dark:text-gray-600 fill-black"
viewBox="0 0 100 101"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z"
fill="currentColor"
/>
<path
d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z"
fill="currentFill"
/>
</svg>
<span className="sr-only">Loading...</span>
</div>
</div>
)}
</Card>
{uploadResult && (
<div className="w-full max-w-sm">
<Card className="overflow-hidden">
<CardHeader>
<CardTitle>Upload Result</CardTitle>
</CardHeader>
<CardContent className="h-64 overflow-y-auto p-4">
<p className="font-semibold">
Anzahl erfolgreicher Updates: {uploadResult.successful}
</p>
{uploadResult.errors.length > 0 && (
<div className="mt-2">
<h4 className="font-semibold">Errors:</h4>
<ul className="list-disc list-inside">
{uploadResult.errors.map((error, index) => (
<li key={index}>
<span className="font-medium">Order ID:</span>{" "}
{error.orderId || "N/A"},
<span className="font-medium"> Error:</span>{" "}
{error.error}
</li>
))}
</ul>
</div>
)}
</CardContent>
</Card>
</div>
)}
</div>
);
}

Some files were not shown because too many files have changed in this diff Show More