Compare commits
1 Commits
feat/brand
...
8f2d21c0e1
| Author | SHA1 | Date | |
|---|---|---|---|
| 8f2d21c0e1 |
@@ -125,18 +125,6 @@ jobs:
|
|||||||
docker build -t "$FRONTEND_IMAGE" ./frontend
|
docker build -t "$FRONTEND_IMAGE" ./frontend
|
||||||
docker push "$FRONTEND_IMAGE"
|
docker push "$FRONTEND_IMAGE"
|
||||||
|
|
||||||
- name: Cleanup Docker on runner (prevent vdisk growth)
|
|
||||||
if: always()
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
set +e
|
|
||||||
|
|
||||||
# Keep recent artifacts, drop old local residue from CI builds.
|
|
||||||
docker container prune -f --filter "until=168h" || true
|
|
||||||
docker image prune -a -f --filter "until=168h" || true
|
|
||||||
docker builder prune -a -f --filter "until=168h" || true
|
|
||||||
docker network prune -f --filter "until=168h" || true
|
|
||||||
|
|
||||||
deploy:
|
deploy:
|
||||||
needs: build-and-push
|
needs: build-and-push
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
@@ -217,12 +205,9 @@ jobs:
|
|||||||
ADMIN_TTL="${ADMIN_TTL:-480}"
|
ADMIN_TTL="${ADMIN_TTL:-480}"
|
||||||
printf 'ADMIN_PASSWORD="%s"\nADMIN_SESSION_SECRET="%s"\nADMIN_SESSION_TTL_MINUTES="%s"\n' \
|
printf 'ADMIN_PASSWORD="%s"\nADMIN_SESSION_SECRET="%s"\nADMIN_SESSION_TTL_MINUTES="%s"\n' \
|
||||||
"${{ secrets.ADMIN_PASSWORD }}" "${{ secrets.ADMIN_SESSION_SECRET }}" "$ADMIN_TTL" >> /tmp/full_env.env
|
"${{ secrets.ADMIN_PASSWORD }}" "${{ secrets.ADMIN_SESSION_SECRET }}" "$ADMIN_TTL" >> /tmp/full_env.env
|
||||||
if [[ -n "${{ secrets.OPENAI_API_KEY }}" ]]; then
|
|
||||||
printf 'OPENAI_API_KEY="%s"\n' "${{ secrets.OPENAI_API_KEY }}" >> /tmp/full_env.env
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "Preparing to send env file with variables:"
|
echo "Preparing to send env file with variables:"
|
||||||
grep -Ev "PASSWORD|SECRET|KEY|TOKEN" /tmp/full_env.env || true
|
grep -Ev "PASSWORD|SECRET" /tmp/full_env.env || true
|
||||||
|
|
||||||
ssh -i ~/.ssh/id_ed25519 -o BatchMode=yes "${{ secrets.SERVER_USER }}@${{ secrets.SERVER_HOST }}" \
|
ssh -i ~/.ssh/id_ed25519 -o BatchMode=yes "${{ secrets.SERVER_USER }}@${{ secrets.SERVER_HOST }}" \
|
||||||
"setenv ${{ env.ENV }}" < /tmp/full_env.env
|
"setenv ${{ env.ENV }}" < /tmp/full_env.env
|
||||||
|
|||||||
6
.gitignore
vendored
6
.gitignore
vendored
@@ -44,14 +44,8 @@ build/
|
|||||||
|
|
||||||
./storage_orders
|
./storage_orders
|
||||||
./storage_quotes
|
./storage_quotes
|
||||||
./storage_requests
|
|
||||||
./storage_media
|
|
||||||
./storage_shop
|
|
||||||
storage_orders
|
storage_orders
|
||||||
storage_quotes
|
storage_quotes
|
||||||
storage_requests
|
|
||||||
storage_media
|
|
||||||
storage_shop
|
|
||||||
|
|
||||||
# Qodana local reports/artifacts
|
# Qodana local reports/artifacts
|
||||||
backend/.qodana/
|
backend/.qodana/
|
||||||
|
|||||||
55
README.md
55
README.md
@@ -11,7 +11,7 @@ Un'applicazione Full Stack (Angular + Spring Boot) per calcolare preventivi di s
|
|||||||
|
|
||||||
## Stack Tecnologico
|
## Stack Tecnologico
|
||||||
|
|
||||||
- **Backend**: Java 21, Spring Boot 3.4, PostgreSQL.
|
- **Backend**: Java 21, Spring Boot 3.4, PostgreSQL, Flyway.
|
||||||
- **Frontend**: Angular 19, Angular Material, Three.js.
|
- **Frontend**: Angular 19, Angular Material, Three.js.
|
||||||
- **Slicer**: OrcaSlicer (invocato via CLI).
|
- **Slicer**: OrcaSlicer (invocato via CLI).
|
||||||
|
|
||||||
@@ -21,20 +21,14 @@ Un'applicazione Full Stack (Angular + Spring Boot) per calcolare preventivi di s
|
|||||||
* **Node.js 22** e **npm** installati.
|
* **Node.js 22** e **npm** installati.
|
||||||
* **PostgreSQL** attivo.
|
* **PostgreSQL** attivo.
|
||||||
* **OrcaSlicer** installato sul sistema.
|
* **OrcaSlicer** installato sul sistema.
|
||||||
* **FFmpeg** installato sul sistema o presente nell'immagine Docker del backend.
|
|
||||||
|
|
||||||
## Avvio Rapido
|
## Avvio Rapido
|
||||||
|
|
||||||
### 1. Database
|
### 1. Database
|
||||||
Crea un database PostgreSQL chiamato `printcalc`. Lo schema viene gestito dal progetto tramite configurazione JPA/SQL del repository.
|
Crea un database PostgreSQL chiamato `printcalc`. Le tabelle verranno create automaticamente al primo avvio tramite Flyway.
|
||||||
|
|
||||||
### 2. Backend
|
### 2. Backend
|
||||||
Configura il percorso di OrcaSlicer in `backend/src/main/resources/application.properties` o tramite la variabile d'ambiente `SLICER_PATH`. Per il media service pubblico puoi configurare anche:
|
Configura il percorso di OrcaSlicer in `backend/src/main/resources/application.properties` o tramite la variabile d'ambiente `SLICER_PATH`.
|
||||||
|
|
||||||
- `MEDIA_STORAGE_ROOT` per la root `storage_media` usata dal backend (`original/`, `public/`, `private/`)
|
|
||||||
- `SHOP_STORAGE_ROOT` per la root `storage_shop` usata dal backend per i modelli dei prodotti shop
|
|
||||||
- `MEDIA_FFMPEG_PATH` per il binario `ffmpeg` (nel deploy Docker default: `/usr/local/bin/ffmpeg-media`)
|
|
||||||
- `MEDIA_UPLOAD_MAX_FILE_SIZE_BYTES` per il limite per asset immagine
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd backend
|
cd backend
|
||||||
@@ -63,54 +57,11 @@ I prezzi non sono più gestiti tramite variabili d'ambiente fisse ma tramite tab
|
|||||||
* `/backend`: API Spring Boot.
|
* `/backend`: API Spring Boot.
|
||||||
* `/frontend`: Applicazione Angular.
|
* `/frontend`: Applicazione Angular.
|
||||||
* `/backend/profiles`: Contiene i file di configurazione per OrcaSlicer.
|
* `/backend/profiles`: Contiene i file di configurazione per OrcaSlicer.
|
||||||
* `/storage_media`: Originali e varianti media pubbliche/private su filesystem.
|
|
||||||
* `/storage_shop`: Modelli e file prodotti dello shop.
|
|
||||||
|
|
||||||
## Media pubblici
|
|
||||||
|
|
||||||
Il backend salva sempre l'originale in `storage_media/original/` e precomputa le varianti pubbliche in `storage_media/public/`. La cartella `storage_media/private/` è predisposta per asset non pubblici.
|
|
||||||
|
|
||||||
Nel deploy Docker i volumi attesi sono `/mnt/cache/appdata/print-calculator/${ENV}/storage_media:/app/storage_media` e `/mnt/cache/appdata/print-calculator/${ENV}/storage_shop:/app/storage_shop`.
|
|
||||||
|
|
||||||
Nginx non deve passare dal backend per i file pubblici. Configurazione attesa:
|
|
||||||
|
|
||||||
```nginx
|
|
||||||
location /media/ {
|
|
||||||
alias /mnt/cache/appdata/print-calculator/${ENV}/storage_media/public/;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Usage key iniziali previste per frontend:
|
|
||||||
|
|
||||||
- `HOME_SECTION / shop-gallery`
|
|
||||||
- `HOME_SECTION / founders-gallery`
|
|
||||||
- `HOME_SECTION / capability-prototyping`
|
|
||||||
- `HOME_SECTION / capability-custom-parts`
|
|
||||||
- `HOME_SECTION / capability-small-series`
|
|
||||||
- `HOME_SECTION / capability-cad`
|
|
||||||
- `ABOUT_MEMBER / joe`
|
|
||||||
- `ABOUT_MEMBER / matteo`
|
|
||||||
- riservati per estensioni future: `SHOP_PRODUCT`, `SHOP_CATEGORY`, `SHOP_GALLERY`
|
|
||||||
|
|
||||||
Operativamente:
|
|
||||||
|
|
||||||
- carica i file dal media admin endpoint del backend
|
|
||||||
- associa ogni asset con `POST /api/admin/media/usages`
|
|
||||||
- per `ABOUT_MEMBER` imposta `isPrimary=true` sulla foto principale del membro
|
|
||||||
- home e about leggono da `GET /api/public/media/usages?usageType=...&usageKey=...`
|
|
||||||
- il frontend usa `<picture>` e preferisce AVIF/WEBP con fallback JPEG, senza usare l'originale
|
|
||||||
- nel back-office frontend la gestione operativa della home passa dalla pagina `admin/home-media`
|
|
||||||
|
|
||||||
## Troubleshooting
|
## Troubleshooting
|
||||||
|
|
||||||
### Percorso OrcaSlicer
|
### Percorso OrcaSlicer
|
||||||
Assicurati che `slicer.path` punti al binario corretto. Su macOS è solitamente `/Applications/OrcaSlicer.app/Contents/MacOS/OrcaSlicer`. Su Linux è il percorso all'AppImage (estratta o meno).
|
Assicurati che `slicer.path` punti al binario corretto. Su macOS è solitamente `/Applications/OrcaSlicer.app/Contents/MacOS/OrcaSlicer`. Su Linux è il percorso all'AppImage (estratta o meno).
|
||||||
|
|
||||||
### FFmpeg e media pubblici
|
|
||||||
Verifica che `MEDIA_FFMPEG_PATH` punti a un `ffmpeg` con supporto JPEG, WebP e AVIF (encoder + muxer AVIF). Nel container backend il default è `/usr/local/bin/ffmpeg-media`: usa `/usr/bin/ffmpeg` se già compatibile, altrimenti installa un fallback statico con supporto AVIF. Se gli URL media restituiti dalle API admin non sono raggiungibili, controlla che `APP_FRONTEND_BASE_URL` punti al dominio corretto, che `location /media/` sia esposto da Nginx e che il volume `storage_media` sia montato correttamente.
|
|
||||||
|
|
||||||
### Database connection
|
### Database connection
|
||||||
Verifica le credenziali in `application.properties`. Se usi Docker, puoi passare `DB_URL`, `DB_USERNAME` e `DB_PASSWORD` come variabili d'ambiente.
|
Verifica le credenziali in `application.properties`. Se usi Docker, puoi passare `DB_URL`, `DB_USERNAME` e `DB_PASSWORD` come variabili d'ambiente.
|
||||||
|
|
||||||
### Deploy e traduzioni OpenAI
|
|
||||||
Nel deploy Gitea la chiave OpenAI deve stare nel secret `OPENAI_API_KEY`. La pipeline la aggiunge al file `.env` dell'ambiente durante il deploy e il container backend la riceve come variabile runtime. I file `deploy/envs/*.env` restano per i valori specifici di `dev/int/prod`.
|
|
||||||
|
|||||||
@@ -12,49 +12,17 @@ RUN ./gradlew bootJar -x test --no-daemon
|
|||||||
FROM eclipse-temurin:21-jre-jammy
|
FROM eclipse-temurin:21-jre-jammy
|
||||||
ARG ORCA_VERSION=2.3.1
|
ARG ORCA_VERSION=2.3.1
|
||||||
ARG ORCA_DOWNLOAD_URL
|
ARG ORCA_DOWNLOAD_URL
|
||||||
ARG FFMPEG_STATIC_URL=https://johnvansickle.com/ffmpeg/releases/ffmpeg-release-amd64-static.tar.xz
|
|
||||||
|
|
||||||
# Install system dependencies for OrcaSlicer and media processing.
|
# Install system dependencies for OrcaSlicer (same as before)
|
||||||
# Prefer system ffmpeg; if AVIF support is incomplete, install a static ffmpeg fallback.
|
RUN apt-get update && apt-get install -y \
|
||||||
RUN set -eux; \
|
|
||||||
apt-get update; \
|
|
||||||
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
|
|
||||||
ffmpeg \
|
|
||||||
wget \
|
wget \
|
||||||
xz-utils \
|
|
||||||
ca-certificates \
|
|
||||||
assimp-utils \
|
assimp-utils \
|
||||||
libgl1 \
|
libgl1 \
|
||||||
libglib2.0-0 \
|
libglib2.0-0 \
|
||||||
libgtk-3-0 \
|
libgtk-3-0 \
|
||||||
libdbus-1-3 \
|
libdbus-1-3 \
|
||||||
libwebkit2gtk-4.0-37; \
|
libwebkit2gtk-4.0-37 \
|
||||||
check_ffmpeg_support() { \
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
ffmpeg_bin="$1"; \
|
|
||||||
"$ffmpeg_bin" -hide_banner -encoders > /tmp/ffmpeg-encoders.txt 2>&1 || return 1; \
|
|
||||||
"$ffmpeg_bin" -hide_banner -muxers > /tmp/ffmpeg-muxers.txt 2>&1 || return 1; \
|
|
||||||
grep -Eq '[[:space:]]mjpeg[[:space:]]' /tmp/ffmpeg-encoders.txt || return 1; \
|
|
||||||
grep -Eq '[[:space:]](libwebp|webp)[[:space:]]' /tmp/ffmpeg-encoders.txt || return 1; \
|
|
||||||
grep -Eq '[[:space:]](libaom-av1|librav1e|libsvtav1)[[:space:]]' /tmp/ffmpeg-encoders.txt || return 1; \
|
|
||||||
grep -Eq '[[:space:]]avif([[:space:]]|,|$)' /tmp/ffmpeg-muxers.txt || return 1; \
|
|
||||||
return 0; \
|
|
||||||
}; \
|
|
||||||
if check_ffmpeg_support /usr/bin/ffmpeg; then \
|
|
||||||
ln -sf /usr/bin/ffmpeg /usr/local/bin/ffmpeg-media; \
|
|
||||||
else \
|
|
||||||
echo "System ffmpeg lacks AVIF support, installing static fallback from ${FFMPEG_STATIC_URL}"; \
|
|
||||||
wget -q "${FFMPEG_STATIC_URL}" -O /tmp/ffmpeg-static.tar.xz; \
|
|
||||||
tar -xJf /tmp/ffmpeg-static.tar.xz -C /tmp; \
|
|
||||||
FFMPEG_STATIC_BIN="$(find /tmp -maxdepth 2 -type f -name ffmpeg | head -n 1)"; \
|
|
||||||
test -n "${FFMPEG_STATIC_BIN}"; \
|
|
||||||
install -m 0755 "${FFMPEG_STATIC_BIN}" /usr/local/bin/ffmpeg-media; \
|
|
||||||
check_ffmpeg_support /usr/local/bin/ffmpeg-media; \
|
|
||||||
fi; \
|
|
||||||
rm -f /tmp/ffmpeg-muxers.txt; \
|
|
||||||
rm -f /tmp/ffmpeg-encoders.txt; \
|
|
||||||
rm -f /tmp/ffmpeg-static.tar.xz; \
|
|
||||||
rm -rf /tmp/ffmpeg-*-amd64-static; \
|
|
||||||
rm -rf /var/lib/apt/lists/*
|
|
||||||
|
|
||||||
# Install OrcaSlicer
|
# Install OrcaSlicer
|
||||||
WORKDIR /opt
|
WORKDIR /opt
|
||||||
@@ -94,8 +62,6 @@ ENV PATH="/opt/orcaslicer/usr/bin:${PATH}"
|
|||||||
# Set Slicer Path env variable for Java app
|
# Set Slicer Path env variable for Java app
|
||||||
ENV SLICER_PATH="/opt/orcaslicer/AppRun"
|
ENV SLICER_PATH="/opt/orcaslicer/AppRun"
|
||||||
ENV ASSIMP_PATH="assimp"
|
ENV ASSIMP_PATH="assimp"
|
||||||
# Use ffmpeg selected at image build time (system or static fallback) for media generation.
|
|
||||||
ENV MEDIA_FFMPEG_PATH="/usr/local/bin/ffmpeg-media"
|
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
# Copy JAR from build stage
|
# Copy JAR from build stage
|
||||||
|
|||||||
@@ -42,7 +42,6 @@ dependencies {
|
|||||||
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
|
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
|
||||||
implementation 'net.codecrete.qrbill:qrbill-generator:3.4.0'
|
implementation 'net.codecrete.qrbill:qrbill-generator:3.4.0'
|
||||||
implementation 'org.springframework.boot:spring-boot-starter-mail'
|
implementation 'org.springframework.boot:spring-boot-starter-mail'
|
||||||
implementation 'org.jsoup:jsoup:1.18.3'
|
|
||||||
implementation platform('org.lwjgl:lwjgl-bom:3.3.4')
|
implementation platform('org.lwjgl:lwjgl-bom:3.3.4')
|
||||||
implementation 'org.lwjgl:lwjgl'
|
implementation 'org.lwjgl:lwjgl'
|
||||||
implementation 'org.lwjgl:lwjgl-assimp'
|
implementation 'org.lwjgl:lwjgl-assimp'
|
||||||
|
|||||||
@@ -1,61 +1,10 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
set -e
|
|
||||||
|
|
||||||
# In container default to the ffmpeg selected during image build.
|
|
||||||
if [ -z "${MEDIA_FFMPEG_PATH:-}" ]; then
|
|
||||||
MEDIA_FFMPEG_PATH="/usr/local/bin/ffmpeg-media"
|
|
||||||
fi
|
|
||||||
export MEDIA_FFMPEG_PATH
|
|
||||||
|
|
||||||
validate_ffmpeg_support() {
|
|
||||||
ffmpeg_bin="$1"
|
|
||||||
if ! command -v "$ffmpeg_bin" >/dev/null 2>&1; then
|
|
||||||
echo "ERROR: FFmpeg executable not found: ${ffmpeg_bin}" >&2
|
|
||||||
exit 11
|
|
||||||
fi
|
|
||||||
|
|
||||||
encoders="$(mktemp)"
|
|
||||||
muxers="$(mktemp)"
|
|
||||||
trap 'rm -f "$encoders" "$muxers"' EXIT
|
|
||||||
|
|
||||||
"$ffmpeg_bin" -hide_banner -encoders > "$encoders" 2>&1 || {
|
|
||||||
echo "ERROR: Unable to inspect FFmpeg encoders from ${ffmpeg_bin}" >&2
|
|
||||||
cat "$encoders" >&2
|
|
||||||
exit 12
|
|
||||||
}
|
|
||||||
"$ffmpeg_bin" -hide_banner -muxers > "$muxers" 2>&1 || {
|
|
||||||
echo "ERROR: Unable to inspect FFmpeg muxers from ${ffmpeg_bin}" >&2
|
|
||||||
cat "$muxers" >&2
|
|
||||||
exit 13
|
|
||||||
}
|
|
||||||
|
|
||||||
grep -Eq '[[:space:]]mjpeg[[:space:]]' "$encoders" || {
|
|
||||||
echo "ERROR: FFmpeg '${ffmpeg_bin}' missing JPEG encoder (mjpeg)." >&2
|
|
||||||
exit 14
|
|
||||||
}
|
|
||||||
grep -Eq '[[:space:]](libwebp|webp)[[:space:]]' "$encoders" || {
|
|
||||||
echo "ERROR: FFmpeg '${ffmpeg_bin}' missing WebP encoder." >&2
|
|
||||||
exit 15
|
|
||||||
}
|
|
||||||
grep -Eq '[[:space:]](libaom-av1|librav1e|libsvtav1)[[:space:]]' "$encoders" || {
|
|
||||||
echo "ERROR: FFmpeg '${ffmpeg_bin}' missing AVIF-capable encoder." >&2
|
|
||||||
exit 16
|
|
||||||
}
|
|
||||||
grep -Eq '[[:space:]]avif([[:space:]]|,|$)' "$muxers" || {
|
|
||||||
echo "ERROR: FFmpeg '${ffmpeg_bin}' missing AVIF muxer." >&2
|
|
||||||
exit 17
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
validate_ffmpeg_support "$MEDIA_FFMPEG_PATH"
|
|
||||||
|
|
||||||
echo "----------------------------------------------------------------"
|
echo "----------------------------------------------------------------"
|
||||||
echo "Starting Backend Application"
|
echo "Starting Backend Application"
|
||||||
echo "DB_URL: $DB_URL"
|
echo "DB_URL: $DB_URL"
|
||||||
echo "DB_USERNAME: $DB_USERNAME"
|
echo "DB_USERNAME: $DB_USERNAME"
|
||||||
echo "SPRING_DATASOURCE_URL: $SPRING_DATASOURCE_URL"
|
echo "SPRING_DATASOURCE_URL: $SPRING_DATASOURCE_URL"
|
||||||
echo "SLICER_PATH: $SLICER_PATH"
|
echo "SLICER_PATH: $SLICER_PATH"
|
||||||
echo "MEDIA_FFMPEG_PATH: $MEDIA_FFMPEG_PATH"
|
|
||||||
echo "----------------------------------------------------------------"
|
echo "----------------------------------------------------------------"
|
||||||
|
|
||||||
# Determine which environment variables to use for database connection
|
# Determine which environment variables to use for database connection
|
||||||
|
|||||||
@@ -2,46 +2,519 @@ package com.printcalculator.controller;
|
|||||||
|
|
||||||
import com.printcalculator.dto.QuoteRequestDto;
|
import com.printcalculator.dto.QuoteRequestDto;
|
||||||
import com.printcalculator.entity.CustomQuoteRequest;
|
import com.printcalculator.entity.CustomQuoteRequest;
|
||||||
import com.printcalculator.service.request.CustomQuoteRequestControllerService;
|
import com.printcalculator.entity.CustomQuoteRequestAttachment;
|
||||||
|
import com.printcalculator.repository.CustomQuoteRequestAttachmentRepository;
|
||||||
|
import com.printcalculator.repository.CustomQuoteRequestRepository;
|
||||||
|
import com.printcalculator.service.storage.ClamAVService;
|
||||||
|
import com.printcalculator.service.email.EmailNotificationService;
|
||||||
import jakarta.validation.Valid;
|
import jakarta.validation.Valid;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.http.MediaType;
|
import org.springframework.http.MediaType;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.util.StringUtils;
|
||||||
import org.springframework.web.bind.annotation.PathVariable;
|
import org.springframework.web.bind.annotation.*;
|
||||||
import org.springframework.web.bind.annotation.PostMapping;
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
|
||||||
import org.springframework.web.bind.annotation.RequestPart;
|
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
|
||||||
import org.springframework.web.multipart.MultipartFile;
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.InvalidPathException;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.nio.file.StandardCopyOption;
|
||||||
|
import java.time.OffsetDateTime;
|
||||||
|
import java.time.Year;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.time.format.FormatStyle;
|
||||||
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/api/custom-quote-requests")
|
@RequestMapping("/api/custom-quote-requests")
|
||||||
public class CustomQuoteRequestController {
|
public class CustomQuoteRequestController {
|
||||||
|
|
||||||
private final CustomQuoteRequestControllerService customQuoteRequestControllerService;
|
private static final Logger logger = LoggerFactory.getLogger(CustomQuoteRequestController.class);
|
||||||
|
private final CustomQuoteRequestRepository requestRepo;
|
||||||
|
private final CustomQuoteRequestAttachmentRepository attachmentRepo;
|
||||||
|
private final ClamAVService clamAVService;
|
||||||
|
private final EmailNotificationService emailNotificationService;
|
||||||
|
|
||||||
public CustomQuoteRequestController(CustomQuoteRequestControllerService customQuoteRequestControllerService) {
|
@Value("${app.mail.contact-request.admin.enabled:true}")
|
||||||
this.customQuoteRequestControllerService = customQuoteRequestControllerService;
|
private boolean contactRequestAdminMailEnabled;
|
||||||
|
|
||||||
|
@Value("${app.mail.contact-request.admin.address:infog@3d-fab.ch}")
|
||||||
|
private String contactRequestAdminMailAddress;
|
||||||
|
|
||||||
|
@Value("${app.mail.contact-request.customer.enabled:true}")
|
||||||
|
private boolean contactRequestCustomerMailEnabled;
|
||||||
|
|
||||||
|
// TODO: Inject Storage Service
|
||||||
|
private static final Path STORAGE_ROOT = Paths.get("storage_requests").toAbsolutePath().normalize();
|
||||||
|
private static final Pattern SAFE_EXTENSION_PATTERN = Pattern.compile("^[a-z0-9]{1,10}$");
|
||||||
|
private static final Set<String> FORBIDDEN_COMPRESSED_EXTENSIONS = Set.of(
|
||||||
|
"zip", "rar", "7z", "tar", "gz", "tgz", "bz2", "tbz2", "xz", "txz", "zst"
|
||||||
|
);
|
||||||
|
private static final Set<String> FORBIDDEN_COMPRESSED_MIME_TYPES = Set.of(
|
||||||
|
"application/zip",
|
||||||
|
"application/x-zip-compressed",
|
||||||
|
"application/x-rar-compressed",
|
||||||
|
"application/vnd.rar",
|
||||||
|
"application/x-7z-compressed",
|
||||||
|
"application/gzip",
|
||||||
|
"application/x-gzip",
|
||||||
|
"application/x-tar",
|
||||||
|
"application/x-bzip2",
|
||||||
|
"application/x-xz",
|
||||||
|
"application/zstd",
|
||||||
|
"application/x-zstd"
|
||||||
|
);
|
||||||
|
|
||||||
|
public CustomQuoteRequestController(CustomQuoteRequestRepository requestRepo,
|
||||||
|
CustomQuoteRequestAttachmentRepository attachmentRepo,
|
||||||
|
ClamAVService clamAVService,
|
||||||
|
EmailNotificationService emailNotificationService) {
|
||||||
|
this.requestRepo = requestRepo;
|
||||||
|
this.attachmentRepo = attachmentRepo;
|
||||||
|
this.clamAVService = clamAVService;
|
||||||
|
this.emailNotificationService = emailNotificationService;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 1. Create Custom Quote Request
|
||||||
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||||
@Transactional
|
@Transactional
|
||||||
public ResponseEntity<CustomQuoteRequest> createCustomQuoteRequest(
|
public ResponseEntity<CustomQuoteRequest> createCustomQuoteRequest(
|
||||||
@Valid @RequestPart("request") QuoteRequestDto requestDto,
|
@Valid @RequestPart("request") QuoteRequestDto requestDto,
|
||||||
@RequestPart(value = "files", required = false) List<MultipartFile> files
|
@RequestPart(value = "files", required = false) List<MultipartFile> files
|
||||||
) throws IOException {
|
) throws IOException {
|
||||||
return ResponseEntity.ok(customQuoteRequestControllerService.createCustomQuoteRequest(requestDto, files));
|
if (!requestDto.isAcceptTerms() || !requestDto.isAcceptPrivacy()) {
|
||||||
}
|
throw new ResponseStatusException(
|
||||||
|
HttpStatus.BAD_REQUEST,
|
||||||
|
"Accettazione Termini e Privacy obbligatoria."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
String language = normalizeLanguage(requestDto.getLanguage());
|
||||||
|
|
||||||
|
// 1. Create Request
|
||||||
|
CustomQuoteRequest request = new CustomQuoteRequest();
|
||||||
|
request.setRequestType(requestDto.getRequestType());
|
||||||
|
request.setCustomerType(requestDto.getCustomerType());
|
||||||
|
request.setEmail(requestDto.getEmail());
|
||||||
|
request.setPhone(requestDto.getPhone());
|
||||||
|
request.setName(requestDto.getName());
|
||||||
|
request.setCompanyName(requestDto.getCompanyName());
|
||||||
|
request.setContactPerson(requestDto.getContactPerson());
|
||||||
|
request.setMessage(requestDto.getMessage());
|
||||||
|
request.setStatus("PENDING");
|
||||||
|
request.setCreatedAt(OffsetDateTime.now());
|
||||||
|
request.setUpdatedAt(OffsetDateTime.now());
|
||||||
|
|
||||||
|
request = requestRepo.save(request);
|
||||||
|
|
||||||
|
// 2. Handle Attachments
|
||||||
|
int attachmentsCount = 0;
|
||||||
|
if (files != null && !files.isEmpty()) {
|
||||||
|
if (files.size() > 15) {
|
||||||
|
throw new IOException("Too many files. Max 15 allowed.");
|
||||||
|
}
|
||||||
|
|
||||||
|
for (MultipartFile file : files) {
|
||||||
|
if (file.isEmpty()) continue;
|
||||||
|
|
||||||
|
if (isCompressedFile(file)) {
|
||||||
|
throw new ResponseStatusException(
|
||||||
|
HttpStatus.BAD_REQUEST,
|
||||||
|
"Compressed files are not allowed."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Scan for virus
|
||||||
|
clamAVService.scan(file.getInputStream());
|
||||||
|
|
||||||
|
CustomQuoteRequestAttachment attachment = new CustomQuoteRequestAttachment();
|
||||||
|
attachment.setRequest(request);
|
||||||
|
attachment.setOriginalFilename(file.getOriginalFilename());
|
||||||
|
attachment.setMimeType(file.getContentType());
|
||||||
|
attachment.setFileSizeBytes(file.getSize());
|
||||||
|
attachment.setCreatedAt(OffsetDateTime.now());
|
||||||
|
|
||||||
|
// Generate path
|
||||||
|
UUID fileUuid = UUID.randomUUID();
|
||||||
|
String storedFilename = fileUuid + ".upload";
|
||||||
|
|
||||||
|
// Note: We don't have attachment ID yet.
|
||||||
|
// We'll save attachment first to get ID.
|
||||||
|
attachment.setStoredFilename(storedFilename);
|
||||||
|
attachment.setStoredRelativePath("PENDING");
|
||||||
|
|
||||||
|
attachment = attachmentRepo.save(attachment);
|
||||||
|
|
||||||
|
Path relativePath = Path.of(
|
||||||
|
"quote-requests",
|
||||||
|
request.getId().toString(),
|
||||||
|
"attachments",
|
||||||
|
attachment.getId().toString(),
|
||||||
|
storedFilename
|
||||||
|
);
|
||||||
|
attachment.setStoredRelativePath(relativePath.toString());
|
||||||
|
attachmentRepo.save(attachment);
|
||||||
|
|
||||||
|
// Save file to disk
|
||||||
|
Path absolutePath = resolveWithinStorageRoot(relativePath);
|
||||||
|
Files.createDirectories(absolutePath.getParent());
|
||||||
|
try (InputStream inputStream = file.getInputStream()) {
|
||||||
|
Files.copy(inputStream, absolutePath, StandardCopyOption.REPLACE_EXISTING);
|
||||||
|
}
|
||||||
|
attachmentsCount++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sendAdminContactRequestNotification(request, attachmentsCount);
|
||||||
|
sendCustomerContactRequestConfirmation(request, attachmentsCount, language);
|
||||||
|
|
||||||
|
return ResponseEntity.ok(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Get Request
|
||||||
@GetMapping("/{id}")
|
@GetMapping("/{id}")
|
||||||
public ResponseEntity<CustomQuoteRequest> getCustomQuoteRequest(@PathVariable UUID id) {
|
public ResponseEntity<CustomQuoteRequest> getCustomQuoteRequest(@PathVariable UUID id) {
|
||||||
return customQuoteRequestControllerService.getCustomQuoteRequest(id)
|
return requestRepo.findById(id)
|
||||||
.map(ResponseEntity::ok)
|
.map(ResponseEntity::ok)
|
||||||
.orElse(ResponseEntity.notFound().build());
|
.orElse(ResponseEntity.notFound().build());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Helper
|
||||||
|
private String getExtension(String filename) {
|
||||||
|
if (filename == null) return "dat";
|
||||||
|
String cleaned = StringUtils.cleanPath(filename);
|
||||||
|
if (cleaned.contains("..")) {
|
||||||
|
return "dat";
|
||||||
|
}
|
||||||
|
int i = cleaned.lastIndexOf('.');
|
||||||
|
if (i > 0 && i < cleaned.length() - 1) {
|
||||||
|
String ext = cleaned.substring(i + 1).toLowerCase(Locale.ROOT);
|
||||||
|
if (SAFE_EXTENSION_PATTERN.matcher(ext).matches()) {
|
||||||
|
return ext;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "dat";
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isCompressedFile(MultipartFile file) {
|
||||||
|
String ext = getExtension(file.getOriginalFilename());
|
||||||
|
if (FORBIDDEN_COMPRESSED_EXTENSIONS.contains(ext)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
String mime = file.getContentType();
|
||||||
|
return mime != null && FORBIDDEN_COMPRESSED_MIME_TYPES.contains(mime.toLowerCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
private Path resolveWithinStorageRoot(Path relativePath) {
|
||||||
|
try {
|
||||||
|
Path normalizedRelative = relativePath.normalize();
|
||||||
|
if (normalizedRelative.isAbsolute()) {
|
||||||
|
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid attachment path");
|
||||||
|
}
|
||||||
|
Path absolutePath = STORAGE_ROOT.resolve(normalizedRelative).normalize();
|
||||||
|
if (!absolutePath.startsWith(STORAGE_ROOT)) {
|
||||||
|
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid attachment path");
|
||||||
|
}
|
||||||
|
return absolutePath;
|
||||||
|
} catch (InvalidPathException e) {
|
||||||
|
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid attachment path");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void sendAdminContactRequestNotification(CustomQuoteRequest request, int attachmentsCount) {
|
||||||
|
if (!contactRequestAdminMailEnabled) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (contactRequestAdminMailAddress == null || contactRequestAdminMailAddress.isBlank()) {
|
||||||
|
logger.warn("Contact request admin notification enabled but no admin address configured.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, Object> templateData = new HashMap<>();
|
||||||
|
templateData.put("requestId", request.getId());
|
||||||
|
templateData.put("createdAt", request.getCreatedAt());
|
||||||
|
templateData.put("requestType", safeValue(request.getRequestType()));
|
||||||
|
templateData.put("customerType", safeValue(request.getCustomerType()));
|
||||||
|
templateData.put("name", safeValue(request.getName()));
|
||||||
|
templateData.put("companyName", safeValue(request.getCompanyName()));
|
||||||
|
templateData.put("contactPerson", safeValue(request.getContactPerson()));
|
||||||
|
templateData.put("email", safeValue(request.getEmail()));
|
||||||
|
templateData.put("phone", safeValue(request.getPhone()));
|
||||||
|
templateData.put("message", safeValue(request.getMessage()));
|
||||||
|
templateData.put("attachmentsCount", attachmentsCount);
|
||||||
|
templateData.put("currentYear", Year.now().getValue());
|
||||||
|
|
||||||
|
emailNotificationService.sendEmail(
|
||||||
|
contactRequestAdminMailAddress,
|
||||||
|
"Nuova richiesta di contatto #" + request.getId(),
|
||||||
|
"contact-request-admin",
|
||||||
|
templateData
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void sendCustomerContactRequestConfirmation(CustomQuoteRequest request, int attachmentsCount, String language) {
|
||||||
|
if (!contactRequestCustomerMailEnabled) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (request.getEmail() == null || request.getEmail().isBlank()) {
|
||||||
|
logger.warn("Contact request confirmation skipped: missing customer email for request {}", request.getId());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, Object> templateData = new HashMap<>();
|
||||||
|
templateData.put("requestId", request.getId());
|
||||||
|
templateData.put(
|
||||||
|
"createdAt",
|
||||||
|
request.getCreatedAt().format(
|
||||||
|
DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).withLocale(localeForLanguage(language))
|
||||||
|
)
|
||||||
|
);
|
||||||
|
templateData.put("recipientName", resolveRecipientName(request, language));
|
||||||
|
templateData.put("requestType", localizeRequestType(request.getRequestType(), language));
|
||||||
|
templateData.put("customerType", localizeCustomerType(request.getCustomerType(), language));
|
||||||
|
templateData.put("name", safeValue(request.getName()));
|
||||||
|
templateData.put("companyName", safeValue(request.getCompanyName()));
|
||||||
|
templateData.put("contactPerson", safeValue(request.getContactPerson()));
|
||||||
|
templateData.put("email", safeValue(request.getEmail()));
|
||||||
|
templateData.put("phone", safeValue(request.getPhone()));
|
||||||
|
templateData.put("message", safeValue(request.getMessage()));
|
||||||
|
templateData.put("attachmentsCount", attachmentsCount);
|
||||||
|
templateData.put("currentYear", Year.now().getValue());
|
||||||
|
String subject = applyCustomerContactRequestTexts(templateData, language, request.getId());
|
||||||
|
|
||||||
|
emailNotificationService.sendEmail(
|
||||||
|
request.getEmail(),
|
||||||
|
subject,
|
||||||
|
"contact-request-customer",
|
||||||
|
templateData
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String applyCustomerContactRequestTexts(
|
||||||
|
Map<String, Object> templateData,
|
||||||
|
String language,
|
||||||
|
UUID requestId
|
||||||
|
) {
|
||||||
|
return switch (language) {
|
||||||
|
case "en" -> {
|
||||||
|
templateData.put("emailTitle", "Contact request received");
|
||||||
|
templateData.put("headlineText", "We received your contact request");
|
||||||
|
templateData.put("greetingText", "Hi " + templateData.get("recipientName") + ",");
|
||||||
|
templateData.put("introText", "Thank you for contacting us. Our team will reply as soon as possible.");
|
||||||
|
templateData.put("requestIdHintText", "Please keep this request ID for future order references:");
|
||||||
|
templateData.put("detailsTitleText", "Request details");
|
||||||
|
templateData.put("labelRequestId", "Request ID");
|
||||||
|
templateData.put("labelDate", "Date");
|
||||||
|
templateData.put("labelRequestType", "Request type");
|
||||||
|
templateData.put("labelCustomerType", "Customer type");
|
||||||
|
templateData.put("labelName", "Name");
|
||||||
|
templateData.put("labelCompany", "Company");
|
||||||
|
templateData.put("labelContactPerson", "Contact person");
|
||||||
|
templateData.put("labelEmail", "Email");
|
||||||
|
templateData.put("labelPhone", "Phone");
|
||||||
|
templateData.put("labelMessage", "Message");
|
||||||
|
templateData.put("labelAttachments", "Attachments");
|
||||||
|
templateData.put("supportText", "If you need help, reply to this email.");
|
||||||
|
templateData.put("footerText", "Automated request-receipt confirmation from 3D-Fab.");
|
||||||
|
yield "We received your contact request #" + requestId + " - 3D-Fab";
|
||||||
|
}
|
||||||
|
case "de" -> {
|
||||||
|
templateData.put("emailTitle", "Kontaktanfrage erhalten");
|
||||||
|
templateData.put("headlineText", "Wir haben Ihre Kontaktanfrage erhalten");
|
||||||
|
templateData.put("greetingText", "Hallo " + templateData.get("recipientName") + ",");
|
||||||
|
templateData.put("introText", "Vielen Dank fuer Ihre Anfrage. Unser Team antwortet Ihnen so schnell wie moeglich.");
|
||||||
|
templateData.put("requestIdHintText", "Bitte speichern Sie diese Anfrage-ID fuer zukuenftige Bestellreferenzen:");
|
||||||
|
templateData.put("detailsTitleText", "Anfragedetails");
|
||||||
|
templateData.put("labelRequestId", "Anfrage-ID");
|
||||||
|
templateData.put("labelDate", "Datum");
|
||||||
|
templateData.put("labelRequestType", "Anfragetyp");
|
||||||
|
templateData.put("labelCustomerType", "Kundentyp");
|
||||||
|
templateData.put("labelName", "Name");
|
||||||
|
templateData.put("labelCompany", "Firma");
|
||||||
|
templateData.put("labelContactPerson", "Kontaktperson");
|
||||||
|
templateData.put("labelEmail", "E-Mail");
|
||||||
|
templateData.put("labelPhone", "Telefon");
|
||||||
|
templateData.put("labelMessage", "Nachricht");
|
||||||
|
templateData.put("labelAttachments", "Anhaenge");
|
||||||
|
templateData.put("supportText", "Wenn Sie Hilfe brauchen, antworten Sie auf diese E-Mail.");
|
||||||
|
templateData.put("footerText", "Automatische Bestaetigung des Anfrageeingangs von 3D-Fab.");
|
||||||
|
yield "Wir haben Ihre Kontaktanfrage erhalten #" + requestId + " - 3D-Fab";
|
||||||
|
}
|
||||||
|
case "fr" -> {
|
||||||
|
templateData.put("emailTitle", "Demande de contact recue");
|
||||||
|
templateData.put("headlineText", "Nous avons recu votre demande de contact");
|
||||||
|
templateData.put("greetingText", "Bonjour " + templateData.get("recipientName") + ",");
|
||||||
|
templateData.put("introText", "Merci pour votre message. Notre equipe vous repondra des que possible.");
|
||||||
|
templateData.put("requestIdHintText", "Veuillez conserver cet ID de demande pour vos futures references de commande :");
|
||||||
|
templateData.put("detailsTitleText", "Details de la demande");
|
||||||
|
templateData.put("labelRequestId", "ID de demande");
|
||||||
|
templateData.put("labelDate", "Date");
|
||||||
|
templateData.put("labelRequestType", "Type de demande");
|
||||||
|
templateData.put("labelCustomerType", "Type de client");
|
||||||
|
templateData.put("labelName", "Nom");
|
||||||
|
templateData.put("labelCompany", "Entreprise");
|
||||||
|
templateData.put("labelContactPerson", "Contact");
|
||||||
|
templateData.put("labelEmail", "Email");
|
||||||
|
templateData.put("labelPhone", "Telephone");
|
||||||
|
templateData.put("labelMessage", "Message");
|
||||||
|
templateData.put("labelAttachments", "Pieces jointes");
|
||||||
|
templateData.put("supportText", "Si vous avez besoin d'aide, repondez a cet email.");
|
||||||
|
templateData.put("footerText", "Confirmation automatique de reception de demande par 3D-Fab.");
|
||||||
|
yield "Nous avons recu votre demande de contact #" + requestId + " - 3D-Fab";
|
||||||
|
}
|
||||||
|
default -> {
|
||||||
|
templateData.put("emailTitle", "Richiesta di contatto ricevuta");
|
||||||
|
templateData.put("headlineText", "Abbiamo ricevuto la tua richiesta di contatto");
|
||||||
|
templateData.put("greetingText", "Ciao " + templateData.get("recipientName") + ",");
|
||||||
|
templateData.put("introText", "Grazie per averci contattato. Il nostro team ti rispondera' il prima possibile.");
|
||||||
|
templateData.put("requestIdHintText", "Conserva questo ID richiesta per i futuri riferimenti d'ordine:");
|
||||||
|
templateData.put("detailsTitleText", "Dettagli richiesta");
|
||||||
|
templateData.put("labelRequestId", "ID richiesta");
|
||||||
|
templateData.put("labelDate", "Data");
|
||||||
|
templateData.put("labelRequestType", "Tipo richiesta");
|
||||||
|
templateData.put("labelCustomerType", "Tipo cliente");
|
||||||
|
templateData.put("labelName", "Nome");
|
||||||
|
templateData.put("labelCompany", "Azienda");
|
||||||
|
templateData.put("labelContactPerson", "Contatto");
|
||||||
|
templateData.put("labelEmail", "Email");
|
||||||
|
templateData.put("labelPhone", "Telefono");
|
||||||
|
templateData.put("labelMessage", "Messaggio");
|
||||||
|
templateData.put("labelAttachments", "Allegati");
|
||||||
|
templateData.put("supportText", "Se hai bisogno, rispondi direttamente a questa email.");
|
||||||
|
templateData.put("footerText", "Conferma automatica di ricezione richiesta da 3D-Fab.");
|
||||||
|
yield "Abbiamo ricevuto la tua richiesta di contatto #" + requestId + " - 3D-Fab";
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private String localizeRequestType(String requestType, String language) {
|
||||||
|
if (requestType == null || requestType.isBlank()) {
|
||||||
|
return "-";
|
||||||
|
}
|
||||||
|
|
||||||
|
String normalized = requestType.trim().toLowerCase(Locale.ROOT);
|
||||||
|
return switch (language) {
|
||||||
|
case "en" -> switch (normalized) {
|
||||||
|
case "custom", "print_service" -> "Custom part request";
|
||||||
|
case "series" -> "Series production request";
|
||||||
|
case "consult", "design_service" -> "Consultation request";
|
||||||
|
case "question" -> "General question";
|
||||||
|
default -> requestType;
|
||||||
|
};
|
||||||
|
case "de" -> switch (normalized) {
|
||||||
|
case "custom", "print_service" -> "Anfrage fuer Einzelteil";
|
||||||
|
case "series" -> "Anfrage fuer Serienproduktion";
|
||||||
|
case "consult", "design_service" -> "Beratungsanfrage";
|
||||||
|
case "question" -> "Allgemeine Frage";
|
||||||
|
default -> requestType;
|
||||||
|
};
|
||||||
|
case "fr" -> switch (normalized) {
|
||||||
|
case "custom", "print_service" -> "Demande de piece personnalisee";
|
||||||
|
case "series" -> "Demande de production en serie";
|
||||||
|
case "consult", "design_service" -> "Demande de conseil";
|
||||||
|
case "question" -> "Question generale";
|
||||||
|
default -> requestType;
|
||||||
|
};
|
||||||
|
default -> switch (normalized) {
|
||||||
|
case "custom", "print_service" -> "Richiesta pezzo personalizzato";
|
||||||
|
case "series" -> "Richiesta produzione in serie";
|
||||||
|
case "consult", "design_service" -> "Richiesta consulenza";
|
||||||
|
case "question" -> "Domanda generale";
|
||||||
|
default -> requestType;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private String localizeCustomerType(String customerType, String language) {
|
||||||
|
if (customerType == null || customerType.isBlank()) {
|
||||||
|
return "-";
|
||||||
|
}
|
||||||
|
String normalized = customerType.trim().toLowerCase(Locale.ROOT);
|
||||||
|
return switch (language) {
|
||||||
|
case "en" -> switch (normalized) {
|
||||||
|
case "private" -> "Private";
|
||||||
|
case "business" -> "Business";
|
||||||
|
default -> customerType;
|
||||||
|
};
|
||||||
|
case "de" -> switch (normalized) {
|
||||||
|
case "private" -> "Privat";
|
||||||
|
case "business" -> "Unternehmen";
|
||||||
|
default -> customerType;
|
||||||
|
};
|
||||||
|
case "fr" -> switch (normalized) {
|
||||||
|
case "private" -> "Prive";
|
||||||
|
case "business" -> "Entreprise";
|
||||||
|
default -> customerType;
|
||||||
|
};
|
||||||
|
default -> switch (normalized) {
|
||||||
|
case "private" -> "Privato";
|
||||||
|
case "business" -> "Azienda";
|
||||||
|
default -> customerType;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private Locale localeForLanguage(String language) {
|
||||||
|
return switch (language) {
|
||||||
|
case "en" -> Locale.ENGLISH;
|
||||||
|
case "de" -> Locale.GERMAN;
|
||||||
|
case "fr" -> Locale.FRENCH;
|
||||||
|
default -> Locale.ITALIAN;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private String normalizeLanguage(String language) {
|
||||||
|
if (language == null || language.isBlank()) {
|
||||||
|
return "it";
|
||||||
|
}
|
||||||
|
String normalized = language.toLowerCase(Locale.ROOT).trim();
|
||||||
|
if (normalized.startsWith("en")) {
|
||||||
|
return "en";
|
||||||
|
}
|
||||||
|
if (normalized.startsWith("de")) {
|
||||||
|
return "de";
|
||||||
|
}
|
||||||
|
if (normalized.startsWith("fr")) {
|
||||||
|
return "fr";
|
||||||
|
}
|
||||||
|
return "it";
|
||||||
|
}
|
||||||
|
|
||||||
|
private String resolveRecipientName(CustomQuoteRequest request, String language) {
|
||||||
|
if (request.getName() != null && !request.getName().isBlank()) {
|
||||||
|
return request.getName().trim();
|
||||||
|
}
|
||||||
|
if (request.getContactPerson() != null && !request.getContactPerson().isBlank()) {
|
||||||
|
return request.getContactPerson().trim();
|
||||||
|
}
|
||||||
|
if (request.getCompanyName() != null && !request.getCompanyName().isBlank()) {
|
||||||
|
return request.getCompanyName().trim();
|
||||||
|
}
|
||||||
|
return switch (language) {
|
||||||
|
case "en" -> "customer";
|
||||||
|
case "de" -> "Kunde";
|
||||||
|
case "fr" -> "client";
|
||||||
|
default -> "cliente";
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private String safeValue(String value) {
|
||||||
|
if (value == null || value.isBlank()) {
|
||||||
|
return "-";
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,10 +12,8 @@ import com.printcalculator.repository.FilamentVariantRepository;
|
|||||||
import com.printcalculator.repository.MaterialOrcaProfileMapRepository;
|
import com.printcalculator.repository.MaterialOrcaProfileMapRepository;
|
||||||
import com.printcalculator.repository.NozzleOptionRepository;
|
import com.printcalculator.repository.NozzleOptionRepository;
|
||||||
import com.printcalculator.repository.PrinterMachineRepository;
|
import com.printcalculator.repository.PrinterMachineRepository;
|
||||||
import com.printcalculator.repository.PrinterMachineProfileRepository;
|
|
||||||
import com.printcalculator.service.NozzleLayerHeightPolicyService;
|
import com.printcalculator.service.NozzleLayerHeightPolicyService;
|
||||||
import com.printcalculator.service.OrcaProfileResolver;
|
import com.printcalculator.service.OrcaProfileResolver;
|
||||||
import com.printcalculator.service.ProfileManager;
|
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
@@ -24,11 +22,8 @@ import org.springframework.web.bind.annotation.RestController;
|
|||||||
|
|
||||||
import java.math.BigDecimal;
|
import java.math.BigDecimal;
|
||||||
import java.util.Comparator;
|
import java.util.Comparator;
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.LinkedHashSet;
|
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
@@ -39,29 +34,23 @@ public class OptionsController {
|
|||||||
private final FilamentVariantRepository variantRepo;
|
private final FilamentVariantRepository variantRepo;
|
||||||
private final NozzleOptionRepository nozzleRepo;
|
private final NozzleOptionRepository nozzleRepo;
|
||||||
private final PrinterMachineRepository printerMachineRepo;
|
private final PrinterMachineRepository printerMachineRepo;
|
||||||
private final PrinterMachineProfileRepository printerMachineProfileRepo;
|
|
||||||
private final MaterialOrcaProfileMapRepository materialOrcaMapRepo;
|
private final MaterialOrcaProfileMapRepository materialOrcaMapRepo;
|
||||||
private final OrcaProfileResolver orcaProfileResolver;
|
private final OrcaProfileResolver orcaProfileResolver;
|
||||||
private final ProfileManager profileManager;
|
|
||||||
private final NozzleLayerHeightPolicyService nozzleLayerHeightPolicyService;
|
private final NozzleLayerHeightPolicyService nozzleLayerHeightPolicyService;
|
||||||
|
|
||||||
public OptionsController(FilamentMaterialTypeRepository materialRepo,
|
public OptionsController(FilamentMaterialTypeRepository materialRepo,
|
||||||
FilamentVariantRepository variantRepo,
|
FilamentVariantRepository variantRepo,
|
||||||
NozzleOptionRepository nozzleRepo,
|
NozzleOptionRepository nozzleRepo,
|
||||||
PrinterMachineRepository printerMachineRepo,
|
PrinterMachineRepository printerMachineRepo,
|
||||||
PrinterMachineProfileRepository printerMachineProfileRepo,
|
|
||||||
MaterialOrcaProfileMapRepository materialOrcaMapRepo,
|
MaterialOrcaProfileMapRepository materialOrcaMapRepo,
|
||||||
OrcaProfileResolver orcaProfileResolver,
|
OrcaProfileResolver orcaProfileResolver,
|
||||||
ProfileManager profileManager,
|
|
||||||
NozzleLayerHeightPolicyService nozzleLayerHeightPolicyService) {
|
NozzleLayerHeightPolicyService nozzleLayerHeightPolicyService) {
|
||||||
this.materialRepo = materialRepo;
|
this.materialRepo = materialRepo;
|
||||||
this.variantRepo = variantRepo;
|
this.variantRepo = variantRepo;
|
||||||
this.nozzleRepo = nozzleRepo;
|
this.nozzleRepo = nozzleRepo;
|
||||||
this.printerMachineRepo = printerMachineRepo;
|
this.printerMachineRepo = printerMachineRepo;
|
||||||
this.printerMachineProfileRepo = printerMachineProfileRepo;
|
|
||||||
this.materialOrcaMapRepo = materialOrcaMapRepo;
|
this.materialOrcaMapRepo = materialOrcaMapRepo;
|
||||||
this.orcaProfileResolver = orcaProfileResolver;
|
this.orcaProfileResolver = orcaProfileResolver;
|
||||||
this.profileManager = profileManager;
|
|
||||||
this.nozzleLayerHeightPolicyService = nozzleLayerHeightPolicyService;
|
this.nozzleLayerHeightPolicyService = nozzleLayerHeightPolicyService;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -94,10 +83,6 @@ public class OptionsController {
|
|||||||
v.getId(),
|
v.getId(),
|
||||||
v.getVariantDisplayName(),
|
v.getVariantDisplayName(),
|
||||||
v.getColorName(),
|
v.getColorName(),
|
||||||
v.getColorLabelIt(),
|
|
||||||
v.getColorLabelEn(),
|
|
||||||
v.getColorLabelDe(),
|
|
||||||
v.getColorLabelFr(),
|
|
||||||
resolveHexColor(v),
|
resolveHexColor(v),
|
||||||
v.getFinishType() != null ? v.getFinishType() : "GLOSSY",
|
v.getFinishType() != null ? v.getFinishType() : "GLOSSY",
|
||||||
v.getStockSpools() != null ? v.getStockSpools().doubleValue() : 0d,
|
v.getStockSpools() != null ? v.getStockSpools().doubleValue() : 0d,
|
||||||
@@ -131,27 +116,8 @@ public class OptionsController {
|
|||||||
new OptionsResponse.InfillPatternOption("cubic", "Cubic")
|
new OptionsResponse.InfillPatternOption("cubic", "Cubic")
|
||||||
);
|
);
|
||||||
|
|
||||||
PrinterMachine targetMachine = resolveMachine(printerMachineId);
|
|
||||||
|
|
||||||
Set<BigDecimal> supportedMachineNozzles = targetMachine != null
|
|
||||||
? printerMachineProfileRepo.findByPrinterMachineAndIsActiveTrue(targetMachine).stream()
|
|
||||||
.map(PrinterMachineProfile::getNozzleDiameterMm)
|
|
||||||
.filter(v -> v != null)
|
|
||||||
.map(nozzleLayerHeightPolicyService::normalizeNozzle)
|
|
||||||
.collect(Collectors.toCollection(LinkedHashSet::new))
|
|
||||||
: Set.of();
|
|
||||||
|
|
||||||
boolean restrictNozzlesByMachineProfile = !supportedMachineNozzles.isEmpty();
|
|
||||||
|
|
||||||
List<OptionsResponse.NozzleOptionDTO> nozzles = nozzleRepo.findAll().stream()
|
List<OptionsResponse.NozzleOptionDTO> nozzles = nozzleRepo.findAll().stream()
|
||||||
.filter(n -> Boolean.TRUE.equals(n.getIsActive()))
|
.filter(n -> Boolean.TRUE.equals(n.getIsActive()))
|
||||||
.filter(n -> {
|
|
||||||
if (!restrictNozzlesByMachineProfile) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
BigDecimal normalized = nozzleLayerHeightPolicyService.normalizeNozzle(n.getNozzleDiameterMm());
|
|
||||||
return normalized != null && supportedMachineNozzles.contains(normalized);
|
|
||||||
})
|
|
||||||
.sorted(Comparator.comparing(NozzleOption::getNozzleDiameterMm))
|
.sorted(Comparator.comparing(NozzleOption::getNozzleDiameterMm))
|
||||||
.map(n -> new OptionsResponse.NozzleOptionDTO(
|
.map(n -> new OptionsResponse.NozzleOptionDTO(
|
||||||
n.getNozzleDiameterMm().doubleValue(),
|
n.getNozzleDiameterMm().doubleValue(),
|
||||||
@@ -163,62 +129,16 @@ public class OptionsController {
|
|||||||
.toList();
|
.toList();
|
||||||
|
|
||||||
Map<BigDecimal, List<BigDecimal>> rulesByNozzle = nozzleLayerHeightPolicyService.getActiveRulesByNozzle();
|
Map<BigDecimal, List<BigDecimal>> rulesByNozzle = nozzleLayerHeightPolicyService.getActiveRulesByNozzle();
|
||||||
Set<BigDecimal> visibleNozzlesFromOptions = nozzles.stream()
|
|
||||||
.map(OptionsResponse.NozzleOptionDTO::value)
|
|
||||||
.map(BigDecimal::valueOf)
|
|
||||||
.map(nozzleLayerHeightPolicyService::normalizeNozzle)
|
|
||||||
.filter(v -> v != null)
|
|
||||||
.collect(Collectors.toCollection(LinkedHashSet::new));
|
|
||||||
|
|
||||||
Map<BigDecimal, List<BigDecimal>> effectiveRulesByNozzle = new LinkedHashMap<>();
|
|
||||||
for (BigDecimal nozzle : visibleNozzlesFromOptions) {
|
|
||||||
List<BigDecimal> policyLayers = rulesByNozzle.getOrDefault(nozzle, List.of());
|
|
||||||
List<BigDecimal> compatibleProcessLayers = resolveCompatibleProcessLayers(targetMachine, nozzle);
|
|
||||||
List<BigDecimal> effective = mergePolicyAndProcessLayers(policyLayers, compatibleProcessLayers);
|
|
||||||
if (!effective.isEmpty()) {
|
|
||||||
effectiveRulesByNozzle.put(nozzle, effective);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (effectiveRulesByNozzle.isEmpty()) {
|
|
||||||
for (BigDecimal nozzle : visibleNozzlesFromOptions) {
|
|
||||||
List<BigDecimal> policyLayers = rulesByNozzle.getOrDefault(nozzle, List.of());
|
|
||||||
if (!policyLayers.isEmpty()) {
|
|
||||||
effectiveRulesByNozzle.put(nozzle, policyLayers);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Set<BigDecimal> visibleNozzles = new LinkedHashSet<>(effectiveRulesByNozzle.keySet());
|
|
||||||
nozzles = nozzles.stream()
|
|
||||||
.filter(option -> {
|
|
||||||
BigDecimal normalized = nozzleLayerHeightPolicyService.normalizeNozzle(
|
|
||||||
BigDecimal.valueOf(option.value())
|
|
||||||
);
|
|
||||||
return normalized != null && visibleNozzles.contains(normalized);
|
|
||||||
})
|
|
||||||
.toList();
|
|
||||||
|
|
||||||
BigDecimal selectedNozzle = nozzleLayerHeightPolicyService.resolveNozzle(
|
BigDecimal selectedNozzle = nozzleLayerHeightPolicyService.resolveNozzle(
|
||||||
nozzleDiameter != null ? BigDecimal.valueOf(nozzleDiameter) : null
|
nozzleDiameter != null ? BigDecimal.valueOf(nozzleDiameter) : null
|
||||||
);
|
);
|
||||||
if (!visibleNozzles.isEmpty() && !visibleNozzles.contains(selectedNozzle)) {
|
|
||||||
selectedNozzle = visibleNozzles.iterator().next();
|
|
||||||
}
|
|
||||||
|
|
||||||
List<OptionsResponse.LayerHeightOptionDTO> layers = toLayerDtos(
|
List<OptionsResponse.LayerHeightOptionDTO> layers = toLayerDtos(rulesByNozzle.getOrDefault(selectedNozzle, List.of()));
|
||||||
effectiveRulesByNozzle.getOrDefault(selectedNozzle, List.of())
|
|
||||||
);
|
|
||||||
if (layers.isEmpty()) {
|
if (layers.isEmpty()) {
|
||||||
if (!visibleNozzles.isEmpty()) {
|
layers = rulesByNozzle.values().stream().findFirst().map(this::toLayerDtos).orElse(List.of());
|
||||||
BigDecimal fallbackNozzle = visibleNozzles.iterator().next();
|
|
||||||
layers = toLayerDtos(effectiveRulesByNozzle.getOrDefault(fallbackNozzle, List.of()));
|
|
||||||
}
|
|
||||||
if (layers.isEmpty()) {
|
|
||||||
layers = rulesByNozzle.values().stream().findFirst().map(this::toLayerDtos).orElse(List.of());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
List<OptionsResponse.NozzleLayerHeightOptionsDTO> layerHeightsByNozzle = effectiveRulesByNozzle.entrySet().stream()
|
List<OptionsResponse.NozzleLayerHeightOptionsDTO> layerHeightsByNozzle = rulesByNozzle.entrySet().stream()
|
||||||
.map(entry -> new OptionsResponse.NozzleLayerHeightOptionsDTO(
|
.map(entry -> new OptionsResponse.NozzleLayerHeightOptionsDTO(
|
||||||
entry.getKey().doubleValue(),
|
entry.getKey().doubleValue(),
|
||||||
toLayerDtos(entry.getValue())
|
toLayerDtos(entry.getValue())
|
||||||
@@ -236,7 +156,13 @@ public class OptionsController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private Set<Long> resolveCompatibleMaterialTypeIds(Long printerMachineId, Double nozzleDiameter) {
|
private Set<Long> resolveCompatibleMaterialTypeIds(Long printerMachineId, Double nozzleDiameter) {
|
||||||
PrinterMachine machine = resolveMachine(printerMachineId);
|
PrinterMachine machine = null;
|
||||||
|
if (printerMachineId != null) {
|
||||||
|
machine = printerMachineRepo.findById(printerMachineId).orElse(null);
|
||||||
|
}
|
||||||
|
if (machine == null) {
|
||||||
|
machine = printerMachineRepo.findFirstByIsActiveTrue().orElse(null);
|
||||||
|
}
|
||||||
if (machine == null) {
|
if (machine == null) {
|
||||||
return Set.of();
|
return Set.of();
|
||||||
}
|
}
|
||||||
@@ -261,17 +187,6 @@ public class OptionsController {
|
|||||||
.collect(Collectors.toSet());
|
.collect(Collectors.toSet());
|
||||||
}
|
}
|
||||||
|
|
||||||
private PrinterMachine resolveMachine(Long printerMachineId) {
|
|
||||||
PrinterMachine machine = null;
|
|
||||||
if (printerMachineId != null) {
|
|
||||||
machine = printerMachineRepo.findById(printerMachineId).orElse(null);
|
|
||||||
}
|
|
||||||
if (machine == null) {
|
|
||||||
machine = printerMachineRepo.findFirstByIsActiveTrue().orElse(null);
|
|
||||||
}
|
|
||||||
return machine;
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<OptionsResponse.LayerHeightOptionDTO> toLayerDtos(List<BigDecimal> layers) {
|
private List<OptionsResponse.LayerHeightOptionDTO> toLayerDtos(List<BigDecimal> layers) {
|
||||||
return layers.stream()
|
return layers.stream()
|
||||||
.sorted(Comparator.naturalOrder())
|
.sorted(Comparator.naturalOrder())
|
||||||
@@ -282,52 +197,6 @@ public class OptionsController {
|
|||||||
.toList();
|
.toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<BigDecimal> resolveCompatibleProcessLayers(PrinterMachine machine, BigDecimal nozzle) {
|
|
||||||
if (machine == null || nozzle == null) {
|
|
||||||
return List.of();
|
|
||||||
}
|
|
||||||
PrinterMachineProfile profile = orcaProfileResolver.resolveMachineProfile(machine, nozzle).orElse(null);
|
|
||||||
if (profile == null || profile.getOrcaMachineProfileName() == null) {
|
|
||||||
return List.of();
|
|
||||||
}
|
|
||||||
return profileManager.findCompatibleProcessLayers(profile.getOrcaMachineProfileName());
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<BigDecimal> mergePolicyAndProcessLayers(List<BigDecimal> policyLayers,
|
|
||||||
List<BigDecimal> processLayers) {
|
|
||||||
if ((processLayers == null || processLayers.isEmpty())
|
|
||||||
&& (policyLayers == null || policyLayers.isEmpty())) {
|
|
||||||
return List.of();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (processLayers == null || processLayers.isEmpty()) {
|
|
||||||
return policyLayers != null ? policyLayers : List.of();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (policyLayers == null || policyLayers.isEmpty()) {
|
|
||||||
return processLayers;
|
|
||||||
}
|
|
||||||
|
|
||||||
Set<BigDecimal> allowedByPolicy = policyLayers.stream()
|
|
||||||
.map(nozzleLayerHeightPolicyService::normalizeLayer)
|
|
||||||
.filter(v -> v != null)
|
|
||||||
.collect(Collectors.toCollection(LinkedHashSet::new));
|
|
||||||
|
|
||||||
List<BigDecimal> intersection = processLayers.stream()
|
|
||||||
.map(nozzleLayerHeightPolicyService::normalizeLayer)
|
|
||||||
.filter(v -> v != null && allowedByPolicy.contains(v))
|
|
||||||
.collect(Collectors.toCollection(ArrayList::new));
|
|
||||||
|
|
||||||
if (!intersection.isEmpty()) {
|
|
||||||
return intersection;
|
|
||||||
}
|
|
||||||
|
|
||||||
return processLayers.stream()
|
|
||||||
.map(nozzleLayerHeightPolicyService::normalizeLayer)
|
|
||||||
.filter(v -> v != null)
|
|
||||||
.collect(Collectors.toCollection(ArrayList::new));
|
|
||||||
}
|
|
||||||
|
|
||||||
private String resolveHexColor(FilamentVariant variant) {
|
private String resolveHexColor(FilamentVariant variant) {
|
||||||
if (variant.getColorHex() != null && !variant.getColorHex().isBlank()) {
|
if (variant.getColorHex() != null && !variant.getColorHex().isBlank()) {
|
||||||
return variant.getColorHex();
|
return variant.getColorHex();
|
||||||
|
|||||||
@@ -1,62 +1,146 @@
|
|||||||
package com.printcalculator.controller;
|
package com.printcalculator.controller;
|
||||||
|
|
||||||
import com.printcalculator.dto.CreateOrderRequest;
|
import com.printcalculator.dto.*;
|
||||||
import com.printcalculator.dto.OrderDto;
|
import com.printcalculator.entity.*;
|
||||||
import com.printcalculator.service.order.OrderControllerService;
|
import com.printcalculator.repository.*;
|
||||||
import jakarta.validation.Valid;
|
import com.printcalculator.service.payment.InvoicePdfRenderingService;
|
||||||
|
import com.printcalculator.service.OrderService;
|
||||||
|
import com.printcalculator.service.payment.PaymentService;
|
||||||
|
import com.printcalculator.service.payment.QrBillService;
|
||||||
|
import com.printcalculator.service.storage.StorageService;
|
||||||
|
import com.printcalculator.service.payment.TwintPaymentService;
|
||||||
import org.springframework.http.MediaType;
|
import org.springframework.http.MediaType;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.*;
|
||||||
import org.springframework.web.bind.annotation.PathVariable;
|
|
||||||
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.RequestParam;
|
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
|
||||||
import org.springframework.web.multipart.MultipartFile;
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.Map;
|
|
||||||
|
import java.nio.file.InvalidPathException;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/api/orders")
|
@RequestMapping("/api/orders")
|
||||||
public class OrderController {
|
public class OrderController {
|
||||||
|
private static final Pattern SAFE_EXTENSION_PATTERN = Pattern.compile("^[a-z0-9]{1,10}$");
|
||||||
|
private static final Set<String> PERSONAL_DATA_REDACTED_STATUSES = Set.of(
|
||||||
|
"IN_PRODUCTION",
|
||||||
|
"SHIPPED",
|
||||||
|
"COMPLETED"
|
||||||
|
);
|
||||||
|
|
||||||
private final OrderControllerService orderControllerService;
|
private final OrderService orderService;
|
||||||
|
private final OrderRepository orderRepo;
|
||||||
|
private final OrderItemRepository orderItemRepo;
|
||||||
|
private final QuoteSessionRepository quoteSessionRepo;
|
||||||
|
private final QuoteLineItemRepository quoteLineItemRepo;
|
||||||
|
private final CustomerRepository customerRepo;
|
||||||
|
private final StorageService storageService;
|
||||||
|
private final InvoicePdfRenderingService invoiceService;
|
||||||
|
private final QrBillService qrBillService;
|
||||||
|
private final TwintPaymentService twintPaymentService;
|
||||||
|
private final PaymentService paymentService;
|
||||||
|
private final PaymentRepository paymentRepo;
|
||||||
|
|
||||||
public OrderController(OrderControllerService orderControllerService) {
|
|
||||||
this.orderControllerService = orderControllerService;
|
public OrderController(OrderService orderService,
|
||||||
|
OrderRepository orderRepo,
|
||||||
|
OrderItemRepository orderItemRepo,
|
||||||
|
QuoteSessionRepository quoteSessionRepo,
|
||||||
|
QuoteLineItemRepository quoteLineItemRepo,
|
||||||
|
CustomerRepository customerRepo,
|
||||||
|
StorageService storageService,
|
||||||
|
InvoicePdfRenderingService invoiceService,
|
||||||
|
QrBillService qrBillService,
|
||||||
|
TwintPaymentService twintPaymentService,
|
||||||
|
PaymentService paymentService,
|
||||||
|
PaymentRepository paymentRepo) {
|
||||||
|
this.orderService = orderService;
|
||||||
|
this.orderRepo = orderRepo;
|
||||||
|
this.orderItemRepo = orderItemRepo;
|
||||||
|
this.quoteSessionRepo = quoteSessionRepo;
|
||||||
|
this.quoteLineItemRepo = quoteLineItemRepo;
|
||||||
|
this.customerRepo = customerRepo;
|
||||||
|
this.storageService = storageService;
|
||||||
|
this.invoiceService = invoiceService;
|
||||||
|
this.qrBillService = qrBillService;
|
||||||
|
this.twintPaymentService = twintPaymentService;
|
||||||
|
this.paymentService = paymentService;
|
||||||
|
this.paymentRepo = paymentRepo;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// 1. Create Order from Quote
|
||||||
@PostMapping("/from-quote/{quoteSessionId}")
|
@PostMapping("/from-quote/{quoteSessionId}")
|
||||||
@Transactional
|
@Transactional
|
||||||
public ResponseEntity<OrderDto> createOrderFromQuote(
|
public ResponseEntity<OrderDto> createOrderFromQuote(
|
||||||
@PathVariable UUID quoteSessionId,
|
@PathVariable UUID quoteSessionId,
|
||||||
@Valid @RequestBody CreateOrderRequest request
|
@Valid @RequestBody com.printcalculator.dto.CreateOrderRequest request
|
||||||
) {
|
) {
|
||||||
return ResponseEntity.ok(orderControllerService.createOrderFromQuote(quoteSessionId, request));
|
Order order = orderService.createOrderFromQuote(quoteSessionId, request);
|
||||||
|
List<OrderItem> items = orderItemRepo.findByOrder_Id(order.getId());
|
||||||
|
return ResponseEntity.ok(convertToDto(order, items));
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping(value = "/{orderId}/items/{orderItemId}/file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
@PostMapping(value = "/{orderId}/items/{orderItemId}/file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||||
@Transactional
|
@Transactional
|
||||||
public ResponseEntity<Void> uploadOrderItemFile(
|
public ResponseEntity<Void> uploadOrderItemFile(
|
||||||
@PathVariable UUID orderId,
|
@PathVariable UUID orderId,
|
||||||
@PathVariable UUID orderItemId,
|
@PathVariable UUID orderItemId,
|
||||||
@RequestParam("file") MultipartFile file
|
@RequestParam("file") MultipartFile file
|
||||||
) throws IOException {
|
) throws IOException {
|
||||||
boolean uploaded = orderControllerService.uploadOrderItemFile(orderId, orderItemId, file);
|
|
||||||
if (!uploaded) {
|
OrderItem item = orderItemRepo.findById(orderItemId)
|
||||||
|
.orElseThrow(() -> new RuntimeException("OrderItem not found"));
|
||||||
|
|
||||||
|
if (!item.getOrder().getId().equals(orderId)) {
|
||||||
return ResponseEntity.badRequest().build();
|
return ResponseEntity.badRequest().build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
String relativePath = item.getStoredRelativePath();
|
||||||
|
Path destinationRelativePath;
|
||||||
|
if (relativePath == null || relativePath.equals("PENDING")) {
|
||||||
|
String ext = getExtension(file.getOriginalFilename());
|
||||||
|
String storedFilename = UUID.randomUUID() + "." + ext;
|
||||||
|
destinationRelativePath = Path.of("orders", orderId.toString(), "3d-files", orderItemId.toString(), storedFilename);
|
||||||
|
item.setStoredRelativePath(destinationRelativePath.toString());
|
||||||
|
item.setStoredFilename(storedFilename);
|
||||||
|
} else {
|
||||||
|
destinationRelativePath = resolveOrderItemRelativePath(relativePath, orderId, orderItemId);
|
||||||
|
if (destinationRelativePath == null) {
|
||||||
|
return ResponseEntity.badRequest().build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
storageService.store(file, destinationRelativePath);
|
||||||
|
item.setFileSizeBytes(file.getSize());
|
||||||
|
item.setMimeType(file.getContentType());
|
||||||
|
orderItemRepo.save(item);
|
||||||
|
|
||||||
return ResponseEntity.ok().build();
|
return ResponseEntity.ok().build();
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/{orderId}")
|
@GetMapping("/{orderId}")
|
||||||
public ResponseEntity<OrderDto> getOrder(@PathVariable UUID orderId) {
|
public ResponseEntity<OrderDto> getOrder(@PathVariable UUID orderId) {
|
||||||
return orderControllerService.getOrder(orderId)
|
return orderRepo.findById(orderId)
|
||||||
.map(ResponseEntity::ok)
|
.map(o -> {
|
||||||
|
List<OrderItem> items = orderItemRepo.findByOrder_Id(o.getId());
|
||||||
|
return ResponseEntity.ok(convertToDto(o, items));
|
||||||
|
})
|
||||||
.orElse(ResponseEntity.notFound().build());
|
.orElse(ResponseEntity.notFound().build());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,29 +150,89 @@ public class OrderController {
|
|||||||
@PathVariable UUID orderId,
|
@PathVariable UUID orderId,
|
||||||
@RequestBody Map<String, String> payload
|
@RequestBody Map<String, String> payload
|
||||||
) {
|
) {
|
||||||
return orderControllerService.reportPayment(orderId, payload.get("method"))
|
String method = payload.get("method");
|
||||||
.map(ResponseEntity::ok)
|
paymentService.reportPayment(orderId, method);
|
||||||
.orElse(ResponseEntity.notFound().build());
|
return getOrder(orderId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/{orderId}/confirmation")
|
@GetMapping("/{orderId}/confirmation")
|
||||||
public ResponseEntity<byte[]> getConfirmation(@PathVariable UUID orderId) {
|
public ResponseEntity<byte[]> getConfirmation(@PathVariable UUID orderId) {
|
||||||
return orderControllerService.getConfirmation(orderId);
|
return generateDocument(orderId, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/{orderId}/invoice")
|
@GetMapping("/{orderId}/invoice")
|
||||||
public ResponseEntity<byte[]> getInvoice(@PathVariable UUID orderId) {
|
public ResponseEntity<byte[]> getInvoice(@PathVariable UUID orderId) {
|
||||||
|
// Paid invoices are sent by email after back-office payment confirmation.
|
||||||
|
// The public endpoint must not expose a "paid" invoice download.
|
||||||
return ResponseEntity.notFound().build();
|
return ResponseEntity.notFound().build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private ResponseEntity<byte[]> generateDocument(UUID orderId, boolean isConfirmation) {
|
||||||
|
Order order = orderRepo.findById(orderId)
|
||||||
|
.orElseThrow(() -> new RuntimeException("Order not found"));
|
||||||
|
|
||||||
|
if (isConfirmation) {
|
||||||
|
Path relativePath = buildConfirmationPdfRelativePath(order);
|
||||||
|
try {
|
||||||
|
byte[] existingPdf = storageService.loadAsResource(relativePath).getInputStream().readAllBytes();
|
||||||
|
return ResponseEntity.ok()
|
||||||
|
.header("Content-Disposition", "attachment; filename=\"confirmation-" + getDisplayOrderNumber(order) + ".pdf\"")
|
||||||
|
.contentType(MediaType.APPLICATION_PDF)
|
||||||
|
.body(existingPdf);
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
// Fallback to on-the-fly generation if the stored file is missing or unreadable.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
List<OrderItem> items = orderItemRepo.findByOrder_Id(orderId);
|
||||||
|
Payment payment = paymentRepo.findByOrder_Id(orderId).orElse(null);
|
||||||
|
|
||||||
|
byte[] pdf = invoiceService.generateDocumentPdf(order, items, isConfirmation, qrBillService, payment);
|
||||||
|
String typePrefix = isConfirmation ? "confirmation-" : "invoice-";
|
||||||
|
String truncatedUuid = order.getId().toString().substring(0, 8);
|
||||||
|
return ResponseEntity.ok()
|
||||||
|
.header("Content-Disposition", "attachment; filename=\"" + typePrefix + truncatedUuid + ".pdf\"")
|
||||||
|
.contentType(MediaType.APPLICATION_PDF)
|
||||||
|
.body(pdf);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Path buildConfirmationPdfRelativePath(Order order) {
|
||||||
|
return Path.of(
|
||||||
|
"orders",
|
||||||
|
order.getId().toString(),
|
||||||
|
"documents",
|
||||||
|
"confirmation-" + getDisplayOrderNumber(order) + ".pdf"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@GetMapping("/{orderId}/twint")
|
@GetMapping("/{orderId}/twint")
|
||||||
public ResponseEntity<Map<String, String>> getTwintPayment(@PathVariable UUID orderId) {
|
public ResponseEntity<Map<String, String>> getTwintPayment(@PathVariable UUID orderId) {
|
||||||
return orderControllerService.getTwintPayment(orderId);
|
Order order = orderRepo.findById(orderId).orElse(null);
|
||||||
|
if (order == null) {
|
||||||
|
return ResponseEntity.notFound().build();
|
||||||
|
}
|
||||||
|
|
||||||
|
byte[] qrPng = twintPaymentService.generateQrPng(order, 360);
|
||||||
|
String qrDataUri = "data:image/png;base64," + Base64.getEncoder().encodeToString(qrPng);
|
||||||
|
|
||||||
|
Map<String, String> data = new HashMap<>();
|
||||||
|
data.put("paymentUrl", twintPaymentService.getTwintPaymentUrl(order));
|
||||||
|
data.put("openUrl", "/api/orders/" + orderId + "/twint/open");
|
||||||
|
data.put("qrImageUrl", "/api/orders/" + orderId + "/twint/qr");
|
||||||
|
data.put("qrImageDataUri", qrDataUri);
|
||||||
|
return ResponseEntity.ok(data);
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/{orderId}/twint/open")
|
@GetMapping("/{orderId}/twint/open")
|
||||||
public ResponseEntity<Void> openTwintPayment(@PathVariable UUID orderId) {
|
public ResponseEntity<Void> openTwintPayment(@PathVariable UUID orderId) {
|
||||||
return orderControllerService.openTwintPayment(orderId);
|
Order order = orderRepo.findById(orderId).orElse(null);
|
||||||
|
if (order == null) {
|
||||||
|
return ResponseEntity.notFound().build();
|
||||||
|
}
|
||||||
|
|
||||||
|
return ResponseEntity.status(302)
|
||||||
|
.location(URI.create(twintPaymentService.getTwintPaymentUrl(order)))
|
||||||
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/{orderId}/twint/qr")
|
@GetMapping("/{orderId}/twint/qr")
|
||||||
@@ -96,6 +240,150 @@ public class OrderController {
|
|||||||
@PathVariable UUID orderId,
|
@PathVariable UUID orderId,
|
||||||
@RequestParam(defaultValue = "320") int size
|
@RequestParam(defaultValue = "320") int size
|
||||||
) {
|
) {
|
||||||
return orderControllerService.getTwintQr(orderId, size);
|
Order order = orderRepo.findById(orderId).orElse(null);
|
||||||
|
if (order == null) {
|
||||||
|
return ResponseEntity.notFound().build();
|
||||||
|
}
|
||||||
|
|
||||||
|
int normalizedSize = Math.max(200, Math.min(size, 600));
|
||||||
|
byte[] png = twintPaymentService.generateQrPng(order, normalizedSize);
|
||||||
|
|
||||||
|
return ResponseEntity.ok()
|
||||||
|
.contentType(MediaType.IMAGE_PNG)
|
||||||
|
.body(png);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private String getExtension(String filename) {
|
||||||
|
if (filename == null) return "stl";
|
||||||
|
String cleaned = StringUtils.cleanPath(filename);
|
||||||
|
if (cleaned.contains("..")) {
|
||||||
|
return "stl";
|
||||||
|
}
|
||||||
|
int i = cleaned.lastIndexOf('.');
|
||||||
|
if (i > 0 && i < cleaned.length() - 1) {
|
||||||
|
String ext = cleaned.substring(i + 1).toLowerCase(Locale.ROOT);
|
||||||
|
if (SAFE_EXTENSION_PATTERN.matcher(ext).matches()) {
|
||||||
|
return ext;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "stl";
|
||||||
|
}
|
||||||
|
|
||||||
|
private Path resolveOrderItemRelativePath(String storedRelativePath, UUID orderId, UUID orderItemId) {
|
||||||
|
try {
|
||||||
|
Path candidate = Path.of(storedRelativePath).normalize();
|
||||||
|
if (candidate.isAbsolute()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
Path expectedPrefix = Path.of("orders", orderId.toString(), "3d-files", orderItemId.toString());
|
||||||
|
if (!candidate.startsWith(expectedPrefix)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return candidate;
|
||||||
|
} catch (InvalidPathException e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private OrderDto convertToDto(Order order, List<OrderItem> items) {
|
||||||
|
OrderDto dto = new OrderDto();
|
||||||
|
dto.setId(order.getId());
|
||||||
|
dto.setOrderNumber(getDisplayOrderNumber(order));
|
||||||
|
dto.setStatus(order.getStatus());
|
||||||
|
|
||||||
|
paymentRepo.findByOrder_Id(order.getId()).ifPresent(p -> {
|
||||||
|
dto.setPaymentStatus(p.getStatus());
|
||||||
|
dto.setPaymentMethod(p.getMethod());
|
||||||
|
});
|
||||||
|
|
||||||
|
boolean redactPersonalData = shouldRedactPersonalData(order.getStatus());
|
||||||
|
if (!redactPersonalData) {
|
||||||
|
dto.setCustomerEmail(order.getCustomerEmail());
|
||||||
|
dto.setCustomerPhone(order.getCustomerPhone());
|
||||||
|
dto.setBillingCustomerType(order.getBillingCustomerType());
|
||||||
|
}
|
||||||
|
dto.setPreferredLanguage(order.getPreferredLanguage());
|
||||||
|
dto.setCurrency(order.getCurrency());
|
||||||
|
dto.setSetupCostChf(order.getSetupCostChf());
|
||||||
|
dto.setShippingCostChf(order.getShippingCostChf());
|
||||||
|
dto.setDiscountChf(order.getDiscountChf());
|
||||||
|
dto.setSubtotalChf(order.getSubtotalChf());
|
||||||
|
dto.setIsCadOrder(order.getIsCadOrder());
|
||||||
|
dto.setSourceRequestId(order.getSourceRequestId());
|
||||||
|
dto.setCadHours(order.getCadHours());
|
||||||
|
dto.setCadHourlyRateChf(order.getCadHourlyRateChf());
|
||||||
|
dto.setCadTotalChf(order.getCadTotalChf());
|
||||||
|
dto.setTotalChf(order.getTotalChf());
|
||||||
|
dto.setCreatedAt(order.getCreatedAt());
|
||||||
|
dto.setShippingSameAsBilling(order.getShippingSameAsBilling());
|
||||||
|
|
||||||
|
if (!redactPersonalData) {
|
||||||
|
AddressDto billing = new AddressDto();
|
||||||
|
billing.setFirstName(order.getBillingFirstName());
|
||||||
|
billing.setLastName(order.getBillingLastName());
|
||||||
|
billing.setCompanyName(order.getBillingCompanyName());
|
||||||
|
billing.setContactPerson(order.getBillingContactPerson());
|
||||||
|
billing.setAddressLine1(order.getBillingAddressLine1());
|
||||||
|
billing.setAddressLine2(order.getBillingAddressLine2());
|
||||||
|
billing.setZip(order.getBillingZip());
|
||||||
|
billing.setCity(order.getBillingCity());
|
||||||
|
billing.setCountryCode(order.getBillingCountryCode());
|
||||||
|
dto.setBillingAddress(billing);
|
||||||
|
|
||||||
|
if (!order.getShippingSameAsBilling()) {
|
||||||
|
AddressDto shipping = new AddressDto();
|
||||||
|
shipping.setFirstName(order.getShippingFirstName());
|
||||||
|
shipping.setLastName(order.getShippingLastName());
|
||||||
|
shipping.setCompanyName(order.getShippingCompanyName());
|
||||||
|
shipping.setContactPerson(order.getShippingContactPerson());
|
||||||
|
shipping.setAddressLine1(order.getShippingAddressLine1());
|
||||||
|
shipping.setAddressLine2(order.getShippingAddressLine2());
|
||||||
|
shipping.setZip(order.getShippingZip());
|
||||||
|
shipping.setCity(order.getShippingCity());
|
||||||
|
shipping.setCountryCode(order.getShippingCountryCode());
|
||||||
|
dto.setShippingAddress(shipping);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
List<OrderItemDto> itemDtos = items.stream().map(i -> {
|
||||||
|
OrderItemDto idto = new OrderItemDto();
|
||||||
|
idto.setId(i.getId());
|
||||||
|
idto.setOriginalFilename(i.getOriginalFilename());
|
||||||
|
idto.setMaterialCode(i.getMaterialCode());
|
||||||
|
idto.setColorCode(i.getColorCode());
|
||||||
|
idto.setQuality(i.getQuality());
|
||||||
|
idto.setNozzleDiameterMm(i.getNozzleDiameterMm());
|
||||||
|
idto.setLayerHeightMm(i.getLayerHeightMm());
|
||||||
|
idto.setInfillPercent(i.getInfillPercent());
|
||||||
|
idto.setInfillPattern(i.getInfillPattern());
|
||||||
|
idto.setSupportsEnabled(i.getSupportsEnabled());
|
||||||
|
idto.setQuantity(i.getQuantity());
|
||||||
|
idto.setPrintTimeSeconds(i.getPrintTimeSeconds());
|
||||||
|
idto.setMaterialGrams(i.getMaterialGrams());
|
||||||
|
idto.setUnitPriceChf(i.getUnitPriceChf());
|
||||||
|
idto.setLineTotalChf(i.getLineTotalChf());
|
||||||
|
return idto;
|
||||||
|
}).collect(Collectors.toList());
|
||||||
|
dto.setItems(itemDtos);
|
||||||
|
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean shouldRedactPersonalData(String status) {
|
||||||
|
if (status == null || status.isBlank()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return PERSONAL_DATA_REDACTED_STATUSES.contains(status.trim().toUpperCase(Locale.ROOT));
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getDisplayOrderNumber(Order order) {
|
||||||
|
String orderNumber = order.getOrderNumber();
|
||||||
|
if (orderNumber != null && !orderNumber.isBlank()) {
|
||||||
|
return orderNumber;
|
||||||
|
}
|
||||||
|
return order.getId() != null ? order.getId().toString() : "unknown";
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,31 +0,0 @@
|
|||||||
package com.printcalculator.controller;
|
|
||||||
|
|
||||||
import com.printcalculator.dto.PublicMediaUsageDto;
|
|
||||||
import com.printcalculator.service.media.PublicMediaQueryService;
|
|
||||||
import org.springframework.http.ResponseEntity;
|
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
|
||||||
import org.springframework.web.bind.annotation.RequestParam;
|
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
@RestController
|
|
||||||
@RequestMapping("/api/public/media")
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public class PublicMediaController {
|
|
||||||
|
|
||||||
private final PublicMediaQueryService publicMediaQueryService;
|
|
||||||
|
|
||||||
public PublicMediaController(PublicMediaQueryService publicMediaQueryService) {
|
|
||||||
this.publicMediaQueryService = publicMediaQueryService;
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping("/usages")
|
|
||||||
public ResponseEntity<List<PublicMediaUsageDto>> getUsageMedia(@RequestParam String usageType,
|
|
||||||
@RequestParam String usageKey,
|
|
||||||
@RequestParam(required = false) String lang) {
|
|
||||||
return ResponseEntity.ok(publicMediaQueryService.getUsageMedia(usageType, usageKey, lang));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,77 +0,0 @@
|
|||||||
package com.printcalculator.controller;
|
|
||||||
|
|
||||||
import com.printcalculator.dto.ShopCategoryDetailDto;
|
|
||||||
import com.printcalculator.dto.ShopCategoryTreeDto;
|
|
||||||
import com.printcalculator.dto.ShopProductCatalogResponseDto;
|
|
||||||
import com.printcalculator.dto.ShopProductDetailDto;
|
|
||||||
import com.printcalculator.service.shop.PublicShopCatalogService;
|
|
||||||
import org.springframework.core.io.Resource;
|
|
||||||
import org.springframework.core.io.UrlResource;
|
|
||||||
import org.springframework.http.HttpHeaders;
|
|
||||||
import org.springframework.http.MediaType;
|
|
||||||
import org.springframework.http.ResponseEntity;
|
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
|
||||||
import org.springframework.web.bind.annotation.PathVariable;
|
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
|
||||||
import org.springframework.web.bind.annotation.RequestParam;
|
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
@RestController
|
|
||||||
@RequestMapping("/api/shop")
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public class PublicShopController {
|
|
||||||
private final PublicShopCatalogService publicShopCatalogService;
|
|
||||||
|
|
||||||
public PublicShopController(PublicShopCatalogService publicShopCatalogService) {
|
|
||||||
this.publicShopCatalogService = publicShopCatalogService;
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping("/categories")
|
|
||||||
public ResponseEntity<List<ShopCategoryTreeDto>> getCategories(@RequestParam(required = false) String lang) {
|
|
||||||
return ResponseEntity.ok(publicShopCatalogService.getCategories(lang));
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping("/categories/{slug}")
|
|
||||||
public ResponseEntity<ShopCategoryDetailDto> getCategory(@PathVariable String slug,
|
|
||||||
@RequestParam(required = false) String lang) {
|
|
||||||
return ResponseEntity.ok(publicShopCatalogService.getCategory(slug, lang));
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping("/products")
|
|
||||||
public ResponseEntity<ShopProductCatalogResponseDto> getProducts(
|
|
||||||
@RequestParam(required = false) String categorySlug,
|
|
||||||
@RequestParam(required = false) Boolean featured,
|
|
||||||
@RequestParam(required = false) String lang
|
|
||||||
) {
|
|
||||||
return ResponseEntity.ok(publicShopCatalogService.getProductCatalog(categorySlug, featured, lang));
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping("/products/{slug}")
|
|
||||||
public ResponseEntity<ShopProductDetailDto> getProduct(@PathVariable String slug,
|
|
||||||
@RequestParam(required = false) String lang) {
|
|
||||||
return ResponseEntity.ok(publicShopCatalogService.getProduct(slug, lang));
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping("/products/{slug}/model")
|
|
||||||
public ResponseEntity<Resource> getProductModel(@PathVariable String slug) throws IOException {
|
|
||||||
PublicShopCatalogService.ProductModelDownload model = publicShopCatalogService.getProductModelDownload(slug);
|
|
||||||
Resource resource = new UrlResource(model.path().toUri());
|
|
||||||
MediaType contentType = MediaType.APPLICATION_OCTET_STREAM;
|
|
||||||
if (model.mimeType() != null && !model.mimeType().isBlank()) {
|
|
||||||
try {
|
|
||||||
contentType = MediaType.parseMediaType(model.mimeType());
|
|
||||||
} catch (IllegalArgumentException ignored) {
|
|
||||||
contentType = MediaType.APPLICATION_OCTET_STREAM;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return ResponseEntity.ok()
|
|
||||||
.contentType(contentType)
|
|
||||||
.header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + model.filename() + "\"")
|
|
||||||
.body(resource);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -18,7 +18,6 @@ import java.math.BigDecimal;
|
|||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Locale;
|
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
import static org.springframework.http.HttpStatus.BAD_REQUEST;
|
import static org.springframework.http.HttpStatus.BAD_REQUEST;
|
||||||
@@ -125,9 +124,6 @@ public class QuoteController {
|
|||||||
if (file.isEmpty()) {
|
if (file.isEmpty()) {
|
||||||
return ResponseEntity.badRequest().build();
|
return ResponseEntity.badRequest().build();
|
||||||
}
|
}
|
||||||
if (!isSupportedInputFile(file)) {
|
|
||||||
throw new ResponseStatusException(BAD_REQUEST, "Unsupported file type. Allowed: stl, 3mf");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Scan for virus
|
// Scan for virus
|
||||||
clamAVService.scan(file.getInputStream());
|
clamAVService.scan(file.getInputStream());
|
||||||
@@ -157,14 +153,4 @@ public class QuoteController {
|
|||||||
Files.deleteIfExists(tempInput);
|
Files.deleteIfExists(tempInput);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean isSupportedInputFile(MultipartFile file) {
|
|
||||||
String originalFilename = file.getOriginalFilename();
|
|
||||||
if (originalFilename == null || originalFilename.isBlank()) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
String normalized = originalFilename.toLowerCase(Locale.ROOT);
|
|
||||||
return normalized.endsWith(".stl") || normalized.endsWith(".3mf");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -62,7 +62,6 @@ public class QuoteSessionController {
|
|||||||
public ResponseEntity<QuoteSession> createSession() {
|
public ResponseEntity<QuoteSession> createSession() {
|
||||||
QuoteSession session = new QuoteSession();
|
QuoteSession session = new QuoteSession();
|
||||||
session.setStatus("ACTIVE");
|
session.setStatus("ACTIVE");
|
||||||
session.setSessionType("PRINT_QUOTE");
|
|
||||||
session.setPricingVersion("v1");
|
session.setPricingVersion("v1");
|
||||||
session.setMaterialCode("PLA");
|
session.setMaterialCode("PLA");
|
||||||
session.setSupportsEnabled(false);
|
session.setSupportsEnabled(false);
|
||||||
@@ -130,7 +129,6 @@ public class QuoteSessionController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/{id}")
|
@GetMapping("/{id}")
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public ResponseEntity<Map<String, Object>> getQuoteSession(@PathVariable UUID id) {
|
public ResponseEntity<Map<String, Object>> getQuoteSession(@PathVariable UUID id) {
|
||||||
QuoteSession session = sessionRepo.findById(id)
|
QuoteSession session = sessionRepo.findById(id)
|
||||||
.orElseThrow(() -> new RuntimeException("Session not found"));
|
.orElseThrow(() -> new RuntimeException("Session not found"));
|
||||||
|
|||||||
@@ -1,85 +0,0 @@
|
|||||||
package com.printcalculator.controller;
|
|
||||||
|
|
||||||
import com.printcalculator.dto.ShopCartAddItemRequest;
|
|
||||||
import com.printcalculator.dto.ShopCartUpdateItemRequest;
|
|
||||||
import com.printcalculator.service.shop.ShopCartCookieService;
|
|
||||||
import com.printcalculator.service.shop.ShopCartService;
|
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
|
||||||
import jakarta.servlet.http.HttpServletResponse;
|
|
||||||
import jakarta.validation.Valid;
|
|
||||||
import org.springframework.http.HttpHeaders;
|
|
||||||
import org.springframework.http.ResponseEntity;
|
|
||||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
|
||||||
import org.springframework.web.bind.annotation.PatchMapping;
|
|
||||||
import org.springframework.web.bind.annotation.PathVariable;
|
|
||||||
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;
|
|
||||||
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
@RestController
|
|
||||||
@RequestMapping("/api/shop/cart")
|
|
||||||
public class ShopCartController {
|
|
||||||
private final ShopCartService shopCartService;
|
|
||||||
private final ShopCartCookieService shopCartCookieService;
|
|
||||||
|
|
||||||
public ShopCartController(ShopCartService shopCartService, ShopCartCookieService shopCartCookieService) {
|
|
||||||
this.shopCartService = shopCartService;
|
|
||||||
this.shopCartCookieService = shopCartCookieService;
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping
|
|
||||||
public ResponseEntity<?> getCart(HttpServletRequest request, HttpServletResponse response) {
|
|
||||||
ShopCartService.CartResult result = shopCartService.loadCart(request);
|
|
||||||
applyCookie(response, result);
|
|
||||||
return ResponseEntity.ok(result.response());
|
|
||||||
}
|
|
||||||
|
|
||||||
@PostMapping("/items")
|
|
||||||
public ResponseEntity<?> addItem(HttpServletRequest request,
|
|
||||||
HttpServletResponse response,
|
|
||||||
@Valid @RequestBody ShopCartAddItemRequest payload) {
|
|
||||||
ShopCartService.CartResult result = shopCartService.addItem(request, payload);
|
|
||||||
applyCookie(response, result);
|
|
||||||
return ResponseEntity.ok(result.response());
|
|
||||||
}
|
|
||||||
|
|
||||||
@PatchMapping("/items/{lineItemId}")
|
|
||||||
public ResponseEntity<?> updateItem(HttpServletRequest request,
|
|
||||||
HttpServletResponse response,
|
|
||||||
@PathVariable UUID lineItemId,
|
|
||||||
@Valid @RequestBody ShopCartUpdateItemRequest payload) {
|
|
||||||
ShopCartService.CartResult result = shopCartService.updateItem(request, lineItemId, payload);
|
|
||||||
applyCookie(response, result);
|
|
||||||
return ResponseEntity.ok(result.response());
|
|
||||||
}
|
|
||||||
|
|
||||||
@DeleteMapping("/items/{lineItemId}")
|
|
||||||
public ResponseEntity<?> removeItem(HttpServletRequest request,
|
|
||||||
HttpServletResponse response,
|
|
||||||
@PathVariable UUID lineItemId) {
|
|
||||||
ShopCartService.CartResult result = shopCartService.removeItem(request, lineItemId);
|
|
||||||
applyCookie(response, result);
|
|
||||||
return ResponseEntity.ok(result.response());
|
|
||||||
}
|
|
||||||
|
|
||||||
@DeleteMapping
|
|
||||||
public ResponseEntity<?> clearCart(HttpServletRequest request, HttpServletResponse response) {
|
|
||||||
ShopCartService.CartResult result = shopCartService.clearCart(request);
|
|
||||||
applyCookie(response, result);
|
|
||||||
return ResponseEntity.ok(result.response());
|
|
||||||
}
|
|
||||||
|
|
||||||
private void applyCookie(HttpServletResponse response, ShopCartService.CartResult result) {
|
|
||||||
if (result.clearCookie()) {
|
|
||||||
response.addHeader(HttpHeaders.SET_COOKIE, shopCartCookieService.buildClearCookie().toString());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (result.sessionId() != null) {
|
|
||||||
response.addHeader(HttpHeaders.SET_COOKIE, shopCartCookieService.buildSessionCookie(result.sessionId()).toString());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
package com.printcalculator.controller;
|
|
||||||
|
|
||||||
import com.printcalculator.service.shop.ShopSitemapService;
|
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
|
||||||
import org.springframework.http.CacheControl;
|
|
||||||
import org.springframework.http.MediaType;
|
|
||||||
import org.springframework.http.ResponseEntity;
|
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
|
||||||
|
|
||||||
import java.time.Duration;
|
|
||||||
|
|
||||||
@RestController
|
|
||||||
public class SitemapController {
|
|
||||||
private final ShopSitemapService shopSitemapService;
|
|
||||||
private final long cacheSeconds;
|
|
||||||
|
|
||||||
public SitemapController(
|
|
||||||
ShopSitemapService shopSitemapService,
|
|
||||||
@Value("${app.sitemap.shop.cache-seconds:3600}") long cacheSeconds
|
|
||||||
) {
|
|
||||||
this.shopSitemapService = shopSitemapService;
|
|
||||||
this.cacheSeconds = Math.max(cacheSeconds, 0L);
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping(value = "/api/sitemap-shop.xml", produces = MediaType.APPLICATION_XML_VALUE)
|
|
||||||
public ResponseEntity<String> getShopSitemap() {
|
|
||||||
CacheControl cacheControl = cacheSeconds > 0
|
|
||||||
? CacheControl.maxAge(Duration.ofSeconds(cacheSeconds)).cachePublic()
|
|
||||||
: CacheControl.noCache();
|
|
||||||
|
|
||||||
return ResponseEntity.ok()
|
|
||||||
.contentType(MediaType.parseMediaType("application/xml;charset=UTF-8"))
|
|
||||||
.cacheControl(cacheControl)
|
|
||||||
.body(shopSitemapService.getShopSitemapXml());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -4,39 +4,77 @@ import com.printcalculator.dto.AdminFilamentMaterialTypeDto;
|
|||||||
import com.printcalculator.dto.AdminFilamentVariantDto;
|
import com.printcalculator.dto.AdminFilamentVariantDto;
|
||||||
import com.printcalculator.dto.AdminUpsertFilamentMaterialTypeRequest;
|
import com.printcalculator.dto.AdminUpsertFilamentMaterialTypeRequest;
|
||||||
import com.printcalculator.dto.AdminUpsertFilamentVariantRequest;
|
import com.printcalculator.dto.AdminUpsertFilamentVariantRequest;
|
||||||
import com.printcalculator.service.admin.AdminFilamentControllerService;
|
import com.printcalculator.entity.FilamentMaterialType;
|
||||||
|
import com.printcalculator.entity.FilamentVariant;
|
||||||
|
import com.printcalculator.repository.FilamentMaterialTypeRepository;
|
||||||
|
import com.printcalculator.repository.FilamentVariantRepository;
|
||||||
|
import com.printcalculator.repository.OrderItemRepository;
|
||||||
|
import com.printcalculator.repository.QuoteLineItemRepository;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
import org.springframework.web.bind.annotation.*;
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
import org.springframework.web.bind.annotation.PathVariable;
|
|
||||||
import org.springframework.web.bind.annotation.PostMapping;
|
|
||||||
import org.springframework.web.bind.annotation.PutMapping;
|
|
||||||
import org.springframework.web.bind.annotation.RequestBody;
|
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.time.OffsetDateTime;
|
||||||
|
import java.util.Comparator;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
import static org.springframework.http.HttpStatus.BAD_REQUEST;
|
||||||
|
import static org.springframework.http.HttpStatus.CONFLICT;
|
||||||
|
import static org.springframework.http.HttpStatus.NOT_FOUND;
|
||||||
|
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/api/admin/filaments")
|
@RequestMapping("/api/admin/filaments")
|
||||||
@Transactional(readOnly = true)
|
@Transactional(readOnly = true)
|
||||||
public class AdminFilamentController {
|
public class AdminFilamentController {
|
||||||
|
private static final BigDecimal MAX_NUMERIC_6_3 = new BigDecimal("999.999");
|
||||||
|
private static final Pattern HEX_COLOR_PATTERN = Pattern.compile("^#[0-9A-Fa-f]{6}$");
|
||||||
|
private static final Set<String> ALLOWED_FINISH_TYPES = Set.of(
|
||||||
|
"GLOSSY", "MATTE", "MARBLE", "SILK", "TRANSLUCENT", "SPECIAL"
|
||||||
|
);
|
||||||
|
|
||||||
private final AdminFilamentControllerService adminFilamentControllerService;
|
private final FilamentMaterialTypeRepository materialRepo;
|
||||||
|
private final FilamentVariantRepository variantRepo;
|
||||||
|
private final QuoteLineItemRepository quoteLineItemRepo;
|
||||||
|
private final OrderItemRepository orderItemRepo;
|
||||||
|
|
||||||
public AdminFilamentController(AdminFilamentControllerService adminFilamentControllerService) {
|
public AdminFilamentController(
|
||||||
this.adminFilamentControllerService = adminFilamentControllerService;
|
FilamentMaterialTypeRepository materialRepo,
|
||||||
|
FilamentVariantRepository variantRepo,
|
||||||
|
QuoteLineItemRepository quoteLineItemRepo,
|
||||||
|
OrderItemRepository orderItemRepo
|
||||||
|
) {
|
||||||
|
this.materialRepo = materialRepo;
|
||||||
|
this.variantRepo = variantRepo;
|
||||||
|
this.quoteLineItemRepo = quoteLineItemRepo;
|
||||||
|
this.orderItemRepo = orderItemRepo;
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/materials")
|
@GetMapping("/materials")
|
||||||
public ResponseEntity<List<AdminFilamentMaterialTypeDto>> getMaterials() {
|
public ResponseEntity<List<AdminFilamentMaterialTypeDto>> getMaterials() {
|
||||||
return ResponseEntity.ok(adminFilamentControllerService.getMaterials());
|
List<AdminFilamentMaterialTypeDto> response = materialRepo.findAll().stream()
|
||||||
|
.sorted(Comparator.comparing(FilamentMaterialType::getMaterialCode, String.CASE_INSENSITIVE_ORDER))
|
||||||
|
.map(this::toMaterialDto)
|
||||||
|
.toList();
|
||||||
|
return ResponseEntity.ok(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/variants")
|
@GetMapping("/variants")
|
||||||
public ResponseEntity<List<AdminFilamentVariantDto>> getVariants() {
|
public ResponseEntity<List<AdminFilamentVariantDto>> getVariants() {
|
||||||
return ResponseEntity.ok(adminFilamentControllerService.getVariants());
|
List<AdminFilamentVariantDto> response = variantRepo.findAll().stream()
|
||||||
|
.sorted(Comparator
|
||||||
|
.comparing((FilamentVariant v) -> {
|
||||||
|
FilamentMaterialType type = v.getFilamentMaterialType();
|
||||||
|
return type != null && type.getMaterialCode() != null ? type.getMaterialCode() : "";
|
||||||
|
}, String.CASE_INSENSITIVE_ORDER)
|
||||||
|
.thenComparing(v -> v.getVariantDisplayName() != null ? v.getVariantDisplayName() : "", String.CASE_INSENSITIVE_ORDER))
|
||||||
|
.map(this::toVariantDto)
|
||||||
|
.toList();
|
||||||
|
return ResponseEntity.ok(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/materials")
|
@PostMapping("/materials")
|
||||||
@@ -44,7 +82,13 @@ public class AdminFilamentController {
|
|||||||
public ResponseEntity<AdminFilamentMaterialTypeDto> createMaterial(
|
public ResponseEntity<AdminFilamentMaterialTypeDto> createMaterial(
|
||||||
@RequestBody AdminUpsertFilamentMaterialTypeRequest payload
|
@RequestBody AdminUpsertFilamentMaterialTypeRequest payload
|
||||||
) {
|
) {
|
||||||
return ResponseEntity.ok(adminFilamentControllerService.createMaterial(payload));
|
String materialCode = normalizeAndValidateMaterialCode(payload);
|
||||||
|
ensureMaterialCodeAvailable(materialCode, null);
|
||||||
|
|
||||||
|
FilamentMaterialType material = new FilamentMaterialType();
|
||||||
|
applyMaterialPayload(material, payload, materialCode);
|
||||||
|
FilamentMaterialType saved = materialRepo.save(material);
|
||||||
|
return ResponseEntity.ok(toMaterialDto(saved));
|
||||||
}
|
}
|
||||||
|
|
||||||
@PutMapping("/materials/{materialTypeId}")
|
@PutMapping("/materials/{materialTypeId}")
|
||||||
@@ -53,7 +97,15 @@ public class AdminFilamentController {
|
|||||||
@PathVariable Long materialTypeId,
|
@PathVariable Long materialTypeId,
|
||||||
@RequestBody AdminUpsertFilamentMaterialTypeRequest payload
|
@RequestBody AdminUpsertFilamentMaterialTypeRequest payload
|
||||||
) {
|
) {
|
||||||
return ResponseEntity.ok(adminFilamentControllerService.updateMaterial(materialTypeId, payload));
|
FilamentMaterialType material = materialRepo.findById(materialTypeId)
|
||||||
|
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "Filament material not found"));
|
||||||
|
|
||||||
|
String materialCode = normalizeAndValidateMaterialCode(payload);
|
||||||
|
ensureMaterialCodeAvailable(materialCode, materialTypeId);
|
||||||
|
|
||||||
|
applyMaterialPayload(material, payload, materialCode);
|
||||||
|
FilamentMaterialType saved = materialRepo.save(material);
|
||||||
|
return ResponseEntity.ok(toMaterialDto(saved));
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/variants")
|
@PostMapping("/variants")
|
||||||
@@ -61,7 +113,17 @@ public class AdminFilamentController {
|
|||||||
public ResponseEntity<AdminFilamentVariantDto> createVariant(
|
public ResponseEntity<AdminFilamentVariantDto> createVariant(
|
||||||
@RequestBody AdminUpsertFilamentVariantRequest payload
|
@RequestBody AdminUpsertFilamentVariantRequest payload
|
||||||
) {
|
) {
|
||||||
return ResponseEntity.ok(adminFilamentControllerService.createVariant(payload));
|
FilamentMaterialType material = validateAndResolveMaterial(payload);
|
||||||
|
String normalizedDisplayName = normalizeAndValidateVariantDisplayName(payload.getVariantDisplayName());
|
||||||
|
String normalizedColorName = normalizeAndValidateColorName(payload.getColorName());
|
||||||
|
validateNumericPayload(payload);
|
||||||
|
ensureVariantDisplayNameAvailable(material, normalizedDisplayName, null);
|
||||||
|
|
||||||
|
FilamentVariant variant = new FilamentVariant();
|
||||||
|
variant.setCreatedAt(OffsetDateTime.now());
|
||||||
|
applyVariantPayload(variant, payload, material, normalizedDisplayName, normalizedColorName);
|
||||||
|
FilamentVariant saved = variantRepo.save(variant);
|
||||||
|
return ResponseEntity.ok(toVariantDto(saved));
|
||||||
}
|
}
|
||||||
|
|
||||||
@PutMapping("/variants/{variantId}")
|
@PutMapping("/variants/{variantId}")
|
||||||
@@ -70,13 +132,224 @@ public class AdminFilamentController {
|
|||||||
@PathVariable Long variantId,
|
@PathVariable Long variantId,
|
||||||
@RequestBody AdminUpsertFilamentVariantRequest payload
|
@RequestBody AdminUpsertFilamentVariantRequest payload
|
||||||
) {
|
) {
|
||||||
return ResponseEntity.ok(adminFilamentControllerService.updateVariant(variantId, payload));
|
FilamentVariant variant = variantRepo.findById(variantId)
|
||||||
|
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "Filament variant not found"));
|
||||||
|
|
||||||
|
FilamentMaterialType material = validateAndResolveMaterial(payload);
|
||||||
|
String normalizedDisplayName = normalizeAndValidateVariantDisplayName(payload.getVariantDisplayName());
|
||||||
|
String normalizedColorName = normalizeAndValidateColorName(payload.getColorName());
|
||||||
|
validateNumericPayload(payload);
|
||||||
|
ensureVariantDisplayNameAvailable(material, normalizedDisplayName, variantId);
|
||||||
|
|
||||||
|
applyVariantPayload(variant, payload, material, normalizedDisplayName, normalizedColorName);
|
||||||
|
FilamentVariant saved = variantRepo.save(variant);
|
||||||
|
return ResponseEntity.ok(toVariantDto(saved));
|
||||||
}
|
}
|
||||||
|
|
||||||
@DeleteMapping("/variants/{variantId}")
|
@DeleteMapping("/variants/{variantId}")
|
||||||
@Transactional
|
@Transactional
|
||||||
public ResponseEntity<Void> deleteVariant(@PathVariable Long variantId) {
|
public ResponseEntity<Void> deleteVariant(@PathVariable Long variantId) {
|
||||||
adminFilamentControllerService.deleteVariant(variantId);
|
FilamentVariant variant = variantRepo.findById(variantId)
|
||||||
|
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "Filament variant not found"));
|
||||||
|
|
||||||
|
if (quoteLineItemRepo.existsByFilamentVariant_Id(variantId) || orderItemRepo.existsByFilamentVariant_Id(variantId)) {
|
||||||
|
throw new ResponseStatusException(CONFLICT, "Variant is already used in quotes/orders and cannot be deleted");
|
||||||
|
}
|
||||||
|
|
||||||
|
variantRepo.delete(variant);
|
||||||
return ResponseEntity.noContent().build();
|
return ResponseEntity.noContent().build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void applyMaterialPayload(
|
||||||
|
FilamentMaterialType material,
|
||||||
|
AdminUpsertFilamentMaterialTypeRequest payload,
|
||||||
|
String normalizedMaterialCode
|
||||||
|
) {
|
||||||
|
boolean isFlexible = payload != null && Boolean.TRUE.equals(payload.getIsFlexible());
|
||||||
|
boolean isTechnical = payload != null && Boolean.TRUE.equals(payload.getIsTechnical());
|
||||||
|
String technicalTypeLabel = payload != null && payload.getTechnicalTypeLabel() != null
|
||||||
|
? payload.getTechnicalTypeLabel().trim()
|
||||||
|
: null;
|
||||||
|
|
||||||
|
material.setMaterialCode(normalizedMaterialCode);
|
||||||
|
material.setIsFlexible(isFlexible);
|
||||||
|
material.setIsTechnical(isTechnical);
|
||||||
|
material.setTechnicalTypeLabel(isTechnical && technicalTypeLabel != null && !technicalTypeLabel.isBlank()
|
||||||
|
? technicalTypeLabel
|
||||||
|
: null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void applyVariantPayload(
|
||||||
|
FilamentVariant variant,
|
||||||
|
AdminUpsertFilamentVariantRequest payload,
|
||||||
|
FilamentMaterialType material,
|
||||||
|
String normalizedDisplayName,
|
||||||
|
String normalizedColorName
|
||||||
|
) {
|
||||||
|
String normalizedColorHex = normalizeAndValidateColorHex(payload.getColorHex());
|
||||||
|
String normalizedFinishType = normalizeAndValidateFinishType(payload.getFinishType(), payload.getIsMatte());
|
||||||
|
String normalizedBrand = normalizeOptional(payload.getBrand());
|
||||||
|
|
||||||
|
variant.setFilamentMaterialType(material);
|
||||||
|
variant.setVariantDisplayName(normalizedDisplayName);
|
||||||
|
variant.setColorName(normalizedColorName);
|
||||||
|
variant.setColorHex(normalizedColorHex);
|
||||||
|
variant.setFinishType(normalizedFinishType);
|
||||||
|
variant.setBrand(normalizedBrand);
|
||||||
|
variant.setIsMatte(Boolean.TRUE.equals(payload.getIsMatte()) || "MATTE".equals(normalizedFinishType));
|
||||||
|
variant.setIsSpecial(Boolean.TRUE.equals(payload.getIsSpecial()));
|
||||||
|
variant.setCostChfPerKg(payload.getCostChfPerKg());
|
||||||
|
variant.setStockSpools(payload.getStockSpools());
|
||||||
|
variant.setSpoolNetKg(payload.getSpoolNetKg());
|
||||||
|
variant.setIsActive(payload.getIsActive() == null || payload.getIsActive());
|
||||||
|
}
|
||||||
|
|
||||||
|
private String normalizeAndValidateMaterialCode(AdminUpsertFilamentMaterialTypeRequest payload) {
|
||||||
|
if (payload == null || payload.getMaterialCode() == null || payload.getMaterialCode().isBlank()) {
|
||||||
|
throw new ResponseStatusException(BAD_REQUEST, "Material code is required");
|
||||||
|
}
|
||||||
|
return payload.getMaterialCode().trim().toUpperCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String normalizeAndValidateVariantDisplayName(String value) {
|
||||||
|
if (value == null || value.isBlank()) {
|
||||||
|
throw new ResponseStatusException(BAD_REQUEST, "Variant display name is required");
|
||||||
|
}
|
||||||
|
return value.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String normalizeAndValidateColorName(String value) {
|
||||||
|
if (value == null || value.isBlank()) {
|
||||||
|
throw new ResponseStatusException(BAD_REQUEST, "Color name is required");
|
||||||
|
}
|
||||||
|
return value.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String normalizeAndValidateColorHex(String value) {
|
||||||
|
if (value == null || value.isBlank()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String normalized = value.trim();
|
||||||
|
if (!HEX_COLOR_PATTERN.matcher(normalized).matches()) {
|
||||||
|
throw new ResponseStatusException(BAD_REQUEST, "Color hex must be in format #RRGGBB");
|
||||||
|
}
|
||||||
|
return normalized.toUpperCase(Locale.ROOT);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String normalizeAndValidateFinishType(String finishType, Boolean isMatte) {
|
||||||
|
String normalized = finishType == null || finishType.isBlank()
|
||||||
|
? (Boolean.TRUE.equals(isMatte) ? "MATTE" : "GLOSSY")
|
||||||
|
: finishType.trim().toUpperCase(Locale.ROOT);
|
||||||
|
if (!ALLOWED_FINISH_TYPES.contains(normalized)) {
|
||||||
|
throw new ResponseStatusException(BAD_REQUEST, "Invalid finish type");
|
||||||
|
}
|
||||||
|
return normalized;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String normalizeOptional(String value) {
|
||||||
|
if (value == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String normalized = value.trim();
|
||||||
|
return normalized.isBlank() ? null : normalized;
|
||||||
|
}
|
||||||
|
|
||||||
|
private FilamentMaterialType validateAndResolveMaterial(AdminUpsertFilamentVariantRequest payload) {
|
||||||
|
if (payload == null || payload.getMaterialTypeId() == null) {
|
||||||
|
throw new ResponseStatusException(BAD_REQUEST, "Material type id is required");
|
||||||
|
}
|
||||||
|
|
||||||
|
return materialRepo.findById(payload.getMaterialTypeId())
|
||||||
|
.orElseThrow(() -> new ResponseStatusException(BAD_REQUEST, "Material type not found"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateNumericPayload(AdminUpsertFilamentVariantRequest payload) {
|
||||||
|
if (payload.getCostChfPerKg() == null || payload.getCostChfPerKg().compareTo(BigDecimal.ZERO) < 0) {
|
||||||
|
throw new ResponseStatusException(BAD_REQUEST, "Cost CHF/kg must be >= 0");
|
||||||
|
}
|
||||||
|
validateNumeric63(payload.getStockSpools(), "Stock spools", true);
|
||||||
|
validateNumeric63(payload.getSpoolNetKg(), "Spool net kg", false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateNumeric63(BigDecimal value, String fieldName, boolean allowZero) {
|
||||||
|
if (value == null) {
|
||||||
|
throw new ResponseStatusException(BAD_REQUEST, fieldName + " is required");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (allowZero) {
|
||||||
|
if (value.compareTo(BigDecimal.ZERO) < 0) {
|
||||||
|
throw new ResponseStatusException(BAD_REQUEST, fieldName + " must be >= 0");
|
||||||
|
}
|
||||||
|
} else if (value.compareTo(BigDecimal.ZERO) <= 0) {
|
||||||
|
throw new ResponseStatusException(BAD_REQUEST, fieldName + " must be > 0");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (value.scale() > 3) {
|
||||||
|
throw new ResponseStatusException(BAD_REQUEST, fieldName + " must have at most 3 decimal places");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (value.compareTo(MAX_NUMERIC_6_3) > 0) {
|
||||||
|
throw new ResponseStatusException(BAD_REQUEST, fieldName + " must be <= 999.999");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ensureMaterialCodeAvailable(String materialCode, Long currentMaterialId) {
|
||||||
|
materialRepo.findByMaterialCode(materialCode).ifPresent(existing -> {
|
||||||
|
if (currentMaterialId == null || !existing.getId().equals(currentMaterialId)) {
|
||||||
|
throw new ResponseStatusException(BAD_REQUEST, "Material code already exists");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ensureVariantDisplayNameAvailable(FilamentMaterialType material, String displayName, Long currentVariantId) {
|
||||||
|
variantRepo.findByFilamentMaterialTypeAndVariantDisplayName(material, displayName).ifPresent(existing -> {
|
||||||
|
if (currentVariantId == null || !existing.getId().equals(currentVariantId)) {
|
||||||
|
throw new ResponseStatusException(BAD_REQUEST, "Variant display name already exists for this material");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private AdminFilamentMaterialTypeDto toMaterialDto(FilamentMaterialType material) {
|
||||||
|
AdminFilamentMaterialTypeDto dto = new AdminFilamentMaterialTypeDto();
|
||||||
|
dto.setId(material.getId());
|
||||||
|
dto.setMaterialCode(material.getMaterialCode());
|
||||||
|
dto.setIsFlexible(material.getIsFlexible());
|
||||||
|
dto.setIsTechnical(material.getIsTechnical());
|
||||||
|
dto.setTechnicalTypeLabel(material.getTechnicalTypeLabel());
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
|
|
||||||
|
private AdminFilamentVariantDto toVariantDto(FilamentVariant variant) {
|
||||||
|
AdminFilamentVariantDto dto = new AdminFilamentVariantDto();
|
||||||
|
dto.setId(variant.getId());
|
||||||
|
|
||||||
|
FilamentMaterialType material = variant.getFilamentMaterialType();
|
||||||
|
if (material != null) {
|
||||||
|
dto.setMaterialTypeId(material.getId());
|
||||||
|
dto.setMaterialCode(material.getMaterialCode());
|
||||||
|
dto.setMaterialIsFlexible(material.getIsFlexible());
|
||||||
|
dto.setMaterialIsTechnical(material.getIsTechnical());
|
||||||
|
dto.setMaterialTechnicalTypeLabel(material.getTechnicalTypeLabel());
|
||||||
|
}
|
||||||
|
|
||||||
|
dto.setVariantDisplayName(variant.getVariantDisplayName());
|
||||||
|
dto.setColorName(variant.getColorName());
|
||||||
|
dto.setColorHex(variant.getColorHex());
|
||||||
|
dto.setFinishType(variant.getFinishType());
|
||||||
|
dto.setBrand(variant.getBrand());
|
||||||
|
dto.setIsMatte(variant.getIsMatte());
|
||||||
|
dto.setIsSpecial(variant.getIsSpecial());
|
||||||
|
dto.setCostChfPerKg(variant.getCostChfPerKg());
|
||||||
|
dto.setStockSpools(variant.getStockSpools());
|
||||||
|
dto.setSpoolNetKg(variant.getSpoolNetKg());
|
||||||
|
BigDecimal stockKg = BigDecimal.ZERO;
|
||||||
|
if (variant.getStockSpools() != null && variant.getSpoolNetKg() != null) {
|
||||||
|
stockKg = variant.getStockSpools().multiply(variant.getSpoolNetKg());
|
||||||
|
}
|
||||||
|
dto.setStockKg(stockKg);
|
||||||
|
dto.setStockFilamentGrams(stockKg.multiply(BigDecimal.valueOf(1000)));
|
||||||
|
dto.setIsActive(variant.getIsActive());
|
||||||
|
dto.setCreatedAt(variant.getCreatedAt());
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,89 +0,0 @@
|
|||||||
package com.printcalculator.controller.admin;
|
|
||||||
|
|
||||||
import com.printcalculator.dto.AdminCreateMediaUsageRequest;
|
|
||||||
import com.printcalculator.dto.AdminMediaAssetDto;
|
|
||||||
import com.printcalculator.dto.AdminMediaUsageDto;
|
|
||||||
import com.printcalculator.dto.AdminUpdateMediaAssetRequest;
|
|
||||||
import com.printcalculator.dto.AdminUpdateMediaUsageRequest;
|
|
||||||
import com.printcalculator.service.admin.AdminMediaControllerService;
|
|
||||||
import org.springframework.http.MediaType;
|
|
||||||
import org.springframework.http.ResponseEntity;
|
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
|
||||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
|
||||||
import org.springframework.web.bind.annotation.PatchMapping;
|
|
||||||
import org.springframework.web.bind.annotation.PathVariable;
|
|
||||||
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.RequestParam;
|
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
|
||||||
import org.springframework.web.multipart.MultipartFile;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
@RestController
|
|
||||||
@RequestMapping("/api/admin/media")
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public class AdminMediaController {
|
|
||||||
|
|
||||||
private final AdminMediaControllerService adminMediaControllerService;
|
|
||||||
|
|
||||||
public AdminMediaController(AdminMediaControllerService adminMediaControllerService) {
|
|
||||||
this.adminMediaControllerService = adminMediaControllerService;
|
|
||||||
}
|
|
||||||
|
|
||||||
@PostMapping(value = "/assets", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
|
||||||
@Transactional
|
|
||||||
public ResponseEntity<AdminMediaAssetDto> uploadAsset(@RequestParam("file") MultipartFile file,
|
|
||||||
@RequestParam(value = "title", required = false) String title,
|
|
||||||
@RequestParam(value = "altText", required = false) String altText,
|
|
||||||
@RequestParam(value = "visibility", required = false) String visibility) {
|
|
||||||
return ResponseEntity.ok(adminMediaControllerService.uploadAsset(file, title, altText, visibility));
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping("/assets")
|
|
||||||
public ResponseEntity<List<AdminMediaAssetDto>> listAssets() {
|
|
||||||
return ResponseEntity.ok(adminMediaControllerService.listAssets());
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping("/assets/{mediaAssetId}")
|
|
||||||
public ResponseEntity<AdminMediaAssetDto> getAsset(@PathVariable UUID mediaAssetId) {
|
|
||||||
return ResponseEntity.ok(adminMediaControllerService.getAsset(mediaAssetId));
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping("/usages")
|
|
||||||
public ResponseEntity<List<AdminMediaUsageDto>> getUsages(@RequestParam String usageType,
|
|
||||||
@RequestParam String usageKey,
|
|
||||||
@RequestParam(required = false) UUID ownerId) {
|
|
||||||
return ResponseEntity.ok(adminMediaControllerService.getUsages(usageType, usageKey, ownerId));
|
|
||||||
}
|
|
||||||
|
|
||||||
@PatchMapping("/assets/{mediaAssetId}")
|
|
||||||
@Transactional
|
|
||||||
public ResponseEntity<AdminMediaAssetDto> updateAsset(@PathVariable UUID mediaAssetId,
|
|
||||||
@RequestBody AdminUpdateMediaAssetRequest payload) {
|
|
||||||
return ResponseEntity.ok(adminMediaControllerService.updateAsset(mediaAssetId, payload));
|
|
||||||
}
|
|
||||||
|
|
||||||
@PostMapping("/usages")
|
|
||||||
@Transactional
|
|
||||||
public ResponseEntity<AdminMediaUsageDto> createUsage(@RequestBody AdminCreateMediaUsageRequest payload) {
|
|
||||||
return ResponseEntity.ok(adminMediaControllerService.createUsage(payload));
|
|
||||||
}
|
|
||||||
|
|
||||||
@PatchMapping("/usages/{mediaUsageId}")
|
|
||||||
@Transactional
|
|
||||||
public ResponseEntity<AdminMediaUsageDto> updateUsage(@PathVariable UUID mediaUsageId,
|
|
||||||
@RequestBody AdminUpdateMediaUsageRequest payload) {
|
|
||||||
return ResponseEntity.ok(adminMediaControllerService.updateUsage(mediaUsageId, payload));
|
|
||||||
}
|
|
||||||
|
|
||||||
@DeleteMapping("/usages/{mediaUsageId}")
|
|
||||||
@Transactional
|
|
||||||
public ResponseEntity<Void> deleteUsage(@PathVariable UUID mediaUsageId) {
|
|
||||||
adminMediaControllerService.deleteUsage(mediaUsageId);
|
|
||||||
return ResponseEntity.noContent().build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,14 +1,37 @@
|
|||||||
package com.printcalculator.controller.admin;
|
package com.printcalculator.controller.admin;
|
||||||
|
|
||||||
|
import com.printcalculator.dto.AdminContactRequestDto;
|
||||||
|
import com.printcalculator.dto.AdminContactRequestAttachmentDto;
|
||||||
|
import com.printcalculator.dto.AdminContactRequestDetailDto;
|
||||||
import com.printcalculator.dto.AdminCadInvoiceCreateRequest;
|
import com.printcalculator.dto.AdminCadInvoiceCreateRequest;
|
||||||
import com.printcalculator.dto.AdminCadInvoiceDto;
|
import com.printcalculator.dto.AdminCadInvoiceDto;
|
||||||
import com.printcalculator.dto.AdminContactRequestDetailDto;
|
|
||||||
import com.printcalculator.dto.AdminContactRequestDto;
|
|
||||||
import com.printcalculator.dto.AdminFilamentStockDto;
|
import com.printcalculator.dto.AdminFilamentStockDto;
|
||||||
import com.printcalculator.dto.AdminQuoteSessionDto;
|
import com.printcalculator.dto.AdminQuoteSessionDto;
|
||||||
import com.printcalculator.dto.AdminUpdateContactRequestStatusRequest;
|
import com.printcalculator.dto.AdminUpdateContactRequestStatusRequest;
|
||||||
import com.printcalculator.service.admin.AdminOperationsControllerService;
|
import com.printcalculator.entity.CustomQuoteRequest;
|
||||||
|
import com.printcalculator.entity.CustomQuoteRequestAttachment;
|
||||||
|
import com.printcalculator.entity.FilamentVariant;
|
||||||
|
import com.printcalculator.entity.FilamentVariantStockKg;
|
||||||
|
import com.printcalculator.entity.Order;
|
||||||
|
import com.printcalculator.entity.QuoteLineItem;
|
||||||
|
import com.printcalculator.entity.QuoteSession;
|
||||||
|
import com.printcalculator.repository.CustomQuoteRequestAttachmentRepository;
|
||||||
|
import com.printcalculator.repository.CustomQuoteRequestRepository;
|
||||||
|
import com.printcalculator.repository.FilamentVariantRepository;
|
||||||
|
import com.printcalculator.repository.FilamentVariantStockKgRepository;
|
||||||
|
import com.printcalculator.repository.OrderRepository;
|
||||||
|
import com.printcalculator.repository.PricingPolicyRepository;
|
||||||
|
import com.printcalculator.repository.QuoteLineItemRepository;
|
||||||
|
import com.printcalculator.repository.QuoteSessionRepository;
|
||||||
|
import com.printcalculator.service.QuoteSessionTotalsService;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.core.io.Resource;
|
import org.springframework.core.io.Resource;
|
||||||
|
import org.springframework.core.io.UrlResource;
|
||||||
|
import org.springframework.data.domain.Sort;
|
||||||
|
import org.springframework.http.ContentDisposition;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||||
@@ -19,34 +42,148 @@ import org.springframework.web.bind.annotation.PostMapping;
|
|||||||
import org.springframework.web.bind.annotation.RequestBody;
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.UncheckedIOException;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.math.RoundingMode;
|
||||||
|
import java.net.MalformedURLException;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.time.OffsetDateTime;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Comparator;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import static org.springframework.http.HttpStatus.BAD_REQUEST;
|
||||||
|
import static org.springframework.http.HttpStatus.CONFLICT;
|
||||||
|
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
import static org.springframework.http.HttpStatus.NOT_FOUND;
|
||||||
|
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/api/admin")
|
@RequestMapping("/api/admin")
|
||||||
@Transactional(readOnly = true)
|
@Transactional(readOnly = true)
|
||||||
public class AdminOperationsController {
|
public class AdminOperationsController {
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(AdminOperationsController.class);
|
||||||
|
private static final Path CONTACT_ATTACHMENTS_ROOT = Paths.get("storage_requests").toAbsolutePath().normalize();
|
||||||
|
private static final Set<String> CONTACT_REQUEST_ALLOWED_STATUSES = Set.of(
|
||||||
|
"NEW", "PENDING", "IN_PROGRESS", "DONE", "CLOSED"
|
||||||
|
);
|
||||||
|
|
||||||
private final AdminOperationsControllerService adminOperationsControllerService;
|
private final FilamentVariantStockKgRepository filamentStockRepo;
|
||||||
|
private final FilamentVariantRepository filamentVariantRepo;
|
||||||
|
private final CustomQuoteRequestRepository customQuoteRequestRepo;
|
||||||
|
private final CustomQuoteRequestAttachmentRepository customQuoteRequestAttachmentRepo;
|
||||||
|
private final QuoteSessionRepository quoteSessionRepo;
|
||||||
|
private final QuoteLineItemRepository quoteLineItemRepo;
|
||||||
|
private final OrderRepository orderRepo;
|
||||||
|
private final PricingPolicyRepository pricingRepo;
|
||||||
|
private final QuoteSessionTotalsService quoteSessionTotalsService;
|
||||||
|
|
||||||
public AdminOperationsController(AdminOperationsControllerService adminOperationsControllerService) {
|
public AdminOperationsController(
|
||||||
this.adminOperationsControllerService = adminOperationsControllerService;
|
FilamentVariantStockKgRepository filamentStockRepo,
|
||||||
|
FilamentVariantRepository filamentVariantRepo,
|
||||||
|
CustomQuoteRequestRepository customQuoteRequestRepo,
|
||||||
|
CustomQuoteRequestAttachmentRepository customQuoteRequestAttachmentRepo,
|
||||||
|
QuoteSessionRepository quoteSessionRepo,
|
||||||
|
QuoteLineItemRepository quoteLineItemRepo,
|
||||||
|
OrderRepository orderRepo,
|
||||||
|
PricingPolicyRepository pricingRepo,
|
||||||
|
QuoteSessionTotalsService quoteSessionTotalsService
|
||||||
|
) {
|
||||||
|
this.filamentStockRepo = filamentStockRepo;
|
||||||
|
this.filamentVariantRepo = filamentVariantRepo;
|
||||||
|
this.customQuoteRequestRepo = customQuoteRequestRepo;
|
||||||
|
this.customQuoteRequestAttachmentRepo = customQuoteRequestAttachmentRepo;
|
||||||
|
this.quoteSessionRepo = quoteSessionRepo;
|
||||||
|
this.quoteLineItemRepo = quoteLineItemRepo;
|
||||||
|
this.orderRepo = orderRepo;
|
||||||
|
this.pricingRepo = pricingRepo;
|
||||||
|
this.quoteSessionTotalsService = quoteSessionTotalsService;
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/filament-stock")
|
@GetMapping("/filament-stock")
|
||||||
public ResponseEntity<List<AdminFilamentStockDto>> getFilamentStock() {
|
public ResponseEntity<List<AdminFilamentStockDto>> getFilamentStock() {
|
||||||
return ResponseEntity.ok(adminOperationsControllerService.getFilamentStock());
|
List<FilamentVariantStockKg> stocks = filamentStockRepo.findAll(Sort.by(Sort.Direction.ASC, "stockKg"));
|
||||||
|
Set<Long> variantIds = stocks.stream()
|
||||||
|
.map(FilamentVariantStockKg::getFilamentVariantId)
|
||||||
|
.collect(Collectors.toSet());
|
||||||
|
|
||||||
|
Map<Long, FilamentVariant> variantsById;
|
||||||
|
if (variantIds.isEmpty()) {
|
||||||
|
variantsById = Collections.emptyMap();
|
||||||
|
} else {
|
||||||
|
variantsById = filamentVariantRepo.findAllById(variantIds).stream()
|
||||||
|
.collect(Collectors.toMap(FilamentVariant::getId, variant -> variant));
|
||||||
|
}
|
||||||
|
|
||||||
|
List<AdminFilamentStockDto> response = stocks.stream().map(stock -> {
|
||||||
|
FilamentVariant variant = variantsById.get(stock.getFilamentVariantId());
|
||||||
|
AdminFilamentStockDto dto = new AdminFilamentStockDto();
|
||||||
|
dto.setFilamentVariantId(stock.getFilamentVariantId());
|
||||||
|
dto.setStockSpools(stock.getStockSpools());
|
||||||
|
dto.setSpoolNetKg(stock.getSpoolNetKg());
|
||||||
|
dto.setStockKg(stock.getStockKg());
|
||||||
|
BigDecimal grams = stock.getStockKg() != null
|
||||||
|
? stock.getStockKg().multiply(BigDecimal.valueOf(1000))
|
||||||
|
: BigDecimal.ZERO;
|
||||||
|
dto.setStockFilamentGrams(grams);
|
||||||
|
|
||||||
|
if (variant != null) {
|
||||||
|
dto.setMaterialCode(
|
||||||
|
variant.getFilamentMaterialType() != null
|
||||||
|
? variant.getFilamentMaterialType().getMaterialCode()
|
||||||
|
: "UNKNOWN"
|
||||||
|
);
|
||||||
|
dto.setVariantDisplayName(variant.getVariantDisplayName());
|
||||||
|
dto.setColorName(variant.getColorName());
|
||||||
|
dto.setActive(variant.getIsActive());
|
||||||
|
} else {
|
||||||
|
dto.setMaterialCode("UNKNOWN");
|
||||||
|
dto.setVariantDisplayName("Variant " + stock.getFilamentVariantId());
|
||||||
|
dto.setColorName("-");
|
||||||
|
dto.setActive(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
return dto;
|
||||||
|
}).toList();
|
||||||
|
|
||||||
|
return ResponseEntity.ok(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/contact-requests")
|
@GetMapping("/contact-requests")
|
||||||
public ResponseEntity<List<AdminContactRequestDto>> getContactRequests() {
|
public ResponseEntity<List<AdminContactRequestDto>> getContactRequests() {
|
||||||
return ResponseEntity.ok(adminOperationsControllerService.getContactRequests());
|
List<AdminContactRequestDto> response = customQuoteRequestRepo.findAll(
|
||||||
|
Sort.by(Sort.Direction.DESC, "createdAt")
|
||||||
|
)
|
||||||
|
.stream()
|
||||||
|
.map(this::toContactRequestDto)
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
return ResponseEntity.ok(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/contact-requests/{requestId}")
|
@GetMapping("/contact-requests/{requestId}")
|
||||||
public ResponseEntity<AdminContactRequestDetailDto> getContactRequestDetail(@PathVariable UUID requestId) {
|
public ResponseEntity<AdminContactRequestDetailDto> getContactRequestDetail(@PathVariable UUID requestId) {
|
||||||
return ResponseEntity.ok(adminOperationsControllerService.getContactRequestDetail(requestId));
|
CustomQuoteRequest request = customQuoteRequestRepo.findById(requestId)
|
||||||
|
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "Contact request not found"));
|
||||||
|
|
||||||
|
List<AdminContactRequestAttachmentDto> attachments = customQuoteRequestAttachmentRepo
|
||||||
|
.findByRequest_IdOrderByCreatedAtAsc(requestId)
|
||||||
|
.stream()
|
||||||
|
.map(this::toContactRequestAttachmentDto)
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
return ResponseEntity.ok(toContactRequestDetailDto(request, attachments));
|
||||||
}
|
}
|
||||||
|
|
||||||
@PatchMapping("/contact-requests/{requestId}/status")
|
@PatchMapping("/contact-requests/{requestId}/status")
|
||||||
@@ -55,7 +192,31 @@ public class AdminOperationsController {
|
|||||||
@PathVariable UUID requestId,
|
@PathVariable UUID requestId,
|
||||||
@RequestBody AdminUpdateContactRequestStatusRequest payload
|
@RequestBody AdminUpdateContactRequestStatusRequest payload
|
||||||
) {
|
) {
|
||||||
return ResponseEntity.ok(adminOperationsControllerService.updateContactRequestStatus(requestId, payload));
|
CustomQuoteRequest request = customQuoteRequestRepo.findById(requestId)
|
||||||
|
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "Contact request not found"));
|
||||||
|
|
||||||
|
String requestedStatus = payload != null && payload.getStatus() != null
|
||||||
|
? payload.getStatus().trim().toUpperCase(Locale.ROOT)
|
||||||
|
: "";
|
||||||
|
|
||||||
|
if (!CONTACT_REQUEST_ALLOWED_STATUSES.contains(requestedStatus)) {
|
||||||
|
throw new ResponseStatusException(
|
||||||
|
BAD_REQUEST,
|
||||||
|
"Invalid status. Allowed: " + String.join(", ", CONTACT_REQUEST_ALLOWED_STATUSES)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
request.setStatus(requestedStatus);
|
||||||
|
request.setUpdatedAt(OffsetDateTime.now());
|
||||||
|
CustomQuoteRequest saved = customQuoteRequestRepo.save(request);
|
||||||
|
|
||||||
|
List<AdminContactRequestAttachmentDto> attachments = customQuoteRequestAttachmentRepo
|
||||||
|
.findByRequest_IdOrderByCreatedAtAsc(requestId)
|
||||||
|
.stream()
|
||||||
|
.map(this::toContactRequestAttachmentDto)
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
return ResponseEntity.ok(toContactRequestDetailDto(saved, attachments));
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/contact-requests/{requestId}/attachments/{attachmentId}/file")
|
@GetMapping("/contact-requests/{requestId}/attachments/{attachmentId}/file")
|
||||||
@@ -63,17 +224,87 @@ public class AdminOperationsController {
|
|||||||
@PathVariable UUID requestId,
|
@PathVariable UUID requestId,
|
||||||
@PathVariable UUID attachmentId
|
@PathVariable UUID attachmentId
|
||||||
) {
|
) {
|
||||||
return adminOperationsControllerService.downloadContactRequestAttachment(requestId, attachmentId);
|
CustomQuoteRequestAttachment attachment = customQuoteRequestAttachmentRepo.findById(attachmentId)
|
||||||
|
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "Attachment not found"));
|
||||||
|
|
||||||
|
if (!attachment.getRequest().getId().equals(requestId)) {
|
||||||
|
throw new ResponseStatusException(NOT_FOUND, "Attachment not found for request");
|
||||||
|
}
|
||||||
|
|
||||||
|
String relativePath = attachment.getStoredRelativePath();
|
||||||
|
if (relativePath == null || relativePath.isBlank() || "PENDING".equals(relativePath)) {
|
||||||
|
throw new ResponseStatusException(NOT_FOUND, "Attachment file not available");
|
||||||
|
}
|
||||||
|
|
||||||
|
String expectedPrefix = "quote-requests/" + requestId + "/attachments/" + attachmentId + "/";
|
||||||
|
if (!relativePath.startsWith(expectedPrefix)) {
|
||||||
|
throw new ResponseStatusException(NOT_FOUND, "Attachment file not available");
|
||||||
|
}
|
||||||
|
|
||||||
|
Path filePath = CONTACT_ATTACHMENTS_ROOT.resolve(relativePath).normalize();
|
||||||
|
if (!filePath.startsWith(CONTACT_ATTACHMENTS_ROOT)) {
|
||||||
|
throw new ResponseStatusException(NOT_FOUND, "Attachment file not available");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Files.exists(filePath)) {
|
||||||
|
throw new ResponseStatusException(NOT_FOUND, "Attachment file not available");
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
Resource resource = new UrlResource(filePath.toUri());
|
||||||
|
if (!resource.exists() || !resource.isReadable()) {
|
||||||
|
throw new ResponseStatusException(NOT_FOUND, "Attachment file not available");
|
||||||
|
}
|
||||||
|
|
||||||
|
MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM;
|
||||||
|
String mimeType = attachment.getMimeType();
|
||||||
|
if (mimeType != null && !mimeType.isBlank()) {
|
||||||
|
try {
|
||||||
|
mediaType = MediaType.parseMediaType(mimeType);
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
mediaType = MediaType.APPLICATION_OCTET_STREAM;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String filename = attachment.getOriginalFilename();
|
||||||
|
if (filename == null || filename.isBlank()) {
|
||||||
|
filename = attachment.getStoredFilename() != null && !attachment.getStoredFilename().isBlank()
|
||||||
|
? attachment.getStoredFilename()
|
||||||
|
: "attachment-" + attachmentId;
|
||||||
|
}
|
||||||
|
|
||||||
|
return ResponseEntity.ok()
|
||||||
|
.contentType(mediaType)
|
||||||
|
.header(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.attachment()
|
||||||
|
.filename(filename, StandardCharsets.UTF_8)
|
||||||
|
.build()
|
||||||
|
.toString())
|
||||||
|
.body(resource);
|
||||||
|
} catch (MalformedURLException e) {
|
||||||
|
throw new ResponseStatusException(NOT_FOUND, "Attachment file not available");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/sessions")
|
@GetMapping("/sessions")
|
||||||
public ResponseEntity<List<AdminQuoteSessionDto>> getQuoteSessions() {
|
public ResponseEntity<List<AdminQuoteSessionDto>> getQuoteSessions() {
|
||||||
return ResponseEntity.ok(adminOperationsControllerService.getQuoteSessions());
|
List<AdminQuoteSessionDto> response = quoteSessionRepo.findAll(
|
||||||
|
Sort.by(Sort.Direction.DESC, "createdAt")
|
||||||
|
)
|
||||||
|
.stream()
|
||||||
|
.map(this::toQuoteSessionDto)
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
return ResponseEntity.ok(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/cad-invoices")
|
@GetMapping("/cad-invoices")
|
||||||
public ResponseEntity<List<AdminCadInvoiceDto>> getCadInvoices() {
|
public ResponseEntity<List<AdminCadInvoiceDto>> getCadInvoices() {
|
||||||
return ResponseEntity.ok(adminOperationsControllerService.getCadInvoices());
|
List<AdminCadInvoiceDto> response = quoteSessionRepo.findByStatusInOrderByCreatedAtDesc(List.of("CAD_ACTIVE", "CONVERTED"))
|
||||||
|
.stream()
|
||||||
|
.filter(this::isCadSessionRecord)
|
||||||
|
.map(this::toCadInvoiceDto)
|
||||||
|
.toList();
|
||||||
|
return ResponseEntity.ok(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/cad-invoices")
|
@PostMapping("/cad-invoices")
|
||||||
@@ -81,13 +312,198 @@ public class AdminOperationsController {
|
|||||||
public ResponseEntity<AdminCadInvoiceDto> createOrUpdateCadInvoice(
|
public ResponseEntity<AdminCadInvoiceDto> createOrUpdateCadInvoice(
|
||||||
@RequestBody AdminCadInvoiceCreateRequest payload
|
@RequestBody AdminCadInvoiceCreateRequest payload
|
||||||
) {
|
) {
|
||||||
return ResponseEntity.ok(adminOperationsControllerService.createOrUpdateCadInvoice(payload));
|
if (payload == null || payload.getCadHours() == null) {
|
||||||
|
throw new ResponseStatusException(BAD_REQUEST, "cadHours is required");
|
||||||
|
}
|
||||||
|
|
||||||
|
BigDecimal cadHours = payload.getCadHours().setScale(2, RoundingMode.HALF_UP);
|
||||||
|
if (cadHours.compareTo(BigDecimal.ZERO) <= 0) {
|
||||||
|
throw new ResponseStatusException(BAD_REQUEST, "cadHours must be > 0");
|
||||||
|
}
|
||||||
|
|
||||||
|
BigDecimal cadRate = payload.getCadHourlyRateChf();
|
||||||
|
if (cadRate == null || cadRate.compareTo(BigDecimal.ZERO) <= 0) {
|
||||||
|
var policy = pricingRepo.findFirstByIsActiveTrueOrderByValidFromDesc();
|
||||||
|
cadRate = policy != null && policy.getCadCostChfPerHour() != null
|
||||||
|
? policy.getCadCostChfPerHour()
|
||||||
|
: BigDecimal.ZERO;
|
||||||
|
}
|
||||||
|
cadRate = cadRate.setScale(2, RoundingMode.HALF_UP);
|
||||||
|
|
||||||
|
QuoteSession session;
|
||||||
|
if (payload.getSessionId() != null) {
|
||||||
|
session = quoteSessionRepo.findById(payload.getSessionId())
|
||||||
|
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "Session not found"));
|
||||||
|
} else {
|
||||||
|
session = new QuoteSession();
|
||||||
|
session.setStatus("CAD_ACTIVE");
|
||||||
|
session.setPricingVersion("v1");
|
||||||
|
session.setMaterialCode("PLA");
|
||||||
|
session.setNozzleDiameterMm(BigDecimal.valueOf(0.4));
|
||||||
|
session.setLayerHeightMm(BigDecimal.valueOf(0.2));
|
||||||
|
session.setInfillPattern("grid");
|
||||||
|
session.setInfillPercent(20);
|
||||||
|
session.setSupportsEnabled(false);
|
||||||
|
session.setSetupCostChf(BigDecimal.ZERO);
|
||||||
|
session.setCreatedAt(OffsetDateTime.now());
|
||||||
|
session.setExpiresAt(OffsetDateTime.now().plusDays(30));
|
||||||
|
}
|
||||||
|
|
||||||
|
if ("CONVERTED".equals(session.getStatus())) {
|
||||||
|
throw new ResponseStatusException(CONFLICT, "Session already converted to order");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (payload.getSourceRequestId() != null) {
|
||||||
|
if (!customQuoteRequestRepo.existsById(payload.getSourceRequestId())) {
|
||||||
|
throw new ResponseStatusException(NOT_FOUND, "Source request not found");
|
||||||
|
}
|
||||||
|
session.setSourceRequestId(payload.getSourceRequestId());
|
||||||
|
} else {
|
||||||
|
session.setSourceRequestId(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
session.setStatus("CAD_ACTIVE");
|
||||||
|
session.setCadHours(cadHours);
|
||||||
|
session.setCadHourlyRateChf(cadRate);
|
||||||
|
if (payload.getNotes() != null) {
|
||||||
|
String trimmedNotes = payload.getNotes().trim();
|
||||||
|
session.setNotes(trimmedNotes.isEmpty() ? null : trimmedNotes);
|
||||||
|
}
|
||||||
|
|
||||||
|
QuoteSession saved = quoteSessionRepo.save(session);
|
||||||
|
return ResponseEntity.ok(toCadInvoiceDto(saved));
|
||||||
}
|
}
|
||||||
|
|
||||||
@DeleteMapping("/sessions/{sessionId}")
|
@DeleteMapping("/sessions/{sessionId}")
|
||||||
@Transactional
|
@Transactional
|
||||||
public ResponseEntity<Void> deleteQuoteSession(@PathVariable UUID sessionId) {
|
public ResponseEntity<Void> deleteQuoteSession(@PathVariable UUID sessionId) {
|
||||||
adminOperationsControllerService.deleteQuoteSession(sessionId);
|
QuoteSession session = quoteSessionRepo.findById(sessionId)
|
||||||
|
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "Session not found"));
|
||||||
|
|
||||||
|
if (orderRepo.existsBySourceQuoteSession_Id(sessionId)) {
|
||||||
|
throw new ResponseStatusException(CONFLICT, "Cannot delete session already linked to an order");
|
||||||
|
}
|
||||||
|
|
||||||
|
deleteSessionFiles(sessionId);
|
||||||
|
quoteSessionRepo.delete(session);
|
||||||
return ResponseEntity.noContent().build();
|
return ResponseEntity.noContent().build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private AdminContactRequestDto toContactRequestDto(CustomQuoteRequest request) {
|
||||||
|
AdminContactRequestDto dto = new AdminContactRequestDto();
|
||||||
|
dto.setId(request.getId());
|
||||||
|
dto.setRequestType(request.getRequestType());
|
||||||
|
dto.setCustomerType(request.getCustomerType());
|
||||||
|
dto.setEmail(request.getEmail());
|
||||||
|
dto.setPhone(request.getPhone());
|
||||||
|
dto.setName(request.getName());
|
||||||
|
dto.setCompanyName(request.getCompanyName());
|
||||||
|
dto.setStatus(request.getStatus());
|
||||||
|
dto.setCreatedAt(request.getCreatedAt());
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
|
|
||||||
|
private AdminContactRequestAttachmentDto toContactRequestAttachmentDto(CustomQuoteRequestAttachment attachment) {
|
||||||
|
AdminContactRequestAttachmentDto dto = new AdminContactRequestAttachmentDto();
|
||||||
|
dto.setId(attachment.getId());
|
||||||
|
dto.setOriginalFilename(attachment.getOriginalFilename());
|
||||||
|
dto.setMimeType(attachment.getMimeType());
|
||||||
|
dto.setFileSizeBytes(attachment.getFileSizeBytes());
|
||||||
|
dto.setCreatedAt(attachment.getCreatedAt());
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
|
|
||||||
|
private AdminContactRequestDetailDto toContactRequestDetailDto(
|
||||||
|
CustomQuoteRequest request,
|
||||||
|
List<AdminContactRequestAttachmentDto> attachments
|
||||||
|
) {
|
||||||
|
AdminContactRequestDetailDto dto = new AdminContactRequestDetailDto();
|
||||||
|
dto.setId(request.getId());
|
||||||
|
dto.setRequestType(request.getRequestType());
|
||||||
|
dto.setCustomerType(request.getCustomerType());
|
||||||
|
dto.setEmail(request.getEmail());
|
||||||
|
dto.setPhone(request.getPhone());
|
||||||
|
dto.setName(request.getName());
|
||||||
|
dto.setCompanyName(request.getCompanyName());
|
||||||
|
dto.setContactPerson(request.getContactPerson());
|
||||||
|
dto.setMessage(request.getMessage());
|
||||||
|
dto.setStatus(request.getStatus());
|
||||||
|
dto.setCreatedAt(request.getCreatedAt());
|
||||||
|
dto.setUpdatedAt(request.getUpdatedAt());
|
||||||
|
dto.setAttachments(attachments);
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
|
|
||||||
|
private AdminQuoteSessionDto toQuoteSessionDto(QuoteSession session) {
|
||||||
|
AdminQuoteSessionDto dto = new AdminQuoteSessionDto();
|
||||||
|
dto.setId(session.getId());
|
||||||
|
dto.setStatus(session.getStatus());
|
||||||
|
dto.setMaterialCode(session.getMaterialCode());
|
||||||
|
dto.setCreatedAt(session.getCreatedAt());
|
||||||
|
dto.setExpiresAt(session.getExpiresAt());
|
||||||
|
dto.setConvertedOrderId(session.getConvertedOrderId());
|
||||||
|
dto.setSourceRequestId(session.getSourceRequestId());
|
||||||
|
dto.setCadHours(session.getCadHours());
|
||||||
|
dto.setCadHourlyRateChf(session.getCadHourlyRateChf());
|
||||||
|
dto.setCadTotalChf(quoteSessionTotalsService.calculateCadTotal(session));
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isCadSessionRecord(QuoteSession session) {
|
||||||
|
if ("CAD_ACTIVE".equals(session.getStatus())) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (!"CONVERTED".equals(session.getStatus())) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
BigDecimal cadHours = session.getCadHours() != null ? session.getCadHours() : BigDecimal.ZERO;
|
||||||
|
return cadHours.compareTo(BigDecimal.ZERO) > 0 || session.getSourceRequestId() != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private AdminCadInvoiceDto toCadInvoiceDto(QuoteSession session) {
|
||||||
|
List<QuoteLineItem> items = quoteLineItemRepo.findByQuoteSessionId(session.getId());
|
||||||
|
QuoteSessionTotalsService.QuoteSessionTotals totals = quoteSessionTotalsService.compute(session, items);
|
||||||
|
|
||||||
|
AdminCadInvoiceDto dto = new AdminCadInvoiceDto();
|
||||||
|
dto.setSessionId(session.getId());
|
||||||
|
dto.setSessionStatus(session.getStatus());
|
||||||
|
dto.setSourceRequestId(session.getSourceRequestId());
|
||||||
|
dto.setCadHours(session.getCadHours() != null ? session.getCadHours() : BigDecimal.ZERO);
|
||||||
|
dto.setCadHourlyRateChf(session.getCadHourlyRateChf() != null ? session.getCadHourlyRateChf() : BigDecimal.ZERO);
|
||||||
|
dto.setCadTotalChf(totals.cadTotalChf());
|
||||||
|
dto.setPrintItemsTotalChf(totals.printItemsTotalChf());
|
||||||
|
dto.setSetupCostChf(totals.setupCostChf());
|
||||||
|
dto.setShippingCostChf(totals.shippingCostChf());
|
||||||
|
dto.setGrandTotalChf(totals.grandTotalChf());
|
||||||
|
dto.setConvertedOrderId(session.getConvertedOrderId());
|
||||||
|
dto.setCheckoutPath("/checkout/cad?session=" + session.getId());
|
||||||
|
dto.setNotes(session.getNotes());
|
||||||
|
dto.setCreatedAt(session.getCreatedAt());
|
||||||
|
|
||||||
|
if (session.getConvertedOrderId() != null) {
|
||||||
|
Order order = orderRepo.findById(session.getConvertedOrderId()).orElse(null);
|
||||||
|
dto.setConvertedOrderStatus(order != null ? order.getStatus() : null);
|
||||||
|
}
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void deleteSessionFiles(UUID sessionId) {
|
||||||
|
Path sessionDir = Paths.get("storage_quotes", sessionId.toString());
|
||||||
|
if (!Files.exists(sessionDir)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try (Stream<Path> walk = Files.walk(sessionDir)) {
|
||||||
|
walk.sorted(Comparator.reverseOrder()).forEach(path -> {
|
||||||
|
try {
|
||||||
|
Files.deleteIfExists(path);
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new UncheckedIOException(e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (IOException | UncheckedIOException e) {
|
||||||
|
logger.error("Failed to delete files for session {}", sessionId, e);
|
||||||
|
throw new ResponseStatusException(INTERNAL_SERVER_ERROR, "Unable to delete session files");
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,25 @@
|
|||||||
package com.printcalculator.controller.admin;
|
package com.printcalculator.controller.admin;
|
||||||
|
|
||||||
|
import com.printcalculator.dto.AddressDto;
|
||||||
import com.printcalculator.dto.AdminOrderStatusUpdateRequest;
|
import com.printcalculator.dto.AdminOrderStatusUpdateRequest;
|
||||||
import com.printcalculator.dto.OrderDto;
|
import com.printcalculator.dto.OrderDto;
|
||||||
import com.printcalculator.service.order.AdminOrderControllerService;
|
import com.printcalculator.dto.OrderItemDto;
|
||||||
|
import com.printcalculator.entity.*;
|
||||||
|
import com.printcalculator.event.OrderShippedEvent;
|
||||||
|
import com.printcalculator.repository.OrderItemRepository;
|
||||||
|
import com.printcalculator.repository.OrderRepository;
|
||||||
|
import com.printcalculator.repository.PaymentRepository;
|
||||||
|
import com.printcalculator.repository.QuoteLineItemRepository;
|
||||||
|
import com.printcalculator.service.payment.InvoicePdfRenderingService;
|
||||||
|
import com.printcalculator.service.payment.PaymentService;
|
||||||
|
import com.printcalculator.service.payment.QrBillService;
|
||||||
|
import com.printcalculator.service.storage.StorageService;
|
||||||
|
import org.springframework.context.ApplicationEventPublisher;
|
||||||
import org.springframework.core.io.Resource;
|
import org.springframework.core.io.Resource;
|
||||||
|
import org.springframework.core.io.UrlResource;
|
||||||
|
import org.springframework.http.ContentDisposition;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
@@ -12,30 +28,80 @@ import org.springframework.web.bind.annotation.PostMapping;
|
|||||||
import org.springframework.web.bind.annotation.RequestBody;
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.InvalidPathException;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.util.Comparator;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
|
import static org.springframework.http.HttpStatus.BAD_REQUEST;
|
||||||
|
import static org.springframework.http.HttpStatus.NOT_FOUND;
|
||||||
|
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/api/admin/orders")
|
@RequestMapping("/api/admin/orders")
|
||||||
@Transactional(readOnly = true)
|
@Transactional(readOnly = true)
|
||||||
public class AdminOrderController {
|
public class AdminOrderController {
|
||||||
|
private static final Path QUOTE_STORAGE_ROOT = Paths.get("storage_quotes").toAbsolutePath().normalize();
|
||||||
|
private static final List<String> ALLOWED_ORDER_STATUSES = List.of(
|
||||||
|
"PENDING_PAYMENT",
|
||||||
|
"PAID",
|
||||||
|
"IN_PRODUCTION",
|
||||||
|
"SHIPPED",
|
||||||
|
"COMPLETED",
|
||||||
|
"CANCELLED"
|
||||||
|
);
|
||||||
|
|
||||||
private final AdminOrderControllerService adminOrderControllerService;
|
private final OrderRepository orderRepo;
|
||||||
|
private final OrderItemRepository orderItemRepo;
|
||||||
|
private final PaymentRepository paymentRepo;
|
||||||
|
private final QuoteLineItemRepository quoteLineItemRepo;
|
||||||
|
private final PaymentService paymentService;
|
||||||
|
private final StorageService storageService;
|
||||||
|
private final InvoicePdfRenderingService invoiceService;
|
||||||
|
private final QrBillService qrBillService;
|
||||||
|
private final ApplicationEventPublisher eventPublisher;
|
||||||
|
|
||||||
public AdminOrderController(AdminOrderControllerService adminOrderControllerService) {
|
public AdminOrderController(
|
||||||
this.adminOrderControllerService = adminOrderControllerService;
|
OrderRepository orderRepo,
|
||||||
|
OrderItemRepository orderItemRepo,
|
||||||
|
PaymentRepository paymentRepo,
|
||||||
|
QuoteLineItemRepository quoteLineItemRepo,
|
||||||
|
PaymentService paymentService,
|
||||||
|
StorageService storageService,
|
||||||
|
InvoicePdfRenderingService invoiceService,
|
||||||
|
QrBillService qrBillService,
|
||||||
|
ApplicationEventPublisher eventPublisher
|
||||||
|
) {
|
||||||
|
this.orderRepo = orderRepo;
|
||||||
|
this.orderItemRepo = orderItemRepo;
|
||||||
|
this.paymentRepo = paymentRepo;
|
||||||
|
this.quoteLineItemRepo = quoteLineItemRepo;
|
||||||
|
this.paymentService = paymentService;
|
||||||
|
this.storageService = storageService;
|
||||||
|
this.invoiceService = invoiceService;
|
||||||
|
this.qrBillService = qrBillService;
|
||||||
|
this.eventPublisher = eventPublisher;
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping
|
@GetMapping
|
||||||
public ResponseEntity<List<OrderDto>> listOrders() {
|
public ResponseEntity<List<OrderDto>> listOrders() {
|
||||||
return ResponseEntity.ok(adminOrderControllerService.listOrders());
|
List<OrderDto> response = orderRepo.findAllByOrderByCreatedAtDesc()
|
||||||
|
.stream()
|
||||||
|
.map(this::toOrderDto)
|
||||||
|
.toList();
|
||||||
|
return ResponseEntity.ok(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/{orderId}")
|
@GetMapping("/{orderId}")
|
||||||
public ResponseEntity<OrderDto> getOrder(@PathVariable UUID orderId) {
|
public ResponseEntity<OrderDto> getOrder(@PathVariable UUID orderId) {
|
||||||
return ResponseEntity.ok(adminOrderControllerService.getOrder(orderId));
|
return ResponseEntity.ok(toOrderDto(getOrderOrThrow(orderId)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/{orderId}/payments/confirm")
|
@PostMapping("/{orderId}/payments/confirm")
|
||||||
@@ -44,7 +110,13 @@ public class AdminOrderController {
|
|||||||
@PathVariable UUID orderId,
|
@PathVariable UUID orderId,
|
||||||
@RequestBody(required = false) Map<String, String> payload
|
@RequestBody(required = false) Map<String, String> payload
|
||||||
) {
|
) {
|
||||||
return ResponseEntity.ok(adminOrderControllerService.updatePaymentMethod(orderId, payload));
|
getOrderOrThrow(orderId);
|
||||||
|
String method = payload != null ? payload.get("method") : null;
|
||||||
|
if (method == null || method.isBlank()) {
|
||||||
|
throw new ResponseStatusException(BAD_REQUEST, "Payment method is required");
|
||||||
|
}
|
||||||
|
paymentService.updatePaymentMethod(orderId, method);
|
||||||
|
return ResponseEntity.ok(toOrderDto(getOrderOrThrow(orderId)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/{orderId}/status")
|
@PostMapping("/{orderId}/status")
|
||||||
@@ -53,7 +125,28 @@ public class AdminOrderController {
|
|||||||
@PathVariable UUID orderId,
|
@PathVariable UUID orderId,
|
||||||
@RequestBody AdminOrderStatusUpdateRequest payload
|
@RequestBody AdminOrderStatusUpdateRequest payload
|
||||||
) {
|
) {
|
||||||
return ResponseEntity.ok(adminOrderControllerService.updateOrderStatus(orderId, payload));
|
if (payload == null || payload.getStatus() == null || payload.getStatus().isBlank()) {
|
||||||
|
throw new ResponseStatusException(org.springframework.http.HttpStatus.BAD_REQUEST, "Status is required");
|
||||||
|
}
|
||||||
|
|
||||||
|
Order order = getOrderOrThrow(orderId);
|
||||||
|
String normalizedStatus = payload.getStatus().trim().toUpperCase(Locale.ROOT);
|
||||||
|
if (!ALLOWED_ORDER_STATUSES.contains(normalizedStatus)) {
|
||||||
|
throw new ResponseStatusException(
|
||||||
|
BAD_REQUEST,
|
||||||
|
"Invalid order status. Allowed values: " + String.join(", ", ALLOWED_ORDER_STATUSES)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
String previousStatus = order.getStatus();
|
||||||
|
order.setStatus(normalizedStatus);
|
||||||
|
Order savedOrder = orderRepo.save(order);
|
||||||
|
|
||||||
|
// Notify customer only on transition to SHIPPED.
|
||||||
|
if (!"SHIPPED".equals(previousStatus) && "SHIPPED".equals(normalizedStatus)) {
|
||||||
|
eventPublisher.publishEvent(new OrderShippedEvent(this, savedOrder));
|
||||||
|
}
|
||||||
|
|
||||||
|
return ResponseEntity.ok(toOrderDto(savedOrder));
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/{orderId}/items/{orderItemId}/file")
|
@GetMapping("/{orderId}/items/{orderItemId}/file")
|
||||||
@@ -61,16 +154,290 @@ public class AdminOrderController {
|
|||||||
@PathVariable UUID orderId,
|
@PathVariable UUID orderId,
|
||||||
@PathVariable UUID orderItemId
|
@PathVariable UUID orderItemId
|
||||||
) {
|
) {
|
||||||
return adminOrderControllerService.downloadOrderItemFile(orderId, orderItemId);
|
OrderItem item = orderItemRepo.findById(orderItemId)
|
||||||
|
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "Order item not found"));
|
||||||
|
|
||||||
|
if (!item.getOrder().getId().equals(orderId)) {
|
||||||
|
throw new ResponseStatusException(NOT_FOUND, "Order item not found for order");
|
||||||
|
}
|
||||||
|
|
||||||
|
String relativePath = item.getStoredRelativePath();
|
||||||
|
if (relativePath == null || relativePath.isBlank() || "PENDING".equals(relativePath)) {
|
||||||
|
throw new ResponseStatusException(NOT_FOUND, "File not available");
|
||||||
|
}
|
||||||
|
Path safeRelativePath = resolveOrderItemRelativePath(relativePath, orderId, orderItemId);
|
||||||
|
if (safeRelativePath == null) {
|
||||||
|
throw new ResponseStatusException(NOT_FOUND, "File not available");
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
Resource resource = storageService.loadAsResource(safeRelativePath);
|
||||||
|
MediaType contentType = MediaType.APPLICATION_OCTET_STREAM;
|
||||||
|
if (item.getMimeType() != null && !item.getMimeType().isBlank()) {
|
||||||
|
try {
|
||||||
|
contentType = MediaType.parseMediaType(item.getMimeType());
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
contentType = MediaType.APPLICATION_OCTET_STREAM;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String filename = item.getOriginalFilename() != null && !item.getOriginalFilename().isBlank()
|
||||||
|
? item.getOriginalFilename()
|
||||||
|
: "order-item-" + orderItemId;
|
||||||
|
|
||||||
|
return ResponseEntity.ok()
|
||||||
|
.contentType(contentType)
|
||||||
|
.header(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.attachment()
|
||||||
|
.filename(filename, StandardCharsets.UTF_8)
|
||||||
|
.build()
|
||||||
|
.toString())
|
||||||
|
.body(resource);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new ResponseStatusException(NOT_FOUND, "File not available");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/{orderId}/documents/confirmation")
|
@GetMapping("/{orderId}/documents/confirmation")
|
||||||
public ResponseEntity<byte[]> downloadOrderConfirmation(@PathVariable UUID orderId) {
|
public ResponseEntity<byte[]> downloadOrderConfirmation(@PathVariable UUID orderId) {
|
||||||
return adminOrderControllerService.downloadOrderConfirmation(orderId);
|
return generateDocument(getOrderOrThrow(orderId), true);
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/{orderId}/documents/invoice")
|
@GetMapping("/{orderId}/documents/invoice")
|
||||||
public ResponseEntity<byte[]> downloadOrderInvoice(@PathVariable UUID orderId) {
|
public ResponseEntity<byte[]> downloadOrderInvoice(@PathVariable UUID orderId) {
|
||||||
return adminOrderControllerService.downloadOrderInvoice(orderId);
|
return generateDocument(getOrderOrThrow(orderId), false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Order getOrderOrThrow(UUID orderId) {
|
||||||
|
return orderRepo.findById(orderId)
|
||||||
|
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "Order not found"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private OrderDto toOrderDto(Order order) {
|
||||||
|
List<OrderItem> items = orderItemRepo.findByOrder_Id(order.getId());
|
||||||
|
OrderDto dto = new OrderDto();
|
||||||
|
dto.setId(order.getId());
|
||||||
|
dto.setOrderNumber(getDisplayOrderNumber(order));
|
||||||
|
dto.setStatus(order.getStatus());
|
||||||
|
|
||||||
|
paymentRepo.findByOrder_Id(order.getId()).ifPresent(p -> {
|
||||||
|
dto.setPaymentStatus(p.getStatus());
|
||||||
|
dto.setPaymentMethod(p.getMethod());
|
||||||
|
});
|
||||||
|
|
||||||
|
dto.setCustomerEmail(order.getCustomerEmail());
|
||||||
|
dto.setCustomerPhone(order.getCustomerPhone());
|
||||||
|
dto.setPreferredLanguage(order.getPreferredLanguage());
|
||||||
|
dto.setBillingCustomerType(order.getBillingCustomerType());
|
||||||
|
dto.setCurrency(order.getCurrency());
|
||||||
|
dto.setSetupCostChf(order.getSetupCostChf());
|
||||||
|
dto.setShippingCostChf(order.getShippingCostChf());
|
||||||
|
dto.setDiscountChf(order.getDiscountChf());
|
||||||
|
dto.setSubtotalChf(order.getSubtotalChf());
|
||||||
|
dto.setIsCadOrder(order.getIsCadOrder());
|
||||||
|
dto.setSourceRequestId(order.getSourceRequestId());
|
||||||
|
dto.setCadHours(order.getCadHours());
|
||||||
|
dto.setCadHourlyRateChf(order.getCadHourlyRateChf());
|
||||||
|
dto.setCadTotalChf(order.getCadTotalChf());
|
||||||
|
dto.setTotalChf(order.getTotalChf());
|
||||||
|
dto.setCreatedAt(order.getCreatedAt());
|
||||||
|
dto.setShippingSameAsBilling(order.getShippingSameAsBilling());
|
||||||
|
QuoteSession sourceSession = order.getSourceQuoteSession();
|
||||||
|
if (sourceSession != null) {
|
||||||
|
dto.setPrintMaterialCode(sourceSession.getMaterialCode());
|
||||||
|
dto.setPrintNozzleDiameterMm(sourceSession.getNozzleDiameterMm());
|
||||||
|
dto.setPrintLayerHeightMm(sourceSession.getLayerHeightMm());
|
||||||
|
dto.setPrintInfillPattern(sourceSession.getInfillPattern());
|
||||||
|
dto.setPrintInfillPercent(sourceSession.getInfillPercent());
|
||||||
|
dto.setPrintSupportsEnabled(sourceSession.getSupportsEnabled());
|
||||||
|
}
|
||||||
|
|
||||||
|
AddressDto billing = new AddressDto();
|
||||||
|
billing.setFirstName(order.getBillingFirstName());
|
||||||
|
billing.setLastName(order.getBillingLastName());
|
||||||
|
billing.setCompanyName(order.getBillingCompanyName());
|
||||||
|
billing.setContactPerson(order.getBillingContactPerson());
|
||||||
|
billing.setAddressLine1(order.getBillingAddressLine1());
|
||||||
|
billing.setAddressLine2(order.getBillingAddressLine2());
|
||||||
|
billing.setZip(order.getBillingZip());
|
||||||
|
billing.setCity(order.getBillingCity());
|
||||||
|
billing.setCountryCode(order.getBillingCountryCode());
|
||||||
|
dto.setBillingAddress(billing);
|
||||||
|
|
||||||
|
if (!Boolean.TRUE.equals(order.getShippingSameAsBilling())) {
|
||||||
|
AddressDto shipping = new AddressDto();
|
||||||
|
shipping.setFirstName(order.getShippingFirstName());
|
||||||
|
shipping.setLastName(order.getShippingLastName());
|
||||||
|
shipping.setCompanyName(order.getShippingCompanyName());
|
||||||
|
shipping.setContactPerson(order.getShippingContactPerson());
|
||||||
|
shipping.setAddressLine1(order.getShippingAddressLine1());
|
||||||
|
shipping.setAddressLine2(order.getShippingAddressLine2());
|
||||||
|
shipping.setZip(order.getShippingZip());
|
||||||
|
shipping.setCity(order.getShippingCity());
|
||||||
|
shipping.setCountryCode(order.getShippingCountryCode());
|
||||||
|
dto.setShippingAddress(shipping);
|
||||||
|
}
|
||||||
|
|
||||||
|
List<OrderItemDto> itemDtos = items.stream().map(i -> {
|
||||||
|
OrderItemDto idto = new OrderItemDto();
|
||||||
|
idto.setId(i.getId());
|
||||||
|
idto.setOriginalFilename(i.getOriginalFilename());
|
||||||
|
idto.setMaterialCode(i.getMaterialCode());
|
||||||
|
idto.setColorCode(i.getColorCode());
|
||||||
|
idto.setQuantity(i.getQuantity());
|
||||||
|
idto.setPrintTimeSeconds(i.getPrintTimeSeconds());
|
||||||
|
idto.setMaterialGrams(i.getMaterialGrams());
|
||||||
|
idto.setUnitPriceChf(i.getUnitPriceChf());
|
||||||
|
idto.setLineTotalChf(i.getLineTotalChf());
|
||||||
|
return idto;
|
||||||
|
}).toList();
|
||||||
|
dto.setItems(itemDtos);
|
||||||
|
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getDisplayOrderNumber(Order order) {
|
||||||
|
String orderNumber = order.getOrderNumber();
|
||||||
|
if (orderNumber != null && !orderNumber.isBlank()) {
|
||||||
|
return orderNumber;
|
||||||
|
}
|
||||||
|
return order.getId() != null ? order.getId().toString() : "unknown";
|
||||||
|
}
|
||||||
|
|
||||||
|
private ResponseEntity<byte[]> generateDocument(Order order, boolean isConfirmation) {
|
||||||
|
String displayOrderNumber = getDisplayOrderNumber(order);
|
||||||
|
if (isConfirmation) {
|
||||||
|
Path relativePath = buildConfirmationPdfRelativePath(order.getId(), displayOrderNumber);
|
||||||
|
try {
|
||||||
|
byte[] existingPdf = storageService.loadAsResource(relativePath).getInputStream().readAllBytes();
|
||||||
|
return ResponseEntity.ok()
|
||||||
|
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"confirmation-" + displayOrderNumber + ".pdf\"")
|
||||||
|
.contentType(MediaType.APPLICATION_PDF)
|
||||||
|
.body(existingPdf);
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
// fallback to generated confirmation document
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
List<OrderItem> items = orderItemRepo.findByOrder_Id(order.getId());
|
||||||
|
Payment payment = paymentRepo.findByOrder_Id(order.getId()).orElse(null);
|
||||||
|
byte[] pdf = invoiceService.generateDocumentPdf(order, items, isConfirmation, qrBillService, payment);
|
||||||
|
|
||||||
|
String prefix = isConfirmation ? "confirmation-" : "invoice-";
|
||||||
|
return ResponseEntity.ok()
|
||||||
|
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + prefix + displayOrderNumber + ".pdf\"")
|
||||||
|
.contentType(MediaType.APPLICATION_PDF)
|
||||||
|
.body(pdf);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Path resolveOrderItemRelativePath(String storedRelativePath, UUID orderId, UUID orderItemId) {
|
||||||
|
try {
|
||||||
|
Path candidate = Path.of(storedRelativePath).normalize();
|
||||||
|
if (candidate.isAbsolute()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
Path expectedPrefix = Path.of("orders", orderId.toString(), "3d-files", orderItemId.toString());
|
||||||
|
if (!candidate.startsWith(expectedPrefix)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return candidate;
|
||||||
|
} catch (InvalidPathException e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Resource loadOrderItemResourceWithRecovery(OrderItem item, Path safeRelativePath) {
|
||||||
|
try {
|
||||||
|
return storageService.loadAsResource(safeRelativePath);
|
||||||
|
} catch (Exception primaryFailure) {
|
||||||
|
Path sourceQuotePath = resolveFallbackQuoteItemPath(item);
|
||||||
|
if (sourceQuotePath == null) {
|
||||||
|
throw new ResponseStatusException(NOT_FOUND, "File not available");
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
storageService.store(sourceQuotePath, safeRelativePath);
|
||||||
|
return storageService.loadAsResource(safeRelativePath);
|
||||||
|
} catch (Exception copyFailure) {
|
||||||
|
try {
|
||||||
|
Resource quoteResource = new UrlResource(sourceQuotePath.toUri());
|
||||||
|
if (quoteResource.exists() || quoteResource.isReadable()) {
|
||||||
|
return quoteResource;
|
||||||
|
}
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
// fall through to 404
|
||||||
|
}
|
||||||
|
throw new ResponseStatusException(NOT_FOUND, "File not available");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Path resolveFallbackQuoteItemPath(OrderItem orderItem) {
|
||||||
|
Order order = orderItem.getOrder();
|
||||||
|
QuoteSession sourceSession = order != null ? order.getSourceQuoteSession() : null;
|
||||||
|
UUID sourceSessionId = sourceSession != null ? sourceSession.getId() : null;
|
||||||
|
if (sourceSessionId == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
String targetFilename = normalizeFilename(orderItem.getOriginalFilename());
|
||||||
|
if (targetFilename == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return quoteLineItemRepo.findByQuoteSessionId(sourceSessionId).stream()
|
||||||
|
.filter(q -> targetFilename.equals(normalizeFilename(q.getOriginalFilename())))
|
||||||
|
.sorted(Comparator.comparingInt((QuoteLineItem q) -> scoreQuoteMatch(orderItem, q)).reversed())
|
||||||
|
.map(q -> resolveStoredQuotePath(q.getStoredPath(), sourceSessionId))
|
||||||
|
.filter(path -> path != null && Files.exists(path))
|
||||||
|
.findFirst()
|
||||||
|
.orElse(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private int scoreQuoteMatch(OrderItem orderItem, QuoteLineItem quoteItem) {
|
||||||
|
int score = 0;
|
||||||
|
if (orderItem.getQuantity() != null && orderItem.getQuantity().equals(quoteItem.getQuantity())) {
|
||||||
|
score += 4;
|
||||||
|
}
|
||||||
|
if (orderItem.getPrintTimeSeconds() != null && orderItem.getPrintTimeSeconds().equals(quoteItem.getPrintTimeSeconds())) {
|
||||||
|
score += 3;
|
||||||
|
}
|
||||||
|
if (orderItem.getMaterialCode() != null
|
||||||
|
&& quoteItem.getMaterialCode() != null
|
||||||
|
&& orderItem.getMaterialCode().equalsIgnoreCase(quoteItem.getMaterialCode())) {
|
||||||
|
score += 3;
|
||||||
|
}
|
||||||
|
if (orderItem.getMaterialGrams() != null
|
||||||
|
&& quoteItem.getMaterialGrams() != null
|
||||||
|
&& orderItem.getMaterialGrams().compareTo(quoteItem.getMaterialGrams()) == 0) {
|
||||||
|
score += 2;
|
||||||
|
}
|
||||||
|
return score;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String normalizeFilename(String filename) {
|
||||||
|
if (filename == null || filename.isBlank()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return filename.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Path resolveStoredQuotePath(String storedPath, UUID expectedSessionId) {
|
||||||
|
if (storedPath == null || storedPath.isBlank()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
Path raw = Path.of(storedPath).normalize();
|
||||||
|
Path resolved = raw.isAbsolute() ? raw : QUOTE_STORAGE_ROOT.resolve(raw).normalize();
|
||||||
|
Path expectedSessionRoot = QUOTE_STORAGE_ROOT.resolve(expectedSessionId.toString()).normalize();
|
||||||
|
if (!resolved.startsWith(expectedSessionRoot)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return resolved;
|
||||||
|
} catch (InvalidPathException e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Path buildConfirmationPdfRelativePath(UUID orderId, String orderNumber) {
|
||||||
|
return Path.of("orders", orderId.toString(), "documents", "confirmation-" + orderNumber + ".pdf");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,64 +0,0 @@
|
|||||||
package com.printcalculator.controller.admin;
|
|
||||||
|
|
||||||
import com.printcalculator.dto.AdminShopCategoryDto;
|
|
||||||
import com.printcalculator.dto.AdminUpsertShopCategoryRequest;
|
|
||||||
import com.printcalculator.service.admin.AdminShopCategoryControllerService;
|
|
||||||
import org.springframework.http.ResponseEntity;
|
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
|
||||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
|
||||||
import org.springframework.web.bind.annotation.PathVariable;
|
|
||||||
import org.springframework.web.bind.annotation.PostMapping;
|
|
||||||
import org.springframework.web.bind.annotation.PutMapping;
|
|
||||||
import org.springframework.web.bind.annotation.RequestBody;
|
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
@RestController
|
|
||||||
@RequestMapping("/api/admin/shop/categories")
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public class AdminShopCategoryController {
|
|
||||||
private final AdminShopCategoryControllerService adminShopCategoryControllerService;
|
|
||||||
|
|
||||||
public AdminShopCategoryController(AdminShopCategoryControllerService adminShopCategoryControllerService) {
|
|
||||||
this.adminShopCategoryControllerService = adminShopCategoryControllerService;
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping
|
|
||||||
public ResponseEntity<List<AdminShopCategoryDto>> getCategories() {
|
|
||||||
return ResponseEntity.ok(adminShopCategoryControllerService.getCategories());
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping("/tree")
|
|
||||||
public ResponseEntity<List<AdminShopCategoryDto>> getCategoryTree() {
|
|
||||||
return ResponseEntity.ok(adminShopCategoryControllerService.getCategoryTree());
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping("/{categoryId}")
|
|
||||||
public ResponseEntity<AdminShopCategoryDto> getCategory(@PathVariable UUID categoryId) {
|
|
||||||
return ResponseEntity.ok(adminShopCategoryControllerService.getCategory(categoryId));
|
|
||||||
}
|
|
||||||
|
|
||||||
@PostMapping
|
|
||||||
@Transactional
|
|
||||||
public ResponseEntity<AdminShopCategoryDto> createCategory(@RequestBody AdminUpsertShopCategoryRequest payload) {
|
|
||||||
return ResponseEntity.ok(adminShopCategoryControllerService.createCategory(payload));
|
|
||||||
}
|
|
||||||
|
|
||||||
@PutMapping("/{categoryId}")
|
|
||||||
@Transactional
|
|
||||||
public ResponseEntity<AdminShopCategoryDto> updateCategory(@PathVariable UUID categoryId,
|
|
||||||
@RequestBody AdminUpsertShopCategoryRequest payload) {
|
|
||||||
return ResponseEntity.ok(adminShopCategoryControllerService.updateCategory(categoryId, payload));
|
|
||||||
}
|
|
||||||
|
|
||||||
@DeleteMapping("/{categoryId}")
|
|
||||||
@Transactional
|
|
||||||
public ResponseEntity<Void> deleteCategory(@PathVariable UUID categoryId) {
|
|
||||||
adminShopCategoryControllerService.deleteCategory(categoryId);
|
|
||||||
return ResponseEntity.noContent().build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,110 +0,0 @@
|
|||||||
package com.printcalculator.controller.admin;
|
|
||||||
|
|
||||||
import com.printcalculator.dto.AdminShopProductDto;
|
|
||||||
import com.printcalculator.dto.AdminTranslateShopProductRequest;
|
|
||||||
import com.printcalculator.dto.AdminTranslateShopProductResponse;
|
|
||||||
import com.printcalculator.dto.AdminUpsertShopProductRequest;
|
|
||||||
import com.printcalculator.service.admin.AdminShopProductControllerService;
|
|
||||||
import com.printcalculator.service.admin.AdminShopProductTranslationService;
|
|
||||||
import org.springframework.core.io.Resource;
|
|
||||||
import org.springframework.core.io.UrlResource;
|
|
||||||
import org.springframework.http.HttpHeaders;
|
|
||||||
import org.springframework.http.MediaType;
|
|
||||||
import org.springframework.http.ResponseEntity;
|
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
|
||||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
|
||||||
import org.springframework.web.bind.annotation.PathVariable;
|
|
||||||
import org.springframework.web.bind.annotation.PostMapping;
|
|
||||||
import org.springframework.web.bind.annotation.PutMapping;
|
|
||||||
import org.springframework.web.bind.annotation.RequestBody;
|
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
|
||||||
import org.springframework.web.bind.annotation.RequestParam;
|
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
|
||||||
import org.springframework.web.multipart.MultipartFile;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
@RestController
|
|
||||||
@RequestMapping("/api/admin/shop/products")
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public class AdminShopProductController {
|
|
||||||
private final AdminShopProductControllerService adminShopProductControllerService;
|
|
||||||
private final AdminShopProductTranslationService adminShopProductTranslationService;
|
|
||||||
|
|
||||||
public AdminShopProductController(AdminShopProductControllerService adminShopProductControllerService,
|
|
||||||
AdminShopProductTranslationService adminShopProductTranslationService) {
|
|
||||||
this.adminShopProductControllerService = adminShopProductControllerService;
|
|
||||||
this.adminShopProductTranslationService = adminShopProductTranslationService;
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping
|
|
||||||
public ResponseEntity<List<AdminShopProductDto>> getProducts() {
|
|
||||||
return ResponseEntity.ok(adminShopProductControllerService.getProducts());
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping("/{productId}")
|
|
||||||
public ResponseEntity<AdminShopProductDto> getProduct(@PathVariable UUID productId) {
|
|
||||||
return ResponseEntity.ok(adminShopProductControllerService.getProduct(productId));
|
|
||||||
}
|
|
||||||
|
|
||||||
@PostMapping
|
|
||||||
@Transactional
|
|
||||||
public ResponseEntity<AdminShopProductDto> createProduct(@RequestBody AdminUpsertShopProductRequest payload) {
|
|
||||||
return ResponseEntity.ok(adminShopProductControllerService.createProduct(payload));
|
|
||||||
}
|
|
||||||
|
|
||||||
@PostMapping("/translate")
|
|
||||||
public ResponseEntity<AdminTranslateShopProductResponse> translateProduct(@RequestBody AdminTranslateShopProductRequest payload) {
|
|
||||||
return ResponseEntity.ok(adminShopProductTranslationService.translateProduct(payload));
|
|
||||||
}
|
|
||||||
|
|
||||||
@PutMapping("/{productId}")
|
|
||||||
@Transactional
|
|
||||||
public ResponseEntity<AdminShopProductDto> updateProduct(@PathVariable UUID productId,
|
|
||||||
@RequestBody AdminUpsertShopProductRequest payload) {
|
|
||||||
return ResponseEntity.ok(adminShopProductControllerService.updateProduct(productId, payload));
|
|
||||||
}
|
|
||||||
|
|
||||||
@DeleteMapping("/{productId}")
|
|
||||||
@Transactional
|
|
||||||
public ResponseEntity<Void> deleteProduct(@PathVariable UUID productId) {
|
|
||||||
adminShopProductControllerService.deleteProduct(productId);
|
|
||||||
return ResponseEntity.noContent().build();
|
|
||||||
}
|
|
||||||
|
|
||||||
@PostMapping("/{productId}/model")
|
|
||||||
@Transactional
|
|
||||||
public ResponseEntity<AdminShopProductDto> uploadProductModel(@PathVariable UUID productId,
|
|
||||||
@RequestParam("file") MultipartFile file) throws IOException {
|
|
||||||
return ResponseEntity.ok(adminShopProductControllerService.uploadProductModel(productId, file));
|
|
||||||
}
|
|
||||||
|
|
||||||
@DeleteMapping("/{productId}/model")
|
|
||||||
@Transactional
|
|
||||||
public ResponseEntity<Void> deleteProductModel(@PathVariable UUID productId) {
|
|
||||||
adminShopProductControllerService.deleteProductModel(productId);
|
|
||||||
return ResponseEntity.noContent().build();
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping("/{productId}/model")
|
|
||||||
public ResponseEntity<Resource> getProductModel(@PathVariable UUID productId) throws IOException {
|
|
||||||
AdminShopProductControllerService.ProductModelDownload model = adminShopProductControllerService.getProductModel(productId);
|
|
||||||
Resource resource = new UrlResource(model.path().toUri());
|
|
||||||
MediaType contentType = MediaType.APPLICATION_OCTET_STREAM;
|
|
||||||
if (model.mimeType() != null && !model.mimeType().isBlank()) {
|
|
||||||
try {
|
|
||||||
contentType = MediaType.parseMediaType(model.mimeType());
|
|
||||||
} catch (IllegalArgumentException ignored) {
|
|
||||||
contentType = MediaType.APPLICATION_OCTET_STREAM;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return ResponseEntity.ok()
|
|
||||||
.contentType(contentType)
|
|
||||||
.header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + model.filename() + "\"")
|
|
||||||
.body(resource);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,79 +0,0 @@
|
|||||||
package com.printcalculator.dto;
|
|
||||||
|
|
||||||
import java.util.UUID;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
public class AdminCreateMediaUsageRequest {
|
|
||||||
private String usageType;
|
|
||||||
private String usageKey;
|
|
||||||
private UUID ownerId;
|
|
||||||
private UUID mediaAssetId;
|
|
||||||
private Integer sortOrder;
|
|
||||||
private Boolean isPrimary;
|
|
||||||
private Boolean isActive;
|
|
||||||
private Map<String, MediaTextTranslationDto> translations;
|
|
||||||
|
|
||||||
public String getUsageType() {
|
|
||||||
return usageType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setUsageType(String usageType) {
|
|
||||||
this.usageType = usageType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getUsageKey() {
|
|
||||||
return usageKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setUsageKey(String usageKey) {
|
|
||||||
this.usageKey = usageKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
public UUID getOwnerId() {
|
|
||||||
return ownerId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setOwnerId(UUID ownerId) {
|
|
||||||
this.ownerId = ownerId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public UUID getMediaAssetId() {
|
|
||||||
return mediaAssetId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setMediaAssetId(UUID mediaAssetId) {
|
|
||||||
this.mediaAssetId = mediaAssetId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getSortOrder() {
|
|
||||||
return sortOrder;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSortOrder(Integer sortOrder) {
|
|
||||||
this.sortOrder = sortOrder;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getIsPrimary() {
|
|
||||||
return isPrimary;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIsPrimary(Boolean primary) {
|
|
||||||
isPrimary = primary;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getIsActive() {
|
|
||||||
return isActive;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIsActive(Boolean active) {
|
|
||||||
isActive = active;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<String, MediaTextTranslationDto> getTranslations() {
|
|
||||||
return translations;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTranslations(Map<String, MediaTextTranslationDto> translations) {
|
|
||||||
this.translations = translations;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -12,10 +12,6 @@ public class AdminFilamentVariantDto {
|
|||||||
private String materialTechnicalTypeLabel;
|
private String materialTechnicalTypeLabel;
|
||||||
private String variantDisplayName;
|
private String variantDisplayName;
|
||||||
private String colorName;
|
private String colorName;
|
||||||
private String colorLabelIt;
|
|
||||||
private String colorLabelEn;
|
|
||||||
private String colorLabelDe;
|
|
||||||
private String colorLabelFr;
|
|
||||||
private String colorHex;
|
private String colorHex;
|
||||||
private String finishType;
|
private String finishType;
|
||||||
private String brand;
|
private String brand;
|
||||||
@@ -93,38 +89,6 @@ public class AdminFilamentVariantDto {
|
|||||||
this.colorName = colorName;
|
this.colorName = colorName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getColorLabelIt() {
|
|
||||||
return colorLabelIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setColorLabelIt(String colorLabelIt) {
|
|
||||||
this.colorLabelIt = colorLabelIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getColorLabelEn() {
|
|
||||||
return colorLabelEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setColorLabelEn(String colorLabelEn) {
|
|
||||||
this.colorLabelEn = colorLabelEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getColorLabelDe() {
|
|
||||||
return colorLabelDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setColorLabelDe(String colorLabelDe) {
|
|
||||||
this.colorLabelDe = colorLabelDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getColorLabelFr() {
|
|
||||||
return colorLabelFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setColorLabelFr(String colorLabelFr) {
|
|
||||||
this.colorLabelFr = colorLabelFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getColorHex() {
|
public String getColorHex() {
|
||||||
return colorHex;
|
return colorHex;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,153 +0,0 @@
|
|||||||
package com.printcalculator.dto;
|
|
||||||
|
|
||||||
import java.time.OffsetDateTime;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
public class AdminMediaAssetDto {
|
|
||||||
private UUID id;
|
|
||||||
private String originalFilename;
|
|
||||||
private String storageKey;
|
|
||||||
private String mimeType;
|
|
||||||
private Long fileSizeBytes;
|
|
||||||
private String sha256Hex;
|
|
||||||
private Integer widthPx;
|
|
||||||
private Integer heightPx;
|
|
||||||
private String status;
|
|
||||||
private String visibility;
|
|
||||||
private String title;
|
|
||||||
private String altText;
|
|
||||||
private OffsetDateTime createdAt;
|
|
||||||
private OffsetDateTime updatedAt;
|
|
||||||
private List<AdminMediaVariantDto> variants = new ArrayList<>();
|
|
||||||
private List<AdminMediaUsageDto> usages = new ArrayList<>();
|
|
||||||
|
|
||||||
public UUID getId() {
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setId(UUID id) {
|
|
||||||
this.id = id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getOriginalFilename() {
|
|
||||||
return originalFilename;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setOriginalFilename(String originalFilename) {
|
|
||||||
this.originalFilename = originalFilename;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getStorageKey() {
|
|
||||||
return storageKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setStorageKey(String storageKey) {
|
|
||||||
this.storageKey = storageKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getMimeType() {
|
|
||||||
return mimeType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setMimeType(String mimeType) {
|
|
||||||
this.mimeType = mimeType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Long getFileSizeBytes() {
|
|
||||||
return fileSizeBytes;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setFileSizeBytes(Long fileSizeBytes) {
|
|
||||||
this.fileSizeBytes = fileSizeBytes;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSha256Hex() {
|
|
||||||
return sha256Hex;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSha256Hex(String sha256Hex) {
|
|
||||||
this.sha256Hex = sha256Hex;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getWidthPx() {
|
|
||||||
return widthPx;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setWidthPx(Integer widthPx) {
|
|
||||||
this.widthPx = widthPx;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getHeightPx() {
|
|
||||||
return heightPx;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setHeightPx(Integer heightPx) {
|
|
||||||
this.heightPx = heightPx;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getStatus() {
|
|
||||||
return status;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setStatus(String status) {
|
|
||||||
this.status = status;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getVisibility() {
|
|
||||||
return visibility;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setVisibility(String visibility) {
|
|
||||||
this.visibility = visibility;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getTitle() {
|
|
||||||
return title;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTitle(String title) {
|
|
||||||
this.title = title;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getAltText() {
|
|
||||||
return altText;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAltText(String altText) {
|
|
||||||
this.altText = altText;
|
|
||||||
}
|
|
||||||
|
|
||||||
public OffsetDateTime getCreatedAt() {
|
|
||||||
return createdAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCreatedAt(OffsetDateTime createdAt) {
|
|
||||||
this.createdAt = createdAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public OffsetDateTime getUpdatedAt() {
|
|
||||||
return updatedAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setUpdatedAt(OffsetDateTime updatedAt) {
|
|
||||||
this.updatedAt = updatedAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<AdminMediaVariantDto> getVariants() {
|
|
||||||
return variants;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setVariants(List<AdminMediaVariantDto> variants) {
|
|
||||||
this.variants = variants;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<AdminMediaUsageDto> getUsages() {
|
|
||||||
return usages;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setUsages(List<AdminMediaUsageDto> usages) {
|
|
||||||
this.usages = usages;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
package com.printcalculator.dto;
|
|
||||||
|
|
||||||
import java.time.OffsetDateTime;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
public class AdminMediaUsageDto {
|
|
||||||
private UUID id;
|
|
||||||
private String usageType;
|
|
||||||
private String usageKey;
|
|
||||||
private UUID ownerId;
|
|
||||||
private UUID mediaAssetId;
|
|
||||||
private Integer sortOrder;
|
|
||||||
private Boolean isPrimary;
|
|
||||||
private Boolean isActive;
|
|
||||||
private Map<String, MediaTextTranslationDto> translations;
|
|
||||||
private OffsetDateTime createdAt;
|
|
||||||
|
|
||||||
public UUID getId() {
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setId(UUID id) {
|
|
||||||
this.id = id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getUsageType() {
|
|
||||||
return usageType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setUsageType(String usageType) {
|
|
||||||
this.usageType = usageType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getUsageKey() {
|
|
||||||
return usageKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setUsageKey(String usageKey) {
|
|
||||||
this.usageKey = usageKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
public UUID getOwnerId() {
|
|
||||||
return ownerId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setOwnerId(UUID ownerId) {
|
|
||||||
this.ownerId = ownerId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public UUID getMediaAssetId() {
|
|
||||||
return mediaAssetId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setMediaAssetId(UUID mediaAssetId) {
|
|
||||||
this.mediaAssetId = mediaAssetId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getSortOrder() {
|
|
||||||
return sortOrder;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSortOrder(Integer sortOrder) {
|
|
||||||
this.sortOrder = sortOrder;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getIsPrimary() {
|
|
||||||
return isPrimary;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIsPrimary(Boolean primary) {
|
|
||||||
isPrimary = primary;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getIsActive() {
|
|
||||||
return isActive;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIsActive(Boolean active) {
|
|
||||||
isActive = active;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<String, MediaTextTranslationDto> getTranslations() {
|
|
||||||
return translations;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTranslations(Map<String, MediaTextTranslationDto> translations) {
|
|
||||||
this.translations = translations;
|
|
||||||
}
|
|
||||||
|
|
||||||
public OffsetDateTime getCreatedAt() {
|
|
||||||
return createdAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCreatedAt(OffsetDateTime createdAt) {
|
|
||||||
this.createdAt = createdAt;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,106 +0,0 @@
|
|||||||
package com.printcalculator.dto;
|
|
||||||
|
|
||||||
import java.time.OffsetDateTime;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
public class AdminMediaVariantDto {
|
|
||||||
private UUID id;
|
|
||||||
private String variantName;
|
|
||||||
private String format;
|
|
||||||
private String storageKey;
|
|
||||||
private String mimeType;
|
|
||||||
private Integer widthPx;
|
|
||||||
private Integer heightPx;
|
|
||||||
private Long fileSizeBytes;
|
|
||||||
private Boolean isGenerated;
|
|
||||||
private String publicUrl;
|
|
||||||
private OffsetDateTime createdAt;
|
|
||||||
|
|
||||||
public UUID getId() {
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setId(UUID id) {
|
|
||||||
this.id = id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getVariantName() {
|
|
||||||
return variantName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setVariantName(String variantName) {
|
|
||||||
this.variantName = variantName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getFormat() {
|
|
||||||
return format;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setFormat(String format) {
|
|
||||||
this.format = format;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getStorageKey() {
|
|
||||||
return storageKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setStorageKey(String storageKey) {
|
|
||||||
this.storageKey = storageKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getMimeType() {
|
|
||||||
return mimeType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setMimeType(String mimeType) {
|
|
||||||
this.mimeType = mimeType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getWidthPx() {
|
|
||||||
return widthPx;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setWidthPx(Integer widthPx) {
|
|
||||||
this.widthPx = widthPx;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getHeightPx() {
|
|
||||||
return heightPx;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setHeightPx(Integer heightPx) {
|
|
||||||
this.heightPx = heightPx;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Long getFileSizeBytes() {
|
|
||||||
return fileSizeBytes;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setFileSizeBytes(Long fileSizeBytes) {
|
|
||||||
this.fileSizeBytes = fileSizeBytes;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getIsGenerated() {
|
|
||||||
return isGenerated;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIsGenerated(Boolean generated) {
|
|
||||||
isGenerated = generated;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getPublicUrl() {
|
|
||||||
return publicUrl;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setPublicUrl(String publicUrl) {
|
|
||||||
this.publicUrl = publicUrl;
|
|
||||||
}
|
|
||||||
|
|
||||||
public OffsetDateTime getCreatedAt() {
|
|
||||||
return createdAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCreatedAt(OffsetDateTime createdAt) {
|
|
||||||
this.createdAt = createdAt;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -7,7 +7,6 @@ import java.util.UUID;
|
|||||||
public class AdminQuoteSessionDto {
|
public class AdminQuoteSessionDto {
|
||||||
private UUID id;
|
private UUID id;
|
||||||
private String status;
|
private String status;
|
||||||
private String sessionType;
|
|
||||||
private String materialCode;
|
private String materialCode;
|
||||||
private OffsetDateTime createdAt;
|
private OffsetDateTime createdAt;
|
||||||
private OffsetDateTime expiresAt;
|
private OffsetDateTime expiresAt;
|
||||||
@@ -33,14 +32,6 @@ public class AdminQuoteSessionDto {
|
|||||||
this.status = status;
|
this.status = status;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getSessionType() {
|
|
||||||
return sessionType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSessionType(String sessionType) {
|
|
||||||
this.sessionType = sessionType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getMaterialCode() {
|
public String getMaterialCode() {
|
||||||
return materialCode;
|
return materialCode;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,359 +0,0 @@
|
|||||||
package com.printcalculator.dto;
|
|
||||||
|
|
||||||
import java.time.OffsetDateTime;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
public class AdminShopCategoryDto {
|
|
||||||
private UUID id;
|
|
||||||
private UUID parentCategoryId;
|
|
||||||
private String parentCategoryName;
|
|
||||||
private String slug;
|
|
||||||
private String name;
|
|
||||||
private String nameIt;
|
|
||||||
private String nameEn;
|
|
||||||
private String nameDe;
|
|
||||||
private String nameFr;
|
|
||||||
private String description;
|
|
||||||
private String descriptionIt;
|
|
||||||
private String descriptionEn;
|
|
||||||
private String descriptionDe;
|
|
||||||
private String descriptionFr;
|
|
||||||
private String seoTitle;
|
|
||||||
private String seoTitleIt;
|
|
||||||
private String seoTitleEn;
|
|
||||||
private String seoTitleDe;
|
|
||||||
private String seoTitleFr;
|
|
||||||
private String seoDescription;
|
|
||||||
private String seoDescriptionIt;
|
|
||||||
private String seoDescriptionEn;
|
|
||||||
private String seoDescriptionDe;
|
|
||||||
private String seoDescriptionFr;
|
|
||||||
private String ogTitle;
|
|
||||||
private String ogDescription;
|
|
||||||
private Boolean indexable;
|
|
||||||
private Boolean isActive;
|
|
||||||
private Integer sortOrder;
|
|
||||||
private Integer depth;
|
|
||||||
private Integer childCount;
|
|
||||||
private Integer directProductCount;
|
|
||||||
private Integer descendantProductCount;
|
|
||||||
private String mediaUsageType;
|
|
||||||
private String mediaUsageKey;
|
|
||||||
private List<AdminShopCategoryRefDto> breadcrumbs;
|
|
||||||
private List<AdminShopCategoryDto> children;
|
|
||||||
private OffsetDateTime createdAt;
|
|
||||||
private OffsetDateTime updatedAt;
|
|
||||||
|
|
||||||
public UUID getId() {
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setId(UUID id) {
|
|
||||||
this.id = id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public UUID getParentCategoryId() {
|
|
||||||
return parentCategoryId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setParentCategoryId(UUID parentCategoryId) {
|
|
||||||
this.parentCategoryId = parentCategoryId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getParentCategoryName() {
|
|
||||||
return parentCategoryName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setParentCategoryName(String parentCategoryName) {
|
|
||||||
this.parentCategoryName = parentCategoryName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSlug() {
|
|
||||||
return slug;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSlug(String slug) {
|
|
||||||
this.slug = slug;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getName() {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setName(String name) {
|
|
||||||
this.name = name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getNameIt() {
|
|
||||||
return nameIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setNameIt(String nameIt) {
|
|
||||||
this.nameIt = nameIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getNameEn() {
|
|
||||||
return nameEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setNameEn(String nameEn) {
|
|
||||||
this.nameEn = nameEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getNameDe() {
|
|
||||||
return nameDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setNameDe(String nameDe) {
|
|
||||||
this.nameDe = nameDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getNameFr() {
|
|
||||||
return nameFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setNameFr(String nameFr) {
|
|
||||||
this.nameFr = nameFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescription() {
|
|
||||||
return description;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescription(String description) {
|
|
||||||
this.description = description;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescriptionIt() {
|
|
||||||
return descriptionIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescriptionIt(String descriptionIt) {
|
|
||||||
this.descriptionIt = descriptionIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescriptionEn() {
|
|
||||||
return descriptionEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescriptionEn(String descriptionEn) {
|
|
||||||
this.descriptionEn = descriptionEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescriptionDe() {
|
|
||||||
return descriptionDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescriptionDe(String descriptionDe) {
|
|
||||||
this.descriptionDe = descriptionDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescriptionFr() {
|
|
||||||
return descriptionFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescriptionFr(String descriptionFr) {
|
|
||||||
this.descriptionFr = descriptionFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoTitle() {
|
|
||||||
return seoTitle;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitle(String seoTitle) {
|
|
||||||
this.seoTitle = seoTitle;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoTitleIt() {
|
|
||||||
return seoTitleIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitleIt(String seoTitleIt) {
|
|
||||||
this.seoTitleIt = seoTitleIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoTitleEn() {
|
|
||||||
return seoTitleEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitleEn(String seoTitleEn) {
|
|
||||||
this.seoTitleEn = seoTitleEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoTitleDe() {
|
|
||||||
return seoTitleDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitleDe(String seoTitleDe) {
|
|
||||||
this.seoTitleDe = seoTitleDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoTitleFr() {
|
|
||||||
return seoTitleFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitleFr(String seoTitleFr) {
|
|
||||||
this.seoTitleFr = seoTitleFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoDescription() {
|
|
||||||
return seoDescription;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescription(String seoDescription) {
|
|
||||||
this.seoDescription = seoDescription;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoDescriptionIt() {
|
|
||||||
return seoDescriptionIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescriptionIt(String seoDescriptionIt) {
|
|
||||||
this.seoDescriptionIt = seoDescriptionIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoDescriptionEn() {
|
|
||||||
return seoDescriptionEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescriptionEn(String seoDescriptionEn) {
|
|
||||||
this.seoDescriptionEn = seoDescriptionEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoDescriptionDe() {
|
|
||||||
return seoDescriptionDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescriptionDe(String seoDescriptionDe) {
|
|
||||||
this.seoDescriptionDe = seoDescriptionDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoDescriptionFr() {
|
|
||||||
return seoDescriptionFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescriptionFr(String seoDescriptionFr) {
|
|
||||||
this.seoDescriptionFr = seoDescriptionFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getOgTitle() {
|
|
||||||
return ogTitle;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setOgTitle(String ogTitle) {
|
|
||||||
this.ogTitle = ogTitle;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getOgDescription() {
|
|
||||||
return ogDescription;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setOgDescription(String ogDescription) {
|
|
||||||
this.ogDescription = ogDescription;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getIndexable() {
|
|
||||||
return indexable;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIndexable(Boolean indexable) {
|
|
||||||
this.indexable = indexable;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getIsActive() {
|
|
||||||
return isActive;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIsActive(Boolean active) {
|
|
||||||
isActive = active;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getSortOrder() {
|
|
||||||
return sortOrder;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSortOrder(Integer sortOrder) {
|
|
||||||
this.sortOrder = sortOrder;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getDepth() {
|
|
||||||
return depth;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDepth(Integer depth) {
|
|
||||||
this.depth = depth;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getChildCount() {
|
|
||||||
return childCount;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setChildCount(Integer childCount) {
|
|
||||||
this.childCount = childCount;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getDirectProductCount() {
|
|
||||||
return directProductCount;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDirectProductCount(Integer directProductCount) {
|
|
||||||
this.directProductCount = directProductCount;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getDescendantProductCount() {
|
|
||||||
return descendantProductCount;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescendantProductCount(Integer descendantProductCount) {
|
|
||||||
this.descendantProductCount = descendantProductCount;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getMediaUsageType() {
|
|
||||||
return mediaUsageType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setMediaUsageType(String mediaUsageType) {
|
|
||||||
this.mediaUsageType = mediaUsageType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getMediaUsageKey() {
|
|
||||||
return mediaUsageKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setMediaUsageKey(String mediaUsageKey) {
|
|
||||||
this.mediaUsageKey = mediaUsageKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<AdminShopCategoryRefDto> getBreadcrumbs() {
|
|
||||||
return breadcrumbs;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setBreadcrumbs(List<AdminShopCategoryRefDto> breadcrumbs) {
|
|
||||||
this.breadcrumbs = breadcrumbs;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<AdminShopCategoryDto> getChildren() {
|
|
||||||
return children;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setChildren(List<AdminShopCategoryDto> children) {
|
|
||||||
this.children = children;
|
|
||||||
}
|
|
||||||
|
|
||||||
public OffsetDateTime getCreatedAt() {
|
|
||||||
return createdAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCreatedAt(OffsetDateTime createdAt) {
|
|
||||||
this.createdAt = createdAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public OffsetDateTime getUpdatedAt() {
|
|
||||||
return updatedAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setUpdatedAt(OffsetDateTime updatedAt) {
|
|
||||||
this.updatedAt = updatedAt;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
package com.printcalculator.dto;
|
|
||||||
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
public class AdminShopCategoryRefDto {
|
|
||||||
private UUID id;
|
|
||||||
private String slug;
|
|
||||||
private String name;
|
|
||||||
|
|
||||||
public UUID getId() {
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setId(UUID id) {
|
|
||||||
this.id = id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSlug() {
|
|
||||||
return slug;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSlug(String slug) {
|
|
||||||
this.slug = slug;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getName() {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setName(String name) {
|
|
||||||
this.name = name;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,441 +0,0 @@
|
|||||||
package com.printcalculator.dto;
|
|
||||||
|
|
||||||
import java.math.BigDecimal;
|
|
||||||
import java.time.OffsetDateTime;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
public class AdminShopProductDto {
|
|
||||||
private UUID id;
|
|
||||||
private UUID categoryId;
|
|
||||||
private String categoryName;
|
|
||||||
private String categorySlug;
|
|
||||||
private String slug;
|
|
||||||
private String name;
|
|
||||||
private String nameIt;
|
|
||||||
private String nameEn;
|
|
||||||
private String nameDe;
|
|
||||||
private String nameFr;
|
|
||||||
private String excerpt;
|
|
||||||
private String excerptIt;
|
|
||||||
private String excerptEn;
|
|
||||||
private String excerptDe;
|
|
||||||
private String excerptFr;
|
|
||||||
private String description;
|
|
||||||
private String descriptionIt;
|
|
||||||
private String descriptionEn;
|
|
||||||
private String descriptionDe;
|
|
||||||
private String descriptionFr;
|
|
||||||
private String seoTitle;
|
|
||||||
private String seoTitleIt;
|
|
||||||
private String seoTitleEn;
|
|
||||||
private String seoTitleDe;
|
|
||||||
private String seoTitleFr;
|
|
||||||
private String seoDescription;
|
|
||||||
private String seoDescriptionIt;
|
|
||||||
private String seoDescriptionEn;
|
|
||||||
private String seoDescriptionDe;
|
|
||||||
private String seoDescriptionFr;
|
|
||||||
private String ogTitle;
|
|
||||||
private String ogDescription;
|
|
||||||
private Boolean indexable;
|
|
||||||
private Boolean isFeatured;
|
|
||||||
private Boolean isActive;
|
|
||||||
private Integer sortOrder;
|
|
||||||
private Integer variantCount;
|
|
||||||
private Integer activeVariantCount;
|
|
||||||
private BigDecimal priceFromChf;
|
|
||||||
private BigDecimal priceToChf;
|
|
||||||
private String mediaUsageType;
|
|
||||||
private String mediaUsageKey;
|
|
||||||
private List<AdminMediaUsageDto> mediaUsages;
|
|
||||||
private List<PublicMediaUsageDto> images;
|
|
||||||
private ShopProductModelDto model3d;
|
|
||||||
private List<AdminShopProductVariantDto> variants;
|
|
||||||
private OffsetDateTime createdAt;
|
|
||||||
private OffsetDateTime updatedAt;
|
|
||||||
|
|
||||||
public UUID getId() {
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setId(UUID id) {
|
|
||||||
this.id = id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public UUID getCategoryId() {
|
|
||||||
return categoryId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCategoryId(UUID categoryId) {
|
|
||||||
this.categoryId = categoryId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getCategoryName() {
|
|
||||||
return categoryName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCategoryName(String categoryName) {
|
|
||||||
this.categoryName = categoryName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getCategorySlug() {
|
|
||||||
return categorySlug;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCategorySlug(String categorySlug) {
|
|
||||||
this.categorySlug = categorySlug;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSlug() {
|
|
||||||
return slug;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSlug(String slug) {
|
|
||||||
this.slug = slug;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getName() {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setName(String name) {
|
|
||||||
this.name = name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getNameIt() {
|
|
||||||
return nameIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setNameIt(String nameIt) {
|
|
||||||
this.nameIt = nameIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getNameEn() {
|
|
||||||
return nameEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setNameEn(String nameEn) {
|
|
||||||
this.nameEn = nameEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getNameDe() {
|
|
||||||
return nameDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setNameDe(String nameDe) {
|
|
||||||
this.nameDe = nameDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getNameFr() {
|
|
||||||
return nameFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setNameFr(String nameFr) {
|
|
||||||
this.nameFr = nameFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getExcerpt() {
|
|
||||||
return excerpt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setExcerpt(String excerpt) {
|
|
||||||
this.excerpt = excerpt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getExcerptIt() {
|
|
||||||
return excerptIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setExcerptIt(String excerptIt) {
|
|
||||||
this.excerptIt = excerptIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getExcerptEn() {
|
|
||||||
return excerptEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setExcerptEn(String excerptEn) {
|
|
||||||
this.excerptEn = excerptEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getExcerptDe() {
|
|
||||||
return excerptDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setExcerptDe(String excerptDe) {
|
|
||||||
this.excerptDe = excerptDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getExcerptFr() {
|
|
||||||
return excerptFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setExcerptFr(String excerptFr) {
|
|
||||||
this.excerptFr = excerptFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescription() {
|
|
||||||
return description;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescription(String description) {
|
|
||||||
this.description = description;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescriptionIt() {
|
|
||||||
return descriptionIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescriptionIt(String descriptionIt) {
|
|
||||||
this.descriptionIt = descriptionIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescriptionEn() {
|
|
||||||
return descriptionEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescriptionEn(String descriptionEn) {
|
|
||||||
this.descriptionEn = descriptionEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescriptionDe() {
|
|
||||||
return descriptionDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescriptionDe(String descriptionDe) {
|
|
||||||
this.descriptionDe = descriptionDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescriptionFr() {
|
|
||||||
return descriptionFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescriptionFr(String descriptionFr) {
|
|
||||||
this.descriptionFr = descriptionFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoTitle() {
|
|
||||||
return seoTitle;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitle(String seoTitle) {
|
|
||||||
this.seoTitle = seoTitle;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoTitleIt() {
|
|
||||||
return seoTitleIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitleIt(String seoTitleIt) {
|
|
||||||
this.seoTitleIt = seoTitleIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoTitleEn() {
|
|
||||||
return seoTitleEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitleEn(String seoTitleEn) {
|
|
||||||
this.seoTitleEn = seoTitleEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoTitleDe() {
|
|
||||||
return seoTitleDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitleDe(String seoTitleDe) {
|
|
||||||
this.seoTitleDe = seoTitleDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoTitleFr() {
|
|
||||||
return seoTitleFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitleFr(String seoTitleFr) {
|
|
||||||
this.seoTitleFr = seoTitleFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoDescription() {
|
|
||||||
return seoDescription;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescription(String seoDescription) {
|
|
||||||
this.seoDescription = seoDescription;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoDescriptionIt() {
|
|
||||||
return seoDescriptionIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescriptionIt(String seoDescriptionIt) {
|
|
||||||
this.seoDescriptionIt = seoDescriptionIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoDescriptionEn() {
|
|
||||||
return seoDescriptionEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescriptionEn(String seoDescriptionEn) {
|
|
||||||
this.seoDescriptionEn = seoDescriptionEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoDescriptionDe() {
|
|
||||||
return seoDescriptionDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescriptionDe(String seoDescriptionDe) {
|
|
||||||
this.seoDescriptionDe = seoDescriptionDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoDescriptionFr() {
|
|
||||||
return seoDescriptionFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescriptionFr(String seoDescriptionFr) {
|
|
||||||
this.seoDescriptionFr = seoDescriptionFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getOgTitle() {
|
|
||||||
return ogTitle;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setOgTitle(String ogTitle) {
|
|
||||||
this.ogTitle = ogTitle;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getOgDescription() {
|
|
||||||
return ogDescription;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setOgDescription(String ogDescription) {
|
|
||||||
this.ogDescription = ogDescription;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getIndexable() {
|
|
||||||
return indexable;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIndexable(Boolean indexable) {
|
|
||||||
this.indexable = indexable;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getIsFeatured() {
|
|
||||||
return isFeatured;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIsFeatured(Boolean featured) {
|
|
||||||
isFeatured = featured;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getIsActive() {
|
|
||||||
return isActive;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIsActive(Boolean active) {
|
|
||||||
isActive = active;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getSortOrder() {
|
|
||||||
return sortOrder;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSortOrder(Integer sortOrder) {
|
|
||||||
this.sortOrder = sortOrder;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getVariantCount() {
|
|
||||||
return variantCount;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setVariantCount(Integer variantCount) {
|
|
||||||
this.variantCount = variantCount;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getActiveVariantCount() {
|
|
||||||
return activeVariantCount;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setActiveVariantCount(Integer activeVariantCount) {
|
|
||||||
this.activeVariantCount = activeVariantCount;
|
|
||||||
}
|
|
||||||
|
|
||||||
public BigDecimal getPriceFromChf() {
|
|
||||||
return priceFromChf;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setPriceFromChf(BigDecimal priceFromChf) {
|
|
||||||
this.priceFromChf = priceFromChf;
|
|
||||||
}
|
|
||||||
|
|
||||||
public BigDecimal getPriceToChf() {
|
|
||||||
return priceToChf;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setPriceToChf(BigDecimal priceToChf) {
|
|
||||||
this.priceToChf = priceToChf;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getMediaUsageType() {
|
|
||||||
return mediaUsageType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setMediaUsageType(String mediaUsageType) {
|
|
||||||
this.mediaUsageType = mediaUsageType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getMediaUsageKey() {
|
|
||||||
return mediaUsageKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setMediaUsageKey(String mediaUsageKey) {
|
|
||||||
this.mediaUsageKey = mediaUsageKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<AdminMediaUsageDto> getMediaUsages() {
|
|
||||||
return mediaUsages;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setMediaUsages(List<AdminMediaUsageDto> mediaUsages) {
|
|
||||||
this.mediaUsages = mediaUsages;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<PublicMediaUsageDto> getImages() {
|
|
||||||
return images;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setImages(List<PublicMediaUsageDto> images) {
|
|
||||||
this.images = images;
|
|
||||||
}
|
|
||||||
|
|
||||||
public ShopProductModelDto getModel3d() {
|
|
||||||
return model3d;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setModel3d(ShopProductModelDto model3d) {
|
|
||||||
this.model3d = model3d;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<AdminShopProductVariantDto> getVariants() {
|
|
||||||
return variants;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setVariants(List<AdminShopProductVariantDto> variants) {
|
|
||||||
this.variants = variants;
|
|
||||||
}
|
|
||||||
|
|
||||||
public OffsetDateTime getCreatedAt() {
|
|
||||||
return createdAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCreatedAt(OffsetDateTime createdAt) {
|
|
||||||
this.createdAt = createdAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public OffsetDateTime getUpdatedAt() {
|
|
||||||
return updatedAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setUpdatedAt(OffsetDateTime updatedAt) {
|
|
||||||
this.updatedAt = updatedAt;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,152 +0,0 @@
|
|||||||
package com.printcalculator.dto;
|
|
||||||
|
|
||||||
import java.math.BigDecimal;
|
|
||||||
import java.time.OffsetDateTime;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
public class AdminShopProductVariantDto {
|
|
||||||
private UUID id;
|
|
||||||
private String sku;
|
|
||||||
private String variantLabel;
|
|
||||||
private String colorName;
|
|
||||||
private String colorLabelIt;
|
|
||||||
private String colorLabelEn;
|
|
||||||
private String colorLabelDe;
|
|
||||||
private String colorLabelFr;
|
|
||||||
private String colorHex;
|
|
||||||
private String internalMaterialCode;
|
|
||||||
private BigDecimal priceChf;
|
|
||||||
private Boolean isDefault;
|
|
||||||
private Boolean isActive;
|
|
||||||
private Integer sortOrder;
|
|
||||||
private OffsetDateTime createdAt;
|
|
||||||
private OffsetDateTime updatedAt;
|
|
||||||
|
|
||||||
public UUID getId() {
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setId(UUID id) {
|
|
||||||
this.id = id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSku() {
|
|
||||||
return sku;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSku(String sku) {
|
|
||||||
this.sku = sku;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getVariantLabel() {
|
|
||||||
return variantLabel;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setVariantLabel(String variantLabel) {
|
|
||||||
this.variantLabel = variantLabel;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getColorName() {
|
|
||||||
return colorName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setColorName(String colorName) {
|
|
||||||
this.colorName = colorName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getColorLabelIt() {
|
|
||||||
return colorLabelIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setColorLabelIt(String colorLabelIt) {
|
|
||||||
this.colorLabelIt = colorLabelIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getColorLabelEn() {
|
|
||||||
return colorLabelEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setColorLabelEn(String colorLabelEn) {
|
|
||||||
this.colorLabelEn = colorLabelEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getColorLabelDe() {
|
|
||||||
return colorLabelDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setColorLabelDe(String colorLabelDe) {
|
|
||||||
this.colorLabelDe = colorLabelDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getColorLabelFr() {
|
|
||||||
return colorLabelFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setColorLabelFr(String colorLabelFr) {
|
|
||||||
this.colorLabelFr = colorLabelFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getColorHex() {
|
|
||||||
return colorHex;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setColorHex(String colorHex) {
|
|
||||||
this.colorHex = colorHex;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getInternalMaterialCode() {
|
|
||||||
return internalMaterialCode;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setInternalMaterialCode(String internalMaterialCode) {
|
|
||||||
this.internalMaterialCode = internalMaterialCode;
|
|
||||||
}
|
|
||||||
|
|
||||||
public BigDecimal getPriceChf() {
|
|
||||||
return priceChf;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setPriceChf(BigDecimal priceChf) {
|
|
||||||
this.priceChf = priceChf;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getIsDefault() {
|
|
||||||
return isDefault;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIsDefault(Boolean aDefault) {
|
|
||||||
isDefault = aDefault;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getIsActive() {
|
|
||||||
return isActive;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIsActive(Boolean active) {
|
|
||||||
isActive = active;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getSortOrder() {
|
|
||||||
return sortOrder;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSortOrder(Integer sortOrder) {
|
|
||||||
this.sortOrder = sortOrder;
|
|
||||||
}
|
|
||||||
|
|
||||||
public OffsetDateTime getCreatedAt() {
|
|
||||||
return createdAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCreatedAt(OffsetDateTime createdAt) {
|
|
||||||
this.createdAt = createdAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public OffsetDateTime getUpdatedAt() {
|
|
||||||
return updatedAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setUpdatedAt(OffsetDateTime updatedAt) {
|
|
||||||
this.updatedAt = updatedAt;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,89 +0,0 @@
|
|||||||
package com.printcalculator.dto;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
public class AdminTranslateShopProductRequest {
|
|
||||||
private UUID categoryId;
|
|
||||||
private String sourceLanguage;
|
|
||||||
private Boolean overwriteExisting;
|
|
||||||
private List<String> materialCodes;
|
|
||||||
private Map<String, String> names;
|
|
||||||
private Map<String, String> excerpts;
|
|
||||||
private Map<String, String> descriptions;
|
|
||||||
private Map<String, String> seoTitles;
|
|
||||||
private Map<String, String> seoDescriptions;
|
|
||||||
|
|
||||||
public UUID getCategoryId() {
|
|
||||||
return categoryId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCategoryId(UUID categoryId) {
|
|
||||||
this.categoryId = categoryId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSourceLanguage() {
|
|
||||||
return sourceLanguage;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSourceLanguage(String sourceLanguage) {
|
|
||||||
this.sourceLanguage = sourceLanguage;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getOverwriteExisting() {
|
|
||||||
return overwriteExisting;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setOverwriteExisting(Boolean overwriteExisting) {
|
|
||||||
this.overwriteExisting = overwriteExisting;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<String> getMaterialCodes() {
|
|
||||||
return materialCodes;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setMaterialCodes(List<String> materialCodes) {
|
|
||||||
this.materialCodes = materialCodes;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<String, String> getNames() {
|
|
||||||
return names;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setNames(Map<String, String> names) {
|
|
||||||
this.names = names;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<String, String> getExcerpts() {
|
|
||||||
return excerpts;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setExcerpts(Map<String, String> excerpts) {
|
|
||||||
this.excerpts = excerpts;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<String, String> getDescriptions() {
|
|
||||||
return descriptions;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescriptions(Map<String, String> descriptions) {
|
|
||||||
this.descriptions = descriptions;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<String, String> getSeoTitles() {
|
|
||||||
return seoTitles;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitles(Map<String, String> seoTitles) {
|
|
||||||
this.seoTitles = seoTitles;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<String, String> getSeoDescriptions() {
|
|
||||||
return seoDescriptions;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescriptions(Map<String, String> seoDescriptions) {
|
|
||||||
this.seoDescriptions = seoDescriptions;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,70 +0,0 @@
|
|||||||
package com.printcalculator.dto;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
public class AdminTranslateShopProductResponse {
|
|
||||||
private String sourceLanguage;
|
|
||||||
private List<String> targetLanguages;
|
|
||||||
private Map<String, String> names;
|
|
||||||
private Map<String, String> excerpts;
|
|
||||||
private Map<String, String> descriptions;
|
|
||||||
private Map<String, String> seoTitles;
|
|
||||||
private Map<String, String> seoDescriptions;
|
|
||||||
|
|
||||||
public String getSourceLanguage() {
|
|
||||||
return sourceLanguage;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSourceLanguage(String sourceLanguage) {
|
|
||||||
this.sourceLanguage = sourceLanguage;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<String> getTargetLanguages() {
|
|
||||||
return targetLanguages;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTargetLanguages(List<String> targetLanguages) {
|
|
||||||
this.targetLanguages = targetLanguages;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<String, String> getNames() {
|
|
||||||
return names;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setNames(Map<String, String> names) {
|
|
||||||
this.names = names;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<String, String> getExcerpts() {
|
|
||||||
return excerpts;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setExcerpts(Map<String, String> excerpts) {
|
|
||||||
this.excerpts = excerpts;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<String, String> getDescriptions() {
|
|
||||||
return descriptions;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescriptions(Map<String, String> descriptions) {
|
|
||||||
this.descriptions = descriptions;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<String, String> getSeoTitles() {
|
|
||||||
return seoTitles;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitles(Map<String, String> seoTitles) {
|
|
||||||
this.seoTitles = seoTitles;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<String, String> getSeoDescriptions() {
|
|
||||||
return seoDescriptions;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescriptions(Map<String, String> seoDescriptions) {
|
|
||||||
this.seoDescriptions = seoDescriptions;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
package com.printcalculator.dto;
|
|
||||||
|
|
||||||
public class AdminUpdateMediaAssetRequest {
|
|
||||||
private String title;
|
|
||||||
private String altText;
|
|
||||||
private String visibility;
|
|
||||||
private String status;
|
|
||||||
|
|
||||||
public String getTitle() {
|
|
||||||
return title;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTitle(String title) {
|
|
||||||
this.title = title;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getAltText() {
|
|
||||||
return altText;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAltText(String altText) {
|
|
||||||
this.altText = altText;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getVisibility() {
|
|
||||||
return visibility;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setVisibility(String visibility) {
|
|
||||||
this.visibility = visibility;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getStatus() {
|
|
||||||
return status;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setStatus(String status) {
|
|
||||||
this.status = status;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,79 +0,0 @@
|
|||||||
package com.printcalculator.dto;
|
|
||||||
|
|
||||||
import java.util.UUID;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
public class AdminUpdateMediaUsageRequest {
|
|
||||||
private String usageType;
|
|
||||||
private String usageKey;
|
|
||||||
private UUID ownerId;
|
|
||||||
private UUID mediaAssetId;
|
|
||||||
private Integer sortOrder;
|
|
||||||
private Boolean isPrimary;
|
|
||||||
private Boolean isActive;
|
|
||||||
private Map<String, MediaTextTranslationDto> translations;
|
|
||||||
|
|
||||||
public String getUsageType() {
|
|
||||||
return usageType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setUsageType(String usageType) {
|
|
||||||
this.usageType = usageType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getUsageKey() {
|
|
||||||
return usageKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setUsageKey(String usageKey) {
|
|
||||||
this.usageKey = usageKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
public UUID getOwnerId() {
|
|
||||||
return ownerId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setOwnerId(UUID ownerId) {
|
|
||||||
this.ownerId = ownerId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public UUID getMediaAssetId() {
|
|
||||||
return mediaAssetId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setMediaAssetId(UUID mediaAssetId) {
|
|
||||||
this.mediaAssetId = mediaAssetId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getSortOrder() {
|
|
||||||
return sortOrder;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSortOrder(Integer sortOrder) {
|
|
||||||
this.sortOrder = sortOrder;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getIsPrimary() {
|
|
||||||
return isPrimary;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIsPrimary(Boolean primary) {
|
|
||||||
isPrimary = primary;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getIsActive() {
|
|
||||||
return isActive;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIsActive(Boolean active) {
|
|
||||||
isActive = active;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<String, MediaTextTranslationDto> getTranslations() {
|
|
||||||
return translations;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTranslations(Map<String, MediaTextTranslationDto> translations) {
|
|
||||||
this.translations = translations;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -6,10 +6,6 @@ public class AdminUpsertFilamentVariantRequest {
|
|||||||
private Long materialTypeId;
|
private Long materialTypeId;
|
||||||
private String variantDisplayName;
|
private String variantDisplayName;
|
||||||
private String colorName;
|
private String colorName;
|
||||||
private String colorLabelIt;
|
|
||||||
private String colorLabelEn;
|
|
||||||
private String colorLabelDe;
|
|
||||||
private String colorLabelFr;
|
|
||||||
private String colorHex;
|
private String colorHex;
|
||||||
private String finishType;
|
private String finishType;
|
||||||
private String brand;
|
private String brand;
|
||||||
@@ -44,38 +40,6 @@ public class AdminUpsertFilamentVariantRequest {
|
|||||||
this.colorName = colorName;
|
this.colorName = colorName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getColorLabelIt() {
|
|
||||||
return colorLabelIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setColorLabelIt(String colorLabelIt) {
|
|
||||||
this.colorLabelIt = colorLabelIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getColorLabelEn() {
|
|
||||||
return colorLabelEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setColorLabelEn(String colorLabelEn) {
|
|
||||||
this.colorLabelEn = colorLabelEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getColorLabelDe() {
|
|
||||||
return colorLabelDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setColorLabelDe(String colorLabelDe) {
|
|
||||||
this.colorLabelDe = colorLabelDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getColorLabelFr() {
|
|
||||||
return colorLabelFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setColorLabelFr(String colorLabelFr) {
|
|
||||||
this.colorLabelFr = colorLabelFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getColorHex() {
|
public String getColorHex() {
|
||||||
return colorHex;
|
return colorHex;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,249 +0,0 @@
|
|||||||
package com.printcalculator.dto;
|
|
||||||
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
public class AdminUpsertShopCategoryRequest {
|
|
||||||
private UUID parentCategoryId;
|
|
||||||
private String slug;
|
|
||||||
private String name;
|
|
||||||
private String nameIt;
|
|
||||||
private String nameEn;
|
|
||||||
private String nameDe;
|
|
||||||
private String nameFr;
|
|
||||||
private String description;
|
|
||||||
private String descriptionIt;
|
|
||||||
private String descriptionEn;
|
|
||||||
private String descriptionDe;
|
|
||||||
private String descriptionFr;
|
|
||||||
private String seoTitle;
|
|
||||||
private String seoTitleIt;
|
|
||||||
private String seoTitleEn;
|
|
||||||
private String seoTitleDe;
|
|
||||||
private String seoTitleFr;
|
|
||||||
private String seoDescription;
|
|
||||||
private String seoDescriptionIt;
|
|
||||||
private String seoDescriptionEn;
|
|
||||||
private String seoDescriptionDe;
|
|
||||||
private String seoDescriptionFr;
|
|
||||||
private String ogTitle;
|
|
||||||
private String ogDescription;
|
|
||||||
private Boolean indexable;
|
|
||||||
private Boolean isActive;
|
|
||||||
private Integer sortOrder;
|
|
||||||
|
|
||||||
public UUID getParentCategoryId() {
|
|
||||||
return parentCategoryId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setParentCategoryId(UUID parentCategoryId) {
|
|
||||||
this.parentCategoryId = parentCategoryId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSlug() {
|
|
||||||
return slug;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSlug(String slug) {
|
|
||||||
this.slug = slug;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getName() {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setName(String name) {
|
|
||||||
this.name = name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getNameIt() {
|
|
||||||
return nameIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setNameIt(String nameIt) {
|
|
||||||
this.nameIt = nameIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getNameEn() {
|
|
||||||
return nameEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setNameEn(String nameEn) {
|
|
||||||
this.nameEn = nameEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getNameDe() {
|
|
||||||
return nameDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setNameDe(String nameDe) {
|
|
||||||
this.nameDe = nameDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getNameFr() {
|
|
||||||
return nameFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setNameFr(String nameFr) {
|
|
||||||
this.nameFr = nameFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescription() {
|
|
||||||
return description;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescription(String description) {
|
|
||||||
this.description = description;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescriptionIt() {
|
|
||||||
return descriptionIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescriptionIt(String descriptionIt) {
|
|
||||||
this.descriptionIt = descriptionIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescriptionEn() {
|
|
||||||
return descriptionEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescriptionEn(String descriptionEn) {
|
|
||||||
this.descriptionEn = descriptionEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescriptionDe() {
|
|
||||||
return descriptionDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescriptionDe(String descriptionDe) {
|
|
||||||
this.descriptionDe = descriptionDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescriptionFr() {
|
|
||||||
return descriptionFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescriptionFr(String descriptionFr) {
|
|
||||||
this.descriptionFr = descriptionFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoTitle() {
|
|
||||||
return seoTitle;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitle(String seoTitle) {
|
|
||||||
this.seoTitle = seoTitle;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoTitleIt() {
|
|
||||||
return seoTitleIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitleIt(String seoTitleIt) {
|
|
||||||
this.seoTitleIt = seoTitleIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoTitleEn() {
|
|
||||||
return seoTitleEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitleEn(String seoTitleEn) {
|
|
||||||
this.seoTitleEn = seoTitleEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoTitleDe() {
|
|
||||||
return seoTitleDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitleDe(String seoTitleDe) {
|
|
||||||
this.seoTitleDe = seoTitleDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoTitleFr() {
|
|
||||||
return seoTitleFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitleFr(String seoTitleFr) {
|
|
||||||
this.seoTitleFr = seoTitleFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoDescription() {
|
|
||||||
return seoDescription;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescription(String seoDescription) {
|
|
||||||
this.seoDescription = seoDescription;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoDescriptionIt() {
|
|
||||||
return seoDescriptionIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescriptionIt(String seoDescriptionIt) {
|
|
||||||
this.seoDescriptionIt = seoDescriptionIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoDescriptionEn() {
|
|
||||||
return seoDescriptionEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescriptionEn(String seoDescriptionEn) {
|
|
||||||
this.seoDescriptionEn = seoDescriptionEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoDescriptionDe() {
|
|
||||||
return seoDescriptionDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescriptionDe(String seoDescriptionDe) {
|
|
||||||
this.seoDescriptionDe = seoDescriptionDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoDescriptionFr() {
|
|
||||||
return seoDescriptionFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescriptionFr(String seoDescriptionFr) {
|
|
||||||
this.seoDescriptionFr = seoDescriptionFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getOgTitle() {
|
|
||||||
return ogTitle;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setOgTitle(String ogTitle) {
|
|
||||||
this.ogTitle = ogTitle;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getOgDescription() {
|
|
||||||
return ogDescription;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setOgDescription(String ogDescription) {
|
|
||||||
this.ogDescription = ogDescription;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getIndexable() {
|
|
||||||
return indexable;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIndexable(Boolean indexable) {
|
|
||||||
this.indexable = indexable;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getIsActive() {
|
|
||||||
return isActive;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIsActive(Boolean active) {
|
|
||||||
isActive = active;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getSortOrder() {
|
|
||||||
return sortOrder;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSortOrder(Integer sortOrder) {
|
|
||||||
this.sortOrder = sortOrder;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,313 +0,0 @@
|
|||||||
package com.printcalculator.dto;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
public class AdminUpsertShopProductRequest {
|
|
||||||
private UUID categoryId;
|
|
||||||
private String slug;
|
|
||||||
private String name;
|
|
||||||
private String nameIt;
|
|
||||||
private String nameEn;
|
|
||||||
private String nameDe;
|
|
||||||
private String nameFr;
|
|
||||||
private String excerpt;
|
|
||||||
private String excerptIt;
|
|
||||||
private String excerptEn;
|
|
||||||
private String excerptDe;
|
|
||||||
private String excerptFr;
|
|
||||||
private String description;
|
|
||||||
private String descriptionIt;
|
|
||||||
private String descriptionEn;
|
|
||||||
private String descriptionDe;
|
|
||||||
private String descriptionFr;
|
|
||||||
private String seoTitle;
|
|
||||||
private String seoTitleIt;
|
|
||||||
private String seoTitleEn;
|
|
||||||
private String seoTitleDe;
|
|
||||||
private String seoTitleFr;
|
|
||||||
private String seoDescription;
|
|
||||||
private String seoDescriptionIt;
|
|
||||||
private String seoDescriptionEn;
|
|
||||||
private String seoDescriptionDe;
|
|
||||||
private String seoDescriptionFr;
|
|
||||||
private String ogTitle;
|
|
||||||
private String ogDescription;
|
|
||||||
private Boolean indexable;
|
|
||||||
private Boolean isFeatured;
|
|
||||||
private Boolean isActive;
|
|
||||||
private Integer sortOrder;
|
|
||||||
private List<AdminUpsertShopProductVariantRequest> variants;
|
|
||||||
|
|
||||||
public UUID getCategoryId() {
|
|
||||||
return categoryId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCategoryId(UUID categoryId) {
|
|
||||||
this.categoryId = categoryId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSlug() {
|
|
||||||
return slug;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSlug(String slug) {
|
|
||||||
this.slug = slug;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getName() {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setName(String name) {
|
|
||||||
this.name = name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getNameIt() {
|
|
||||||
return nameIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setNameIt(String nameIt) {
|
|
||||||
this.nameIt = nameIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getNameEn() {
|
|
||||||
return nameEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setNameEn(String nameEn) {
|
|
||||||
this.nameEn = nameEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getNameDe() {
|
|
||||||
return nameDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setNameDe(String nameDe) {
|
|
||||||
this.nameDe = nameDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getNameFr() {
|
|
||||||
return nameFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setNameFr(String nameFr) {
|
|
||||||
this.nameFr = nameFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getExcerpt() {
|
|
||||||
return excerpt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setExcerpt(String excerpt) {
|
|
||||||
this.excerpt = excerpt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getExcerptIt() {
|
|
||||||
return excerptIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setExcerptIt(String excerptIt) {
|
|
||||||
this.excerptIt = excerptIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getExcerptEn() {
|
|
||||||
return excerptEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setExcerptEn(String excerptEn) {
|
|
||||||
this.excerptEn = excerptEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getExcerptDe() {
|
|
||||||
return excerptDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setExcerptDe(String excerptDe) {
|
|
||||||
this.excerptDe = excerptDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getExcerptFr() {
|
|
||||||
return excerptFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setExcerptFr(String excerptFr) {
|
|
||||||
this.excerptFr = excerptFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescription() {
|
|
||||||
return description;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescription(String description) {
|
|
||||||
this.description = description;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescriptionIt() {
|
|
||||||
return descriptionIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescriptionIt(String descriptionIt) {
|
|
||||||
this.descriptionIt = descriptionIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescriptionEn() {
|
|
||||||
return descriptionEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescriptionEn(String descriptionEn) {
|
|
||||||
this.descriptionEn = descriptionEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescriptionDe() {
|
|
||||||
return descriptionDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescriptionDe(String descriptionDe) {
|
|
||||||
this.descriptionDe = descriptionDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescriptionFr() {
|
|
||||||
return descriptionFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescriptionFr(String descriptionFr) {
|
|
||||||
this.descriptionFr = descriptionFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoTitle() {
|
|
||||||
return seoTitle;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitle(String seoTitle) {
|
|
||||||
this.seoTitle = seoTitle;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoTitleIt() {
|
|
||||||
return seoTitleIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitleIt(String seoTitleIt) {
|
|
||||||
this.seoTitleIt = seoTitleIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoTitleEn() {
|
|
||||||
return seoTitleEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitleEn(String seoTitleEn) {
|
|
||||||
this.seoTitleEn = seoTitleEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoTitleDe() {
|
|
||||||
return seoTitleDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitleDe(String seoTitleDe) {
|
|
||||||
this.seoTitleDe = seoTitleDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoTitleFr() {
|
|
||||||
return seoTitleFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitleFr(String seoTitleFr) {
|
|
||||||
this.seoTitleFr = seoTitleFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoDescription() {
|
|
||||||
return seoDescription;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescription(String seoDescription) {
|
|
||||||
this.seoDescription = seoDescription;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoDescriptionIt() {
|
|
||||||
return seoDescriptionIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescriptionIt(String seoDescriptionIt) {
|
|
||||||
this.seoDescriptionIt = seoDescriptionIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoDescriptionEn() {
|
|
||||||
return seoDescriptionEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescriptionEn(String seoDescriptionEn) {
|
|
||||||
this.seoDescriptionEn = seoDescriptionEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoDescriptionDe() {
|
|
||||||
return seoDescriptionDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescriptionDe(String seoDescriptionDe) {
|
|
||||||
this.seoDescriptionDe = seoDescriptionDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoDescriptionFr() {
|
|
||||||
return seoDescriptionFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescriptionFr(String seoDescriptionFr) {
|
|
||||||
this.seoDescriptionFr = seoDescriptionFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getOgTitle() {
|
|
||||||
return ogTitle;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setOgTitle(String ogTitle) {
|
|
||||||
this.ogTitle = ogTitle;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getOgDescription() {
|
|
||||||
return ogDescription;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setOgDescription(String ogDescription) {
|
|
||||||
this.ogDescription = ogDescription;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getIndexable() {
|
|
||||||
return indexable;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIndexable(Boolean indexable) {
|
|
||||||
this.indexable = indexable;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getIsFeatured() {
|
|
||||||
return isFeatured;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIsFeatured(Boolean featured) {
|
|
||||||
isFeatured = featured;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getIsActive() {
|
|
||||||
return isActive;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIsActive(Boolean active) {
|
|
||||||
isActive = active;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getSortOrder() {
|
|
||||||
return sortOrder;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSortOrder(Integer sortOrder) {
|
|
||||||
this.sortOrder = sortOrder;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<AdminUpsertShopProductVariantRequest> getVariants() {
|
|
||||||
return variants;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setVariants(List<AdminUpsertShopProductVariantRequest> variants) {
|
|
||||||
this.variants = variants;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,133 +0,0 @@
|
|||||||
package com.printcalculator.dto;
|
|
||||||
|
|
||||||
import java.math.BigDecimal;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
public class AdminUpsertShopProductVariantRequest {
|
|
||||||
private UUID id;
|
|
||||||
private String sku;
|
|
||||||
private String variantLabel;
|
|
||||||
private String colorName;
|
|
||||||
private String colorLabelIt;
|
|
||||||
private String colorLabelEn;
|
|
||||||
private String colorLabelDe;
|
|
||||||
private String colorLabelFr;
|
|
||||||
private String colorHex;
|
|
||||||
private String internalMaterialCode;
|
|
||||||
private BigDecimal priceChf;
|
|
||||||
private Boolean isDefault;
|
|
||||||
private Boolean isActive;
|
|
||||||
private Integer sortOrder;
|
|
||||||
|
|
||||||
public UUID getId() {
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setId(UUID id) {
|
|
||||||
this.id = id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSku() {
|
|
||||||
return sku;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSku(String sku) {
|
|
||||||
this.sku = sku;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getVariantLabel() {
|
|
||||||
return variantLabel;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setVariantLabel(String variantLabel) {
|
|
||||||
this.variantLabel = variantLabel;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getColorName() {
|
|
||||||
return colorName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setColorName(String colorName) {
|
|
||||||
this.colorName = colorName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getColorLabelIt() {
|
|
||||||
return colorLabelIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setColorLabelIt(String colorLabelIt) {
|
|
||||||
this.colorLabelIt = colorLabelIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getColorLabelEn() {
|
|
||||||
return colorLabelEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setColorLabelEn(String colorLabelEn) {
|
|
||||||
this.colorLabelEn = colorLabelEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getColorLabelDe() {
|
|
||||||
return colorLabelDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setColorLabelDe(String colorLabelDe) {
|
|
||||||
this.colorLabelDe = colorLabelDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getColorLabelFr() {
|
|
||||||
return colorLabelFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setColorLabelFr(String colorLabelFr) {
|
|
||||||
this.colorLabelFr = colorLabelFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getColorHex() {
|
|
||||||
return colorHex;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setColorHex(String colorHex) {
|
|
||||||
this.colorHex = colorHex;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getInternalMaterialCode() {
|
|
||||||
return internalMaterialCode;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setInternalMaterialCode(String internalMaterialCode) {
|
|
||||||
this.internalMaterialCode = internalMaterialCode;
|
|
||||||
}
|
|
||||||
|
|
||||||
public BigDecimal getPriceChf() {
|
|
||||||
return priceChf;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setPriceChf(BigDecimal priceChf) {
|
|
||||||
this.priceChf = priceChf;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getIsDefault() {
|
|
||||||
return isDefault;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIsDefault(Boolean aDefault) {
|
|
||||||
isDefault = aDefault;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getIsActive() {
|
|
||||||
return isActive;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIsActive(Boolean active) {
|
|
||||||
isActive = active;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getSortOrder() {
|
|
||||||
return sortOrder;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSortOrder(Integer sortOrder) {
|
|
||||||
this.sortOrder = sortOrder;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
package com.printcalculator.dto;
|
|
||||||
|
|
||||||
public class MediaTextTranslationDto {
|
|
||||||
private String title;
|
|
||||||
private String altText;
|
|
||||||
|
|
||||||
public String getTitle() {
|
|
||||||
return title;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTitle(String title) {
|
|
||||||
this.title = title;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getAltText() {
|
|
||||||
return altText;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAltText(String altText) {
|
|
||||||
this.altText = altText;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -15,10 +15,6 @@ public record OptionsResponse(
|
|||||||
Long id,
|
Long id,
|
||||||
String name,
|
String name,
|
||||||
String colorName,
|
String colorName,
|
||||||
String colorLabelIt,
|
|
||||||
String colorLabelEn,
|
|
||||||
String colorLabelDe,
|
|
||||||
String colorLabelFr,
|
|
||||||
String hexColor,
|
String hexColor,
|
||||||
String finishType,
|
String finishType,
|
||||||
Double stockSpools,
|
Double stockSpools,
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ import java.util.UUID;
|
|||||||
public class OrderDto {
|
public class OrderDto {
|
||||||
private UUID id;
|
private UUID id;
|
||||||
private String orderNumber;
|
private String orderNumber;
|
||||||
private String sourceType;
|
|
||||||
private String status;
|
private String status;
|
||||||
private String paymentStatus;
|
private String paymentStatus;
|
||||||
private String paymentMethod;
|
private String paymentMethod;
|
||||||
@@ -46,9 +45,6 @@ public class OrderDto {
|
|||||||
public String getOrderNumber() { return orderNumber; }
|
public String getOrderNumber() { return orderNumber; }
|
||||||
public void setOrderNumber(String orderNumber) { this.orderNumber = orderNumber; }
|
public void setOrderNumber(String orderNumber) { this.orderNumber = orderNumber; }
|
||||||
|
|
||||||
public String getSourceType() { return sourceType; }
|
|
||||||
public void setSourceType(String sourceType) { this.sourceType = sourceType; }
|
|
||||||
|
|
||||||
public String getStatus() { return status; }
|
public String getStatus() { return status; }
|
||||||
public void setStatus(String status) { this.status = status; }
|
public void setStatus(String status) { this.status = status; }
|
||||||
|
|
||||||
|
|||||||
@@ -5,30 +5,9 @@ import java.util.UUID;
|
|||||||
|
|
||||||
public class OrderItemDto {
|
public class OrderItemDto {
|
||||||
private UUID id;
|
private UUID id;
|
||||||
private String itemType;
|
|
||||||
private String originalFilename;
|
private String originalFilename;
|
||||||
private String displayName;
|
|
||||||
private String materialCode;
|
private String materialCode;
|
||||||
private String colorCode;
|
private String colorCode;
|
||||||
private Long filamentVariantId;
|
|
||||||
private UUID shopProductId;
|
|
||||||
private UUID shopProductVariantId;
|
|
||||||
private String shopProductSlug;
|
|
||||||
private String shopProductName;
|
|
||||||
private String shopVariantLabel;
|
|
||||||
private String shopVariantColorName;
|
|
||||||
private String shopVariantColorLabelIt;
|
|
||||||
private String shopVariantColorLabelEn;
|
|
||||||
private String shopVariantColorLabelDe;
|
|
||||||
private String shopVariantColorLabelFr;
|
|
||||||
private String shopVariantColorHex;
|
|
||||||
private String filamentVariantDisplayName;
|
|
||||||
private String filamentColorName;
|
|
||||||
private String filamentColorLabelIt;
|
|
||||||
private String filamentColorLabelEn;
|
|
||||||
private String filamentColorLabelDe;
|
|
||||||
private String filamentColorLabelFr;
|
|
||||||
private String filamentColorHex;
|
|
||||||
private String quality;
|
private String quality;
|
||||||
private BigDecimal nozzleDiameterMm;
|
private BigDecimal nozzleDiameterMm;
|
||||||
private BigDecimal layerHeightMm;
|
private BigDecimal layerHeightMm;
|
||||||
@@ -45,78 +24,15 @@ public class OrderItemDto {
|
|||||||
public UUID getId() { return id; }
|
public UUID getId() { return id; }
|
||||||
public void setId(UUID id) { this.id = id; }
|
public void setId(UUID id) { this.id = id; }
|
||||||
|
|
||||||
public String getItemType() { return itemType; }
|
|
||||||
public void setItemType(String itemType) { this.itemType = itemType; }
|
|
||||||
|
|
||||||
public String getOriginalFilename() { return originalFilename; }
|
public String getOriginalFilename() { return originalFilename; }
|
||||||
public void setOriginalFilename(String originalFilename) { this.originalFilename = originalFilename; }
|
public void setOriginalFilename(String originalFilename) { this.originalFilename = originalFilename; }
|
||||||
|
|
||||||
public String getDisplayName() { return displayName; }
|
|
||||||
public void setDisplayName(String displayName) { this.displayName = displayName; }
|
|
||||||
|
|
||||||
public String getMaterialCode() { return materialCode; }
|
public String getMaterialCode() { return materialCode; }
|
||||||
public void setMaterialCode(String materialCode) { this.materialCode = materialCode; }
|
public void setMaterialCode(String materialCode) { this.materialCode = materialCode; }
|
||||||
|
|
||||||
public String getColorCode() { return colorCode; }
|
public String getColorCode() { return colorCode; }
|
||||||
public void setColorCode(String colorCode) { this.colorCode = colorCode; }
|
public void setColorCode(String colorCode) { this.colorCode = colorCode; }
|
||||||
|
|
||||||
public Long getFilamentVariantId() { return filamentVariantId; }
|
|
||||||
public void setFilamentVariantId(Long filamentVariantId) { this.filamentVariantId = filamentVariantId; }
|
|
||||||
|
|
||||||
public UUID getShopProductId() { return shopProductId; }
|
|
||||||
public void setShopProductId(UUID shopProductId) { this.shopProductId = shopProductId; }
|
|
||||||
|
|
||||||
public UUID getShopProductVariantId() { return shopProductVariantId; }
|
|
||||||
public void setShopProductVariantId(UUID shopProductVariantId) { this.shopProductVariantId = shopProductVariantId; }
|
|
||||||
|
|
||||||
public String getShopProductSlug() { return shopProductSlug; }
|
|
||||||
public void setShopProductSlug(String shopProductSlug) { this.shopProductSlug = shopProductSlug; }
|
|
||||||
|
|
||||||
public String getShopProductName() { return shopProductName; }
|
|
||||||
public void setShopProductName(String shopProductName) { this.shopProductName = shopProductName; }
|
|
||||||
|
|
||||||
public String getShopVariantLabel() { return shopVariantLabel; }
|
|
||||||
public void setShopVariantLabel(String shopVariantLabel) { this.shopVariantLabel = shopVariantLabel; }
|
|
||||||
|
|
||||||
public String getShopVariantColorName() { return shopVariantColorName; }
|
|
||||||
public void setShopVariantColorName(String shopVariantColorName) { this.shopVariantColorName = shopVariantColorName; }
|
|
||||||
|
|
||||||
public String getShopVariantColorLabelIt() { return shopVariantColorLabelIt; }
|
|
||||||
public void setShopVariantColorLabelIt(String shopVariantColorLabelIt) { this.shopVariantColorLabelIt = shopVariantColorLabelIt; }
|
|
||||||
|
|
||||||
public String getShopVariantColorLabelEn() { return shopVariantColorLabelEn; }
|
|
||||||
public void setShopVariantColorLabelEn(String shopVariantColorLabelEn) { this.shopVariantColorLabelEn = shopVariantColorLabelEn; }
|
|
||||||
|
|
||||||
public String getShopVariantColorLabelDe() { return shopVariantColorLabelDe; }
|
|
||||||
public void setShopVariantColorLabelDe(String shopVariantColorLabelDe) { this.shopVariantColorLabelDe = shopVariantColorLabelDe; }
|
|
||||||
|
|
||||||
public String getShopVariantColorLabelFr() { return shopVariantColorLabelFr; }
|
|
||||||
public void setShopVariantColorLabelFr(String shopVariantColorLabelFr) { this.shopVariantColorLabelFr = shopVariantColorLabelFr; }
|
|
||||||
|
|
||||||
public String getShopVariantColorHex() { return shopVariantColorHex; }
|
|
||||||
public void setShopVariantColorHex(String shopVariantColorHex) { this.shopVariantColorHex = shopVariantColorHex; }
|
|
||||||
|
|
||||||
public String getFilamentVariantDisplayName() { return filamentVariantDisplayName; }
|
|
||||||
public void setFilamentVariantDisplayName(String filamentVariantDisplayName) { this.filamentVariantDisplayName = filamentVariantDisplayName; }
|
|
||||||
|
|
||||||
public String getFilamentColorName() { return filamentColorName; }
|
|
||||||
public void setFilamentColorName(String filamentColorName) { this.filamentColorName = filamentColorName; }
|
|
||||||
|
|
||||||
public String getFilamentColorLabelIt() { return filamentColorLabelIt; }
|
|
||||||
public void setFilamentColorLabelIt(String filamentColorLabelIt) { this.filamentColorLabelIt = filamentColorLabelIt; }
|
|
||||||
|
|
||||||
public String getFilamentColorLabelEn() { return filamentColorLabelEn; }
|
|
||||||
public void setFilamentColorLabelEn(String filamentColorLabelEn) { this.filamentColorLabelEn = filamentColorLabelEn; }
|
|
||||||
|
|
||||||
public String getFilamentColorLabelDe() { return filamentColorLabelDe; }
|
|
||||||
public void setFilamentColorLabelDe(String filamentColorLabelDe) { this.filamentColorLabelDe = filamentColorLabelDe; }
|
|
||||||
|
|
||||||
public String getFilamentColorLabelFr() { return filamentColorLabelFr; }
|
|
||||||
public void setFilamentColorLabelFr(String filamentColorLabelFr) { this.filamentColorLabelFr = filamentColorLabelFr; }
|
|
||||||
|
|
||||||
public String getFilamentColorHex() { return filamentColorHex; }
|
|
||||||
public void setFilamentColorHex(String filamentColorHex) { this.filamentColorHex = filamentColorHex; }
|
|
||||||
|
|
||||||
public String getQuality() { return quality; }
|
public String getQuality() { return quality; }
|
||||||
public void setQuality(String quality) { this.quality = quality; }
|
public void setQuality(String quality) { this.quality = quality; }
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ public class PrintSettingsDto {
|
|||||||
// Common
|
// Common
|
||||||
private String material; // e.g. "PLA", "PLA TOUGH", "PETG"
|
private String material; // e.g. "PLA", "PLA TOUGH", "PETG"
|
||||||
private String color; // e.g. "White", "#FFFFFF"
|
private String color; // e.g. "White", "#FFFFFF"
|
||||||
private Integer quantity;
|
|
||||||
private Long filamentVariantId;
|
private Long filamentVariantId;
|
||||||
private Long printerMachineId;
|
private Long printerMachineId;
|
||||||
|
|
||||||
@@ -59,14 +58,6 @@ public class PrintSettingsDto {
|
|||||||
this.filamentVariantId = filamentVariantId;
|
this.filamentVariantId = filamentVariantId;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Integer getQuantity() {
|
|
||||||
return quantity;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setQuantity(Integer quantity) {
|
|
||||||
this.quantity = quantity;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Long getPrinterMachineId() {
|
public Long getPrinterMachineId() {
|
||||||
return printerMachineId;
|
return printerMachineId;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,96 +0,0 @@
|
|||||||
package com.printcalculator.dto;
|
|
||||||
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
public class PublicMediaUsageDto {
|
|
||||||
private UUID mediaAssetId;
|
|
||||||
private String title;
|
|
||||||
private String altText;
|
|
||||||
private String usageType;
|
|
||||||
private String usageKey;
|
|
||||||
private Integer sortOrder;
|
|
||||||
private Boolean isPrimary;
|
|
||||||
private PublicMediaVariantDto thumb;
|
|
||||||
private PublicMediaVariantDto card;
|
|
||||||
private PublicMediaVariantDto hero;
|
|
||||||
|
|
||||||
public UUID getMediaAssetId() {
|
|
||||||
return mediaAssetId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setMediaAssetId(UUID mediaAssetId) {
|
|
||||||
this.mediaAssetId = mediaAssetId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getTitle() {
|
|
||||||
return title;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTitle(String title) {
|
|
||||||
this.title = title;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getAltText() {
|
|
||||||
return altText;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAltText(String altText) {
|
|
||||||
this.altText = altText;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getUsageType() {
|
|
||||||
return usageType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setUsageType(String usageType) {
|
|
||||||
this.usageType = usageType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getUsageKey() {
|
|
||||||
return usageKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setUsageKey(String usageKey) {
|
|
||||||
this.usageKey = usageKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getSortOrder() {
|
|
||||||
return sortOrder;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSortOrder(Integer sortOrder) {
|
|
||||||
this.sortOrder = sortOrder;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getIsPrimary() {
|
|
||||||
return isPrimary;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIsPrimary(Boolean primary) {
|
|
||||||
isPrimary = primary;
|
|
||||||
}
|
|
||||||
|
|
||||||
public PublicMediaVariantDto getThumb() {
|
|
||||||
return thumb;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setThumb(PublicMediaVariantDto thumb) {
|
|
||||||
this.thumb = thumb;
|
|
||||||
}
|
|
||||||
|
|
||||||
public PublicMediaVariantDto getCard() {
|
|
||||||
return card;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCard(PublicMediaVariantDto card) {
|
|
||||||
this.card = card;
|
|
||||||
}
|
|
||||||
|
|
||||||
public PublicMediaVariantDto getHero() {
|
|
||||||
return hero;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setHero(PublicMediaVariantDto hero) {
|
|
||||||
this.hero = hero;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
package com.printcalculator.dto;
|
|
||||||
|
|
||||||
public class PublicMediaVariantDto {
|
|
||||||
private String avifUrl;
|
|
||||||
private String webpUrl;
|
|
||||||
private String jpegUrl;
|
|
||||||
|
|
||||||
public String getAvifUrl() {
|
|
||||||
return avifUrl;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAvifUrl(String avifUrl) {
|
|
||||||
this.avifUrl = avifUrl;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getWebpUrl() {
|
|
||||||
return webpUrl;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setWebpUrl(String webpUrl) {
|
|
||||||
this.webpUrl = webpUrl;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getJpegUrl() {
|
|
||||||
return jpegUrl;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setJpegUrl(String jpegUrl) {
|
|
||||||
this.jpegUrl = jpegUrl;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
package com.printcalculator.dto;
|
|
||||||
|
|
||||||
import jakarta.validation.constraints.Min;
|
|
||||||
import jakarta.validation.constraints.NotNull;
|
|
||||||
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
public class ShopCartAddItemRequest {
|
|
||||||
@NotNull
|
|
||||||
private UUID shopProductVariantId;
|
|
||||||
|
|
||||||
@Min(1)
|
|
||||||
private Integer quantity = 1;
|
|
||||||
|
|
||||||
public UUID getShopProductVariantId() {
|
|
||||||
return shopProductVariantId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setShopProductVariantId(UUID shopProductVariantId) {
|
|
||||||
this.shopProductVariantId = shopProductVariantId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getQuantity() {
|
|
||||||
return quantity;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setQuantity(Integer quantity) {
|
|
||||||
this.quantity = quantity;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
package com.printcalculator.dto;
|
|
||||||
|
|
||||||
import jakarta.validation.constraints.Min;
|
|
||||||
import jakarta.validation.constraints.NotNull;
|
|
||||||
|
|
||||||
public class ShopCartUpdateItemRequest {
|
|
||||||
@NotNull
|
|
||||||
@Min(1)
|
|
||||||
private Integer quantity;
|
|
||||||
|
|
||||||
public Integer getQuantity() {
|
|
||||||
return quantity;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setQuantity(Integer quantity) {
|
|
||||||
this.quantity = quantity;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
package com.printcalculator.dto;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
public record ShopCategoryDetailDto(
|
|
||||||
UUID id,
|
|
||||||
String slug,
|
|
||||||
String name,
|
|
||||||
String description,
|
|
||||||
String seoTitle,
|
|
||||||
String seoDescription,
|
|
||||||
String ogTitle,
|
|
||||||
String ogDescription,
|
|
||||||
Boolean indexable,
|
|
||||||
Integer sortOrder,
|
|
||||||
Integer productCount,
|
|
||||||
List<ShopCategoryRefDto> breadcrumbs,
|
|
||||||
PublicMediaUsageDto primaryImage,
|
|
||||||
List<PublicMediaUsageDto> images,
|
|
||||||
List<ShopCategoryTreeDto> children
|
|
||||||
) {
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
package com.printcalculator.dto;
|
|
||||||
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
public record ShopCategoryRefDto(
|
|
||||||
UUID id,
|
|
||||||
String slug,
|
|
||||||
String name
|
|
||||||
) {
|
|
||||||
}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
package com.printcalculator.dto;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
public record ShopCategoryTreeDto(
|
|
||||||
UUID id,
|
|
||||||
UUID parentCategoryId,
|
|
||||||
String slug,
|
|
||||||
String name,
|
|
||||||
String description,
|
|
||||||
String seoTitle,
|
|
||||||
String seoDescription,
|
|
||||||
String ogTitle,
|
|
||||||
String ogDescription,
|
|
||||||
Boolean indexable,
|
|
||||||
Integer sortOrder,
|
|
||||||
Integer productCount,
|
|
||||||
PublicMediaUsageDto primaryImage,
|
|
||||||
List<ShopCategoryTreeDto> children
|
|
||||||
) {
|
|
||||||
}
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
package com.printcalculator.dto;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
public record ShopProductCatalogResponseDto(
|
|
||||||
String categorySlug,
|
|
||||||
Boolean featuredOnly,
|
|
||||||
ShopCategoryDetailDto category,
|
|
||||||
List<ShopProductSummaryDto> products
|
|
||||||
) {
|
|
||||||
}
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
package com.printcalculator.dto;
|
|
||||||
|
|
||||||
import java.math.BigDecimal;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
public record ShopProductDetailDto(
|
|
||||||
UUID id,
|
|
||||||
String slug,
|
|
||||||
String name,
|
|
||||||
String excerpt,
|
|
||||||
String description,
|
|
||||||
String seoTitle,
|
|
||||||
String seoDescription,
|
|
||||||
String ogTitle,
|
|
||||||
String ogDescription,
|
|
||||||
Boolean indexable,
|
|
||||||
Boolean isFeatured,
|
|
||||||
Integer sortOrder,
|
|
||||||
ShopCategoryRefDto category,
|
|
||||||
List<ShopCategoryRefDto> breadcrumbs,
|
|
||||||
BigDecimal priceFromChf,
|
|
||||||
BigDecimal priceToChf,
|
|
||||||
ShopProductVariantOptionDto defaultVariant,
|
|
||||||
List<ShopProductVariantOptionDto> variants,
|
|
||||||
PublicMediaUsageDto primaryImage,
|
|
||||||
List<PublicMediaUsageDto> images,
|
|
||||||
ShopProductModelDto model3d,
|
|
||||||
String publicPath,
|
|
||||||
Map<String, String> localizedPaths
|
|
||||||
) {
|
|
||||||
}
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
package com.printcalculator.dto;
|
|
||||||
|
|
||||||
import java.math.BigDecimal;
|
|
||||||
|
|
||||||
public record ShopProductModelDto(
|
|
||||||
String url,
|
|
||||||
String originalFilename,
|
|
||||||
String mimeType,
|
|
||||||
Long fileSizeBytes,
|
|
||||||
BigDecimal boundingBoxXMm,
|
|
||||||
BigDecimal boundingBoxYMm,
|
|
||||||
BigDecimal boundingBoxZMm
|
|
||||||
) {
|
|
||||||
}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
package com.printcalculator.dto;
|
|
||||||
|
|
||||||
import java.math.BigDecimal;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
public record ShopProductSummaryDto(
|
|
||||||
UUID id,
|
|
||||||
String slug,
|
|
||||||
String name,
|
|
||||||
String excerpt,
|
|
||||||
Boolean isFeatured,
|
|
||||||
Integer sortOrder,
|
|
||||||
ShopCategoryRefDto category,
|
|
||||||
BigDecimal priceFromChf,
|
|
||||||
BigDecimal priceToChf,
|
|
||||||
ShopProductVariantOptionDto defaultVariant,
|
|
||||||
PublicMediaUsageDto primaryImage,
|
|
||||||
ShopProductModelDto model3d,
|
|
||||||
String publicPath,
|
|
||||||
Map<String, String> localizedPaths
|
|
||||||
) {
|
|
||||||
}
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
package com.printcalculator.dto;
|
|
||||||
|
|
||||||
import java.math.BigDecimal;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
public record ShopProductVariantOptionDto(
|
|
||||||
UUID id,
|
|
||||||
String sku,
|
|
||||||
String variantLabel,
|
|
||||||
String colorName,
|
|
||||||
String colorLabel,
|
|
||||||
String colorHex,
|
|
||||||
BigDecimal priceChf,
|
|
||||||
Boolean isDefault
|
|
||||||
) {
|
|
||||||
}
|
|
||||||
@@ -24,18 +24,6 @@ public class FilamentVariant {
|
|||||||
@Column(name = "color_name", nullable = false, length = Integer.MAX_VALUE)
|
@Column(name = "color_name", nullable = false, length = Integer.MAX_VALUE)
|
||||||
private String colorName;
|
private String colorName;
|
||||||
|
|
||||||
@Column(name = "color_label_it", length = Integer.MAX_VALUE)
|
|
||||||
private String colorLabelIt;
|
|
||||||
|
|
||||||
@Column(name = "color_label_en", length = Integer.MAX_VALUE)
|
|
||||||
private String colorLabelEn;
|
|
||||||
|
|
||||||
@Column(name = "color_label_de", length = Integer.MAX_VALUE)
|
|
||||||
private String colorLabelDe;
|
|
||||||
|
|
||||||
@Column(name = "color_label_fr", length = Integer.MAX_VALUE)
|
|
||||||
private String colorLabelFr;
|
|
||||||
|
|
||||||
@Column(name = "color_hex", length = Integer.MAX_VALUE)
|
@Column(name = "color_hex", length = Integer.MAX_VALUE)
|
||||||
private String colorHex;
|
private String colorHex;
|
||||||
|
|
||||||
@@ -105,38 +93,6 @@ public class FilamentVariant {
|
|||||||
this.colorName = colorName;
|
this.colorName = colorName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getColorLabelIt() {
|
|
||||||
return colorLabelIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setColorLabelIt(String colorLabelIt) {
|
|
||||||
this.colorLabelIt = colorLabelIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getColorLabelEn() {
|
|
||||||
return colorLabelEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setColorLabelEn(String colorLabelEn) {
|
|
||||||
this.colorLabelEn = colorLabelEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getColorLabelDe() {
|
|
||||||
return colorLabelDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setColorLabelDe(String colorLabelDe) {
|
|
||||||
this.colorLabelDe = colorLabelDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getColorLabelFr() {
|
|
||||||
return colorLabelFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setColorLabelFr(String colorLabelFr) {
|
|
||||||
this.colorLabelFr = colorLabelFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getColorHex() {
|
public String getColorHex() {
|
||||||
return colorHex;
|
return colorHex;
|
||||||
}
|
}
|
||||||
@@ -217,60 +173,4 @@ public class FilamentVariant {
|
|||||||
this.createdAt = createdAt;
|
this.createdAt = createdAt;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getColorLabelForLanguage(String language) {
|
|
||||||
return resolveLocalizedValue(
|
|
||||||
language,
|
|
||||||
colorName,
|
|
||||||
colorLabelIt,
|
|
||||||
colorLabelEn,
|
|
||||||
colorLabelDe,
|
|
||||||
colorLabelFr
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String resolveLocalizedValue(String language,
|
|
||||||
String fallback,
|
|
||||||
String valueIt,
|
|
||||||
String valueEn,
|
|
||||||
String valueDe,
|
|
||||||
String valueFr) {
|
|
||||||
String normalizedLanguage = normalizeLanguage(language);
|
|
||||||
String preferred = switch (normalizedLanguage) {
|
|
||||||
case "it" -> valueIt;
|
|
||||||
case "en" -> valueEn;
|
|
||||||
case "de" -> valueDe;
|
|
||||||
case "fr" -> valueFr;
|
|
||||||
default -> null;
|
|
||||||
};
|
|
||||||
String resolved = firstNonBlank(preferred, fallback);
|
|
||||||
if (resolved != null) {
|
|
||||||
return resolved;
|
|
||||||
}
|
|
||||||
return firstNonBlank(valueIt, valueEn, valueDe, valueFr);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeLanguage(String language) {
|
|
||||||
if (language == null) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
String normalized = language.trim().toLowerCase();
|
|
||||||
int separatorIndex = normalized.indexOf('-');
|
|
||||||
if (separatorIndex > 0) {
|
|
||||||
normalized = normalized.substring(0, separatorIndex);
|
|
||||||
}
|
|
||||||
return normalized;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String firstNonBlank(String... values) {
|
|
||||||
if (values == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
for (String value : values) {
|
|
||||||
if (value != null && !value.isBlank()) {
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,177 +0,0 @@
|
|||||||
package com.printcalculator.entity;
|
|
||||||
|
|
||||||
import jakarta.persistence.Column;
|
|
||||||
import jakarta.persistence.Entity;
|
|
||||||
import jakarta.persistence.GeneratedValue;
|
|
||||||
import jakarta.persistence.GenerationType;
|
|
||||||
import jakarta.persistence.Id;
|
|
||||||
import jakarta.persistence.Index;
|
|
||||||
import jakarta.persistence.Table;
|
|
||||||
import org.hibernate.annotations.ColumnDefault;
|
|
||||||
|
|
||||||
import java.time.OffsetDateTime;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
@Entity
|
|
||||||
@Table(name = "media_asset", indexes = {
|
|
||||||
@Index(name = "ix_media_asset_status_visibility_created_at", columnList = "status, visibility, created_at")
|
|
||||||
})
|
|
||||||
public class MediaAsset {
|
|
||||||
@Id
|
|
||||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
|
||||||
@Column(name = "media_asset_id", nullable = false)
|
|
||||||
private UUID id;
|
|
||||||
|
|
||||||
@Column(name = "original_filename", nullable = false, length = Integer.MAX_VALUE)
|
|
||||||
private String originalFilename;
|
|
||||||
|
|
||||||
@Column(name = "storage_key", nullable = false, length = Integer.MAX_VALUE, unique = true)
|
|
||||||
private String storageKey;
|
|
||||||
|
|
||||||
@Column(name = "mime_type", nullable = false, length = Integer.MAX_VALUE)
|
|
||||||
private String mimeType;
|
|
||||||
|
|
||||||
@Column(name = "file_size_bytes", nullable = false)
|
|
||||||
private Long fileSizeBytes;
|
|
||||||
|
|
||||||
@Column(name = "sha256_hex", nullable = false, length = Integer.MAX_VALUE)
|
|
||||||
private String sha256Hex;
|
|
||||||
|
|
||||||
@Column(name = "width_px")
|
|
||||||
private Integer widthPx;
|
|
||||||
|
|
||||||
@Column(name = "height_px")
|
|
||||||
private Integer heightPx;
|
|
||||||
|
|
||||||
@Column(name = "status", nullable = false, length = Integer.MAX_VALUE)
|
|
||||||
private String status;
|
|
||||||
|
|
||||||
@Column(name = "visibility", nullable = false, length = Integer.MAX_VALUE)
|
|
||||||
private String visibility;
|
|
||||||
|
|
||||||
@Column(name = "title", length = Integer.MAX_VALUE)
|
|
||||||
private String title;
|
|
||||||
|
|
||||||
@Column(name = "alt_text", length = Integer.MAX_VALUE)
|
|
||||||
private String altText;
|
|
||||||
|
|
||||||
@ColumnDefault("now()")
|
|
||||||
@Column(name = "created_at", nullable = false)
|
|
||||||
private OffsetDateTime createdAt;
|
|
||||||
|
|
||||||
@ColumnDefault("now()")
|
|
||||||
@Column(name = "updated_at", nullable = false)
|
|
||||||
private OffsetDateTime updatedAt;
|
|
||||||
|
|
||||||
public UUID getId() {
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setId(UUID id) {
|
|
||||||
this.id = id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getOriginalFilename() {
|
|
||||||
return originalFilename;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setOriginalFilename(String originalFilename) {
|
|
||||||
this.originalFilename = originalFilename;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getStorageKey() {
|
|
||||||
return storageKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setStorageKey(String storageKey) {
|
|
||||||
this.storageKey = storageKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getMimeType() {
|
|
||||||
return mimeType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setMimeType(String mimeType) {
|
|
||||||
this.mimeType = mimeType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Long getFileSizeBytes() {
|
|
||||||
return fileSizeBytes;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setFileSizeBytes(Long fileSizeBytes) {
|
|
||||||
this.fileSizeBytes = fileSizeBytes;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSha256Hex() {
|
|
||||||
return sha256Hex;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSha256Hex(String sha256Hex) {
|
|
||||||
this.sha256Hex = sha256Hex;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getWidthPx() {
|
|
||||||
return widthPx;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setWidthPx(Integer widthPx) {
|
|
||||||
this.widthPx = widthPx;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getHeightPx() {
|
|
||||||
return heightPx;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setHeightPx(Integer heightPx) {
|
|
||||||
this.heightPx = heightPx;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getStatus() {
|
|
||||||
return status;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setStatus(String status) {
|
|
||||||
this.status = status;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getVisibility() {
|
|
||||||
return visibility;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setVisibility(String visibility) {
|
|
||||||
this.visibility = visibility;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getTitle() {
|
|
||||||
return title;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTitle(String title) {
|
|
||||||
this.title = title;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getAltText() {
|
|
||||||
return altText;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAltText(String altText) {
|
|
||||||
this.altText = altText;
|
|
||||||
}
|
|
||||||
|
|
||||||
public OffsetDateTime getCreatedAt() {
|
|
||||||
return createdAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCreatedAt(OffsetDateTime createdAt) {
|
|
||||||
this.createdAt = createdAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public OffsetDateTime getUpdatedAt() {
|
|
||||||
return updatedAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setUpdatedAt(OffsetDateTime updatedAt) {
|
|
||||||
this.updatedAt = updatedAt;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,273 +0,0 @@
|
|||||||
package com.printcalculator.entity;
|
|
||||||
|
|
||||||
import jakarta.persistence.Column;
|
|
||||||
import jakarta.persistence.Entity;
|
|
||||||
import jakarta.persistence.FetchType;
|
|
||||||
import jakarta.persistence.GeneratedValue;
|
|
||||||
import jakarta.persistence.GenerationType;
|
|
||||||
import jakarta.persistence.Id;
|
|
||||||
import jakarta.persistence.Index;
|
|
||||||
import jakarta.persistence.JoinColumn;
|
|
||||||
import jakarta.persistence.ManyToOne;
|
|
||||||
import jakarta.persistence.Table;
|
|
||||||
import org.hibernate.annotations.ColumnDefault;
|
|
||||||
import org.hibernate.annotations.OnDelete;
|
|
||||||
import org.hibernate.annotations.OnDeleteAction;
|
|
||||||
|
|
||||||
import java.time.OffsetDateTime;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
@Entity
|
|
||||||
@Table(name = "media_usage", indexes = {
|
|
||||||
@Index(name = "ix_media_usage_scope", columnList = "usage_type, usage_key, is_active, sort_order")
|
|
||||||
})
|
|
||||||
public class MediaUsage {
|
|
||||||
@Id
|
|
||||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
|
||||||
@Column(name = "media_usage_id", nullable = false)
|
|
||||||
private UUID id;
|
|
||||||
|
|
||||||
@Column(name = "usage_type", nullable = false, length = Integer.MAX_VALUE)
|
|
||||||
private String usageType;
|
|
||||||
|
|
||||||
@Column(name = "usage_key", nullable = false, length = Integer.MAX_VALUE)
|
|
||||||
private String usageKey;
|
|
||||||
|
|
||||||
@Column(name = "owner_id")
|
|
||||||
private UUID ownerId;
|
|
||||||
|
|
||||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
|
||||||
@OnDelete(action = OnDeleteAction.CASCADE)
|
|
||||||
@JoinColumn(name = "media_asset_id", nullable = false)
|
|
||||||
private MediaAsset mediaAsset;
|
|
||||||
|
|
||||||
@ColumnDefault("0")
|
|
||||||
@Column(name = "sort_order", nullable = false)
|
|
||||||
private Integer sortOrder;
|
|
||||||
|
|
||||||
@ColumnDefault("false")
|
|
||||||
@Column(name = "is_primary", nullable = false)
|
|
||||||
private Boolean isPrimary;
|
|
||||||
|
|
||||||
@ColumnDefault("true")
|
|
||||||
@Column(name = "is_active", nullable = false)
|
|
||||||
private Boolean isActive;
|
|
||||||
|
|
||||||
@Column(name = "title_it", length = Integer.MAX_VALUE)
|
|
||||||
private String titleIt;
|
|
||||||
|
|
||||||
@Column(name = "title_en", length = Integer.MAX_VALUE)
|
|
||||||
private String titleEn;
|
|
||||||
|
|
||||||
@Column(name = "title_de", length = Integer.MAX_VALUE)
|
|
||||||
private String titleDe;
|
|
||||||
|
|
||||||
@Column(name = "title_fr", length = Integer.MAX_VALUE)
|
|
||||||
private String titleFr;
|
|
||||||
|
|
||||||
@Column(name = "alt_text_it", length = Integer.MAX_VALUE)
|
|
||||||
private String altTextIt;
|
|
||||||
|
|
||||||
@Column(name = "alt_text_en", length = Integer.MAX_VALUE)
|
|
||||||
private String altTextEn;
|
|
||||||
|
|
||||||
@Column(name = "alt_text_de", length = Integer.MAX_VALUE)
|
|
||||||
private String altTextDe;
|
|
||||||
|
|
||||||
@Column(name = "alt_text_fr", length = Integer.MAX_VALUE)
|
|
||||||
private String altTextFr;
|
|
||||||
|
|
||||||
@ColumnDefault("now()")
|
|
||||||
@Column(name = "created_at", nullable = false)
|
|
||||||
private OffsetDateTime createdAt;
|
|
||||||
|
|
||||||
public UUID getId() {
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setId(UUID id) {
|
|
||||||
this.id = id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getUsageType() {
|
|
||||||
return usageType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setUsageType(String usageType) {
|
|
||||||
this.usageType = usageType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getUsageKey() {
|
|
||||||
return usageKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setUsageKey(String usageKey) {
|
|
||||||
this.usageKey = usageKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
public UUID getOwnerId() {
|
|
||||||
return ownerId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setOwnerId(UUID ownerId) {
|
|
||||||
this.ownerId = ownerId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public MediaAsset getMediaAsset() {
|
|
||||||
return mediaAsset;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setMediaAsset(MediaAsset mediaAsset) {
|
|
||||||
this.mediaAsset = mediaAsset;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getSortOrder() {
|
|
||||||
return sortOrder;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSortOrder(Integer sortOrder) {
|
|
||||||
this.sortOrder = sortOrder;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getIsPrimary() {
|
|
||||||
return isPrimary;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIsPrimary(Boolean primary) {
|
|
||||||
isPrimary = primary;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getIsActive() {
|
|
||||||
return isActive;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIsActive(Boolean active) {
|
|
||||||
isActive = active;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getTitleIt() {
|
|
||||||
return titleIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTitleIt(String titleIt) {
|
|
||||||
this.titleIt = titleIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getTitleEn() {
|
|
||||||
return titleEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTitleEn(String titleEn) {
|
|
||||||
this.titleEn = titleEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getTitleDe() {
|
|
||||||
return titleDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTitleDe(String titleDe) {
|
|
||||||
this.titleDe = titleDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getTitleFr() {
|
|
||||||
return titleFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTitleFr(String titleFr) {
|
|
||||||
this.titleFr = titleFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getAltTextIt() {
|
|
||||||
return altTextIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAltTextIt(String altTextIt) {
|
|
||||||
this.altTextIt = altTextIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getAltTextEn() {
|
|
||||||
return altTextEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAltTextEn(String altTextEn) {
|
|
||||||
this.altTextEn = altTextEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getAltTextDe() {
|
|
||||||
return altTextDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAltTextDe(String altTextDe) {
|
|
||||||
this.altTextDe = altTextDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getAltTextFr() {
|
|
||||||
return altTextFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAltTextFr(String altTextFr) {
|
|
||||||
this.altTextFr = altTextFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public OffsetDateTime getCreatedAt() {
|
|
||||||
return createdAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCreatedAt(OffsetDateTime createdAt) {
|
|
||||||
this.createdAt = createdAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getTitleForLanguage(String language) {
|
|
||||||
if (language == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return switch (language.trim().toLowerCase()) {
|
|
||||||
case "it" -> titleIt;
|
|
||||||
case "en" -> titleEn;
|
|
||||||
case "de" -> titleDe;
|
|
||||||
case "fr" -> titleFr;
|
|
||||||
default -> null;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTitleForLanguage(String language, String value) {
|
|
||||||
if (language == null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
switch (language.trim().toLowerCase()) {
|
|
||||||
case "it" -> titleIt = value;
|
|
||||||
case "en" -> titleEn = value;
|
|
||||||
case "de" -> titleDe = value;
|
|
||||||
case "fr" -> titleFr = value;
|
|
||||||
default -> {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getAltTextForLanguage(String language) {
|
|
||||||
if (language == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return switch (language.trim().toLowerCase()) {
|
|
||||||
case "it" -> altTextIt;
|
|
||||||
case "en" -> altTextEn;
|
|
||||||
case "de" -> altTextDe;
|
|
||||||
case "fr" -> altTextFr;
|
|
||||||
default -> null;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAltTextForLanguage(String language, String value) {
|
|
||||||
if (language == null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
switch (language.trim().toLowerCase()) {
|
|
||||||
case "it" -> altTextIt = value;
|
|
||||||
case "en" -> altTextEn = value;
|
|
||||||
case "de" -> altTextDe = value;
|
|
||||||
case "fr" -> altTextFr = value;
|
|
||||||
default -> {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,154 +0,0 @@
|
|||||||
package com.printcalculator.entity;
|
|
||||||
|
|
||||||
import jakarta.persistence.Column;
|
|
||||||
import jakarta.persistence.Entity;
|
|
||||||
import jakarta.persistence.FetchType;
|
|
||||||
import jakarta.persistence.GeneratedValue;
|
|
||||||
import jakarta.persistence.GenerationType;
|
|
||||||
import jakarta.persistence.Id;
|
|
||||||
import jakarta.persistence.Index;
|
|
||||||
import jakarta.persistence.JoinColumn;
|
|
||||||
import jakarta.persistence.ManyToOne;
|
|
||||||
import jakarta.persistence.Table;
|
|
||||||
import jakarta.persistence.UniqueConstraint;
|
|
||||||
import org.hibernate.annotations.ColumnDefault;
|
|
||||||
import org.hibernate.annotations.OnDelete;
|
|
||||||
import org.hibernate.annotations.OnDeleteAction;
|
|
||||||
|
|
||||||
import java.time.OffsetDateTime;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
@Entity
|
|
||||||
@Table(name = "media_variant", indexes = {
|
|
||||||
@Index(name = "ix_media_variant_asset", columnList = "media_asset_id")
|
|
||||||
}, uniqueConstraints = {
|
|
||||||
@UniqueConstraint(name = "uq_media_variant_asset_name_format", columnNames = {"media_asset_id", "variant_name", "format"})
|
|
||||||
})
|
|
||||||
public class MediaVariant {
|
|
||||||
@Id
|
|
||||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
|
||||||
@Column(name = "media_variant_id", nullable = false)
|
|
||||||
private UUID id;
|
|
||||||
|
|
||||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
|
||||||
@OnDelete(action = OnDeleteAction.CASCADE)
|
|
||||||
@JoinColumn(name = "media_asset_id", nullable = false)
|
|
||||||
private MediaAsset mediaAsset;
|
|
||||||
|
|
||||||
@Column(name = "variant_name", nullable = false, length = Integer.MAX_VALUE)
|
|
||||||
private String variantName;
|
|
||||||
|
|
||||||
@Column(name = "format", nullable = false, length = Integer.MAX_VALUE)
|
|
||||||
private String format;
|
|
||||||
|
|
||||||
@Column(name = "storage_key", nullable = false, length = Integer.MAX_VALUE, unique = true)
|
|
||||||
private String storageKey;
|
|
||||||
|
|
||||||
@Column(name = "mime_type", nullable = false, length = Integer.MAX_VALUE)
|
|
||||||
private String mimeType;
|
|
||||||
|
|
||||||
@Column(name = "width_px", nullable = false)
|
|
||||||
private Integer widthPx;
|
|
||||||
|
|
||||||
@Column(name = "height_px", nullable = false)
|
|
||||||
private Integer heightPx;
|
|
||||||
|
|
||||||
@Column(name = "file_size_bytes", nullable = false)
|
|
||||||
private Long fileSizeBytes;
|
|
||||||
|
|
||||||
@ColumnDefault("true")
|
|
||||||
@Column(name = "is_generated", nullable = false)
|
|
||||||
private Boolean isGenerated;
|
|
||||||
|
|
||||||
@ColumnDefault("now()")
|
|
||||||
@Column(name = "created_at", nullable = false)
|
|
||||||
private OffsetDateTime createdAt;
|
|
||||||
|
|
||||||
public UUID getId() {
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setId(UUID id) {
|
|
||||||
this.id = id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public MediaAsset getMediaAsset() {
|
|
||||||
return mediaAsset;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setMediaAsset(MediaAsset mediaAsset) {
|
|
||||||
this.mediaAsset = mediaAsset;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getVariantName() {
|
|
||||||
return variantName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setVariantName(String variantName) {
|
|
||||||
this.variantName = variantName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getFormat() {
|
|
||||||
return format;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setFormat(String format) {
|
|
||||||
this.format = format;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getStorageKey() {
|
|
||||||
return storageKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setStorageKey(String storageKey) {
|
|
||||||
this.storageKey = storageKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getMimeType() {
|
|
||||||
return mimeType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setMimeType(String mimeType) {
|
|
||||||
this.mimeType = mimeType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getWidthPx() {
|
|
||||||
return widthPx;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setWidthPx(Integer widthPx) {
|
|
||||||
this.widthPx = widthPx;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getHeightPx() {
|
|
||||||
return heightPx;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setHeightPx(Integer heightPx) {
|
|
||||||
this.heightPx = heightPx;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Long getFileSizeBytes() {
|
|
||||||
return fileSizeBytes;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setFileSizeBytes(Long fileSizeBytes) {
|
|
||||||
this.fileSizeBytes = fileSizeBytes;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getIsGenerated() {
|
|
||||||
return isGenerated;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIsGenerated(Boolean generated) {
|
|
||||||
isGenerated = generated;
|
|
||||||
}
|
|
||||||
|
|
||||||
public OffsetDateTime getCreatedAt() {
|
|
||||||
return createdAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCreatedAt(OffsetDateTime createdAt) {
|
|
||||||
this.createdAt = createdAt;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -20,10 +20,6 @@ public class Order {
|
|||||||
@JoinColumn(name = "source_quote_session_id")
|
@JoinColumn(name = "source_quote_session_id")
|
||||||
private QuoteSession sourceQuoteSession;
|
private QuoteSession sourceQuoteSession;
|
||||||
|
|
||||||
@ColumnDefault("'CALCULATOR'")
|
|
||||||
@Column(name = "source_type", nullable = false, length = Integer.MAX_VALUE)
|
|
||||||
private String sourceType;
|
|
||||||
|
|
||||||
@Column(name = "status", nullable = false, length = Integer.MAX_VALUE)
|
@Column(name = "status", nullable = false, length = Integer.MAX_VALUE)
|
||||||
private String status;
|
private String status;
|
||||||
|
|
||||||
@@ -155,34 +151,6 @@ public class Order {
|
|||||||
@Column(name = "paid_at")
|
@Column(name = "paid_at")
|
||||||
private OffsetDateTime paidAt;
|
private OffsetDateTime paidAt;
|
||||||
|
|
||||||
@PrePersist
|
|
||||||
private void onCreate() {
|
|
||||||
OffsetDateTime now = OffsetDateTime.now();
|
|
||||||
if (createdAt == null) {
|
|
||||||
createdAt = now;
|
|
||||||
}
|
|
||||||
if (updatedAt == null) {
|
|
||||||
updatedAt = now;
|
|
||||||
}
|
|
||||||
if (shippingSameAsBilling == null) {
|
|
||||||
shippingSameAsBilling = true;
|
|
||||||
}
|
|
||||||
if (sourceType == null || sourceType.isBlank()) {
|
|
||||||
sourceType = "CALCULATOR";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@PreUpdate
|
|
||||||
private void onUpdate() {
|
|
||||||
updatedAt = OffsetDateTime.now();
|
|
||||||
if (shippingSameAsBilling == null) {
|
|
||||||
shippingSameAsBilling = true;
|
|
||||||
}
|
|
||||||
if (sourceType == null || sourceType.isBlank()) {
|
|
||||||
sourceType = "CALCULATOR";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public UUID getId() {
|
public UUID getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
@@ -209,14 +177,6 @@ public class Order {
|
|||||||
this.sourceQuoteSession = sourceQuoteSession;
|
this.sourceQuoteSession = sourceQuoteSession;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getSourceType() {
|
|
||||||
return sourceType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSourceType(String sourceType) {
|
|
||||||
this.sourceType = sourceType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getStatus() {
|
public String getStatus() {
|
||||||
return status;
|
return status;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,16 +23,9 @@ public class OrderItem {
|
|||||||
@JoinColumn(name = "order_id", nullable = false)
|
@JoinColumn(name = "order_id", nullable = false)
|
||||||
private Order order;
|
private Order order;
|
||||||
|
|
||||||
@ColumnDefault("'PRINT_FILE'")
|
|
||||||
@Column(name = "item_type", nullable = false, length = Integer.MAX_VALUE)
|
|
||||||
private String itemType;
|
|
||||||
|
|
||||||
@Column(name = "original_filename", nullable = false, length = Integer.MAX_VALUE)
|
@Column(name = "original_filename", nullable = false, length = Integer.MAX_VALUE)
|
||||||
private String originalFilename;
|
private String originalFilename;
|
||||||
|
|
||||||
@Column(name = "display_name", length = Integer.MAX_VALUE)
|
|
||||||
private String displayName;
|
|
||||||
|
|
||||||
@Column(name = "stored_relative_path", nullable = false, length = Integer.MAX_VALUE)
|
@Column(name = "stored_relative_path", nullable = false, length = Integer.MAX_VALUE)
|
||||||
private String storedRelativePath;
|
private String storedRelativePath;
|
||||||
|
|
||||||
@@ -73,29 +66,6 @@ public class OrderItem {
|
|||||||
@JoinColumn(name = "filament_variant_id")
|
@JoinColumn(name = "filament_variant_id")
|
||||||
private FilamentVariant filamentVariant;
|
private FilamentVariant filamentVariant;
|
||||||
|
|
||||||
@ManyToOne(fetch = FetchType.LAZY)
|
|
||||||
@JoinColumn(name = "shop_product_id")
|
|
||||||
private ShopProduct shopProduct;
|
|
||||||
|
|
||||||
@ManyToOne(fetch = FetchType.LAZY)
|
|
||||||
@JoinColumn(name = "shop_product_variant_id")
|
|
||||||
private ShopProductVariant shopProductVariant;
|
|
||||||
|
|
||||||
@Column(name = "shop_product_slug", length = Integer.MAX_VALUE)
|
|
||||||
private String shopProductSlug;
|
|
||||||
|
|
||||||
@Column(name = "shop_product_name", length = Integer.MAX_VALUE)
|
|
||||||
private String shopProductName;
|
|
||||||
|
|
||||||
@Column(name = "shop_variant_label", length = Integer.MAX_VALUE)
|
|
||||||
private String shopVariantLabel;
|
|
||||||
|
|
||||||
@Column(name = "shop_variant_color_name", length = Integer.MAX_VALUE)
|
|
||||||
private String shopVariantColorName;
|
|
||||||
|
|
||||||
@Column(name = "shop_variant_color_hex", length = Integer.MAX_VALUE)
|
|
||||||
private String shopVariantColorHex;
|
|
||||||
|
|
||||||
@Column(name = "color_code", length = Integer.MAX_VALUE)
|
@Column(name = "color_code", length = Integer.MAX_VALUE)
|
||||||
private String colorCode;
|
private String colorCode;
|
||||||
|
|
||||||
@@ -136,14 +106,6 @@ public class OrderItem {
|
|||||||
if (quantity == null) {
|
if (quantity == null) {
|
||||||
quantity = 1;
|
quantity = 1;
|
||||||
}
|
}
|
||||||
if (itemType == null || itemType.isBlank()) {
|
|
||||||
itemType = "PRINT_FILE";
|
|
||||||
}
|
|
||||||
if ((displayName == null || displayName.isBlank()) && originalFilename != null && !originalFilename.isBlank()) {
|
|
||||||
displayName = originalFilename;
|
|
||||||
} else if ((displayName == null || displayName.isBlank()) && shopProductName != null && !shopProductName.isBlank()) {
|
|
||||||
displayName = shopProductName;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public UUID getId() {
|
public UUID getId() {
|
||||||
@@ -162,14 +124,6 @@ public class OrderItem {
|
|||||||
this.order = order;
|
this.order = order;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getItemType() {
|
|
||||||
return itemType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setItemType(String itemType) {
|
|
||||||
this.itemType = itemType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getOriginalFilename() {
|
public String getOriginalFilename() {
|
||||||
return originalFilename;
|
return originalFilename;
|
||||||
}
|
}
|
||||||
@@ -178,14 +132,6 @@ public class OrderItem {
|
|||||||
this.originalFilename = originalFilename;
|
this.originalFilename = originalFilename;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getDisplayName() {
|
|
||||||
return displayName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDisplayName(String displayName) {
|
|
||||||
this.displayName = displayName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getStoredRelativePath() {
|
public String getStoredRelativePath() {
|
||||||
return storedRelativePath;
|
return storedRelativePath;
|
||||||
}
|
}
|
||||||
@@ -290,62 +236,6 @@ public class OrderItem {
|
|||||||
this.filamentVariant = filamentVariant;
|
this.filamentVariant = filamentVariant;
|
||||||
}
|
}
|
||||||
|
|
||||||
public ShopProduct getShopProduct() {
|
|
||||||
return shopProduct;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setShopProduct(ShopProduct shopProduct) {
|
|
||||||
this.shopProduct = shopProduct;
|
|
||||||
}
|
|
||||||
|
|
||||||
public ShopProductVariant getShopProductVariant() {
|
|
||||||
return shopProductVariant;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setShopProductVariant(ShopProductVariant shopProductVariant) {
|
|
||||||
this.shopProductVariant = shopProductVariant;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getShopProductSlug() {
|
|
||||||
return shopProductSlug;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setShopProductSlug(String shopProductSlug) {
|
|
||||||
this.shopProductSlug = shopProductSlug;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getShopProductName() {
|
|
||||||
return shopProductName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setShopProductName(String shopProductName) {
|
|
||||||
this.shopProductName = shopProductName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getShopVariantLabel() {
|
|
||||||
return shopVariantLabel;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setShopVariantLabel(String shopVariantLabel) {
|
|
||||||
this.shopVariantLabel = shopVariantLabel;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getShopVariantColorName() {
|
|
||||||
return shopVariantColorName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setShopVariantColorName(String shopVariantColorName) {
|
|
||||||
this.shopVariantColorName = shopVariantColorName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getShopVariantColorHex() {
|
|
||||||
return shopVariantColorHex;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setShopVariantColorHex(String shopVariantColorHex) {
|
|
||||||
this.shopVariantColorHex = shopVariantColorHex;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getColorCode() {
|
public String getColorCode() {
|
||||||
return colorCode;
|
return colorCode;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -30,16 +30,9 @@ public class QuoteLineItem {
|
|||||||
@Column(name = "status", nullable = false, length = Integer.MAX_VALUE)
|
@Column(name = "status", nullable = false, length = Integer.MAX_VALUE)
|
||||||
private String status;
|
private String status;
|
||||||
|
|
||||||
@ColumnDefault("'PRINT_FILE'")
|
|
||||||
@Column(name = "line_item_type", nullable = false, length = Integer.MAX_VALUE)
|
|
||||||
private String lineItemType;
|
|
||||||
|
|
||||||
@Column(name = "original_filename", nullable = false, length = Integer.MAX_VALUE)
|
@Column(name = "original_filename", nullable = false, length = Integer.MAX_VALUE)
|
||||||
private String originalFilename;
|
private String originalFilename;
|
||||||
|
|
||||||
@Column(name = "display_name", length = Integer.MAX_VALUE)
|
|
||||||
private String displayName;
|
|
||||||
|
|
||||||
@ColumnDefault("1")
|
@ColumnDefault("1")
|
||||||
@Column(name = "quantity", nullable = false)
|
@Column(name = "quantity", nullable = false)
|
||||||
private Integer quantity;
|
private Integer quantity;
|
||||||
@@ -52,31 +45,6 @@ public class QuoteLineItem {
|
|||||||
@com.fasterxml.jackson.annotation.JsonIgnore
|
@com.fasterxml.jackson.annotation.JsonIgnore
|
||||||
private FilamentVariant filamentVariant;
|
private FilamentVariant filamentVariant;
|
||||||
|
|
||||||
@ManyToOne(fetch = FetchType.LAZY)
|
|
||||||
@JoinColumn(name = "shop_product_id")
|
|
||||||
@com.fasterxml.jackson.annotation.JsonIgnore
|
|
||||||
private ShopProduct shopProduct;
|
|
||||||
|
|
||||||
@ManyToOne(fetch = FetchType.LAZY)
|
|
||||||
@JoinColumn(name = "shop_product_variant_id")
|
|
||||||
@com.fasterxml.jackson.annotation.JsonIgnore
|
|
||||||
private ShopProductVariant shopProductVariant;
|
|
||||||
|
|
||||||
@Column(name = "shop_product_slug", length = Integer.MAX_VALUE)
|
|
||||||
private String shopProductSlug;
|
|
||||||
|
|
||||||
@Column(name = "shop_product_name", length = Integer.MAX_VALUE)
|
|
||||||
private String shopProductName;
|
|
||||||
|
|
||||||
@Column(name = "shop_variant_label", length = Integer.MAX_VALUE)
|
|
||||||
private String shopVariantLabel;
|
|
||||||
|
|
||||||
@Column(name = "shop_variant_color_name", length = Integer.MAX_VALUE)
|
|
||||||
private String shopVariantColorName;
|
|
||||||
|
|
||||||
@Column(name = "shop_variant_color_hex", length = Integer.MAX_VALUE)
|
|
||||||
private String shopVariantColorHex;
|
|
||||||
|
|
||||||
@Column(name = "material_code", length = Integer.MAX_VALUE)
|
@Column(name = "material_code", length = Integer.MAX_VALUE)
|
||||||
private String materialCode;
|
private String materialCode;
|
||||||
|
|
||||||
@@ -134,41 +102,6 @@ public class QuoteLineItem {
|
|||||||
@Column(name = "updated_at", nullable = false)
|
@Column(name = "updated_at", nullable = false)
|
||||||
private OffsetDateTime updatedAt;
|
private OffsetDateTime updatedAt;
|
||||||
|
|
||||||
@PrePersist
|
|
||||||
private void onCreate() {
|
|
||||||
OffsetDateTime now = OffsetDateTime.now();
|
|
||||||
if (createdAt == null) {
|
|
||||||
createdAt = now;
|
|
||||||
}
|
|
||||||
if (updatedAt == null) {
|
|
||||||
updatedAt = now;
|
|
||||||
}
|
|
||||||
if (quantity == null) {
|
|
||||||
quantity = 1;
|
|
||||||
}
|
|
||||||
if (lineItemType == null || lineItemType.isBlank()) {
|
|
||||||
lineItemType = "PRINT_FILE";
|
|
||||||
}
|
|
||||||
if ((displayName == null || displayName.isBlank()) && originalFilename != null && !originalFilename.isBlank()) {
|
|
||||||
displayName = originalFilename;
|
|
||||||
} else if ((displayName == null || displayName.isBlank()) && shopProductName != null && !shopProductName.isBlank()) {
|
|
||||||
displayName = shopProductName;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@PreUpdate
|
|
||||||
private void onUpdate() {
|
|
||||||
updatedAt = OffsetDateTime.now();
|
|
||||||
if (lineItemType == null || lineItemType.isBlank()) {
|
|
||||||
lineItemType = "PRINT_FILE";
|
|
||||||
}
|
|
||||||
if ((displayName == null || displayName.isBlank()) && originalFilename != null && !originalFilename.isBlank()) {
|
|
||||||
displayName = originalFilename;
|
|
||||||
} else if ((displayName == null || displayName.isBlank()) && shopProductName != null && !shopProductName.isBlank()) {
|
|
||||||
displayName = shopProductName;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public UUID getId() {
|
public UUID getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
@@ -193,14 +126,6 @@ public class QuoteLineItem {
|
|||||||
this.status = status;
|
this.status = status;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getLineItemType() {
|
|
||||||
return lineItemType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setLineItemType(String lineItemType) {
|
|
||||||
this.lineItemType = lineItemType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getOriginalFilename() {
|
public String getOriginalFilename() {
|
||||||
return originalFilename;
|
return originalFilename;
|
||||||
}
|
}
|
||||||
@@ -209,14 +134,6 @@ public class QuoteLineItem {
|
|||||||
this.originalFilename = originalFilename;
|
this.originalFilename = originalFilename;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getDisplayName() {
|
|
||||||
return displayName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDisplayName(String displayName) {
|
|
||||||
this.displayName = displayName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getQuantity() {
|
public Integer getQuantity() {
|
||||||
return quantity;
|
return quantity;
|
||||||
}
|
}
|
||||||
@@ -241,62 +158,6 @@ public class QuoteLineItem {
|
|||||||
this.filamentVariant = filamentVariant;
|
this.filamentVariant = filamentVariant;
|
||||||
}
|
}
|
||||||
|
|
||||||
public ShopProduct getShopProduct() {
|
|
||||||
return shopProduct;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setShopProduct(ShopProduct shopProduct) {
|
|
||||||
this.shopProduct = shopProduct;
|
|
||||||
}
|
|
||||||
|
|
||||||
public ShopProductVariant getShopProductVariant() {
|
|
||||||
return shopProductVariant;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setShopProductVariant(ShopProductVariant shopProductVariant) {
|
|
||||||
this.shopProductVariant = shopProductVariant;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getShopProductSlug() {
|
|
||||||
return shopProductSlug;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setShopProductSlug(String shopProductSlug) {
|
|
||||||
this.shopProductSlug = shopProductSlug;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getShopProductName() {
|
|
||||||
return shopProductName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setShopProductName(String shopProductName) {
|
|
||||||
this.shopProductName = shopProductName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getShopVariantLabel() {
|
|
||||||
return shopVariantLabel;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setShopVariantLabel(String shopVariantLabel) {
|
|
||||||
this.shopVariantLabel = shopVariantLabel;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getShopVariantColorName() {
|
|
||||||
return shopVariantColorName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setShopVariantColorName(String shopVariantColorName) {
|
|
||||||
this.shopVariantColorName = shopVariantColorName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getShopVariantColorHex() {
|
|
||||||
return shopVariantColorHex;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setShopVariantColorHex(String shopVariantColorHex) {
|
|
||||||
this.shopVariantColorHex = shopVariantColorHex;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getMaterialCode() {
|
public String getMaterialCode() {
|
||||||
return materialCode;
|
return materialCode;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,10 +22,6 @@ public class QuoteSession {
|
|||||||
@Column(name = "status", nullable = false, length = Integer.MAX_VALUE)
|
@Column(name = "status", nullable = false, length = Integer.MAX_VALUE)
|
||||||
private String status;
|
private String status;
|
||||||
|
|
||||||
@ColumnDefault("'PRINT_QUOTE'")
|
|
||||||
@Column(name = "session_type", nullable = false, length = Integer.MAX_VALUE)
|
|
||||||
private String sessionType;
|
|
||||||
|
|
||||||
@Column(name = "pricing_version", nullable = false, length = Integer.MAX_VALUE)
|
@Column(name = "pricing_version", nullable = false, length = Integer.MAX_VALUE)
|
||||||
private String pricingVersion;
|
private String pricingVersion;
|
||||||
|
|
||||||
@@ -74,19 +70,6 @@ public class QuoteSession {
|
|||||||
@Column(name = "cad_hourly_rate_chf", precision = 10, scale = 2)
|
@Column(name = "cad_hourly_rate_chf", precision = 10, scale = 2)
|
||||||
private BigDecimal cadHourlyRateChf;
|
private BigDecimal cadHourlyRateChf;
|
||||||
|
|
||||||
@PrePersist
|
|
||||||
private void onCreate() {
|
|
||||||
if (sessionType == null || sessionType.isBlank()) {
|
|
||||||
sessionType = "PRINT_QUOTE";
|
|
||||||
}
|
|
||||||
if (supportsEnabled == null) {
|
|
||||||
supportsEnabled = false;
|
|
||||||
}
|
|
||||||
if (createdAt == null) {
|
|
||||||
createdAt = OffsetDateTime.now();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public UUID getId() {
|
public UUID getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
@@ -103,14 +86,6 @@ public class QuoteSession {
|
|||||||
this.status = status;
|
this.status = status;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getSessionType() {
|
|
||||||
return sessionType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSessionType(String sessionType) {
|
|
||||||
this.sessionType = sessionType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getPricingVersion() {
|
public String getPricingVersion() {
|
||||||
return pricingVersion;
|
return pricingVersion;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,505 +0,0 @@
|
|||||||
package com.printcalculator.entity;
|
|
||||||
|
|
||||||
import jakarta.persistence.Column;
|
|
||||||
import jakarta.persistence.Entity;
|
|
||||||
import jakarta.persistence.FetchType;
|
|
||||||
import jakarta.persistence.GeneratedValue;
|
|
||||||
import jakarta.persistence.GenerationType;
|
|
||||||
import jakarta.persistence.Id;
|
|
||||||
import jakarta.persistence.Index;
|
|
||||||
import jakarta.persistence.JoinColumn;
|
|
||||||
import jakarta.persistence.ManyToOne;
|
|
||||||
import jakarta.persistence.PrePersist;
|
|
||||||
import jakarta.persistence.PreUpdate;
|
|
||||||
import jakarta.persistence.Table;
|
|
||||||
import org.hibernate.annotations.ColumnDefault;
|
|
||||||
|
|
||||||
import java.time.OffsetDateTime;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
@Entity
|
|
||||||
@Table(name = "shop_category", indexes = {
|
|
||||||
@Index(name = "ix_shop_category_parent_sort", columnList = "parent_category_id, sort_order"),
|
|
||||||
@Index(name = "ix_shop_category_active_sort", columnList = "is_active, sort_order")
|
|
||||||
})
|
|
||||||
public class ShopCategory {
|
|
||||||
public static final List<String> SUPPORTED_LANGUAGES = List.of("it", "en", "de", "fr");
|
|
||||||
|
|
||||||
@Id
|
|
||||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
|
||||||
@Column(name = "shop_category_id", nullable = false)
|
|
||||||
private UUID id;
|
|
||||||
|
|
||||||
@ManyToOne(fetch = FetchType.LAZY)
|
|
||||||
@JoinColumn(name = "parent_category_id")
|
|
||||||
private ShopCategory parentCategory;
|
|
||||||
|
|
||||||
@Column(name = "slug", nullable = false, unique = true, length = Integer.MAX_VALUE)
|
|
||||||
private String slug;
|
|
||||||
|
|
||||||
@Column(name = "name", nullable = false, length = Integer.MAX_VALUE)
|
|
||||||
private String name;
|
|
||||||
|
|
||||||
@Column(name = "name_it", length = Integer.MAX_VALUE)
|
|
||||||
private String nameIt;
|
|
||||||
|
|
||||||
@Column(name = "name_en", length = Integer.MAX_VALUE)
|
|
||||||
private String nameEn;
|
|
||||||
|
|
||||||
@Column(name = "name_de", length = Integer.MAX_VALUE)
|
|
||||||
private String nameDe;
|
|
||||||
|
|
||||||
@Column(name = "name_fr", length = Integer.MAX_VALUE)
|
|
||||||
private String nameFr;
|
|
||||||
|
|
||||||
@Column(name = "description", length = Integer.MAX_VALUE)
|
|
||||||
private String description;
|
|
||||||
|
|
||||||
@Column(name = "description_it", length = Integer.MAX_VALUE)
|
|
||||||
private String descriptionIt;
|
|
||||||
|
|
||||||
@Column(name = "description_en", length = Integer.MAX_VALUE)
|
|
||||||
private String descriptionEn;
|
|
||||||
|
|
||||||
@Column(name = "description_de", length = Integer.MAX_VALUE)
|
|
||||||
private String descriptionDe;
|
|
||||||
|
|
||||||
@Column(name = "description_fr", length = Integer.MAX_VALUE)
|
|
||||||
private String descriptionFr;
|
|
||||||
|
|
||||||
@Column(name = "seo_title", length = Integer.MAX_VALUE)
|
|
||||||
private String seoTitle;
|
|
||||||
|
|
||||||
@Column(name = "seo_title_it", length = Integer.MAX_VALUE)
|
|
||||||
private String seoTitleIt;
|
|
||||||
|
|
||||||
@Column(name = "seo_title_en", length = Integer.MAX_VALUE)
|
|
||||||
private String seoTitleEn;
|
|
||||||
|
|
||||||
@Column(name = "seo_title_de", length = Integer.MAX_VALUE)
|
|
||||||
private String seoTitleDe;
|
|
||||||
|
|
||||||
@Column(name = "seo_title_fr", length = Integer.MAX_VALUE)
|
|
||||||
private String seoTitleFr;
|
|
||||||
|
|
||||||
@Column(name = "seo_description", length = Integer.MAX_VALUE)
|
|
||||||
private String seoDescription;
|
|
||||||
|
|
||||||
@Column(name = "seo_description_it", length = Integer.MAX_VALUE)
|
|
||||||
private String seoDescriptionIt;
|
|
||||||
|
|
||||||
@Column(name = "seo_description_en", length = Integer.MAX_VALUE)
|
|
||||||
private String seoDescriptionEn;
|
|
||||||
|
|
||||||
@Column(name = "seo_description_de", length = Integer.MAX_VALUE)
|
|
||||||
private String seoDescriptionDe;
|
|
||||||
|
|
||||||
@Column(name = "seo_description_fr", length = Integer.MAX_VALUE)
|
|
||||||
private String seoDescriptionFr;
|
|
||||||
|
|
||||||
@Column(name = "og_title", length = Integer.MAX_VALUE)
|
|
||||||
private String ogTitle;
|
|
||||||
|
|
||||||
@Column(name = "og_description", length = Integer.MAX_VALUE)
|
|
||||||
private String ogDescription;
|
|
||||||
|
|
||||||
@ColumnDefault("true")
|
|
||||||
@Column(name = "indexable", nullable = false)
|
|
||||||
private Boolean indexable;
|
|
||||||
|
|
||||||
@ColumnDefault("true")
|
|
||||||
@Column(name = "is_active", nullable = false)
|
|
||||||
private Boolean isActive;
|
|
||||||
|
|
||||||
@ColumnDefault("0")
|
|
||||||
@Column(name = "sort_order", nullable = false)
|
|
||||||
private Integer sortOrder;
|
|
||||||
|
|
||||||
@ColumnDefault("now()")
|
|
||||||
@Column(name = "created_at", nullable = false)
|
|
||||||
private OffsetDateTime createdAt;
|
|
||||||
|
|
||||||
@ColumnDefault("now()")
|
|
||||||
@Column(name = "updated_at", nullable = false)
|
|
||||||
private OffsetDateTime updatedAt;
|
|
||||||
|
|
||||||
@PrePersist
|
|
||||||
private void onCreate() {
|
|
||||||
OffsetDateTime now = OffsetDateTime.now();
|
|
||||||
if (createdAt == null) {
|
|
||||||
createdAt = now;
|
|
||||||
}
|
|
||||||
if (updatedAt == null) {
|
|
||||||
updatedAt = now;
|
|
||||||
}
|
|
||||||
if (indexable == null) {
|
|
||||||
indexable = true;
|
|
||||||
}
|
|
||||||
if (isActive == null) {
|
|
||||||
isActive = true;
|
|
||||||
}
|
|
||||||
if (sortOrder == null) {
|
|
||||||
sortOrder = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@PreUpdate
|
|
||||||
private void onUpdate() {
|
|
||||||
updatedAt = OffsetDateTime.now();
|
|
||||||
if (indexable == null) {
|
|
||||||
indexable = true;
|
|
||||||
}
|
|
||||||
if (isActive == null) {
|
|
||||||
isActive = true;
|
|
||||||
}
|
|
||||||
if (sortOrder == null) {
|
|
||||||
sortOrder = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public UUID getId() {
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setId(UUID id) {
|
|
||||||
this.id = id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public ShopCategory getParentCategory() {
|
|
||||||
return parentCategory;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setParentCategory(ShopCategory parentCategory) {
|
|
||||||
this.parentCategory = parentCategory;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSlug() {
|
|
||||||
return slug;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSlug(String slug) {
|
|
||||||
this.slug = slug;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getName() {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setName(String name) {
|
|
||||||
this.name = name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getNameIt() {
|
|
||||||
return nameIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setNameIt(String nameIt) {
|
|
||||||
this.nameIt = nameIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getNameEn() {
|
|
||||||
return nameEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setNameEn(String nameEn) {
|
|
||||||
this.nameEn = nameEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getNameDe() {
|
|
||||||
return nameDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setNameDe(String nameDe) {
|
|
||||||
this.nameDe = nameDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getNameFr() {
|
|
||||||
return nameFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setNameFr(String nameFr) {
|
|
||||||
this.nameFr = nameFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescription() {
|
|
||||||
return description;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescription(String description) {
|
|
||||||
this.description = description;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescriptionIt() {
|
|
||||||
return descriptionIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescriptionIt(String descriptionIt) {
|
|
||||||
this.descriptionIt = descriptionIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescriptionEn() {
|
|
||||||
return descriptionEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescriptionEn(String descriptionEn) {
|
|
||||||
this.descriptionEn = descriptionEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescriptionDe() {
|
|
||||||
return descriptionDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescriptionDe(String descriptionDe) {
|
|
||||||
this.descriptionDe = descriptionDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescriptionFr() {
|
|
||||||
return descriptionFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescriptionFr(String descriptionFr) {
|
|
||||||
this.descriptionFr = descriptionFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoTitle() {
|
|
||||||
return seoTitle;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitle(String seoTitle) {
|
|
||||||
this.seoTitle = seoTitle;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoTitleIt() {
|
|
||||||
return seoTitleIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitleIt(String seoTitleIt) {
|
|
||||||
this.seoTitleIt = seoTitleIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoTitleEn() {
|
|
||||||
return seoTitleEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitleEn(String seoTitleEn) {
|
|
||||||
this.seoTitleEn = seoTitleEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoTitleDe() {
|
|
||||||
return seoTitleDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitleDe(String seoTitleDe) {
|
|
||||||
this.seoTitleDe = seoTitleDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoTitleFr() {
|
|
||||||
return seoTitleFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitleFr(String seoTitleFr) {
|
|
||||||
this.seoTitleFr = seoTitleFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoDescription() {
|
|
||||||
return seoDescription;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescription(String seoDescription) {
|
|
||||||
this.seoDescription = seoDescription;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoDescriptionIt() {
|
|
||||||
return seoDescriptionIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescriptionIt(String seoDescriptionIt) {
|
|
||||||
this.seoDescriptionIt = seoDescriptionIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoDescriptionEn() {
|
|
||||||
return seoDescriptionEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescriptionEn(String seoDescriptionEn) {
|
|
||||||
this.seoDescriptionEn = seoDescriptionEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoDescriptionDe() {
|
|
||||||
return seoDescriptionDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescriptionDe(String seoDescriptionDe) {
|
|
||||||
this.seoDescriptionDe = seoDescriptionDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoDescriptionFr() {
|
|
||||||
return seoDescriptionFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescriptionFr(String seoDescriptionFr) {
|
|
||||||
this.seoDescriptionFr = seoDescriptionFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getOgTitle() {
|
|
||||||
return ogTitle;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setOgTitle(String ogTitle) {
|
|
||||||
this.ogTitle = ogTitle;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getOgDescription() {
|
|
||||||
return ogDescription;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setOgDescription(String ogDescription) {
|
|
||||||
this.ogDescription = ogDescription;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getIndexable() {
|
|
||||||
return indexable;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIndexable(Boolean indexable) {
|
|
||||||
this.indexable = indexable;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getIsActive() {
|
|
||||||
return isActive;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIsActive(Boolean active) {
|
|
||||||
isActive = active;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getSortOrder() {
|
|
||||||
return sortOrder;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSortOrder(Integer sortOrder) {
|
|
||||||
this.sortOrder = sortOrder;
|
|
||||||
}
|
|
||||||
|
|
||||||
public OffsetDateTime getCreatedAt() {
|
|
||||||
return createdAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCreatedAt(OffsetDateTime createdAt) {
|
|
||||||
this.createdAt = createdAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public OffsetDateTime getUpdatedAt() {
|
|
||||||
return updatedAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setUpdatedAt(OffsetDateTime updatedAt) {
|
|
||||||
this.updatedAt = updatedAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getNameForLanguage(String language) {
|
|
||||||
return resolveLocalizedValue(language, name, nameIt, nameEn, nameDe, nameFr);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setNameForLanguage(String language, String value) {
|
|
||||||
switch (normalizeLanguage(language)) {
|
|
||||||
case "it" -> nameIt = value;
|
|
||||||
case "en" -> nameEn = value;
|
|
||||||
case "de" -> nameDe = value;
|
|
||||||
case "fr" -> nameFr = value;
|
|
||||||
default -> {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescriptionForLanguage(String language) {
|
|
||||||
return resolveLocalizedValue(language, description, descriptionIt, descriptionEn, descriptionDe, descriptionFr);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescriptionForLanguage(String language, String value) {
|
|
||||||
switch (normalizeLanguage(language)) {
|
|
||||||
case "it" -> descriptionIt = value;
|
|
||||||
case "en" -> descriptionEn = value;
|
|
||||||
case "de" -> descriptionDe = value;
|
|
||||||
case "fr" -> descriptionFr = value;
|
|
||||||
default -> {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoTitleForLanguage(String language) {
|
|
||||||
return resolveLocalizedValue(language, seoTitle, seoTitleIt, seoTitleEn, seoTitleDe, seoTitleFr);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitleForLanguage(String language, String value) {
|
|
||||||
switch (normalizeLanguage(language)) {
|
|
||||||
case "it" -> seoTitleIt = value;
|
|
||||||
case "en" -> seoTitleEn = value;
|
|
||||||
case "de" -> seoTitleDe = value;
|
|
||||||
case "fr" -> seoTitleFr = value;
|
|
||||||
default -> {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoDescriptionForLanguage(String language) {
|
|
||||||
return resolveLocalizedValue(language, seoDescription, seoDescriptionIt, seoDescriptionEn, seoDescriptionDe, seoDescriptionFr);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescriptionForLanguage(String language, String value) {
|
|
||||||
switch (normalizeLanguage(language)) {
|
|
||||||
case "it" -> seoDescriptionIt = value;
|
|
||||||
case "en" -> seoDescriptionEn = value;
|
|
||||||
case "de" -> seoDescriptionDe = value;
|
|
||||||
case "fr" -> seoDescriptionFr = value;
|
|
||||||
default -> {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private String resolveLocalizedValue(String language,
|
|
||||||
String fallback,
|
|
||||||
String valueIt,
|
|
||||||
String valueEn,
|
|
||||||
String valueDe,
|
|
||||||
String valueFr) {
|
|
||||||
String normalizedLanguage = normalizeLanguage(language);
|
|
||||||
String preferred = switch (normalizedLanguage) {
|
|
||||||
case "it" -> valueIt;
|
|
||||||
case "en" -> valueEn;
|
|
||||||
case "de" -> valueDe;
|
|
||||||
case "fr" -> valueFr;
|
|
||||||
default -> null;
|
|
||||||
};
|
|
||||||
String resolved = firstNonBlank(preferred, fallback);
|
|
||||||
if (resolved != null) {
|
|
||||||
return resolved;
|
|
||||||
}
|
|
||||||
return firstNonBlank(valueIt, valueEn, valueDe, valueFr);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeLanguage(String language) {
|
|
||||||
if (language == null) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
String normalized = language.trim().toLowerCase();
|
|
||||||
int separatorIndex = normalized.indexOf('-');
|
|
||||||
if (separatorIndex > 0) {
|
|
||||||
normalized = normalized.substring(0, separatorIndex);
|
|
||||||
}
|
|
||||||
return normalized;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String firstNonBlank(String... values) {
|
|
||||||
if (values == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
for (String value : values) {
|
|
||||||
if (value != null && !value.isBlank()) {
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,593 +0,0 @@
|
|||||||
package com.printcalculator.entity;
|
|
||||||
|
|
||||||
import jakarta.persistence.Column;
|
|
||||||
import jakarta.persistence.Entity;
|
|
||||||
import jakarta.persistence.FetchType;
|
|
||||||
import jakarta.persistence.GeneratedValue;
|
|
||||||
import jakarta.persistence.GenerationType;
|
|
||||||
import jakarta.persistence.Id;
|
|
||||||
import jakarta.persistence.Index;
|
|
||||||
import jakarta.persistence.JoinColumn;
|
|
||||||
import jakarta.persistence.ManyToOne;
|
|
||||||
import jakarta.persistence.PrePersist;
|
|
||||||
import jakarta.persistence.PreUpdate;
|
|
||||||
import jakarta.persistence.Table;
|
|
||||||
import org.hibernate.annotations.ColumnDefault;
|
|
||||||
|
|
||||||
import java.time.OffsetDateTime;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
@Entity
|
|
||||||
@Table(name = "shop_product", indexes = {
|
|
||||||
@Index(name = "ix_shop_product_category_active_sort", columnList = "shop_category_id, is_active, sort_order"),
|
|
||||||
@Index(name = "ix_shop_product_featured_sort", columnList = "is_featured, is_active, sort_order")
|
|
||||||
})
|
|
||||||
public class ShopProduct {
|
|
||||||
public static final List<String> SUPPORTED_LANGUAGES = List.of("it", "en", "de", "fr");
|
|
||||||
|
|
||||||
@Id
|
|
||||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
|
||||||
@Column(name = "shop_product_id", nullable = false)
|
|
||||||
private UUID id;
|
|
||||||
|
|
||||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
|
||||||
@JoinColumn(name = "shop_category_id", nullable = false)
|
|
||||||
private ShopCategory category;
|
|
||||||
|
|
||||||
@Column(name = "slug", nullable = false, unique = true, length = Integer.MAX_VALUE)
|
|
||||||
private String slug;
|
|
||||||
|
|
||||||
@Column(name = "name", nullable = false, length = Integer.MAX_VALUE)
|
|
||||||
private String name;
|
|
||||||
|
|
||||||
@Column(name = "name_it", length = Integer.MAX_VALUE)
|
|
||||||
private String nameIt;
|
|
||||||
|
|
||||||
@Column(name = "name_en", length = Integer.MAX_VALUE)
|
|
||||||
private String nameEn;
|
|
||||||
|
|
||||||
@Column(name = "name_de", length = Integer.MAX_VALUE)
|
|
||||||
private String nameDe;
|
|
||||||
|
|
||||||
@Column(name = "name_fr", length = Integer.MAX_VALUE)
|
|
||||||
private String nameFr;
|
|
||||||
|
|
||||||
@Column(name = "excerpt", length = Integer.MAX_VALUE)
|
|
||||||
private String excerpt;
|
|
||||||
|
|
||||||
@Column(name = "excerpt_it", length = Integer.MAX_VALUE)
|
|
||||||
private String excerptIt;
|
|
||||||
|
|
||||||
@Column(name = "excerpt_en", length = Integer.MAX_VALUE)
|
|
||||||
private String excerptEn;
|
|
||||||
|
|
||||||
@Column(name = "excerpt_de", length = Integer.MAX_VALUE)
|
|
||||||
private String excerptDe;
|
|
||||||
|
|
||||||
@Column(name = "excerpt_fr", length = Integer.MAX_VALUE)
|
|
||||||
private String excerptFr;
|
|
||||||
|
|
||||||
@Column(name = "description", length = Integer.MAX_VALUE)
|
|
||||||
private String description;
|
|
||||||
|
|
||||||
@Column(name = "description_it", length = Integer.MAX_VALUE)
|
|
||||||
private String descriptionIt;
|
|
||||||
|
|
||||||
@Column(name = "description_en", length = Integer.MAX_VALUE)
|
|
||||||
private String descriptionEn;
|
|
||||||
|
|
||||||
@Column(name = "description_de", length = Integer.MAX_VALUE)
|
|
||||||
private String descriptionDe;
|
|
||||||
|
|
||||||
@Column(name = "description_fr", length = Integer.MAX_VALUE)
|
|
||||||
private String descriptionFr;
|
|
||||||
|
|
||||||
@Column(name = "seo_title", length = Integer.MAX_VALUE)
|
|
||||||
private String seoTitle;
|
|
||||||
|
|
||||||
@Column(name = "seo_title_it", length = Integer.MAX_VALUE)
|
|
||||||
private String seoTitleIt;
|
|
||||||
|
|
||||||
@Column(name = "seo_title_en", length = Integer.MAX_VALUE)
|
|
||||||
private String seoTitleEn;
|
|
||||||
|
|
||||||
@Column(name = "seo_title_de", length = Integer.MAX_VALUE)
|
|
||||||
private String seoTitleDe;
|
|
||||||
|
|
||||||
@Column(name = "seo_title_fr", length = Integer.MAX_VALUE)
|
|
||||||
private String seoTitleFr;
|
|
||||||
|
|
||||||
@Column(name = "seo_description", length = Integer.MAX_VALUE)
|
|
||||||
private String seoDescription;
|
|
||||||
|
|
||||||
@Column(name = "seo_description_it", length = Integer.MAX_VALUE)
|
|
||||||
private String seoDescriptionIt;
|
|
||||||
|
|
||||||
@Column(name = "seo_description_en", length = Integer.MAX_VALUE)
|
|
||||||
private String seoDescriptionEn;
|
|
||||||
|
|
||||||
@Column(name = "seo_description_de", length = Integer.MAX_VALUE)
|
|
||||||
private String seoDescriptionDe;
|
|
||||||
|
|
||||||
@Column(name = "seo_description_fr", length = Integer.MAX_VALUE)
|
|
||||||
private String seoDescriptionFr;
|
|
||||||
|
|
||||||
@Column(name = "og_title", length = Integer.MAX_VALUE)
|
|
||||||
private String ogTitle;
|
|
||||||
|
|
||||||
@Column(name = "og_description", length = Integer.MAX_VALUE)
|
|
||||||
private String ogDescription;
|
|
||||||
|
|
||||||
@ColumnDefault("true")
|
|
||||||
@Column(name = "indexable", nullable = false)
|
|
||||||
private Boolean indexable;
|
|
||||||
|
|
||||||
@ColumnDefault("false")
|
|
||||||
@Column(name = "is_featured", nullable = false)
|
|
||||||
private Boolean isFeatured;
|
|
||||||
|
|
||||||
@ColumnDefault("true")
|
|
||||||
@Column(name = "is_active", nullable = false)
|
|
||||||
private Boolean isActive;
|
|
||||||
|
|
||||||
@ColumnDefault("0")
|
|
||||||
@Column(name = "sort_order", nullable = false)
|
|
||||||
private Integer sortOrder;
|
|
||||||
|
|
||||||
@ColumnDefault("now()")
|
|
||||||
@Column(name = "created_at", nullable = false)
|
|
||||||
private OffsetDateTime createdAt;
|
|
||||||
|
|
||||||
@ColumnDefault("now()")
|
|
||||||
@Column(name = "updated_at", nullable = false)
|
|
||||||
private OffsetDateTime updatedAt;
|
|
||||||
|
|
||||||
@PrePersist
|
|
||||||
private void onCreate() {
|
|
||||||
OffsetDateTime now = OffsetDateTime.now();
|
|
||||||
if (createdAt == null) {
|
|
||||||
createdAt = now;
|
|
||||||
}
|
|
||||||
if (updatedAt == null) {
|
|
||||||
updatedAt = now;
|
|
||||||
}
|
|
||||||
if (indexable == null) {
|
|
||||||
indexable = true;
|
|
||||||
}
|
|
||||||
if (isFeatured == null) {
|
|
||||||
isFeatured = false;
|
|
||||||
}
|
|
||||||
if (isActive == null) {
|
|
||||||
isActive = true;
|
|
||||||
}
|
|
||||||
if (sortOrder == null) {
|
|
||||||
sortOrder = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@PreUpdate
|
|
||||||
private void onUpdate() {
|
|
||||||
updatedAt = OffsetDateTime.now();
|
|
||||||
if (indexable == null) {
|
|
||||||
indexable = true;
|
|
||||||
}
|
|
||||||
if (isFeatured == null) {
|
|
||||||
isFeatured = false;
|
|
||||||
}
|
|
||||||
if (isActive == null) {
|
|
||||||
isActive = true;
|
|
||||||
}
|
|
||||||
if (sortOrder == null) {
|
|
||||||
sortOrder = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public UUID getId() {
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setId(UUID id) {
|
|
||||||
this.id = id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public ShopCategory getCategory() {
|
|
||||||
return category;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCategory(ShopCategory category) {
|
|
||||||
this.category = category;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSlug() {
|
|
||||||
return slug;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSlug(String slug) {
|
|
||||||
this.slug = slug;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getName() {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setName(String name) {
|
|
||||||
this.name = name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getNameIt() {
|
|
||||||
return nameIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setNameIt(String nameIt) {
|
|
||||||
this.nameIt = nameIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getNameEn() {
|
|
||||||
return nameEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setNameEn(String nameEn) {
|
|
||||||
this.nameEn = nameEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getNameDe() {
|
|
||||||
return nameDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setNameDe(String nameDe) {
|
|
||||||
this.nameDe = nameDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getNameFr() {
|
|
||||||
return nameFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setNameFr(String nameFr) {
|
|
||||||
this.nameFr = nameFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getExcerpt() {
|
|
||||||
return excerpt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setExcerpt(String excerpt) {
|
|
||||||
this.excerpt = excerpt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getExcerptIt() {
|
|
||||||
return excerptIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setExcerptIt(String excerptIt) {
|
|
||||||
this.excerptIt = excerptIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getExcerptEn() {
|
|
||||||
return excerptEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setExcerptEn(String excerptEn) {
|
|
||||||
this.excerptEn = excerptEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getExcerptDe() {
|
|
||||||
return excerptDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setExcerptDe(String excerptDe) {
|
|
||||||
this.excerptDe = excerptDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getExcerptFr() {
|
|
||||||
return excerptFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setExcerptFr(String excerptFr) {
|
|
||||||
this.excerptFr = excerptFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescription() {
|
|
||||||
return description;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescription(String description) {
|
|
||||||
this.description = description;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescriptionIt() {
|
|
||||||
return descriptionIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescriptionIt(String descriptionIt) {
|
|
||||||
this.descriptionIt = descriptionIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescriptionEn() {
|
|
||||||
return descriptionEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescriptionEn(String descriptionEn) {
|
|
||||||
this.descriptionEn = descriptionEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescriptionDe() {
|
|
||||||
return descriptionDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescriptionDe(String descriptionDe) {
|
|
||||||
this.descriptionDe = descriptionDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescriptionFr() {
|
|
||||||
return descriptionFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescriptionFr(String descriptionFr) {
|
|
||||||
this.descriptionFr = descriptionFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoTitle() {
|
|
||||||
return seoTitle;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitle(String seoTitle) {
|
|
||||||
this.seoTitle = seoTitle;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoDescription() {
|
|
||||||
return seoDescription;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescription(String seoDescription) {
|
|
||||||
this.seoDescription = seoDescription;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoTitleIt() {
|
|
||||||
return seoTitleIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitleIt(String seoTitleIt) {
|
|
||||||
this.seoTitleIt = seoTitleIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoTitleEn() {
|
|
||||||
return seoTitleEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitleEn(String seoTitleEn) {
|
|
||||||
this.seoTitleEn = seoTitleEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoTitleDe() {
|
|
||||||
return seoTitleDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitleDe(String seoTitleDe) {
|
|
||||||
this.seoTitleDe = seoTitleDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoTitleFr() {
|
|
||||||
return seoTitleFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitleFr(String seoTitleFr) {
|
|
||||||
this.seoTitleFr = seoTitleFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoDescriptionIt() {
|
|
||||||
return seoDescriptionIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescriptionIt(String seoDescriptionIt) {
|
|
||||||
this.seoDescriptionIt = seoDescriptionIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoDescriptionEn() {
|
|
||||||
return seoDescriptionEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescriptionEn(String seoDescriptionEn) {
|
|
||||||
this.seoDescriptionEn = seoDescriptionEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoDescriptionDe() {
|
|
||||||
return seoDescriptionDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescriptionDe(String seoDescriptionDe) {
|
|
||||||
this.seoDescriptionDe = seoDescriptionDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoDescriptionFr() {
|
|
||||||
return seoDescriptionFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescriptionFr(String seoDescriptionFr) {
|
|
||||||
this.seoDescriptionFr = seoDescriptionFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getOgTitle() {
|
|
||||||
return ogTitle;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setOgTitle(String ogTitle) {
|
|
||||||
this.ogTitle = ogTitle;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getOgDescription() {
|
|
||||||
return ogDescription;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setOgDescription(String ogDescription) {
|
|
||||||
this.ogDescription = ogDescription;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getIndexable() {
|
|
||||||
return indexable;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIndexable(Boolean indexable) {
|
|
||||||
this.indexable = indexable;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getIsFeatured() {
|
|
||||||
return isFeatured;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIsFeatured(Boolean featured) {
|
|
||||||
isFeatured = featured;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getIsActive() {
|
|
||||||
return isActive;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIsActive(Boolean active) {
|
|
||||||
isActive = active;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getSortOrder() {
|
|
||||||
return sortOrder;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSortOrder(Integer sortOrder) {
|
|
||||||
this.sortOrder = sortOrder;
|
|
||||||
}
|
|
||||||
|
|
||||||
public OffsetDateTime getCreatedAt() {
|
|
||||||
return createdAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCreatedAt(OffsetDateTime createdAt) {
|
|
||||||
this.createdAt = createdAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public OffsetDateTime getUpdatedAt() {
|
|
||||||
return updatedAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setUpdatedAt(OffsetDateTime updatedAt) {
|
|
||||||
this.updatedAt = updatedAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getNameForLanguage(String language) {
|
|
||||||
return resolveLocalizedValue(language, name, nameIt, nameEn, nameDe, nameFr);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setNameForLanguage(String language, String value) {
|
|
||||||
switch (normalizeLanguage(language)) {
|
|
||||||
case "it" -> nameIt = value;
|
|
||||||
case "en" -> nameEn = value;
|
|
||||||
case "de" -> nameDe = value;
|
|
||||||
case "fr" -> nameFr = value;
|
|
||||||
default -> {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getExcerptForLanguage(String language) {
|
|
||||||
return resolveLocalizedValue(language, excerpt, excerptIt, excerptEn, excerptDe, excerptFr);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setExcerptForLanguage(String language, String value) {
|
|
||||||
switch (normalizeLanguage(language)) {
|
|
||||||
case "it" -> excerptIt = value;
|
|
||||||
case "en" -> excerptEn = value;
|
|
||||||
case "de" -> excerptDe = value;
|
|
||||||
case "fr" -> excerptFr = value;
|
|
||||||
default -> {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescriptionForLanguage(String language) {
|
|
||||||
return resolveLocalizedValue(language, description, descriptionIt, descriptionEn, descriptionDe, descriptionFr);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescriptionForLanguage(String language, String value) {
|
|
||||||
switch (normalizeLanguage(language)) {
|
|
||||||
case "it" -> descriptionIt = value;
|
|
||||||
case "en" -> descriptionEn = value;
|
|
||||||
case "de" -> descriptionDe = value;
|
|
||||||
case "fr" -> descriptionFr = value;
|
|
||||||
default -> {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoTitleForLanguage(String language) {
|
|
||||||
return resolveLocalizedValue(language, seoTitle, seoTitleIt, seoTitleEn, seoTitleDe, seoTitleFr);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoTitleForLanguage(String language, String value) {
|
|
||||||
switch (normalizeLanguage(language)) {
|
|
||||||
case "it" -> seoTitleIt = value;
|
|
||||||
case "en" -> seoTitleEn = value;
|
|
||||||
case "de" -> seoTitleDe = value;
|
|
||||||
case "fr" -> seoTitleFr = value;
|
|
||||||
default -> {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSeoDescriptionForLanguage(String language) {
|
|
||||||
return resolveLocalizedValue(language, seoDescription, seoDescriptionIt, seoDescriptionEn, seoDescriptionDe, seoDescriptionFr);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSeoDescriptionForLanguage(String language, String value) {
|
|
||||||
switch (normalizeLanguage(language)) {
|
|
||||||
case "it" -> seoDescriptionIt = value;
|
|
||||||
case "en" -> seoDescriptionEn = value;
|
|
||||||
case "de" -> seoDescriptionDe = value;
|
|
||||||
case "fr" -> seoDescriptionFr = value;
|
|
||||||
default -> {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private String resolveLocalizedValue(String language,
|
|
||||||
String fallback,
|
|
||||||
String valueIt,
|
|
||||||
String valueEn,
|
|
||||||
String valueDe,
|
|
||||||
String valueFr) {
|
|
||||||
String normalizedLanguage = normalizeLanguage(language);
|
|
||||||
String preferred = switch (normalizedLanguage) {
|
|
||||||
case "it" -> valueIt;
|
|
||||||
case "en" -> valueEn;
|
|
||||||
case "de" -> valueDe;
|
|
||||||
case "fr" -> valueFr;
|
|
||||||
default -> null;
|
|
||||||
};
|
|
||||||
String resolved = firstNonBlank(preferred, fallback);
|
|
||||||
if (resolved != null) {
|
|
||||||
return resolved;
|
|
||||||
}
|
|
||||||
return firstNonBlank(valueIt, valueEn, valueDe, valueFr);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeLanguage(String language) {
|
|
||||||
if (language == null) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
String normalized = language.trim().toLowerCase();
|
|
||||||
int separatorIndex = normalized.indexOf('-');
|
|
||||||
if (separatorIndex > 0) {
|
|
||||||
normalized = normalized.substring(0, separatorIndex);
|
|
||||||
}
|
|
||||||
return normalized;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String firstNonBlank(String... values) {
|
|
||||||
if (values == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
for (String value : values) {
|
|
||||||
if (value != null && !value.isBlank()) {
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,189 +0,0 @@
|
|||||||
package com.printcalculator.entity;
|
|
||||||
|
|
||||||
import jakarta.persistence.Column;
|
|
||||||
import jakarta.persistence.Entity;
|
|
||||||
import jakarta.persistence.FetchType;
|
|
||||||
import jakarta.persistence.GeneratedValue;
|
|
||||||
import jakarta.persistence.GenerationType;
|
|
||||||
import jakarta.persistence.Id;
|
|
||||||
import jakarta.persistence.Index;
|
|
||||||
import jakarta.persistence.JoinColumn;
|
|
||||||
import jakarta.persistence.OneToOne;
|
|
||||||
import jakarta.persistence.PrePersist;
|
|
||||||
import jakarta.persistence.PreUpdate;
|
|
||||||
import jakarta.persistence.Table;
|
|
||||||
import org.hibernate.annotations.ColumnDefault;
|
|
||||||
|
|
||||||
import java.math.BigDecimal;
|
|
||||||
import java.time.OffsetDateTime;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
@Entity
|
|
||||||
@Table(name = "shop_product_model_asset", indexes = {
|
|
||||||
@Index(name = "ix_shop_product_model_asset_product", columnList = "shop_product_id")
|
|
||||||
})
|
|
||||||
public class ShopProductModelAsset {
|
|
||||||
@Id
|
|
||||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
|
||||||
@Column(name = "shop_product_model_asset_id", nullable = false)
|
|
||||||
private UUID id;
|
|
||||||
|
|
||||||
@OneToOne(fetch = FetchType.LAZY, optional = false)
|
|
||||||
@JoinColumn(name = "shop_product_id", nullable = false, unique = true)
|
|
||||||
private ShopProduct product;
|
|
||||||
|
|
||||||
@Column(name = "original_filename", nullable = false, length = Integer.MAX_VALUE)
|
|
||||||
private String originalFilename;
|
|
||||||
|
|
||||||
@Column(name = "stored_relative_path", nullable = false, length = Integer.MAX_VALUE)
|
|
||||||
private String storedRelativePath;
|
|
||||||
|
|
||||||
@Column(name = "stored_filename", nullable = false, length = Integer.MAX_VALUE)
|
|
||||||
private String storedFilename;
|
|
||||||
|
|
||||||
@Column(name = "file_size_bytes")
|
|
||||||
private Long fileSizeBytes;
|
|
||||||
|
|
||||||
@Column(name = "mime_type", length = Integer.MAX_VALUE)
|
|
||||||
private String mimeType;
|
|
||||||
|
|
||||||
@Column(name = "sha256_hex", length = Integer.MAX_VALUE)
|
|
||||||
private String sha256Hex;
|
|
||||||
|
|
||||||
@Column(name = "bounding_box_x_mm", precision = 10, scale = 3)
|
|
||||||
private BigDecimal boundingBoxXMm;
|
|
||||||
|
|
||||||
@Column(name = "bounding_box_y_mm", precision = 10, scale = 3)
|
|
||||||
private BigDecimal boundingBoxYMm;
|
|
||||||
|
|
||||||
@Column(name = "bounding_box_z_mm", precision = 10, scale = 3)
|
|
||||||
private BigDecimal boundingBoxZMm;
|
|
||||||
|
|
||||||
@ColumnDefault("now()")
|
|
||||||
@Column(name = "created_at", nullable = false)
|
|
||||||
private OffsetDateTime createdAt;
|
|
||||||
|
|
||||||
@ColumnDefault("now()")
|
|
||||||
@Column(name = "updated_at", nullable = false)
|
|
||||||
private OffsetDateTime updatedAt;
|
|
||||||
|
|
||||||
@PrePersist
|
|
||||||
private void onCreate() {
|
|
||||||
OffsetDateTime now = OffsetDateTime.now();
|
|
||||||
if (createdAt == null) {
|
|
||||||
createdAt = now;
|
|
||||||
}
|
|
||||||
if (updatedAt == null) {
|
|
||||||
updatedAt = now;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@PreUpdate
|
|
||||||
private void onUpdate() {
|
|
||||||
updatedAt = OffsetDateTime.now();
|
|
||||||
}
|
|
||||||
|
|
||||||
public UUID getId() {
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setId(UUID id) {
|
|
||||||
this.id = id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public ShopProduct getProduct() {
|
|
||||||
return product;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setProduct(ShopProduct product) {
|
|
||||||
this.product = product;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getOriginalFilename() {
|
|
||||||
return originalFilename;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setOriginalFilename(String originalFilename) {
|
|
||||||
this.originalFilename = originalFilename;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getStoredRelativePath() {
|
|
||||||
return storedRelativePath;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setStoredRelativePath(String storedRelativePath) {
|
|
||||||
this.storedRelativePath = storedRelativePath;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getStoredFilename() {
|
|
||||||
return storedFilename;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setStoredFilename(String storedFilename) {
|
|
||||||
this.storedFilename = storedFilename;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Long getFileSizeBytes() {
|
|
||||||
return fileSizeBytes;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setFileSizeBytes(Long fileSizeBytes) {
|
|
||||||
this.fileSizeBytes = fileSizeBytes;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getMimeType() {
|
|
||||||
return mimeType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setMimeType(String mimeType) {
|
|
||||||
this.mimeType = mimeType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSha256Hex() {
|
|
||||||
return sha256Hex;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSha256Hex(String sha256Hex) {
|
|
||||||
this.sha256Hex = sha256Hex;
|
|
||||||
}
|
|
||||||
|
|
||||||
public BigDecimal getBoundingBoxXMm() {
|
|
||||||
return boundingBoxXMm;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setBoundingBoxXMm(BigDecimal boundingBoxXMm) {
|
|
||||||
this.boundingBoxXMm = boundingBoxXMm;
|
|
||||||
}
|
|
||||||
|
|
||||||
public BigDecimal getBoundingBoxYMm() {
|
|
||||||
return boundingBoxYMm;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setBoundingBoxYMm(BigDecimal boundingBoxYMm) {
|
|
||||||
this.boundingBoxYMm = boundingBoxYMm;
|
|
||||||
}
|
|
||||||
|
|
||||||
public BigDecimal getBoundingBoxZMm() {
|
|
||||||
return boundingBoxZMm;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setBoundingBoxZMm(BigDecimal boundingBoxZMm) {
|
|
||||||
this.boundingBoxZMm = boundingBoxZMm;
|
|
||||||
}
|
|
||||||
|
|
||||||
public OffsetDateTime getCreatedAt() {
|
|
||||||
return createdAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCreatedAt(OffsetDateTime createdAt) {
|
|
||||||
this.createdAt = createdAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public OffsetDateTime getUpdatedAt() {
|
|
||||||
return updatedAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setUpdatedAt(OffsetDateTime updatedAt) {
|
|
||||||
this.updatedAt = updatedAt;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,318 +0,0 @@
|
|||||||
package com.printcalculator.entity;
|
|
||||||
|
|
||||||
import jakarta.persistence.Column;
|
|
||||||
import jakarta.persistence.Entity;
|
|
||||||
import jakarta.persistence.FetchType;
|
|
||||||
import jakarta.persistence.GeneratedValue;
|
|
||||||
import jakarta.persistence.GenerationType;
|
|
||||||
import jakarta.persistence.Id;
|
|
||||||
import jakarta.persistence.Index;
|
|
||||||
import jakarta.persistence.JoinColumn;
|
|
||||||
import jakarta.persistence.ManyToOne;
|
|
||||||
import jakarta.persistence.PrePersist;
|
|
||||||
import jakarta.persistence.PreUpdate;
|
|
||||||
import jakarta.persistence.Table;
|
|
||||||
import org.hibernate.annotations.ColumnDefault;
|
|
||||||
|
|
||||||
import java.math.BigDecimal;
|
|
||||||
import java.time.OffsetDateTime;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
@Entity
|
|
||||||
@Table(name = "shop_product_variant", indexes = {
|
|
||||||
@Index(name = "ix_shop_product_variant_product_active_sort", columnList = "shop_product_id, is_active, sort_order"),
|
|
||||||
@Index(name = "ix_shop_product_variant_sku", columnList = "sku")
|
|
||||||
})
|
|
||||||
public class ShopProductVariant {
|
|
||||||
@Id
|
|
||||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
|
||||||
@Column(name = "shop_product_variant_id", nullable = false)
|
|
||||||
private UUID id;
|
|
||||||
|
|
||||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
|
||||||
@JoinColumn(name = "shop_product_id", nullable = false)
|
|
||||||
private ShopProduct product;
|
|
||||||
|
|
||||||
@Column(name = "sku", unique = true, length = Integer.MAX_VALUE)
|
|
||||||
private String sku;
|
|
||||||
|
|
||||||
@Column(name = "variant_label", nullable = false, length = Integer.MAX_VALUE)
|
|
||||||
private String variantLabel;
|
|
||||||
|
|
||||||
@Column(name = "color_name", nullable = false, length = Integer.MAX_VALUE)
|
|
||||||
private String colorName;
|
|
||||||
|
|
||||||
@Column(name = "color_label_it", length = Integer.MAX_VALUE)
|
|
||||||
private String colorLabelIt;
|
|
||||||
|
|
||||||
@Column(name = "color_label_en", length = Integer.MAX_VALUE)
|
|
||||||
private String colorLabelEn;
|
|
||||||
|
|
||||||
@Column(name = "color_label_de", length = Integer.MAX_VALUE)
|
|
||||||
private String colorLabelDe;
|
|
||||||
|
|
||||||
@Column(name = "color_label_fr", length = Integer.MAX_VALUE)
|
|
||||||
private String colorLabelFr;
|
|
||||||
|
|
||||||
@Column(name = "color_hex", length = Integer.MAX_VALUE)
|
|
||||||
private String colorHex;
|
|
||||||
|
|
||||||
@Column(name = "internal_material_code", nullable = false, length = Integer.MAX_VALUE)
|
|
||||||
private String internalMaterialCode;
|
|
||||||
|
|
||||||
@ColumnDefault("0.00")
|
|
||||||
@Column(name = "price_chf", nullable = false, precision = 12, scale = 2)
|
|
||||||
private BigDecimal priceChf;
|
|
||||||
|
|
||||||
@ColumnDefault("false")
|
|
||||||
@Column(name = "is_default", nullable = false)
|
|
||||||
private Boolean isDefault;
|
|
||||||
|
|
||||||
@ColumnDefault("true")
|
|
||||||
@Column(name = "is_active", nullable = false)
|
|
||||||
private Boolean isActive;
|
|
||||||
|
|
||||||
@ColumnDefault("0")
|
|
||||||
@Column(name = "sort_order", nullable = false)
|
|
||||||
private Integer sortOrder;
|
|
||||||
|
|
||||||
@ColumnDefault("now()")
|
|
||||||
@Column(name = "created_at", nullable = false)
|
|
||||||
private OffsetDateTime createdAt;
|
|
||||||
|
|
||||||
@ColumnDefault("now()")
|
|
||||||
@Column(name = "updated_at", nullable = false)
|
|
||||||
private OffsetDateTime updatedAt;
|
|
||||||
|
|
||||||
@PrePersist
|
|
||||||
private void onCreate() {
|
|
||||||
OffsetDateTime now = OffsetDateTime.now();
|
|
||||||
if (createdAt == null) {
|
|
||||||
createdAt = now;
|
|
||||||
}
|
|
||||||
if (updatedAt == null) {
|
|
||||||
updatedAt = now;
|
|
||||||
}
|
|
||||||
if (priceChf == null) {
|
|
||||||
priceChf = BigDecimal.ZERO;
|
|
||||||
}
|
|
||||||
if (isDefault == null) {
|
|
||||||
isDefault = false;
|
|
||||||
}
|
|
||||||
if (isActive == null) {
|
|
||||||
isActive = true;
|
|
||||||
}
|
|
||||||
if (sortOrder == null) {
|
|
||||||
sortOrder = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@PreUpdate
|
|
||||||
private void onUpdate() {
|
|
||||||
updatedAt = OffsetDateTime.now();
|
|
||||||
if (priceChf == null) {
|
|
||||||
priceChf = BigDecimal.ZERO;
|
|
||||||
}
|
|
||||||
if (isDefault == null) {
|
|
||||||
isDefault = false;
|
|
||||||
}
|
|
||||||
if (isActive == null) {
|
|
||||||
isActive = true;
|
|
||||||
}
|
|
||||||
if (sortOrder == null) {
|
|
||||||
sortOrder = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public UUID getId() {
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setId(UUID id) {
|
|
||||||
this.id = id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public ShopProduct getProduct() {
|
|
||||||
return product;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setProduct(ShopProduct product) {
|
|
||||||
this.product = product;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSku() {
|
|
||||||
return sku;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSku(String sku) {
|
|
||||||
this.sku = sku;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getVariantLabel() {
|
|
||||||
return variantLabel;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setVariantLabel(String variantLabel) {
|
|
||||||
this.variantLabel = variantLabel;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getColorName() {
|
|
||||||
return colorName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setColorName(String colorName) {
|
|
||||||
this.colorName = colorName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getColorLabelIt() {
|
|
||||||
return colorLabelIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setColorLabelIt(String colorLabelIt) {
|
|
||||||
this.colorLabelIt = colorLabelIt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getColorLabelEn() {
|
|
||||||
return colorLabelEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setColorLabelEn(String colorLabelEn) {
|
|
||||||
this.colorLabelEn = colorLabelEn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getColorLabelDe() {
|
|
||||||
return colorLabelDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setColorLabelDe(String colorLabelDe) {
|
|
||||||
this.colorLabelDe = colorLabelDe;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getColorLabelFr() {
|
|
||||||
return colorLabelFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setColorLabelFr(String colorLabelFr) {
|
|
||||||
this.colorLabelFr = colorLabelFr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getColorHex() {
|
|
||||||
return colorHex;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setColorHex(String colorHex) {
|
|
||||||
this.colorHex = colorHex;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getInternalMaterialCode() {
|
|
||||||
return internalMaterialCode;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setInternalMaterialCode(String internalMaterialCode) {
|
|
||||||
this.internalMaterialCode = internalMaterialCode;
|
|
||||||
}
|
|
||||||
|
|
||||||
public BigDecimal getPriceChf() {
|
|
||||||
return priceChf;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setPriceChf(BigDecimal priceChf) {
|
|
||||||
this.priceChf = priceChf;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getIsDefault() {
|
|
||||||
return isDefault;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIsDefault(Boolean aDefault) {
|
|
||||||
isDefault = aDefault;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getIsActive() {
|
|
||||||
return isActive;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIsActive(Boolean active) {
|
|
||||||
isActive = active;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getSortOrder() {
|
|
||||||
return sortOrder;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSortOrder(Integer sortOrder) {
|
|
||||||
this.sortOrder = sortOrder;
|
|
||||||
}
|
|
||||||
|
|
||||||
public OffsetDateTime getCreatedAt() {
|
|
||||||
return createdAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCreatedAt(OffsetDateTime createdAt) {
|
|
||||||
this.createdAt = createdAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public OffsetDateTime getUpdatedAt() {
|
|
||||||
return updatedAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setUpdatedAt(OffsetDateTime updatedAt) {
|
|
||||||
this.updatedAt = updatedAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getColorLabelForLanguage(String language) {
|
|
||||||
return resolveLocalizedValue(
|
|
||||||
language,
|
|
||||||
colorName,
|
|
||||||
colorLabelIt,
|
|
||||||
colorLabelEn,
|
|
||||||
colorLabelDe,
|
|
||||||
colorLabelFr
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String resolveLocalizedValue(String language,
|
|
||||||
String fallback,
|
|
||||||
String valueIt,
|
|
||||||
String valueEn,
|
|
||||||
String valueDe,
|
|
||||||
String valueFr) {
|
|
||||||
String normalizedLanguage = normalizeLanguage(language);
|
|
||||||
String preferred = switch (normalizedLanguage) {
|
|
||||||
case "it" -> valueIt;
|
|
||||||
case "en" -> valueEn;
|
|
||||||
case "de" -> valueDe;
|
|
||||||
case "fr" -> valueFr;
|
|
||||||
default -> null;
|
|
||||||
};
|
|
||||||
String resolved = firstNonBlank(preferred, fallback);
|
|
||||||
if (resolved != null) {
|
|
||||||
return resolved;
|
|
||||||
}
|
|
||||||
return firstNonBlank(valueIt, valueEn, valueDe, valueFr);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeLanguage(String language) {
|
|
||||||
if (language == null) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
String normalized = language.trim().toLowerCase();
|
|
||||||
int separatorIndex = normalized.indexOf('-');
|
|
||||||
if (separatorIndex > 0) {
|
|
||||||
normalized = normalized.substring(0, separatorIndex);
|
|
||||||
}
|
|
||||||
return normalized;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String firstNonBlank(String... values) {
|
|
||||||
if (values == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
for (String value : values) {
|
|
||||||
if (value != null && !value.isBlank()) {
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -223,15 +223,10 @@ public class OrderEmailListener {
|
|||||||
order.getCreatedAt().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).withLocale(locale))
|
order.getCreatedAt().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).withLocale(locale))
|
||||||
);
|
);
|
||||||
templateData.put("totalCost", currencyFormatter.format(order.getTotalChf()));
|
templateData.put("totalCost", currencyFormatter.format(order.getTotalChf()));
|
||||||
templateData.put("logoUrl", buildLogoUrl());
|
|
||||||
templateData.put("currentYear", Year.now().getValue());
|
templateData.put("currentYear", Year.now().getValue());
|
||||||
return templateData;
|
return templateData;
|
||||||
}
|
}
|
||||||
|
|
||||||
private String buildLogoUrl() {
|
|
||||||
return frontendBaseUrl.replaceAll("/+$", "") + "/assets/images/brand-logo-yellow.svg";
|
|
||||||
}
|
|
||||||
|
|
||||||
private String applyOrderConfirmationTexts(Map<String, Object> templateData, String language, String orderNumber) {
|
private String applyOrderConfirmationTexts(Map<String, Object> templateData, String language, String orderNumber) {
|
||||||
return switch (language) {
|
return switch (language) {
|
||||||
case "en" -> {
|
case "en" -> {
|
||||||
|
|||||||
@@ -1,11 +0,0 @@
|
|||||||
package com.printcalculator.repository;
|
|
||||||
|
|
||||||
import com.printcalculator.entity.MediaAsset;
|
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
public interface MediaAssetRepository extends JpaRepository<MediaAsset, UUID> {
|
|
||||||
List<MediaAsset> findAllByOrderByCreatedAtDesc();
|
|
||||||
}
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
package com.printcalculator.repository;
|
|
||||||
|
|
||||||
import com.printcalculator.entity.MediaUsage;
|
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
|
||||||
import org.springframework.data.jpa.repository.Query;
|
|
||||||
import org.springframework.data.repository.query.Param;
|
|
||||||
|
|
||||||
import java.util.Collection;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
public interface MediaUsageRepository extends JpaRepository<MediaUsage, UUID> {
|
|
||||||
List<MediaUsage> findByMediaAsset_IdOrderBySortOrderAscCreatedAtAsc(UUID mediaAssetId);
|
|
||||||
|
|
||||||
List<MediaUsage> findByMediaAsset_IdIn(Collection<UUID> mediaAssetIds);
|
|
||||||
|
|
||||||
List<MediaUsage> findByUsageTypeAndUsageKeyAndIsActiveTrueOrderBySortOrderAscCreatedAtAsc(String usageType,
|
|
||||||
String usageKey);
|
|
||||||
|
|
||||||
List<MediaUsage> findByUsageTypeAndUsageKeyOrderBySortOrderAscCreatedAtAsc(String usageType,
|
|
||||||
String usageKey);
|
|
||||||
|
|
||||||
@Query("""
|
|
||||||
select usage from MediaUsage usage
|
|
||||||
where usage.usageType = :usageType
|
|
||||||
and usage.usageKey in :usageKeys
|
|
||||||
and usage.isActive = true
|
|
||||||
order by usage.usageKey asc, usage.sortOrder asc, usage.createdAt asc
|
|
||||||
""")
|
|
||||||
List<MediaUsage> findActiveByUsageTypeAndUsageKeys(@Param("usageType") String usageType,
|
|
||||||
@Param("usageKeys") Collection<String> usageKeys);
|
|
||||||
|
|
||||||
@Query("""
|
|
||||||
select usage from MediaUsage usage
|
|
||||||
where usage.usageType = :usageType
|
|
||||||
and usage.usageKey = :usageKey
|
|
||||||
and ((:ownerId is null and usage.ownerId is null) or usage.ownerId = :ownerId)
|
|
||||||
order by usage.sortOrder asc, usage.createdAt asc
|
|
||||||
""")
|
|
||||||
List<MediaUsage> findByUsageScope(@Param("usageType") String usageType,
|
|
||||||
@Param("usageKey") String usageKey,
|
|
||||||
@Param("ownerId") UUID ownerId);
|
|
||||||
}
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
package com.printcalculator.repository;
|
|
||||||
|
|
||||||
import com.printcalculator.entity.MediaVariant;
|
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
|
||||||
|
|
||||||
import java.util.Collection;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
public interface MediaVariantRepository extends JpaRepository<MediaVariant, UUID> {
|
|
||||||
List<MediaVariant> findByMediaAsset_IdOrderByCreatedAtAsc(UUID mediaAssetId);
|
|
||||||
|
|
||||||
List<MediaVariant> findByMediaAsset_IdIn(Collection<UUID> mediaAssetIds);
|
|
||||||
}
|
|
||||||
@@ -3,9 +3,5 @@ package com.printcalculator.repository;
|
|||||||
import com.printcalculator.entity.NozzleOption;
|
import com.printcalculator.entity.NozzleOption;
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
import java.math.BigDecimal;
|
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
public interface NozzleOptionRepository extends JpaRepository<NozzleOption, Long> {
|
public interface NozzleOptionRepository extends JpaRepository<NozzleOption, Long> {
|
||||||
Optional<NozzleOption> findFirstByNozzleDiameterMmAndIsActiveTrue(BigDecimal nozzleDiameterMm);
|
}
|
||||||
}
|
|
||||||
@@ -9,6 +9,4 @@ import java.util.UUID;
|
|||||||
public interface OrderItemRepository extends JpaRepository<OrderItem, UUID> {
|
public interface OrderItemRepository extends JpaRepository<OrderItem, UUID> {
|
||||||
List<OrderItem> findByOrder_Id(UUID orderId);
|
List<OrderItem> findByOrder_Id(UUID orderId);
|
||||||
boolean existsByFilamentVariant_Id(Long filamentVariantId);
|
boolean existsByFilamentVariant_Id(Long filamentVariantId);
|
||||||
boolean existsByShopProduct_Id(UUID shopProductId);
|
|
||||||
boolean existsByShopProductVariant_Id(UUID shopProductVariantId);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,30 +1,12 @@
|
|||||||
package com.printcalculator.repository;
|
package com.printcalculator.repository;
|
||||||
|
|
||||||
import com.printcalculator.entity.QuoteLineItem;
|
import com.printcalculator.entity.QuoteLineItem;
|
||||||
import org.springframework.data.jpa.repository.EntityGraph;
|
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
public interface QuoteLineItemRepository extends JpaRepository<QuoteLineItem, UUID> {
|
public interface QuoteLineItemRepository extends JpaRepository<QuoteLineItem, UUID> {
|
||||||
@EntityGraph(attributePaths = {"filamentVariant", "shopProduct", "shopProductVariant"})
|
|
||||||
List<QuoteLineItem> findByQuoteSessionId(UUID quoteSessionId);
|
List<QuoteLineItem> findByQuoteSessionId(UUID quoteSessionId);
|
||||||
|
|
||||||
@EntityGraph(attributePaths = {"filamentVariant", "shopProduct", "shopProductVariant"})
|
|
||||||
List<QuoteLineItem> findByQuoteSessionIdOrderByCreatedAtAsc(UUID quoteSessionId);
|
|
||||||
|
|
||||||
@EntityGraph(attributePaths = {"filamentVariant", "shopProduct", "shopProductVariant"})
|
|
||||||
Optional<QuoteLineItem> findByIdAndQuoteSession_Id(UUID lineItemId, UUID quoteSessionId);
|
|
||||||
|
|
||||||
@EntityGraph(attributePaths = {"shopProductVariant"})
|
|
||||||
Optional<QuoteLineItem> findFirstByQuoteSession_IdAndLineItemTypeAndShopProductVariant_Id(
|
|
||||||
UUID quoteSessionId,
|
|
||||||
String lineItemType,
|
|
||||||
UUID shopProductVariantId
|
|
||||||
);
|
|
||||||
boolean existsByFilamentVariant_Id(Long filamentVariantId);
|
boolean existsByFilamentVariant_Id(Long filamentVariantId);
|
||||||
boolean existsByShopProduct_Id(UUID shopProductId);
|
|
||||||
boolean existsByShopProductVariant_Id(UUID shopProductVariantId);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,13 +4,10 @@ import com.printcalculator.entity.QuoteSession;
|
|||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
public interface QuoteSessionRepository extends JpaRepository<QuoteSession, UUID> {
|
public interface QuoteSessionRepository extends JpaRepository<QuoteSession, UUID> {
|
||||||
List<QuoteSession> findByCreatedAtBefore(java.time.OffsetDateTime cutoff);
|
List<QuoteSession> findByCreatedAtBefore(java.time.OffsetDateTime cutoff);
|
||||||
|
|
||||||
List<QuoteSession> findByStatusInOrderByCreatedAtDesc(List<String> statuses);
|
List<QuoteSession> findByStatusInOrderByCreatedAtDesc(List<String> statuses);
|
||||||
|
|
||||||
Optional<QuoteSession> findByIdAndSessionType(UUID id, String sessionType);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,24 +0,0 @@
|
|||||||
package com.printcalculator.repository;
|
|
||||||
|
|
||||||
import com.printcalculator.entity.ShopCategory;
|
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Optional;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
public interface ShopCategoryRepository extends JpaRepository<ShopCategory, UUID> {
|
|
||||||
Optional<ShopCategory> findBySlug(String slug);
|
|
||||||
|
|
||||||
Optional<ShopCategory> findBySlugIgnoreCase(String slug);
|
|
||||||
|
|
||||||
Optional<ShopCategory> findBySlugAndIsActiveTrue(String slug);
|
|
||||||
|
|
||||||
boolean existsBySlugIgnoreCase(String slug);
|
|
||||||
|
|
||||||
boolean existsByParentCategory_Id(UUID parentCategoryId);
|
|
||||||
|
|
||||||
List<ShopCategory> findAllByOrderBySortOrderAscNameAsc();
|
|
||||||
|
|
||||||
List<ShopCategory> findAllByIsActiveTrueOrderBySortOrderAscNameAsc();
|
|
||||||
}
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
package com.printcalculator.repository;
|
|
||||||
|
|
||||||
import com.printcalculator.entity.ShopProductModelAsset;
|
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
|
||||||
|
|
||||||
import java.util.Collection;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Optional;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
public interface ShopProductModelAssetRepository extends JpaRepository<ShopProductModelAsset, UUID> {
|
|
||||||
Optional<ShopProductModelAsset> findByProduct_Id(UUID productId);
|
|
||||||
|
|
||||||
List<ShopProductModelAsset> findByProduct_IdIn(Collection<UUID> productIds);
|
|
||||||
|
|
||||||
void deleteByProduct_Id(UUID productId);
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
package com.printcalculator.repository;
|
|
||||||
|
|
||||||
import com.printcalculator.entity.ShopProduct;
|
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Optional;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
public interface ShopProductRepository extends JpaRepository<ShopProduct, UUID> {
|
|
||||||
Optional<ShopProduct> findBySlug(String slug);
|
|
||||||
|
|
||||||
Optional<ShopProduct> findBySlugIgnoreCase(String slug);
|
|
||||||
|
|
||||||
Optional<ShopProduct> findBySlugAndIsActiveTrue(String slug);
|
|
||||||
|
|
||||||
boolean existsBySlugIgnoreCase(String slug);
|
|
||||||
|
|
||||||
List<ShopProduct> findAllByOrderBySortOrderAscNameAsc();
|
|
||||||
|
|
||||||
List<ShopProduct> findAllByOrderByIsFeaturedDescSortOrderAscNameAsc();
|
|
||||||
|
|
||||||
List<ShopProduct> findByCategory_IdOrderBySortOrderAscNameAsc(UUID categoryId);
|
|
||||||
|
|
||||||
List<ShopProduct> findAllByIsActiveTrueOrderByIsFeaturedDescSortOrderAscNameAsc();
|
|
||||||
|
|
||||||
boolean existsByCategory_Id(UUID categoryId);
|
|
||||||
}
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
package com.printcalculator.repository;
|
|
||||||
|
|
||||||
import com.printcalculator.entity.ShopProductVariant;
|
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
|
||||||
|
|
||||||
import java.util.Collection;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Optional;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
public interface ShopProductVariantRepository extends JpaRepository<ShopProductVariant, UUID> {
|
|
||||||
List<ShopProductVariant> findByProduct_IdOrderBySortOrderAscColorNameAsc(UUID productId);
|
|
||||||
|
|
||||||
List<ShopProductVariant> findByProduct_IdInOrderBySortOrderAscColorNameAsc(Collection<UUID> productIds);
|
|
||||||
|
|
||||||
List<ShopProductVariant> findByProduct_IdAndIsActiveTrueOrderBySortOrderAscColorNameAsc(UUID productId);
|
|
||||||
|
|
||||||
List<ShopProductVariant> findByProduct_IdInAndIsActiveTrueOrderBySortOrderAscColorNameAsc(Collection<UUID> productIds);
|
|
||||||
|
|
||||||
Optional<ShopProductVariant> findFirstByProduct_IdAndIsDefaultTrue(UUID productId);
|
|
||||||
|
|
||||||
boolean existsBySkuIgnoreCase(String sku);
|
|
||||||
|
|
||||||
boolean existsBySkuIgnoreCaseAndIdNot(String sku, UUID variantId);
|
|
||||||
}
|
|
||||||
@@ -12,11 +12,9 @@ import java.util.LinkedHashMap;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.logging.Logger;
|
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
public class NozzleLayerHeightPolicyService {
|
public class NozzleLayerHeightPolicyService {
|
||||||
private static final Logger logger = Logger.getLogger(NozzleLayerHeightPolicyService.class.getName());
|
|
||||||
private static final BigDecimal DEFAULT_NOZZLE = BigDecimal.valueOf(0.40).setScale(2, RoundingMode.HALF_UP);
|
private static final BigDecimal DEFAULT_NOZZLE = BigDecimal.valueOf(0.40).setScale(2, RoundingMode.HALF_UP);
|
||||||
private static final BigDecimal DEFAULT_LAYER = BigDecimal.valueOf(0.20).setScale(3, RoundingMode.HALF_UP);
|
private static final BigDecimal DEFAULT_LAYER = BigDecimal.valueOf(0.20).setScale(3, RoundingMode.HALF_UP);
|
||||||
|
|
||||||
@@ -29,8 +27,7 @@ public class NozzleLayerHeightPolicyService {
|
|||||||
public Map<BigDecimal, List<BigDecimal>> getActiveRulesByNozzle() {
|
public Map<BigDecimal, List<BigDecimal>> getActiveRulesByNozzle() {
|
||||||
List<NozzleLayerHeightOption> rules = ruleRepo.findByIsActiveTrueOrderByNozzleDiameterMmAscLayerHeightMmAsc();
|
List<NozzleLayerHeightOption> rules = ruleRepo.findByIsActiveTrueOrderByNozzleDiameterMmAscLayerHeightMmAsc();
|
||||||
if (rules.isEmpty()) {
|
if (rules.isEmpty()) {
|
||||||
logger.warning("No active nozzle->layer rules found in DB (table nozzle_layer_height_option is empty)");
|
return fallbackRules();
|
||||||
return Map.of();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Map<BigDecimal, List<BigDecimal>> byNozzle = new LinkedHashMap<>();
|
Map<BigDecimal, List<BigDecimal>> byNozzle = new LinkedHashMap<>();
|
||||||
@@ -123,4 +120,24 @@ public class NozzleLayerHeightPolicyService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private Map<BigDecimal, List<BigDecimal>> fallbackRules() {
|
||||||
|
Map<BigDecimal, List<BigDecimal>> fallback = new LinkedHashMap<>();
|
||||||
|
fallback.put(scaleNozzle(0.20), scaleLayers(0.04, 0.06, 0.08, 0.10, 0.12));
|
||||||
|
fallback.put(scaleNozzle(0.40), scaleLayers(0.08, 0.12, 0.16, 0.20, 0.24, 0.28));
|
||||||
|
fallback.put(scaleNozzle(0.60), scaleLayers(0.16, 0.20, 0.24, 0.30, 0.36));
|
||||||
|
fallback.put(scaleNozzle(0.80), scaleLayers(0.20, 0.28, 0.36, 0.40, 0.48, 0.56));
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
private BigDecimal scaleNozzle(double value) {
|
||||||
|
return BigDecimal.valueOf(value).setScale(2, RoundingMode.HALF_UP);
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<BigDecimal> scaleLayers(double... values) {
|
||||||
|
List<BigDecimal> scaled = new ArrayList<>();
|
||||||
|
for (double value : values) {
|
||||||
|
scaled.add(BigDecimal.valueOf(value).setScale(3, RoundingMode.HALF_UP));
|
||||||
|
}
|
||||||
|
return scaled;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,7 +29,6 @@ import java.util.*;
|
|||||||
@Service
|
@Service
|
||||||
public class OrderService {
|
public class OrderService {
|
||||||
private static final Path QUOTE_STORAGE_ROOT = Paths.get("storage_quotes").toAbsolutePath().normalize();
|
private static final Path QUOTE_STORAGE_ROOT = Paths.get("storage_quotes").toAbsolutePath().normalize();
|
||||||
private static final String SHOP_LINE_ITEM_TYPE = "SHOP_PRODUCT";
|
|
||||||
|
|
||||||
private final OrderRepository orderRepo;
|
private final OrderRepository orderRepo;
|
||||||
private final OrderItemRepository orderItemRepo;
|
private final OrderItemRepository orderItemRepo;
|
||||||
@@ -105,7 +104,6 @@ public class OrderService {
|
|||||||
|
|
||||||
Order order = new Order();
|
Order order = new Order();
|
||||||
order.setSourceQuoteSession(session);
|
order.setSourceQuoteSession(session);
|
||||||
order.setSourceType(resolveOrderSourceType(session));
|
|
||||||
order.setCustomer(customer);
|
order.setCustomer(customer);
|
||||||
order.setCustomerEmail(request.getCustomer().getEmail());
|
order.setCustomerEmail(request.getCustomer().getEmail());
|
||||||
order.setCustomerPhone(request.getCustomer().getPhone());
|
order.setCustomerPhone(request.getCustomer().getPhone());
|
||||||
@@ -159,7 +157,7 @@ public class OrderService {
|
|||||||
order.setSubtotalChf(BigDecimal.ZERO);
|
order.setSubtotalChf(BigDecimal.ZERO);
|
||||||
order.setTotalChf(BigDecimal.ZERO);
|
order.setTotalChf(BigDecimal.ZERO);
|
||||||
order.setDiscountChf(BigDecimal.ZERO);
|
order.setDiscountChf(BigDecimal.ZERO);
|
||||||
order.setSetupCostChf(totals.setupCostChf());
|
order.setSetupCostChf(session.getSetupCostChf() != null ? session.getSetupCostChf() : BigDecimal.ZERO);
|
||||||
order.setShippingCostChf(totals.shippingCostChf());
|
order.setShippingCostChf(totals.shippingCostChf());
|
||||||
order.setIsCadOrder(cadTotal.compareTo(BigDecimal.ZERO) > 0 || "CAD_ACTIVE".equals(session.getStatus()));
|
order.setIsCadOrder(cadTotal.compareTo(BigDecimal.ZERO) > 0 || "CAD_ACTIVE".equals(session.getStatus()));
|
||||||
order.setSourceRequestId(session.getSourceRequestId());
|
order.setSourceRequestId(session.getSourceRequestId());
|
||||||
@@ -174,27 +172,12 @@ public class OrderService {
|
|||||||
for (QuoteLineItem qItem : quoteItems) {
|
for (QuoteLineItem qItem : quoteItems) {
|
||||||
OrderItem oItem = new OrderItem();
|
OrderItem oItem = new OrderItem();
|
||||||
oItem.setOrder(order);
|
oItem.setOrder(order);
|
||||||
oItem.setItemType(qItem.getLineItemType() != null ? qItem.getLineItemType() : "PRINT_FILE");
|
|
||||||
oItem.setOriginalFilename(qItem.getOriginalFilename());
|
oItem.setOriginalFilename(qItem.getOriginalFilename());
|
||||||
oItem.setDisplayName(
|
|
||||||
qItem.getDisplayName() != null && !qItem.getDisplayName().isBlank()
|
|
||||||
? qItem.getDisplayName()
|
|
||||||
: qItem.getOriginalFilename()
|
|
||||||
);
|
|
||||||
int quantity = qItem.getQuantity() != null && qItem.getQuantity() > 0 ? qItem.getQuantity() : 1;
|
int quantity = qItem.getQuantity() != null && qItem.getQuantity() > 0 ? qItem.getQuantity() : 1;
|
||||||
oItem.setQuantity(quantity);
|
oItem.setQuantity(quantity);
|
||||||
oItem.setColorCode(qItem.getColorCode());
|
oItem.setColorCode(qItem.getColorCode());
|
||||||
oItem.setFilamentVariant(qItem.getFilamentVariant());
|
oItem.setFilamentVariant(qItem.getFilamentVariant());
|
||||||
oItem.setShopProduct(qItem.getShopProduct());
|
if (qItem.getFilamentVariant() != null
|
||||||
oItem.setShopProductVariant(qItem.getShopProductVariant());
|
|
||||||
oItem.setShopProductSlug(qItem.getShopProductSlug());
|
|
||||||
oItem.setShopProductName(qItem.getShopProductName());
|
|
||||||
oItem.setShopVariantLabel(qItem.getShopVariantLabel());
|
|
||||||
oItem.setShopVariantColorName(qItem.getShopVariantColorName());
|
|
||||||
oItem.setShopVariantColorHex(qItem.getShopVariantColorHex());
|
|
||||||
if (qItem.getMaterialCode() != null && !qItem.getMaterialCode().isBlank()) {
|
|
||||||
oItem.setMaterialCode(qItem.getMaterialCode());
|
|
||||||
} else if (qItem.getFilamentVariant() != null
|
|
||||||
&& qItem.getFilamentVariant().getFilamentMaterialType() != null
|
&& qItem.getFilamentVariant().getFilamentMaterialType() != null
|
||||||
&& qItem.getFilamentVariant().getFilamentMaterialType().getMaterialCode() != null) {
|
&& qItem.getFilamentVariant().getFilamentMaterialType().getMaterialCode() != null) {
|
||||||
oItem.setMaterialCode(qItem.getFilamentVariant().getFilamentMaterialType().getMaterialCode());
|
oItem.setMaterialCode(qItem.getFilamentVariant().getFilamentMaterialType().getMaterialCode());
|
||||||
@@ -236,20 +219,18 @@ public class OrderService {
|
|||||||
|
|
||||||
oItem = orderItemRepo.save(oItem);
|
oItem = orderItemRepo.save(oItem);
|
||||||
|
|
||||||
|
String relativePath = "orders/" + order.getId() + "/3d-files/" + oItem.getId() + "/" + storedFilename;
|
||||||
|
oItem.setStoredRelativePath(relativePath);
|
||||||
|
|
||||||
Path sourcePath = resolveStoredQuotePath(qItem.getStoredPath(), session.getId());
|
Path sourcePath = resolveStoredQuotePath(qItem.getStoredPath(), session.getId());
|
||||||
if (sourcePath == null || !Files.exists(sourcePath)) {
|
if (sourcePath == null || !Files.exists(sourcePath)) {
|
||||||
if (requiresStoredSourceFile(qItem)) {
|
throw new IllegalStateException("Source file not available for quote line item " + qItem.getId());
|
||||||
throw new IllegalStateException("Source file not available for quote line item " + qItem.getId());
|
}
|
||||||
}
|
try {
|
||||||
} else {
|
storageService.store(sourcePath, Paths.get(relativePath));
|
||||||
String relativePath = "orders/" + order.getId() + "/3d-files/" + oItem.getId() + "/" + storedFilename;
|
oItem.setFileSizeBytes(Files.size(sourcePath));
|
||||||
oItem.setStoredRelativePath(relativePath);
|
} catch (IOException e) {
|
||||||
try {
|
throw new RuntimeException("Failed to copy quote file for line item " + qItem.getId(), e);
|
||||||
storageService.store(sourcePath, Paths.get(relativePath));
|
|
||||||
oItem.setFileSizeBytes(Files.size(sourcePath));
|
|
||||||
} catch (IOException e) {
|
|
||||||
throw new RuntimeException("Failed to copy quote file for line item " + qItem.getId(), e);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
oItem = orderItemRepo.save(oItem);
|
oItem = orderItemRepo.save(oItem);
|
||||||
@@ -321,12 +302,6 @@ public class OrderService {
|
|||||||
return "stl";
|
return "stl";
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean requiresStoredSourceFile(QuoteLineItem qItem) {
|
|
||||||
return !SHOP_LINE_ITEM_TYPE.equalsIgnoreCase(
|
|
||||||
qItem.getLineItemType() != null ? qItem.getLineItemType() : ""
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private Path resolveStoredQuotePath(String storedPath, UUID expectedSessionId) {
|
private Path resolveStoredQuotePath(String storedPath, UUID expectedSessionId) {
|
||||||
if (storedPath == null || storedPath.isBlank()) {
|
if (storedPath == null || storedPath.isBlank()) {
|
||||||
return null;
|
return null;
|
||||||
@@ -344,13 +319,6 @@ public class OrderService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private String resolveOrderSourceType(QuoteSession session) {
|
|
||||||
if (session != null && "SHOP_CART".equalsIgnoreCase(session.getSessionType())) {
|
|
||||||
return "SHOP";
|
|
||||||
}
|
|
||||||
return "CALCULATOR";
|
|
||||||
}
|
|
||||||
|
|
||||||
private String getDisplayOrderNumber(Order order) {
|
private String getDisplayOrderNumber(Order order) {
|
||||||
String orderNumber = order.getOrderNumber();
|
String orderNumber = order.getOrderNumber();
|
||||||
if (orderNumber != null && !orderNumber.isBlank()) {
|
if (orderNumber != null && !orderNumber.isBlank()) {
|
||||||
|
|||||||
@@ -7,14 +7,10 @@ import org.springframework.beans.factory.annotation.Value;
|
|||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.math.BigDecimal;
|
|
||||||
import java.math.RoundingMode;
|
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Comparator;
|
|
||||||
import java.util.Collections;
|
|
||||||
import java.util.Iterator;
|
import java.util.Iterator;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.logging.Logger;
|
import java.util.logging.Logger;
|
||||||
@@ -24,21 +20,16 @@ import java.util.HashMap;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.LinkedHashSet;
|
import java.util.LinkedHashSet;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.Locale;
|
|
||||||
import java.util.regex.Matcher;
|
|
||||||
import java.util.regex.Pattern;
|
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
public class ProfileManager {
|
public class ProfileManager {
|
||||||
|
|
||||||
private static final Logger logger = Logger.getLogger(ProfileManager.class.getName());
|
private static final Logger logger = Logger.getLogger(ProfileManager.class.getName());
|
||||||
private static final Pattern LAYER_MM_PATTERN = Pattern.compile("^(\\d+(?:\\.\\d+)?)mm\\b", Pattern.CASE_INSENSITIVE);
|
|
||||||
private final String profilesRoot;
|
private final String profilesRoot;
|
||||||
private final Path resolvedProfilesRoot;
|
private final Path resolvedProfilesRoot;
|
||||||
private final ObjectMapper mapper;
|
private final ObjectMapper mapper;
|
||||||
|
|
||||||
private final Map<String, String> profileAliases;
|
private final Map<String, String> profileAliases;
|
||||||
private volatile List<ProcessProfileMeta> cachedProcessProfiles;
|
|
||||||
|
|
||||||
public ProfileManager(@Value("${profiles.root:profiles}") String profilesRoot, ObjectMapper mapper) {
|
public ProfileManager(@Value("${profiles.root:profiles}") String profilesRoot, ObjectMapper mapper) {
|
||||||
this.profilesRoot = profilesRoot;
|
this.profilesRoot = profilesRoot;
|
||||||
@@ -77,61 +68,6 @@ public class ProfileManager {
|
|||||||
return resolveInheritance(profilePath);
|
return resolveInheritance(profilePath);
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<BigDecimal> findCompatibleProcessLayers(String machineProfileName) {
|
|
||||||
if (machineProfileName == null || machineProfileName.isBlank()) {
|
|
||||||
return List.of();
|
|
||||||
}
|
|
||||||
|
|
||||||
Set<BigDecimal> layers = new LinkedHashSet<>();
|
|
||||||
for (ProcessProfileMeta meta : getOrLoadProcessProfiles()) {
|
|
||||||
if (meta.compatiblePrinters().contains(machineProfileName) && meta.layerHeightMm() != null) {
|
|
||||||
layers.add(meta.layerHeightMm());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (layers.isEmpty()) {
|
|
||||||
return List.of();
|
|
||||||
}
|
|
||||||
|
|
||||||
List<BigDecimal> sorted = new ArrayList<>(layers);
|
|
||||||
sorted.sort(Comparator.naturalOrder());
|
|
||||||
return sorted;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Optional<String> findCompatibleProcessProfileName(String machineProfileName,
|
|
||||||
BigDecimal layerHeightMm,
|
|
||||||
String qualityHint) {
|
|
||||||
if (machineProfileName == null || machineProfileName.isBlank() || layerHeightMm == null) {
|
|
||||||
return Optional.empty();
|
|
||||||
}
|
|
||||||
|
|
||||||
BigDecimal normalizedLayer = layerHeightMm.setScale(3, RoundingMode.HALF_UP);
|
|
||||||
String normalizedQuality = String.valueOf(qualityHint == null ? "" : qualityHint)
|
|
||||||
.trim()
|
|
||||||
.toLowerCase(Locale.ROOT);
|
|
||||||
|
|
||||||
List<ProcessProfileMeta> candidates = new ArrayList<>();
|
|
||||||
for (ProcessProfileMeta meta : getOrLoadProcessProfiles()) {
|
|
||||||
if (!meta.compatiblePrinters().contains(machineProfileName)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (meta.layerHeightMm() == null || meta.layerHeightMm().compareTo(normalizedLayer) != 0) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
candidates.add(meta);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (candidates.isEmpty()) {
|
|
||||||
return Optional.empty();
|
|
||||||
}
|
|
||||||
|
|
||||||
candidates.sort(Comparator
|
|
||||||
.comparingInt((ProcessProfileMeta meta) -> scoreProcessForQuality(meta.name(), normalizedQuality))
|
|
||||||
.reversed()
|
|
||||||
.thenComparing(ProcessProfileMeta::name, String.CASE_INSENSITIVE_ORDER));
|
|
||||||
|
|
||||||
return Optional.ofNullable(candidates.get(0).name());
|
|
||||||
}
|
|
||||||
|
|
||||||
private Path findProfileFile(String name, String type) {
|
private Path findProfileFile(String name, String type) {
|
||||||
if (!Files.isDirectory(resolvedProfilesRoot)) {
|
if (!Files.isDirectory(resolvedProfilesRoot)) {
|
||||||
logger.severe("Profiles root does not exist or is not a directory: " + resolvedProfilesRoot);
|
logger.severe("Profiles root does not exist or is not a directory: " + resolvedProfilesRoot);
|
||||||
@@ -279,125 +215,4 @@ public class ProfileManager {
|
|||||||
}
|
}
|
||||||
return "any";
|
return "any";
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<ProcessProfileMeta> getOrLoadProcessProfiles() {
|
|
||||||
List<ProcessProfileMeta> cached = cachedProcessProfiles;
|
|
||||||
if (cached != null) {
|
|
||||||
return cached;
|
|
||||||
}
|
|
||||||
|
|
||||||
synchronized (this) {
|
|
||||||
if (cachedProcessProfiles != null) {
|
|
||||||
return cachedProcessProfiles;
|
|
||||||
}
|
|
||||||
|
|
||||||
List<ProcessProfileMeta> loaded = new ArrayList<>();
|
|
||||||
if (!Files.isDirectory(resolvedProfilesRoot)) {
|
|
||||||
cachedProcessProfiles = Collections.emptyList();
|
|
||||||
return cachedProcessProfiles;
|
|
||||||
}
|
|
||||||
|
|
||||||
try (Stream<Path> stream = Files.walk(resolvedProfilesRoot)) {
|
|
||||||
List<Path> processFiles = stream
|
|
||||||
.filter(Files::isRegularFile)
|
|
||||||
.filter(path -> path.getFileName().toString().toLowerCase(Locale.ROOT).endsWith(".json"))
|
|
||||||
.filter(path -> pathContainsSegment(path, "process"))
|
|
||||||
.sorted()
|
|
||||||
.toList();
|
|
||||||
|
|
||||||
for (Path processFile : processFiles) {
|
|
||||||
try {
|
|
||||||
JsonNode node = mapper.readTree(processFile.toFile());
|
|
||||||
if (!"process".equalsIgnoreCase(node.path("type").asText())) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
String name = node.path("name").asText("");
|
|
||||||
if (name.isBlank()) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
BigDecimal layer = extractLayerHeightFromProfileName(name);
|
|
||||||
if (layer == null) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
Set<String> compatiblePrinters = new LinkedHashSet<>();
|
|
||||||
JsonNode compatibleNode = node.path("compatible_printers");
|
|
||||||
if (compatibleNode.isArray()) {
|
|
||||||
compatibleNode.forEach(value -> {
|
|
||||||
String printer = value.asText("").trim();
|
|
||||||
if (!printer.isBlank()) {
|
|
||||||
compatiblePrinters.add(printer);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (compatiblePrinters.isEmpty()) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
loaded.add(new ProcessProfileMeta(name, layer, compatiblePrinters));
|
|
||||||
} catch (Exception ignored) {
|
|
||||||
// Ignore malformed or non-process JSON files.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (IOException e) {
|
|
||||||
logger.warning("Failed to scan process profiles: " + e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
cachedProcessProfiles = List.copyOf(loaded);
|
|
||||||
return cachedProcessProfiles;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private BigDecimal extractLayerHeightFromProfileName(String profileName) {
|
|
||||||
if (profileName == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
Matcher matcher = LAYER_MM_PATTERN.matcher(profileName.trim());
|
|
||||||
if (!matcher.find()) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
return new BigDecimal(matcher.group(1)).setScale(3, RoundingMode.HALF_UP);
|
|
||||||
} catch (NumberFormatException ex) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private int scoreProcessForQuality(String processName, String qualityHint) {
|
|
||||||
String normalizedName = String.valueOf(processName == null ? "" : processName)
|
|
||||||
.toLowerCase(Locale.ROOT);
|
|
||||||
if (qualityHint == null || qualityHint.isBlank()) {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
return switch (qualityHint) {
|
|
||||||
case "draft" -> {
|
|
||||||
if (normalizedName.contains("extra draft")) yield 30;
|
|
||||||
if (normalizedName.contains("draft")) yield 20;
|
|
||||||
if (normalizedName.contains("standard")) yield 10;
|
|
||||||
yield 0;
|
|
||||||
}
|
|
||||||
case "extra_fine", "high", "high_definition" -> {
|
|
||||||
if (normalizedName.contains("extra fine")) yield 30;
|
|
||||||
if (normalizedName.contains("high quality")) yield 25;
|
|
||||||
if (normalizedName.contains("fine")) yield 20;
|
|
||||||
if (normalizedName.contains("standard")) yield 5;
|
|
||||||
yield 0;
|
|
||||||
}
|
|
||||||
default -> {
|
|
||||||
if (normalizedName.contains("standard")) yield 30;
|
|
||||||
if (normalizedName.contains("optimal")) yield 25;
|
|
||||||
if (normalizedName.contains("strength")) yield 20;
|
|
||||||
if (normalizedName.contains("high quality")) yield 10;
|
|
||||||
if (normalizedName.contains("draft")) yield 5;
|
|
||||||
yield 0;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private record ProcessProfileMeta(String name, BigDecimal layerHeightMm, Set<String> compatiblePrinters) {
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,29 +3,22 @@ package com.printcalculator.service;
|
|||||||
import com.printcalculator.entity.PricingPolicy;
|
import com.printcalculator.entity.PricingPolicy;
|
||||||
import com.printcalculator.entity.QuoteLineItem;
|
import com.printcalculator.entity.QuoteLineItem;
|
||||||
import com.printcalculator.entity.QuoteSession;
|
import com.printcalculator.entity.QuoteSession;
|
||||||
import com.printcalculator.repository.NozzleOptionRepository;
|
|
||||||
import com.printcalculator.repository.PricingPolicyRepository;
|
import com.printcalculator.repository.PricingPolicyRepository;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import java.math.BigDecimal;
|
import java.math.BigDecimal;
|
||||||
import java.math.RoundingMode;
|
import java.math.RoundingMode;
|
||||||
import java.util.LinkedHashSet;
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Set;
|
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
public class QuoteSessionTotalsService {
|
public class QuoteSessionTotalsService {
|
||||||
private final PricingPolicyRepository pricingRepo;
|
private final PricingPolicyRepository pricingRepo;
|
||||||
private final QuoteCalculator quoteCalculator;
|
private final QuoteCalculator quoteCalculator;
|
||||||
private final NozzleOptionRepository nozzleOptionRepo;
|
|
||||||
|
|
||||||
public QuoteSessionTotalsService(PricingPolicyRepository pricingRepo,
|
public QuoteSessionTotalsService(PricingPolicyRepository pricingRepo, QuoteCalculator quoteCalculator) {
|
||||||
QuoteCalculator quoteCalculator,
|
|
||||||
NozzleOptionRepository nozzleOptionRepo) {
|
|
||||||
this.pricingRepo = pricingRepo;
|
this.pricingRepo = pricingRepo;
|
||||||
this.quoteCalculator = quoteCalculator;
|
this.quoteCalculator = quoteCalculator;
|
||||||
this.nozzleOptionRepo = nozzleOptionRepo;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public QuoteSessionTotals compute(QuoteSession session, List<QuoteLineItem> items) {
|
public QuoteSessionTotals compute(QuoteSession session, List<QuoteLineItem> items) {
|
||||||
@@ -50,9 +43,7 @@ public class QuoteSessionTotalsService {
|
|||||||
BigDecimal cadTotal = calculateCadTotal(session);
|
BigDecimal cadTotal = calculateCadTotal(session);
|
||||||
BigDecimal itemsTotal = printItemsTotal.add(cadTotal);
|
BigDecimal itemsTotal = printItemsTotal.add(cadTotal);
|
||||||
|
|
||||||
BigDecimal baseSetupFee = session.getSetupCostChf() != null ? session.getSetupCostChf() : BigDecimal.ZERO;
|
BigDecimal setupFee = session.getSetupCostChf() != null ? session.getSetupCostChf() : BigDecimal.ZERO;
|
||||||
BigDecimal nozzleChangeCost = calculateNozzleChangeCost(items);
|
|
||||||
BigDecimal setupFee = baseSetupFee.add(nozzleChangeCost).setScale(2, RoundingMode.HALF_UP);
|
|
||||||
BigDecimal shippingCost = calculateShippingCost(items);
|
BigDecimal shippingCost = calculateShippingCost(items);
|
||||||
BigDecimal grandTotal = itemsTotal.add(setupFee).add(shippingCost);
|
BigDecimal grandTotal = itemsTotal.add(setupFee).add(shippingCost);
|
||||||
|
|
||||||
@@ -61,8 +52,6 @@ public class QuoteSessionTotalsService {
|
|||||||
globalMachineCost,
|
globalMachineCost,
|
||||||
cadTotal,
|
cadTotal,
|
||||||
itemsTotal,
|
itemsTotal,
|
||||||
baseSetupFee.setScale(2, RoundingMode.HALF_UP),
|
|
||||||
nozzleChangeCost,
|
|
||||||
setupFee,
|
setupFee,
|
||||||
shippingCost,
|
shippingCost,
|
||||||
grandTotal,
|
grandTotal,
|
||||||
@@ -115,36 +104,6 @@ public class QuoteSessionTotalsService {
|
|||||||
return BigDecimal.valueOf(2.00);
|
return BigDecimal.valueOf(2.00);
|
||||||
}
|
}
|
||||||
|
|
||||||
private BigDecimal calculateNozzleChangeCost(List<QuoteLineItem> items) {
|
|
||||||
if (items == null || items.isEmpty()) {
|
|
||||||
return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
|
|
||||||
}
|
|
||||||
|
|
||||||
Set<BigDecimal> uniqueNozzles = new LinkedHashSet<>();
|
|
||||||
for (QuoteLineItem item : items) {
|
|
||||||
if (item == null || item.getNozzleDiameterMm() == null) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
uniqueNozzles.add(item.getNozzleDiameterMm().setScale(2, RoundingMode.HALF_UP));
|
|
||||||
}
|
|
||||||
|
|
||||||
BigDecimal totalFee = BigDecimal.ZERO;
|
|
||||||
for (BigDecimal nozzle : uniqueNozzles) {
|
|
||||||
BigDecimal nozzleFee = nozzleOptionRepo
|
|
||||||
.findFirstByNozzleDiameterMmAndIsActiveTrue(nozzle)
|
|
||||||
.map(option -> option.getExtraNozzleChangeFeeChf() != null
|
|
||||||
? option.getExtraNozzleChangeFeeChf()
|
|
||||||
: BigDecimal.ZERO)
|
|
||||||
.orElse(BigDecimal.ZERO);
|
|
||||||
|
|
||||||
if (nozzleFee.compareTo(BigDecimal.ZERO) > 0) {
|
|
||||||
totalFee = totalFee.add(nozzleFee);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return totalFee.setScale(2, RoundingMode.HALF_UP);
|
|
||||||
}
|
|
||||||
|
|
||||||
private int normalizeQuantity(Integer quantity) {
|
private int normalizeQuantity(Integer quantity) {
|
||||||
if (quantity == null || quantity < 1) {
|
if (quantity == null || quantity < 1) {
|
||||||
return 1;
|
return 1;
|
||||||
@@ -157,8 +116,6 @@ public class QuoteSessionTotalsService {
|
|||||||
BigDecimal globalMachineCostChf,
|
BigDecimal globalMachineCostChf,
|
||||||
BigDecimal cadTotalChf,
|
BigDecimal cadTotalChf,
|
||||||
BigDecimal itemsTotalChf,
|
BigDecimal itemsTotalChf,
|
||||||
BigDecimal baseSetupCostChf,
|
|
||||||
BigDecimal nozzleChangeCostChf,
|
|
||||||
BigDecimal setupCostChf,
|
BigDecimal setupCostChf,
|
||||||
BigDecimal shippingCostChf,
|
BigDecimal shippingCostChf,
|
||||||
BigDecimal grandTotalChf,
|
BigDecimal grandTotalChf,
|
||||||
|
|||||||
@@ -1,354 +0,0 @@
|
|||||||
package com.printcalculator.service.admin;
|
|
||||||
|
|
||||||
import com.printcalculator.dto.AdminFilamentMaterialTypeDto;
|
|
||||||
import com.printcalculator.dto.AdminFilamentVariantDto;
|
|
||||||
import com.printcalculator.dto.AdminUpsertFilamentMaterialTypeRequest;
|
|
||||||
import com.printcalculator.dto.AdminUpsertFilamentVariantRequest;
|
|
||||||
import com.printcalculator.entity.FilamentMaterialType;
|
|
||||||
import com.printcalculator.entity.FilamentVariant;
|
|
||||||
import com.printcalculator.repository.FilamentMaterialTypeRepository;
|
|
||||||
import com.printcalculator.repository.FilamentVariantRepository;
|
|
||||||
import com.printcalculator.repository.OrderItemRepository;
|
|
||||||
import com.printcalculator.repository.QuoteLineItemRepository;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
|
||||||
import org.springframework.web.server.ResponseStatusException;
|
|
||||||
|
|
||||||
import java.math.BigDecimal;
|
|
||||||
import java.time.OffsetDateTime;
|
|
||||||
import java.util.Comparator;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Locale;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.regex.Pattern;
|
|
||||||
|
|
||||||
import static org.springframework.http.HttpStatus.BAD_REQUEST;
|
|
||||||
import static org.springframework.http.HttpStatus.CONFLICT;
|
|
||||||
import static org.springframework.http.HttpStatus.NOT_FOUND;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public class AdminFilamentControllerService {
|
|
||||||
private static final BigDecimal MAX_NUMERIC_6_3 = new BigDecimal("999.999");
|
|
||||||
private static final Pattern HEX_COLOR_PATTERN = Pattern.compile("^#[0-9A-Fa-f]{6}$");
|
|
||||||
private static final Set<String> ALLOWED_FINISH_TYPES = Set.of(
|
|
||||||
"GLOSSY", "MATTE", "MARBLE", "SILK", "TRANSLUCENT", "SPECIAL"
|
|
||||||
);
|
|
||||||
|
|
||||||
private final FilamentMaterialTypeRepository materialRepo;
|
|
||||||
private final FilamentVariantRepository variantRepo;
|
|
||||||
private final QuoteLineItemRepository quoteLineItemRepo;
|
|
||||||
private final OrderItemRepository orderItemRepo;
|
|
||||||
|
|
||||||
public AdminFilamentControllerService(FilamentMaterialTypeRepository materialRepo,
|
|
||||||
FilamentVariantRepository variantRepo,
|
|
||||||
QuoteLineItemRepository quoteLineItemRepo,
|
|
||||||
OrderItemRepository orderItemRepo) {
|
|
||||||
this.materialRepo = materialRepo;
|
|
||||||
this.variantRepo = variantRepo;
|
|
||||||
this.quoteLineItemRepo = quoteLineItemRepo;
|
|
||||||
this.orderItemRepo = orderItemRepo;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<AdminFilamentMaterialTypeDto> getMaterials() {
|
|
||||||
return materialRepo.findAll().stream()
|
|
||||||
.sorted(Comparator.comparing(FilamentMaterialType::getMaterialCode, String.CASE_INSENSITIVE_ORDER))
|
|
||||||
.map(this::toMaterialDto)
|
|
||||||
.toList();
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<AdminFilamentVariantDto> getVariants() {
|
|
||||||
return variantRepo.findAll().stream()
|
|
||||||
.sorted(Comparator
|
|
||||||
.comparing((FilamentVariant variant) -> {
|
|
||||||
FilamentMaterialType type = variant.getFilamentMaterialType();
|
|
||||||
return type != null && type.getMaterialCode() != null ? type.getMaterialCode() : "";
|
|
||||||
}, String.CASE_INSENSITIVE_ORDER)
|
|
||||||
.thenComparing(variant -> variant.getVariantDisplayName() != null ? variant.getVariantDisplayName() : "", String.CASE_INSENSITIVE_ORDER))
|
|
||||||
.map(this::toVariantDto)
|
|
||||||
.toList();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public AdminFilamentMaterialTypeDto createMaterial(AdminUpsertFilamentMaterialTypeRequest payload) {
|
|
||||||
String materialCode = normalizeAndValidateMaterialCode(payload);
|
|
||||||
ensureMaterialCodeAvailable(materialCode, null);
|
|
||||||
|
|
||||||
FilamentMaterialType material = new FilamentMaterialType();
|
|
||||||
applyMaterialPayload(material, payload, materialCode);
|
|
||||||
FilamentMaterialType saved = materialRepo.save(material);
|
|
||||||
return toMaterialDto(saved);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public AdminFilamentMaterialTypeDto updateMaterial(Long materialTypeId, AdminUpsertFilamentMaterialTypeRequest payload) {
|
|
||||||
FilamentMaterialType material = materialRepo.findById(materialTypeId)
|
|
||||||
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "Filament material not found"));
|
|
||||||
|
|
||||||
String materialCode = normalizeAndValidateMaterialCode(payload);
|
|
||||||
ensureMaterialCodeAvailable(materialCode, materialTypeId);
|
|
||||||
|
|
||||||
applyMaterialPayload(material, payload, materialCode);
|
|
||||||
FilamentMaterialType saved = materialRepo.save(material);
|
|
||||||
return toMaterialDto(saved);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public AdminFilamentVariantDto createVariant(AdminUpsertFilamentVariantRequest payload) {
|
|
||||||
FilamentMaterialType material = validateAndResolveMaterial(payload);
|
|
||||||
String normalizedDisplayName = normalizeAndValidateVariantDisplayName(payload.getVariantDisplayName());
|
|
||||||
String normalizedColorName = normalizeAndValidateColorName(payload.getColorName());
|
|
||||||
validateNumericPayload(payload);
|
|
||||||
ensureVariantDisplayNameAvailable(material, normalizedDisplayName, null);
|
|
||||||
|
|
||||||
FilamentVariant variant = new FilamentVariant();
|
|
||||||
variant.setCreatedAt(OffsetDateTime.now());
|
|
||||||
applyVariantPayload(variant, payload, material, normalizedDisplayName, normalizedColorName);
|
|
||||||
FilamentVariant saved = variantRepo.save(variant);
|
|
||||||
return toVariantDto(saved);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public AdminFilamentVariantDto updateVariant(Long variantId, AdminUpsertFilamentVariantRequest payload) {
|
|
||||||
FilamentVariant variant = variantRepo.findById(variantId)
|
|
||||||
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "Filament variant not found"));
|
|
||||||
|
|
||||||
FilamentMaterialType material = validateAndResolveMaterial(payload);
|
|
||||||
String normalizedDisplayName = normalizeAndValidateVariantDisplayName(payload.getVariantDisplayName());
|
|
||||||
String normalizedColorName = normalizeAndValidateColorName(payload.getColorName());
|
|
||||||
validateNumericPayload(payload);
|
|
||||||
ensureVariantDisplayNameAvailable(material, normalizedDisplayName, variantId);
|
|
||||||
|
|
||||||
applyVariantPayload(variant, payload, material, normalizedDisplayName, normalizedColorName);
|
|
||||||
FilamentVariant saved = variantRepo.save(variant);
|
|
||||||
return toVariantDto(saved);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public void deleteVariant(Long variantId) {
|
|
||||||
FilamentVariant variant = variantRepo.findById(variantId)
|
|
||||||
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "Filament variant not found"));
|
|
||||||
|
|
||||||
if (quoteLineItemRepo.existsByFilamentVariant_Id(variantId) || orderItemRepo.existsByFilamentVariant_Id(variantId)) {
|
|
||||||
throw new ResponseStatusException(CONFLICT, "Variant is already used in quotes/orders and cannot be deleted");
|
|
||||||
}
|
|
||||||
|
|
||||||
variantRepo.delete(variant);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void applyMaterialPayload(FilamentMaterialType material,
|
|
||||||
AdminUpsertFilamentMaterialTypeRequest payload,
|
|
||||||
String normalizedMaterialCode) {
|
|
||||||
boolean isFlexible = payload != null && Boolean.TRUE.equals(payload.getIsFlexible());
|
|
||||||
boolean isTechnical = payload != null && Boolean.TRUE.equals(payload.getIsTechnical());
|
|
||||||
String technicalTypeLabel = payload != null && payload.getTechnicalTypeLabel() != null
|
|
||||||
? payload.getTechnicalTypeLabel().trim()
|
|
||||||
: null;
|
|
||||||
|
|
||||||
material.setMaterialCode(normalizedMaterialCode);
|
|
||||||
material.setIsFlexible(isFlexible);
|
|
||||||
material.setIsTechnical(isTechnical);
|
|
||||||
material.setTechnicalTypeLabel(isTechnical && technicalTypeLabel != null && !technicalTypeLabel.isBlank()
|
|
||||||
? technicalTypeLabel
|
|
||||||
: null);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void applyVariantPayload(FilamentVariant variant,
|
|
||||||
AdminUpsertFilamentVariantRequest payload,
|
|
||||||
FilamentMaterialType material,
|
|
||||||
String normalizedDisplayName,
|
|
||||||
String normalizedColorName) {
|
|
||||||
String normalizedColorHex = normalizeAndValidateColorHex(payload.getColorHex());
|
|
||||||
String normalizedFinishType = normalizeAndValidateFinishType(payload.getFinishType(), payload.getIsMatte());
|
|
||||||
String normalizedBrand = normalizeOptional(payload.getBrand());
|
|
||||||
String fallbackColorLabel = firstNonBlank(
|
|
||||||
normalizeOptional(payload.getColorLabelIt()),
|
|
||||||
normalizeOptional(payload.getColorLabelEn()),
|
|
||||||
normalizeOptional(payload.getColorLabelDe()),
|
|
||||||
normalizeOptional(payload.getColorLabelFr()),
|
|
||||||
normalizedColorName
|
|
||||||
);
|
|
||||||
|
|
||||||
variant.setFilamentMaterialType(material);
|
|
||||||
variant.setVariantDisplayName(normalizedDisplayName);
|
|
||||||
variant.setColorName(normalizedColorName);
|
|
||||||
variant.setColorLabelIt(firstNonBlank(normalizeOptional(payload.getColorLabelIt()), fallbackColorLabel));
|
|
||||||
variant.setColorLabelEn(firstNonBlank(normalizeOptional(payload.getColorLabelEn()), fallbackColorLabel));
|
|
||||||
variant.setColorLabelDe(firstNonBlank(normalizeOptional(payload.getColorLabelDe()), fallbackColorLabel));
|
|
||||||
variant.setColorLabelFr(firstNonBlank(normalizeOptional(payload.getColorLabelFr()), fallbackColorLabel));
|
|
||||||
variant.setColorHex(normalizedColorHex);
|
|
||||||
variant.setFinishType(normalizedFinishType);
|
|
||||||
variant.setBrand(normalizedBrand);
|
|
||||||
variant.setIsMatte(Boolean.TRUE.equals(payload.getIsMatte()) || "MATTE".equals(normalizedFinishType));
|
|
||||||
variant.setIsSpecial(Boolean.TRUE.equals(payload.getIsSpecial()));
|
|
||||||
variant.setCostChfPerKg(payload.getCostChfPerKg());
|
|
||||||
variant.setStockSpools(payload.getStockSpools());
|
|
||||||
variant.setSpoolNetKg(payload.getSpoolNetKg());
|
|
||||||
variant.setIsActive(payload.getIsActive() == null || payload.getIsActive());
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeAndValidateMaterialCode(AdminUpsertFilamentMaterialTypeRequest payload) {
|
|
||||||
if (payload == null || payload.getMaterialCode() == null || payload.getMaterialCode().isBlank()) {
|
|
||||||
throw new ResponseStatusException(BAD_REQUEST, "Material code is required");
|
|
||||||
}
|
|
||||||
return payload.getMaterialCode().trim().toUpperCase(Locale.ROOT);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeAndValidateVariantDisplayName(String value) {
|
|
||||||
if (value == null || value.isBlank()) {
|
|
||||||
throw new ResponseStatusException(BAD_REQUEST, "Variant display name is required");
|
|
||||||
}
|
|
||||||
return value.trim();
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeAndValidateColorName(String value) {
|
|
||||||
if (value == null || value.isBlank()) {
|
|
||||||
throw new ResponseStatusException(BAD_REQUEST, "Color name is required");
|
|
||||||
}
|
|
||||||
return value.trim();
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeAndValidateColorHex(String value) {
|
|
||||||
if (value == null || value.isBlank()) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
String normalized = value.trim();
|
|
||||||
if (!HEX_COLOR_PATTERN.matcher(normalized).matches()) {
|
|
||||||
throw new ResponseStatusException(BAD_REQUEST, "Color hex must be in format #RRGGBB");
|
|
||||||
}
|
|
||||||
return normalized.toUpperCase(Locale.ROOT);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeAndValidateFinishType(String finishType, Boolean isMatte) {
|
|
||||||
String normalized = finishType == null || finishType.isBlank()
|
|
||||||
? (Boolean.TRUE.equals(isMatte) ? "MATTE" : "GLOSSY")
|
|
||||||
: finishType.trim().toUpperCase(Locale.ROOT);
|
|
||||||
if (!ALLOWED_FINISH_TYPES.contains(normalized)) {
|
|
||||||
throw new ResponseStatusException(BAD_REQUEST, "Invalid finish type");
|
|
||||||
}
|
|
||||||
return normalized;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeOptional(String value) {
|
|
||||||
if (value == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
String normalized = value.trim();
|
|
||||||
return normalized.isBlank() ? null : normalized;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String firstNonBlank(String... values) {
|
|
||||||
if (values == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
for (String value : values) {
|
|
||||||
if (value != null && !value.isBlank()) {
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private FilamentMaterialType validateAndResolveMaterial(AdminUpsertFilamentVariantRequest payload) {
|
|
||||||
if (payload == null || payload.getMaterialTypeId() == null) {
|
|
||||||
throw new ResponseStatusException(BAD_REQUEST, "Material type id is required");
|
|
||||||
}
|
|
||||||
|
|
||||||
return materialRepo.findById(payload.getMaterialTypeId())
|
|
||||||
.orElseThrow(() -> new ResponseStatusException(BAD_REQUEST, "Material type not found"));
|
|
||||||
}
|
|
||||||
|
|
||||||
private void validateNumericPayload(AdminUpsertFilamentVariantRequest payload) {
|
|
||||||
if (payload.getCostChfPerKg() == null || payload.getCostChfPerKg().compareTo(BigDecimal.ZERO) < 0) {
|
|
||||||
throw new ResponseStatusException(BAD_REQUEST, "Cost CHF/kg must be >= 0");
|
|
||||||
}
|
|
||||||
validateNumeric63(payload.getStockSpools(), "Stock spools", true);
|
|
||||||
validateNumeric63(payload.getSpoolNetKg(), "Spool net kg", false);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void validateNumeric63(BigDecimal value, String fieldName, boolean allowZero) {
|
|
||||||
if (value == null) {
|
|
||||||
throw new ResponseStatusException(BAD_REQUEST, fieldName + " is required");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (allowZero) {
|
|
||||||
if (value.compareTo(BigDecimal.ZERO) < 0) {
|
|
||||||
throw new ResponseStatusException(BAD_REQUEST, fieldName + " must be >= 0");
|
|
||||||
}
|
|
||||||
} else if (value.compareTo(BigDecimal.ZERO) <= 0) {
|
|
||||||
throw new ResponseStatusException(BAD_REQUEST, fieldName + " must be > 0");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (value.scale() > 3) {
|
|
||||||
throw new ResponseStatusException(BAD_REQUEST, fieldName + " must have at most 3 decimal places");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (value.compareTo(MAX_NUMERIC_6_3) > 0) {
|
|
||||||
throw new ResponseStatusException(BAD_REQUEST, fieldName + " must be <= 999.999");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void ensureMaterialCodeAvailable(String materialCode, Long currentMaterialId) {
|
|
||||||
materialRepo.findByMaterialCode(materialCode).ifPresent(existing -> {
|
|
||||||
if (currentMaterialId == null || !existing.getId().equals(currentMaterialId)) {
|
|
||||||
throw new ResponseStatusException(BAD_REQUEST, "Material code already exists");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private void ensureVariantDisplayNameAvailable(FilamentMaterialType material, String displayName, Long currentVariantId) {
|
|
||||||
variantRepo.findByFilamentMaterialTypeAndVariantDisplayName(material, displayName).ifPresent(existing -> {
|
|
||||||
if (currentVariantId == null || !existing.getId().equals(currentVariantId)) {
|
|
||||||
throw new ResponseStatusException(BAD_REQUEST, "Variant display name already exists for this material");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private AdminFilamentMaterialTypeDto toMaterialDto(FilamentMaterialType material) {
|
|
||||||
AdminFilamentMaterialTypeDto dto = new AdminFilamentMaterialTypeDto();
|
|
||||||
dto.setId(material.getId());
|
|
||||||
dto.setMaterialCode(material.getMaterialCode());
|
|
||||||
dto.setIsFlexible(material.getIsFlexible());
|
|
||||||
dto.setIsTechnical(material.getIsTechnical());
|
|
||||||
dto.setTechnicalTypeLabel(material.getTechnicalTypeLabel());
|
|
||||||
return dto;
|
|
||||||
}
|
|
||||||
|
|
||||||
private AdminFilamentVariantDto toVariantDto(FilamentVariant variant) {
|
|
||||||
AdminFilamentVariantDto dto = new AdminFilamentVariantDto();
|
|
||||||
dto.setId(variant.getId());
|
|
||||||
|
|
||||||
FilamentMaterialType material = variant.getFilamentMaterialType();
|
|
||||||
if (material != null) {
|
|
||||||
dto.setMaterialTypeId(material.getId());
|
|
||||||
dto.setMaterialCode(material.getMaterialCode());
|
|
||||||
dto.setMaterialIsFlexible(material.getIsFlexible());
|
|
||||||
dto.setMaterialIsTechnical(material.getIsTechnical());
|
|
||||||
dto.setMaterialTechnicalTypeLabel(material.getTechnicalTypeLabel());
|
|
||||||
}
|
|
||||||
|
|
||||||
dto.setVariantDisplayName(variant.getVariantDisplayName());
|
|
||||||
dto.setColorName(variant.getColorName());
|
|
||||||
dto.setColorLabelIt(variant.getColorLabelIt());
|
|
||||||
dto.setColorLabelEn(variant.getColorLabelEn());
|
|
||||||
dto.setColorLabelDe(variant.getColorLabelDe());
|
|
||||||
dto.setColorLabelFr(variant.getColorLabelFr());
|
|
||||||
dto.setColorHex(variant.getColorHex());
|
|
||||||
dto.setFinishType(variant.getFinishType());
|
|
||||||
dto.setBrand(variant.getBrand());
|
|
||||||
dto.setIsMatte(variant.getIsMatte());
|
|
||||||
dto.setIsSpecial(variant.getIsSpecial());
|
|
||||||
dto.setCostChfPerKg(variant.getCostChfPerKg());
|
|
||||||
dto.setStockSpools(variant.getStockSpools());
|
|
||||||
dto.setSpoolNetKg(variant.getSpoolNetKg());
|
|
||||||
BigDecimal stockKg = BigDecimal.ZERO;
|
|
||||||
if (variant.getStockSpools() != null && variant.getSpoolNetKg() != null) {
|
|
||||||
stockKg = variant.getStockSpools().multiply(variant.getSpoolNetKg());
|
|
||||||
}
|
|
||||||
dto.setStockKg(stockKg);
|
|
||||||
dto.setStockFilamentGrams(stockKg.multiply(BigDecimal.valueOf(1000)));
|
|
||||||
dto.setIsActive(variant.getIsActive());
|
|
||||||
dto.setCreatedAt(variant.getCreatedAt());
|
|
||||||
return dto;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,870 +0,0 @@
|
|||||||
package com.printcalculator.service.admin;
|
|
||||||
|
|
||||||
import com.printcalculator.dto.AdminCreateMediaUsageRequest;
|
|
||||||
import com.printcalculator.dto.AdminMediaAssetDto;
|
|
||||||
import com.printcalculator.dto.AdminMediaUsageDto;
|
|
||||||
import com.printcalculator.dto.AdminMediaVariantDto;
|
|
||||||
import com.printcalculator.dto.MediaTextTranslationDto;
|
|
||||||
import com.printcalculator.dto.AdminUpdateMediaAssetRequest;
|
|
||||||
import com.printcalculator.dto.AdminUpdateMediaUsageRequest;
|
|
||||||
import com.printcalculator.entity.MediaAsset;
|
|
||||||
import com.printcalculator.entity.MediaUsage;
|
|
||||||
import com.printcalculator.entity.MediaVariant;
|
|
||||||
import com.printcalculator.repository.MediaAssetRepository;
|
|
||||||
import com.printcalculator.repository.MediaUsageRepository;
|
|
||||||
import com.printcalculator.repository.MediaVariantRepository;
|
|
||||||
import com.printcalculator.service.media.MediaFfmpegService;
|
|
||||||
import com.printcalculator.service.media.MediaImageInspector;
|
|
||||||
import com.printcalculator.service.media.MediaStorageService;
|
|
||||||
import com.printcalculator.service.storage.ClamAVService;
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
|
||||||
import org.springframework.http.HttpStatus;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
|
||||||
import org.springframework.util.StringUtils;
|
|
||||||
import org.springframework.web.multipart.MultipartFile;
|
|
||||||
import org.springframework.web.server.ResponseStatusException;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.InputStream;
|
|
||||||
import java.io.UncheckedIOException;
|
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.nio.file.Paths;
|
|
||||||
import java.security.MessageDigest;
|
|
||||||
import java.security.NoSuchAlgorithmException;
|
|
||||||
import java.time.LocalDate;
|
|
||||||
import java.time.OffsetDateTime;
|
|
||||||
import java.time.format.DateTimeFormatter;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.Collection;
|
|
||||||
import java.util.Comparator;
|
|
||||||
import java.util.HexFormat;
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.LinkedHashSet;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Locale;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Objects;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.UUID;
|
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public class AdminMediaControllerService {
|
|
||||||
|
|
||||||
private static final Logger logger = LoggerFactory.getLogger(AdminMediaControllerService.class);
|
|
||||||
|
|
||||||
private static final String STATUS_UPLOADED = "UPLOADED";
|
|
||||||
private static final String STATUS_PROCESSING = "PROCESSING";
|
|
||||||
private static final String STATUS_READY = "READY";
|
|
||||||
private static final String STATUS_FAILED = "FAILED";
|
|
||||||
private static final String STATUS_ARCHIVED = "ARCHIVED";
|
|
||||||
|
|
||||||
private static final String VISIBILITY_PUBLIC = "PUBLIC";
|
|
||||||
private static final String VISIBILITY_PRIVATE = "PRIVATE";
|
|
||||||
|
|
||||||
private static final String FORMAT_ORIGINAL = "ORIGINAL";
|
|
||||||
private static final String FORMAT_JPEG = "JPEG";
|
|
||||||
private static final String FORMAT_WEBP = "WEBP";
|
|
||||||
private static final String FORMAT_AVIF = "AVIF";
|
|
||||||
|
|
||||||
private static final Set<String> ALLOWED_STATUSES = Set.of(
|
|
||||||
STATUS_UPLOADED, STATUS_PROCESSING, STATUS_READY, STATUS_FAILED, STATUS_ARCHIVED
|
|
||||||
);
|
|
||||||
private static final Set<String> ALLOWED_VISIBILITIES = Set.of(VISIBILITY_PUBLIC, VISIBILITY_PRIVATE);
|
|
||||||
private static final Set<String> ALLOWED_UPLOAD_MIME_TYPES = Set.of(
|
|
||||||
"image/jpeg", "image/png", "image/webp"
|
|
||||||
);
|
|
||||||
private static final List<String> SUPPORTED_MEDIA_LANGUAGES = List.of("it", "en", "de", "fr");
|
|
||||||
private static final Map<String, String> GENERATED_FORMAT_MIME_TYPES = Map.of(
|
|
||||||
FORMAT_JPEG, "image/jpeg",
|
|
||||||
FORMAT_WEBP, "image/webp",
|
|
||||||
FORMAT_AVIF, "image/avif"
|
|
||||||
);
|
|
||||||
private static final Map<String, String> GENERATED_FORMAT_EXTENSIONS = Map.of(
|
|
||||||
FORMAT_JPEG, "jpg",
|
|
||||||
FORMAT_WEBP, "webp",
|
|
||||||
FORMAT_AVIF, "avif"
|
|
||||||
);
|
|
||||||
private static final List<PresetDefinition> PRESETS = List.of(
|
|
||||||
new PresetDefinition("thumb", 320),
|
|
||||||
new PresetDefinition("card", 640),
|
|
||||||
new PresetDefinition("hero", 1280)
|
|
||||||
);
|
|
||||||
private static final DateTimeFormatter STORAGE_FOLDER_FORMATTER = DateTimeFormatter.ofPattern("yyyy/MM");
|
|
||||||
|
|
||||||
private final MediaAssetRepository mediaAssetRepository;
|
|
||||||
private final MediaVariantRepository mediaVariantRepository;
|
|
||||||
private final MediaUsageRepository mediaUsageRepository;
|
|
||||||
private final MediaStorageService mediaStorageService;
|
|
||||||
private final MediaImageInspector mediaImageInspector;
|
|
||||||
private final MediaFfmpegService mediaFfmpegService;
|
|
||||||
private final ClamAVService clamAVService;
|
|
||||||
private final long maxUploadFileSizeBytes;
|
|
||||||
|
|
||||||
public AdminMediaControllerService(MediaAssetRepository mediaAssetRepository,
|
|
||||||
MediaVariantRepository mediaVariantRepository,
|
|
||||||
MediaUsageRepository mediaUsageRepository,
|
|
||||||
MediaStorageService mediaStorageService,
|
|
||||||
MediaImageInspector mediaImageInspector,
|
|
||||||
MediaFfmpegService mediaFfmpegService,
|
|
||||||
ClamAVService clamAVService,
|
|
||||||
@Value("${media.upload.max-file-size-bytes:26214400}") long maxUploadFileSizeBytes) {
|
|
||||||
this.mediaAssetRepository = mediaAssetRepository;
|
|
||||||
this.mediaVariantRepository = mediaVariantRepository;
|
|
||||||
this.mediaUsageRepository = mediaUsageRepository;
|
|
||||||
this.mediaStorageService = mediaStorageService;
|
|
||||||
this.mediaImageInspector = mediaImageInspector;
|
|
||||||
this.mediaFfmpegService = mediaFfmpegService;
|
|
||||||
this.clamAVService = clamAVService;
|
|
||||||
this.maxUploadFileSizeBytes = maxUploadFileSizeBytes;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional(noRollbackFor = ResponseStatusException.class)
|
|
||||||
public AdminMediaAssetDto uploadAsset(MultipartFile file,
|
|
||||||
String title,
|
|
||||||
String altText,
|
|
||||||
String visibility) {
|
|
||||||
validateUpload(file);
|
|
||||||
|
|
||||||
Path tempDirectory = null;
|
|
||||||
MediaAsset asset = null;
|
|
||||||
|
|
||||||
try {
|
|
||||||
String normalizedVisibility = normalizeVisibility(visibility, true);
|
|
||||||
tempDirectory = Files.createTempDirectory("media-asset-");
|
|
||||||
Path uploadFile = tempDirectory.resolve("upload.bin");
|
|
||||||
file.transferTo(uploadFile);
|
|
||||||
|
|
||||||
try (InputStream inputStream = Files.newInputStream(uploadFile)) {
|
|
||||||
clamAVService.scan(inputStream);
|
|
||||||
}
|
|
||||||
|
|
||||||
MediaImageInspector.ImageMetadata metadata = mediaImageInspector.inspect(uploadFile);
|
|
||||||
if (!ALLOWED_UPLOAD_MIME_TYPES.contains(metadata.mimeType())) {
|
|
||||||
throw new ResponseStatusException(
|
|
||||||
HttpStatus.BAD_REQUEST,
|
|
||||||
"Unsupported image type. Allowed: jpg, jpeg, png, webp."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
String storageFolder = buildStorageFolder();
|
|
||||||
String originalStorageKey = storageFolder + "/original." + metadata.fileExtension();
|
|
||||||
String normalizedFilename = sanitizeOriginalFilename(file.getOriginalFilename(), metadata.fileExtension());
|
|
||||||
String normalizedTitle = normalizeText(title);
|
|
||||||
String normalizedAltText = normalizeText(altText);
|
|
||||||
long originalFileSize = Files.size(uploadFile);
|
|
||||||
String sha256Hex = computeSha256(uploadFile);
|
|
||||||
|
|
||||||
mediaStorageService.storeOriginal(uploadFile, originalStorageKey);
|
|
||||||
|
|
||||||
OffsetDateTime now = OffsetDateTime.now();
|
|
||||||
asset = new MediaAsset();
|
|
||||||
asset.setOriginalFilename(normalizedFilename);
|
|
||||||
asset.setStorageKey(originalStorageKey);
|
|
||||||
asset.setMimeType(metadata.mimeType());
|
|
||||||
asset.setFileSizeBytes(originalFileSize);
|
|
||||||
asset.setSha256Hex(sha256Hex);
|
|
||||||
asset.setWidthPx(metadata.widthPx());
|
|
||||||
asset.setHeightPx(metadata.heightPx());
|
|
||||||
asset.setStatus(STATUS_UPLOADED);
|
|
||||||
asset.setVisibility(normalizedVisibility);
|
|
||||||
asset.setTitle(normalizedTitle);
|
|
||||||
asset.setAltText(normalizedAltText);
|
|
||||||
asset.setCreatedAt(now);
|
|
||||||
asset.setUpdatedAt(now);
|
|
||||||
asset = mediaAssetRepository.save(asset);
|
|
||||||
|
|
||||||
MediaVariant originalVariant = new MediaVariant();
|
|
||||||
originalVariant.setMediaAsset(asset);
|
|
||||||
originalVariant.setVariantName("original");
|
|
||||||
originalVariant.setFormat(FORMAT_ORIGINAL);
|
|
||||||
originalVariant.setStorageKey(originalStorageKey);
|
|
||||||
originalVariant.setMimeType(metadata.mimeType());
|
|
||||||
originalVariant.setWidthPx(metadata.widthPx());
|
|
||||||
originalVariant.setHeightPx(metadata.heightPx());
|
|
||||||
originalVariant.setFileSizeBytes(originalFileSize);
|
|
||||||
originalVariant.setIsGenerated(false);
|
|
||||||
originalVariant.setCreatedAt(now);
|
|
||||||
mediaVariantRepository.save(originalVariant);
|
|
||||||
|
|
||||||
asset.setStatus(STATUS_PROCESSING);
|
|
||||||
asset.setUpdatedAt(OffsetDateTime.now());
|
|
||||||
asset = mediaAssetRepository.save(asset);
|
|
||||||
|
|
||||||
List<MediaVariant> generatedVariants = generateDerivedVariants(asset, uploadFile, tempDirectory);
|
|
||||||
mediaVariantRepository.saveAll(generatedVariants);
|
|
||||||
|
|
||||||
asset.setStatus(STATUS_READY);
|
|
||||||
asset.setUpdatedAt(OffsetDateTime.now());
|
|
||||||
mediaAssetRepository.save(asset);
|
|
||||||
|
|
||||||
return getAsset(asset.getId());
|
|
||||||
} catch (ResponseStatusException e) {
|
|
||||||
markFailed(asset, e.getReason(), e);
|
|
||||||
throw e;
|
|
||||||
} catch (IOException e) {
|
|
||||||
markFailed(asset, "Media processing failed.", e);
|
|
||||||
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Media processing failed.");
|
|
||||||
} finally {
|
|
||||||
deleteRecursively(tempDirectory);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<AdminMediaAssetDto> listAssets() {
|
|
||||||
return toAssetDtos(mediaAssetRepository.findAllByOrderByCreatedAtDesc());
|
|
||||||
}
|
|
||||||
|
|
||||||
public AdminMediaAssetDto getAsset(UUID mediaAssetId) {
|
|
||||||
MediaAsset asset = getAssetOrThrow(mediaAssetId);
|
|
||||||
return toAssetDtos(List.of(asset)).getFirst();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional(noRollbackFor = ResponseStatusException.class)
|
|
||||||
public AdminMediaAssetDto updateAsset(UUID mediaAssetId, AdminUpdateMediaAssetRequest payload) {
|
|
||||||
if (payload == null) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Payload is required.");
|
|
||||||
}
|
|
||||||
|
|
||||||
MediaAsset asset = getAssetOrThrow(mediaAssetId);
|
|
||||||
String requestedVisibility = normalizeVisibility(payload.getVisibility(), false);
|
|
||||||
String requestedStatus = normalizeStatus(payload.getStatus(), false);
|
|
||||||
|
|
||||||
if (requestedVisibility != null && !requestedVisibility.equals(asset.getVisibility())) {
|
|
||||||
moveGeneratedVariants(asset, requestedVisibility);
|
|
||||||
asset.setVisibility(requestedVisibility);
|
|
||||||
}
|
|
||||||
if (requestedStatus != null) {
|
|
||||||
asset.setStatus(requestedStatus);
|
|
||||||
}
|
|
||||||
if (payload.getTitle() != null) {
|
|
||||||
asset.setTitle(normalizeText(payload.getTitle()));
|
|
||||||
}
|
|
||||||
if (payload.getAltText() != null) {
|
|
||||||
asset.setAltText(normalizeText(payload.getAltText()));
|
|
||||||
}
|
|
||||||
|
|
||||||
asset.setUpdatedAt(OffsetDateTime.now());
|
|
||||||
mediaAssetRepository.save(asset);
|
|
||||||
return getAsset(asset.getId());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public AdminMediaUsageDto createUsage(AdminCreateMediaUsageRequest payload) {
|
|
||||||
if (payload == null) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Payload is required.");
|
|
||||||
}
|
|
||||||
|
|
||||||
MediaAsset asset = getAssetOrThrow(payload.getMediaAssetId());
|
|
||||||
String usageType = requireUsageType(payload.getUsageType());
|
|
||||||
String usageKey = requireUsageKey(payload.getUsageKey());
|
|
||||||
boolean isPrimary = Boolean.TRUE.equals(payload.getIsPrimary());
|
|
||||||
Map<String, MediaTextTranslationDto> translations = requireTranslations(payload.getTranslations());
|
|
||||||
|
|
||||||
if (isPrimary) {
|
|
||||||
unsetPrimaryForScope(usageType, usageKey, payload.getOwnerId(), null);
|
|
||||||
}
|
|
||||||
|
|
||||||
MediaUsage usage = new MediaUsage();
|
|
||||||
usage.setUsageType(usageType);
|
|
||||||
usage.setUsageKey(usageKey);
|
|
||||||
usage.setOwnerId(payload.getOwnerId());
|
|
||||||
usage.setMediaAsset(asset);
|
|
||||||
usage.setSortOrder(payload.getSortOrder() != null ? payload.getSortOrder() : 0);
|
|
||||||
usage.setIsPrimary(isPrimary);
|
|
||||||
usage.setIsActive(payload.getIsActive() == null || payload.getIsActive());
|
|
||||||
usage.setCreatedAt(OffsetDateTime.now());
|
|
||||||
applyTranslations(usage, translations);
|
|
||||||
|
|
||||||
MediaUsage saved = mediaUsageRepository.save(usage);
|
|
||||||
return toUsageDto(saved);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public AdminMediaUsageDto updateUsage(UUID mediaUsageId, AdminUpdateMediaUsageRequest payload) {
|
|
||||||
if (payload == null) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Payload is required.");
|
|
||||||
}
|
|
||||||
|
|
||||||
MediaUsage usage = getUsageOrThrow(mediaUsageId);
|
|
||||||
|
|
||||||
if (payload.getUsageType() != null) {
|
|
||||||
usage.setUsageType(requireUsageType(payload.getUsageType()));
|
|
||||||
}
|
|
||||||
if (payload.getUsageKey() != null) {
|
|
||||||
usage.setUsageKey(requireUsageKey(payload.getUsageKey()));
|
|
||||||
}
|
|
||||||
if (payload.getOwnerId() != null) {
|
|
||||||
usage.setOwnerId(payload.getOwnerId());
|
|
||||||
}
|
|
||||||
if (payload.getMediaAssetId() != null) {
|
|
||||||
usage.setMediaAsset(getAssetOrThrow(payload.getMediaAssetId()));
|
|
||||||
}
|
|
||||||
if (payload.getSortOrder() != null) {
|
|
||||||
usage.setSortOrder(payload.getSortOrder());
|
|
||||||
}
|
|
||||||
if (payload.getIsActive() != null) {
|
|
||||||
usage.setIsActive(payload.getIsActive());
|
|
||||||
}
|
|
||||||
if (payload.getIsPrimary() != null) {
|
|
||||||
usage.setIsPrimary(payload.getIsPrimary());
|
|
||||||
}
|
|
||||||
if (payload.getTranslations() != null) {
|
|
||||||
applyTranslations(usage, requireTranslations(payload.getTranslations()));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Boolean.TRUE.equals(usage.getIsPrimary())) {
|
|
||||||
unsetPrimaryForScope(usage.getUsageType(), usage.getUsageKey(), usage.getOwnerId(), usage.getId());
|
|
||||||
}
|
|
||||||
|
|
||||||
MediaUsage saved = mediaUsageRepository.save(usage);
|
|
||||||
return toUsageDto(saved);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public void deleteUsage(UUID mediaUsageId) {
|
|
||||||
mediaUsageRepository.delete(getUsageOrThrow(mediaUsageId));
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<AdminMediaUsageDto> getUsages(String usageType, String usageKey, UUID ownerId) {
|
|
||||||
String normalizedUsageType = requireUsageType(usageType);
|
|
||||||
String normalizedUsageKey = requireUsageKey(usageKey);
|
|
||||||
return mediaUsageRepository.findByUsageScope(normalizedUsageType, normalizedUsageKey, ownerId)
|
|
||||||
.stream()
|
|
||||||
.sorted(Comparator
|
|
||||||
.comparing(MediaUsage::getSortOrder, Comparator.nullsLast(Integer::compareTo))
|
|
||||||
.thenComparing(MediaUsage::getCreatedAt, Comparator.nullsLast(OffsetDateTime::compareTo)))
|
|
||||||
.map(this::toUsageDto)
|
|
||||||
.toList();
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<MediaVariant> generateDerivedVariants(MediaAsset asset, Path sourceFile, Path tempDirectory) throws IOException {
|
|
||||||
Path generatedDirectory = Files.createDirectories(tempDirectory.resolve("generated"));
|
|
||||||
String storageFolder = extractStorageFolder(asset.getStorageKey());
|
|
||||||
|
|
||||||
List<PendingGeneratedVariant> pendingVariants = new ArrayList<>();
|
|
||||||
Set<String> skippedFormats = new LinkedHashSet<>();
|
|
||||||
for (PresetDefinition preset : PRESETS) {
|
|
||||||
VariantDimensions dimensions = computeVariantDimensions(
|
|
||||||
asset.getWidthPx(),
|
|
||||||
asset.getHeightPx(),
|
|
||||||
preset.maxDimension()
|
|
||||||
);
|
|
||||||
|
|
||||||
for (String format : List.of(FORMAT_JPEG, FORMAT_WEBP, FORMAT_AVIF)) {
|
|
||||||
if (!mediaFfmpegService.canEncode(format)) {
|
|
||||||
skippedFormats.add(format);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
String extension = GENERATED_FORMAT_EXTENSIONS.get(format);
|
|
||||||
Path outputFile = generatedDirectory.resolve(preset.name() + "." + extension);
|
|
||||||
try {
|
|
||||||
mediaFfmpegService.generateVariant(
|
|
||||||
sourceFile,
|
|
||||||
outputFile,
|
|
||||||
dimensions.widthPx(),
|
|
||||||
dimensions.heightPx(),
|
|
||||||
format
|
|
||||||
);
|
|
||||||
} catch (IOException e) {
|
|
||||||
if (FORMAT_AVIF.equals(format)) {
|
|
||||||
skippedFormats.add(format);
|
|
||||||
logger.warn(
|
|
||||||
"Skipping AVIF variant generation for asset {} preset '{}' because FFmpeg AVIF generation failed: {}",
|
|
||||||
asset.getId(),
|
|
||||||
preset.name(),
|
|
||||||
e.getMessage()
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
|
|
||||||
MediaVariant variant = new MediaVariant();
|
|
||||||
variant.setMediaAsset(asset);
|
|
||||||
variant.setVariantName(preset.name());
|
|
||||||
variant.setFormat(format);
|
|
||||||
variant.setStorageKey(storageFolder + "/" + preset.name() + "." + extension);
|
|
||||||
variant.setMimeType(GENERATED_FORMAT_MIME_TYPES.get(format));
|
|
||||||
variant.setWidthPx(dimensions.widthPx());
|
|
||||||
variant.setHeightPx(dimensions.heightPx());
|
|
||||||
variant.setFileSizeBytes(Files.size(outputFile));
|
|
||||||
variant.setIsGenerated(true);
|
|
||||||
variant.setCreatedAt(OffsetDateTime.now());
|
|
||||||
|
|
||||||
pendingVariants.add(new PendingGeneratedVariant(variant, outputFile));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!skippedFormats.isEmpty()) {
|
|
||||||
logger.warn(
|
|
||||||
"Skipping media formats for asset {} because FFmpeg support is unavailable: {}",
|
|
||||||
asset.getId(),
|
|
||||||
String.join(", ", skippedFormats)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
List<String> storedKeys = new ArrayList<>();
|
|
||||||
try {
|
|
||||||
for (PendingGeneratedVariant pendingVariant : pendingVariants) {
|
|
||||||
storeGeneratedVariant(asset.getVisibility(), pendingVariant);
|
|
||||||
storedKeys.add(pendingVariant.variant().getStorageKey());
|
|
||||||
}
|
|
||||||
} catch (IOException e) {
|
|
||||||
cleanupStoredGeneratedVariants(asset.getVisibility(), storedKeys);
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
|
|
||||||
return pendingVariants.stream()
|
|
||||||
.map(PendingGeneratedVariant::variant)
|
|
||||||
.toList();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void storeGeneratedVariant(String visibility, PendingGeneratedVariant pendingVariant) throws IOException {
|
|
||||||
if (VISIBILITY_PUBLIC.equals(visibility)) {
|
|
||||||
mediaStorageService.storePublic(pendingVariant.file(), pendingVariant.variant().getStorageKey());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
mediaStorageService.storePrivate(pendingVariant.file(), pendingVariant.variant().getStorageKey());
|
|
||||||
}
|
|
||||||
|
|
||||||
private void cleanupStoredGeneratedVariants(String visibility, Collection<String> storageKeys) {
|
|
||||||
for (String storageKey : storageKeys) {
|
|
||||||
try {
|
|
||||||
mediaStorageService.deleteGenerated(visibility, storageKey);
|
|
||||||
} catch (IOException cleanupException) {
|
|
||||||
logger.warn("Failed to clean up media variant {}", storageKey, cleanupException);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void moveGeneratedVariants(MediaAsset asset, String requestedVisibility) {
|
|
||||||
List<MediaVariant> variants = mediaVariantRepository.findByMediaAsset_IdOrderByCreatedAtAsc(asset.getId());
|
|
||||||
List<String> movedStorageKeys = new ArrayList<>();
|
|
||||||
try {
|
|
||||||
for (MediaVariant variant : variants) {
|
|
||||||
if (FORMAT_ORIGINAL.equals(variant.getFormat())) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
mediaStorageService.moveGenerated(variant.getStorageKey(), asset.getVisibility(), requestedVisibility);
|
|
||||||
movedStorageKeys.add(variant.getStorageKey());
|
|
||||||
}
|
|
||||||
} catch (IOException e) {
|
|
||||||
reverseMovedVariants(asset.getVisibility(), requestedVisibility, movedStorageKeys);
|
|
||||||
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to move media files.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void reverseMovedVariants(String originalVisibility, String requestedVisibility, List<String> movedStorageKeys) {
|
|
||||||
List<String> reversedOrder = new ArrayList<>(movedStorageKeys);
|
|
||||||
java.util.Collections.reverse(reversedOrder);
|
|
||||||
for (String storageKey : reversedOrder) {
|
|
||||||
try {
|
|
||||||
mediaStorageService.moveGenerated(storageKey, requestedVisibility, originalVisibility);
|
|
||||||
} catch (IOException reverseException) {
|
|
||||||
logger.error("Failed to restore media variant {}", storageKey, reverseException);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void unsetPrimaryForScope(String usageType, String usageKey, UUID ownerId, UUID excludeUsageId) {
|
|
||||||
List<MediaUsage> existingUsages = mediaUsageRepository.findByUsageScope(usageType, usageKey, ownerId);
|
|
||||||
List<MediaUsage> usagesToUpdate = existingUsages.stream()
|
|
||||||
.filter(existing -> excludeUsageId == null || !existing.getId().equals(excludeUsageId))
|
|
||||||
.filter(existing -> Boolean.TRUE.equals(existing.getIsPrimary()))
|
|
||||||
.peek(existing -> existing.setIsPrimary(false))
|
|
||||||
.toList();
|
|
||||||
|
|
||||||
if (!usagesToUpdate.isEmpty()) {
|
|
||||||
mediaUsageRepository.saveAll(usagesToUpdate);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<AdminMediaAssetDto> toAssetDtos(List<MediaAsset> assets) {
|
|
||||||
if (assets == null || assets.isEmpty()) {
|
|
||||||
return List.of();
|
|
||||||
}
|
|
||||||
|
|
||||||
List<UUID> assetIds = assets.stream()
|
|
||||||
.map(MediaAsset::getId)
|
|
||||||
.filter(Objects::nonNull)
|
|
||||||
.toList();
|
|
||||||
|
|
||||||
Map<UUID, List<MediaVariant>> variantsByAssetId = mediaVariantRepository.findByMediaAsset_IdIn(assetIds)
|
|
||||||
.stream()
|
|
||||||
.sorted(this::compareVariants)
|
|
||||||
.collect(Collectors.groupingBy(variant -> variant.getMediaAsset().getId(), LinkedHashMap::new, Collectors.toList()));
|
|
||||||
|
|
||||||
Map<UUID, List<MediaUsage>> usagesByAssetId = mediaUsageRepository.findByMediaAsset_IdIn(assetIds)
|
|
||||||
.stream()
|
|
||||||
.sorted(Comparator
|
|
||||||
.comparing(MediaUsage::getSortOrder, Comparator.nullsLast(Integer::compareTo))
|
|
||||||
.thenComparing(MediaUsage::getCreatedAt, Comparator.nullsLast(OffsetDateTime::compareTo)))
|
|
||||||
.collect(Collectors.groupingBy(usage -> usage.getMediaAsset().getId(), LinkedHashMap::new, Collectors.toList()));
|
|
||||||
|
|
||||||
return assets.stream()
|
|
||||||
.map(asset -> toAssetDto(
|
|
||||||
asset,
|
|
||||||
variantsByAssetId.getOrDefault(asset.getId(), List.of()),
|
|
||||||
usagesByAssetId.getOrDefault(asset.getId(), List.of())
|
|
||||||
))
|
|
||||||
.toList();
|
|
||||||
}
|
|
||||||
|
|
||||||
private AdminMediaAssetDto toAssetDto(MediaAsset asset, List<MediaVariant> variants, List<MediaUsage> usages) {
|
|
||||||
AdminMediaAssetDto dto = new AdminMediaAssetDto();
|
|
||||||
dto.setId(asset.getId());
|
|
||||||
dto.setOriginalFilename(asset.getOriginalFilename());
|
|
||||||
dto.setStorageKey(asset.getStorageKey());
|
|
||||||
dto.setMimeType(asset.getMimeType());
|
|
||||||
dto.setFileSizeBytes(asset.getFileSizeBytes());
|
|
||||||
dto.setSha256Hex(asset.getSha256Hex());
|
|
||||||
dto.setWidthPx(asset.getWidthPx());
|
|
||||||
dto.setHeightPx(asset.getHeightPx());
|
|
||||||
dto.setStatus(asset.getStatus());
|
|
||||||
dto.setVisibility(asset.getVisibility());
|
|
||||||
dto.setTitle(asset.getTitle());
|
|
||||||
dto.setAltText(asset.getAltText());
|
|
||||||
dto.setCreatedAt(asset.getCreatedAt());
|
|
||||||
dto.setUpdatedAt(asset.getUpdatedAt());
|
|
||||||
dto.setVariants(variants.stream().map(variant -> toVariantDto(asset, variant)).toList());
|
|
||||||
dto.setUsages(usages.stream().map(this::toUsageDto).toList());
|
|
||||||
return dto;
|
|
||||||
}
|
|
||||||
|
|
||||||
private AdminMediaVariantDto toVariantDto(MediaAsset asset, MediaVariant variant) {
|
|
||||||
AdminMediaVariantDto dto = new AdminMediaVariantDto();
|
|
||||||
dto.setId(variant.getId());
|
|
||||||
dto.setVariantName(variant.getVariantName());
|
|
||||||
dto.setFormat(variant.getFormat());
|
|
||||||
dto.setStorageKey(variant.getStorageKey());
|
|
||||||
dto.setMimeType(variant.getMimeType());
|
|
||||||
dto.setWidthPx(variant.getWidthPx());
|
|
||||||
dto.setHeightPx(variant.getHeightPx());
|
|
||||||
dto.setFileSizeBytes(variant.getFileSizeBytes());
|
|
||||||
dto.setIsGenerated(variant.getIsGenerated());
|
|
||||||
dto.setCreatedAt(variant.getCreatedAt());
|
|
||||||
if (VISIBILITY_PUBLIC.equals(asset.getVisibility()) && !FORMAT_ORIGINAL.equals(variant.getFormat())) {
|
|
||||||
dto.setPublicUrl(mediaStorageService.buildPublicUrl(variant.getStorageKey()));
|
|
||||||
}
|
|
||||||
return dto;
|
|
||||||
}
|
|
||||||
|
|
||||||
private AdminMediaUsageDto toUsageDto(MediaUsage usage) {
|
|
||||||
AdminMediaUsageDto dto = new AdminMediaUsageDto();
|
|
||||||
dto.setId(usage.getId());
|
|
||||||
dto.setUsageType(usage.getUsageType());
|
|
||||||
dto.setUsageKey(usage.getUsageKey());
|
|
||||||
dto.setOwnerId(usage.getOwnerId());
|
|
||||||
dto.setMediaAssetId(usage.getMediaAsset().getId());
|
|
||||||
dto.setSortOrder(usage.getSortOrder());
|
|
||||||
dto.setIsPrimary(usage.getIsPrimary());
|
|
||||||
dto.setIsActive(usage.getIsActive());
|
|
||||||
dto.setTranslations(extractTranslations(usage));
|
|
||||||
dto.setCreatedAt(usage.getCreatedAt());
|
|
||||||
return dto;
|
|
||||||
}
|
|
||||||
|
|
||||||
private int compareVariants(MediaVariant left, MediaVariant right) {
|
|
||||||
return Comparator
|
|
||||||
.comparingInt((MediaVariant variant) -> variantNameOrder(variant.getVariantName()))
|
|
||||||
.thenComparingInt(variant -> formatOrder(variant.getFormat()))
|
|
||||||
.thenComparing(MediaVariant::getCreatedAt, Comparator.nullsLast(OffsetDateTime::compareTo))
|
|
||||||
.compare(left, right);
|
|
||||||
}
|
|
||||||
|
|
||||||
private int variantNameOrder(String variantName) {
|
|
||||||
if ("original".equalsIgnoreCase(variantName)) {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
if ("thumb".equalsIgnoreCase(variantName)) {
|
|
||||||
return 10;
|
|
||||||
}
|
|
||||||
if ("card".equalsIgnoreCase(variantName)) {
|
|
||||||
return 20;
|
|
||||||
}
|
|
||||||
if ("hero".equalsIgnoreCase(variantName)) {
|
|
||||||
return 30;
|
|
||||||
}
|
|
||||||
return 100;
|
|
||||||
}
|
|
||||||
|
|
||||||
private int formatOrder(String format) {
|
|
||||||
return switch (format) {
|
|
||||||
case FORMAT_ORIGINAL -> 0;
|
|
||||||
case FORMAT_JPEG -> 10;
|
|
||||||
case FORMAT_WEBP -> 20;
|
|
||||||
case FORMAT_AVIF -> 30;
|
|
||||||
default -> 100;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private MediaAsset getAssetOrThrow(UUID mediaAssetId) {
|
|
||||||
if (mediaAssetId == null) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Media asset id is required.");
|
|
||||||
}
|
|
||||||
return mediaAssetRepository.findById(mediaAssetId)
|
|
||||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Media asset not found."));
|
|
||||||
}
|
|
||||||
|
|
||||||
private MediaUsage getUsageOrThrow(UUID mediaUsageId) {
|
|
||||||
return mediaUsageRepository.findById(mediaUsageId)
|
|
||||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Media usage not found."));
|
|
||||||
}
|
|
||||||
|
|
||||||
private void validateUpload(MultipartFile file) {
|
|
||||||
if (file == null || file.isEmpty()) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Image file is required.");
|
|
||||||
}
|
|
||||||
if (file.getSize() < 0 || file.getSize() > maxUploadFileSizeBytes) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Image file exceeds the maximum allowed size.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private String requireUsageType(String usageType) {
|
|
||||||
if (usageType == null || usageType.isBlank()) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "usageType is required.");
|
|
||||||
}
|
|
||||||
return usageType.trim().toUpperCase(Locale.ROOT);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String requireUsageKey(String usageKey) {
|
|
||||||
if (usageKey == null || usageKey.isBlank()) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "usageKey is required.");
|
|
||||||
}
|
|
||||||
return usageKey.trim();
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeVisibility(String visibility, boolean defaultPublic) {
|
|
||||||
if (visibility == null) {
|
|
||||||
return defaultPublic ? VISIBILITY_PUBLIC : null;
|
|
||||||
}
|
|
||||||
String normalized = visibility.trim().toUpperCase(Locale.ROOT);
|
|
||||||
if (normalized.isBlank()) {
|
|
||||||
return defaultPublic ? VISIBILITY_PUBLIC : null;
|
|
||||||
}
|
|
||||||
if (!ALLOWED_VISIBILITIES.contains(normalized)) {
|
|
||||||
throw new ResponseStatusException(
|
|
||||||
HttpStatus.BAD_REQUEST,
|
|
||||||
"Invalid visibility. Allowed: " + String.join(", ", new LinkedHashSet<>(ALLOWED_VISIBILITIES))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return normalized;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeStatus(String status, boolean required) {
|
|
||||||
if (status == null) {
|
|
||||||
if (required) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Status is required.");
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
String normalized = status.trim().toUpperCase(Locale.ROOT);
|
|
||||||
if (normalized.isBlank()) {
|
|
||||||
if (required) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Status is required.");
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
if (!ALLOWED_STATUSES.contains(normalized)) {
|
|
||||||
throw new ResponseStatusException(
|
|
||||||
HttpStatus.BAD_REQUEST,
|
|
||||||
"Invalid status. Allowed: " + String.join(", ", new LinkedHashSet<>(ALLOWED_STATUSES))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return normalized;
|
|
||||||
}
|
|
||||||
|
|
||||||
private Map<String, MediaTextTranslationDto> requireTranslations(Map<String, MediaTextTranslationDto> translations) {
|
|
||||||
if (translations == null || translations.isEmpty()) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "translations are required.");
|
|
||||||
}
|
|
||||||
|
|
||||||
Map<String, MediaTextTranslationDto> normalized = new LinkedHashMap<>();
|
|
||||||
for (Map.Entry<String, MediaTextTranslationDto> entry : translations.entrySet()) {
|
|
||||||
String language = normalizeTranslationLanguage(entry.getKey());
|
|
||||||
if (normalized.containsKey(language)) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Duplicate translation language: " + language + ".");
|
|
||||||
}
|
|
||||||
normalized.put(language, entry.getValue());
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!normalized.keySet().equals(new LinkedHashSet<>(SUPPORTED_MEDIA_LANGUAGES))) {
|
|
||||||
throw new ResponseStatusException(
|
|
||||||
HttpStatus.BAD_REQUEST,
|
|
||||||
"translations must include exactly: " + String.join(", ", SUPPORTED_MEDIA_LANGUAGES) + "."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
LinkedHashMap<String, MediaTextTranslationDto> result = new LinkedHashMap<>();
|
|
||||||
for (String language : SUPPORTED_MEDIA_LANGUAGES) {
|
|
||||||
MediaTextTranslationDto translation = normalized.get(language);
|
|
||||||
if (translation == null) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Missing translation for language " + language + ".");
|
|
||||||
}
|
|
||||||
|
|
||||||
String title = normalizeRequiredTranslationValue(translation.getTitle(), language, "title");
|
|
||||||
String altText = normalizeRequiredTranslationValue(translation.getAltText(), language, "altText");
|
|
||||||
|
|
||||||
MediaTextTranslationDto dto = new MediaTextTranslationDto();
|
|
||||||
dto.setTitle(title);
|
|
||||||
dto.setAltText(altText);
|
|
||||||
result.put(language, dto);
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeTranslationLanguage(String language) {
|
|
||||||
if (language == null || language.isBlank()) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Translation language is required.");
|
|
||||||
}
|
|
||||||
String normalized = language.trim().toLowerCase(Locale.ROOT);
|
|
||||||
if (!SUPPORTED_MEDIA_LANGUAGES.contains(normalized)) {
|
|
||||||
throw new ResponseStatusException(
|
|
||||||
HttpStatus.BAD_REQUEST,
|
|
||||||
"Unsupported translation language: " + normalized + "."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return normalized;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeRequiredTranslationValue(String value, String language, String fieldName) {
|
|
||||||
String normalized = normalizeText(value);
|
|
||||||
if (normalized == null || normalized.isBlank()) {
|
|
||||||
throw new ResponseStatusException(
|
|
||||||
HttpStatus.BAD_REQUEST,
|
|
||||||
"Translation " + fieldName + " is required for language " + language + "."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return normalized;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void applyTranslations(MediaUsage usage, Map<String, MediaTextTranslationDto> translations) {
|
|
||||||
for (String language : SUPPORTED_MEDIA_LANGUAGES) {
|
|
||||||
MediaTextTranslationDto translation = translations.get(language);
|
|
||||||
usage.setTitleForLanguage(language, translation.getTitle());
|
|
||||||
usage.setAltTextForLanguage(language, translation.getAltText());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private Map<String, MediaTextTranslationDto> extractTranslations(MediaUsage usage) {
|
|
||||||
LinkedHashMap<String, MediaTextTranslationDto> translations = new LinkedHashMap<>();
|
|
||||||
String fallbackTitle = usage.getMediaAsset() != null ? usage.getMediaAsset().getTitle() : null;
|
|
||||||
String fallbackAltText = usage.getMediaAsset() != null ? usage.getMediaAsset().getAltText() : null;
|
|
||||||
|
|
||||||
for (String language : SUPPORTED_MEDIA_LANGUAGES) {
|
|
||||||
MediaTextTranslationDto dto = new MediaTextTranslationDto();
|
|
||||||
dto.setTitle(firstNonBlank(usage.getTitleForLanguage(language), fallbackTitle));
|
|
||||||
dto.setAltText(firstNonBlank(usage.getAltTextForLanguage(language), fallbackAltText));
|
|
||||||
translations.put(language, dto);
|
|
||||||
}
|
|
||||||
return translations;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String firstNonBlank(String preferred, String fallback) {
|
|
||||||
return StringUtils.hasText(preferred) ? preferred : normalizeText(fallback);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeText(String value) {
|
|
||||||
if (value == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
String normalized = value.trim();
|
|
||||||
return normalized.isBlank() ? null : normalized;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String sanitizeOriginalFilename(String originalFilename, String extension) {
|
|
||||||
String cleaned = StringUtils.cleanPath(originalFilename == null ? "" : originalFilename);
|
|
||||||
int separatorIndex = Math.max(cleaned.lastIndexOf('/'), cleaned.lastIndexOf('\\'));
|
|
||||||
String basename = separatorIndex >= 0 ? cleaned.substring(separatorIndex + 1) : cleaned;
|
|
||||||
basename = basename.replace("\r", "_").replace("\n", "_");
|
|
||||||
if (basename.isBlank()) {
|
|
||||||
return "upload." + extension;
|
|
||||||
}
|
|
||||||
return basename;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String buildStorageFolder() {
|
|
||||||
return STORAGE_FOLDER_FORMATTER.format(LocalDate.now()) + "/" + UUID.randomUUID();
|
|
||||||
}
|
|
||||||
|
|
||||||
private String extractStorageFolder(String originalStorageKey) {
|
|
||||||
Path path = Paths.get(originalStorageKey).normalize();
|
|
||||||
Path parent = path.getParent();
|
|
||||||
if (parent == null) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Invalid media storage key.");
|
|
||||||
}
|
|
||||||
return parent.toString().replace('\\', '/');
|
|
||||||
}
|
|
||||||
|
|
||||||
private VariantDimensions computeVariantDimensions(Integer widthPx, Integer heightPx, int maxDimension) {
|
|
||||||
if (widthPx == null || heightPx == null || widthPx <= 0 || heightPx <= 0) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Invalid image dimensions.");
|
|
||||||
}
|
|
||||||
double scale = Math.min(1.0d, (double) maxDimension / Math.max(widthPx, heightPx));
|
|
||||||
int targetWidth = Math.max(1, (int) Math.round(widthPx * scale));
|
|
||||||
int targetHeight = Math.max(1, (int) Math.round(heightPx * scale));
|
|
||||||
return new VariantDimensions(targetWidth, targetHeight);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String computeSha256(Path file) throws IOException {
|
|
||||||
MessageDigest digest;
|
|
||||||
try {
|
|
||||||
digest = MessageDigest.getInstance("SHA-256");
|
|
||||||
} catch (NoSuchAlgorithmException e) {
|
|
||||||
throw new IllegalStateException("SHA-256 not available.", e);
|
|
||||||
}
|
|
||||||
|
|
||||||
try (InputStream inputStream = Files.newInputStream(file)) {
|
|
||||||
byte[] buffer = new byte[8192];
|
|
||||||
int read;
|
|
||||||
while ((read = inputStream.read(buffer)) >= 0) {
|
|
||||||
digest.update(buffer, 0, read);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return HexFormat.of().formatHex(digest.digest());
|
|
||||||
}
|
|
||||||
|
|
||||||
private void markFailed(MediaAsset asset, String message, Exception exception) {
|
|
||||||
if (asset == null || asset.getId() == null) {
|
|
||||||
logger.warn("Media upload failed before asset persistence: {}", message, exception);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
asset.setStatus(STATUS_FAILED);
|
|
||||||
asset.setUpdatedAt(OffsetDateTime.now());
|
|
||||||
mediaAssetRepository.save(asset);
|
|
||||||
logger.warn("Media asset {} marked as FAILED: {}", asset.getId(), message, exception);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void deleteRecursively(Path directory) {
|
|
||||||
if (directory == null || !Files.exists(directory)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try (var walk = Files.walk(directory)) {
|
|
||||||
walk.sorted(Comparator.reverseOrder()).forEach(path -> {
|
|
||||||
try {
|
|
||||||
Files.deleteIfExists(path);
|
|
||||||
} catch (IOException e) {
|
|
||||||
throw new UncheckedIOException(e);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} catch (IOException e) {
|
|
||||||
logger.warn("Failed to clean temporary media directory {}", directory, e);
|
|
||||||
} catch (UncheckedIOException e) {
|
|
||||||
logger.warn("Failed to clean temporary media directory {}", directory, e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private record PresetDefinition(String name, int maxDimension) {
|
|
||||||
}
|
|
||||||
|
|
||||||
private record VariantDimensions(int widthPx, int heightPx) {
|
|
||||||
}
|
|
||||||
|
|
||||||
private record PendingGeneratedVariant(MediaVariant variant, Path file) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,471 +0,0 @@
|
|||||||
package com.printcalculator.service.admin;
|
|
||||||
|
|
||||||
import com.printcalculator.dto.AdminCadInvoiceCreateRequest;
|
|
||||||
import com.printcalculator.dto.AdminCadInvoiceDto;
|
|
||||||
import com.printcalculator.dto.AdminContactRequestAttachmentDto;
|
|
||||||
import com.printcalculator.dto.AdminContactRequestDetailDto;
|
|
||||||
import com.printcalculator.dto.AdminContactRequestDto;
|
|
||||||
import com.printcalculator.dto.AdminFilamentStockDto;
|
|
||||||
import com.printcalculator.dto.AdminQuoteSessionDto;
|
|
||||||
import com.printcalculator.dto.AdminUpdateContactRequestStatusRequest;
|
|
||||||
import com.printcalculator.entity.CustomQuoteRequest;
|
|
||||||
import com.printcalculator.entity.CustomQuoteRequestAttachment;
|
|
||||||
import com.printcalculator.entity.FilamentVariant;
|
|
||||||
import com.printcalculator.entity.FilamentVariantStockKg;
|
|
||||||
import com.printcalculator.entity.Order;
|
|
||||||
import com.printcalculator.entity.QuoteLineItem;
|
|
||||||
import com.printcalculator.entity.QuoteSession;
|
|
||||||
import com.printcalculator.repository.CustomQuoteRequestAttachmentRepository;
|
|
||||||
import com.printcalculator.repository.CustomQuoteRequestRepository;
|
|
||||||
import com.printcalculator.repository.FilamentVariantRepository;
|
|
||||||
import com.printcalculator.repository.FilamentVariantStockKgRepository;
|
|
||||||
import com.printcalculator.repository.OrderRepository;
|
|
||||||
import com.printcalculator.repository.PricingPolicyRepository;
|
|
||||||
import com.printcalculator.repository.QuoteLineItemRepository;
|
|
||||||
import com.printcalculator.repository.QuoteSessionRepository;
|
|
||||||
import com.printcalculator.service.QuoteSessionTotalsService;
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
import org.springframework.core.io.Resource;
|
|
||||||
import org.springframework.core.io.UrlResource;
|
|
||||||
import org.springframework.data.domain.Sort;
|
|
||||||
import org.springframework.http.ContentDisposition;
|
|
||||||
import org.springframework.http.HttpHeaders;
|
|
||||||
import org.springframework.http.MediaType;
|
|
||||||
import org.springframework.http.ResponseEntity;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
|
||||||
import org.springframework.web.server.ResponseStatusException;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.UncheckedIOException;
|
|
||||||
import java.math.BigDecimal;
|
|
||||||
import java.math.RoundingMode;
|
|
||||||
import java.net.MalformedURLException;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.nio.file.Paths;
|
|
||||||
import java.time.OffsetDateTime;
|
|
||||||
import java.util.Collections;
|
|
||||||
import java.util.Comparator;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Locale;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.UUID;
|
|
||||||
import java.util.stream.Collectors;
|
|
||||||
import java.util.stream.Stream;
|
|
||||||
|
|
||||||
import static org.springframework.http.HttpStatus.BAD_REQUEST;
|
|
||||||
import static org.springframework.http.HttpStatus.CONFLICT;
|
|
||||||
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
|
|
||||||
import static org.springframework.http.HttpStatus.NOT_FOUND;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public class AdminOperationsControllerService {
|
|
||||||
private static final Logger logger = LoggerFactory.getLogger(AdminOperationsControllerService.class);
|
|
||||||
private static final Path CONTACT_ATTACHMENTS_ROOT = Paths.get("storage_requests").toAbsolutePath().normalize();
|
|
||||||
private static final Set<String> CONTACT_REQUEST_ALLOWED_STATUSES = Set.of(
|
|
||||||
"NEW", "PENDING", "IN_PROGRESS", "DONE", "CLOSED"
|
|
||||||
);
|
|
||||||
|
|
||||||
private final FilamentVariantStockKgRepository filamentStockRepo;
|
|
||||||
private final FilamentVariantRepository filamentVariantRepo;
|
|
||||||
private final CustomQuoteRequestRepository customQuoteRequestRepo;
|
|
||||||
private final CustomQuoteRequestAttachmentRepository customQuoteRequestAttachmentRepo;
|
|
||||||
private final QuoteSessionRepository quoteSessionRepo;
|
|
||||||
private final QuoteLineItemRepository quoteLineItemRepo;
|
|
||||||
private final OrderRepository orderRepo;
|
|
||||||
private final PricingPolicyRepository pricingRepo;
|
|
||||||
private final QuoteSessionTotalsService quoteSessionTotalsService;
|
|
||||||
|
|
||||||
public AdminOperationsControllerService(FilamentVariantStockKgRepository filamentStockRepo,
|
|
||||||
FilamentVariantRepository filamentVariantRepo,
|
|
||||||
CustomQuoteRequestRepository customQuoteRequestRepo,
|
|
||||||
CustomQuoteRequestAttachmentRepository customQuoteRequestAttachmentRepo,
|
|
||||||
QuoteSessionRepository quoteSessionRepo,
|
|
||||||
QuoteLineItemRepository quoteLineItemRepo,
|
|
||||||
OrderRepository orderRepo,
|
|
||||||
PricingPolicyRepository pricingRepo,
|
|
||||||
QuoteSessionTotalsService quoteSessionTotalsService) {
|
|
||||||
this.filamentStockRepo = filamentStockRepo;
|
|
||||||
this.filamentVariantRepo = filamentVariantRepo;
|
|
||||||
this.customQuoteRequestRepo = customQuoteRequestRepo;
|
|
||||||
this.customQuoteRequestAttachmentRepo = customQuoteRequestAttachmentRepo;
|
|
||||||
this.quoteSessionRepo = quoteSessionRepo;
|
|
||||||
this.quoteLineItemRepo = quoteLineItemRepo;
|
|
||||||
this.orderRepo = orderRepo;
|
|
||||||
this.pricingRepo = pricingRepo;
|
|
||||||
this.quoteSessionTotalsService = quoteSessionTotalsService;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<AdminFilamentStockDto> getFilamentStock() {
|
|
||||||
List<FilamentVariantStockKg> stocks = filamentStockRepo.findAll(Sort.by(Sort.Direction.ASC, "stockKg"));
|
|
||||||
Set<Long> variantIds = stocks.stream()
|
|
||||||
.map(FilamentVariantStockKg::getFilamentVariantId)
|
|
||||||
.collect(Collectors.toSet());
|
|
||||||
|
|
||||||
Map<Long, FilamentVariant> variantsById;
|
|
||||||
if (variantIds.isEmpty()) {
|
|
||||||
variantsById = Collections.emptyMap();
|
|
||||||
} else {
|
|
||||||
variantsById = filamentVariantRepo.findAllById(variantIds).stream()
|
|
||||||
.collect(Collectors.toMap(FilamentVariant::getId, variant -> variant));
|
|
||||||
}
|
|
||||||
|
|
||||||
return stocks.stream().map(stock -> {
|
|
||||||
FilamentVariant variant = variantsById.get(stock.getFilamentVariantId());
|
|
||||||
AdminFilamentStockDto dto = new AdminFilamentStockDto();
|
|
||||||
dto.setFilamentVariantId(stock.getFilamentVariantId());
|
|
||||||
dto.setStockSpools(stock.getStockSpools());
|
|
||||||
dto.setSpoolNetKg(stock.getSpoolNetKg());
|
|
||||||
dto.setStockKg(stock.getStockKg());
|
|
||||||
BigDecimal grams = stock.getStockKg() != null
|
|
||||||
? stock.getStockKg().multiply(BigDecimal.valueOf(1000))
|
|
||||||
: BigDecimal.ZERO;
|
|
||||||
dto.setStockFilamentGrams(grams);
|
|
||||||
|
|
||||||
if (variant != null) {
|
|
||||||
dto.setMaterialCode(
|
|
||||||
variant.getFilamentMaterialType() != null
|
|
||||||
? variant.getFilamentMaterialType().getMaterialCode()
|
|
||||||
: "UNKNOWN"
|
|
||||||
);
|
|
||||||
dto.setVariantDisplayName(variant.getVariantDisplayName());
|
|
||||||
dto.setColorName(variant.getColorName());
|
|
||||||
dto.setActive(variant.getIsActive());
|
|
||||||
} else {
|
|
||||||
dto.setMaterialCode("UNKNOWN");
|
|
||||||
dto.setVariantDisplayName("Variant " + stock.getFilamentVariantId());
|
|
||||||
dto.setColorName("-");
|
|
||||||
dto.setActive(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
return dto;
|
|
||||||
}).toList();
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<AdminContactRequestDto> getContactRequests() {
|
|
||||||
return customQuoteRequestRepo.findAll(Sort.by(Sort.Direction.DESC, "createdAt"))
|
|
||||||
.stream()
|
|
||||||
.map(this::toContactRequestDto)
|
|
||||||
.toList();
|
|
||||||
}
|
|
||||||
|
|
||||||
public AdminContactRequestDetailDto getContactRequestDetail(UUID requestId) {
|
|
||||||
CustomQuoteRequest request = customQuoteRequestRepo.findById(requestId)
|
|
||||||
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "Contact request not found"));
|
|
||||||
|
|
||||||
List<AdminContactRequestAttachmentDto> attachments = customQuoteRequestAttachmentRepo
|
|
||||||
.findByRequest_IdOrderByCreatedAtAsc(requestId)
|
|
||||||
.stream()
|
|
||||||
.map(this::toContactRequestAttachmentDto)
|
|
||||||
.toList();
|
|
||||||
|
|
||||||
return toContactRequestDetailDto(request, attachments);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public AdminContactRequestDetailDto updateContactRequestStatus(UUID requestId,
|
|
||||||
AdminUpdateContactRequestStatusRequest payload) {
|
|
||||||
CustomQuoteRequest request = customQuoteRequestRepo.findById(requestId)
|
|
||||||
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "Contact request not found"));
|
|
||||||
|
|
||||||
String requestedStatus = payload != null && payload.getStatus() != null
|
|
||||||
? payload.getStatus().trim().toUpperCase(Locale.ROOT)
|
|
||||||
: "";
|
|
||||||
|
|
||||||
if (!CONTACT_REQUEST_ALLOWED_STATUSES.contains(requestedStatus)) {
|
|
||||||
throw new ResponseStatusException(
|
|
||||||
BAD_REQUEST,
|
|
||||||
"Invalid status. Allowed: " + String.join(", ", CONTACT_REQUEST_ALLOWED_STATUSES)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
request.setStatus(requestedStatus);
|
|
||||||
request.setUpdatedAt(OffsetDateTime.now());
|
|
||||||
CustomQuoteRequest saved = customQuoteRequestRepo.save(request);
|
|
||||||
|
|
||||||
List<AdminContactRequestAttachmentDto> attachments = customQuoteRequestAttachmentRepo
|
|
||||||
.findByRequest_IdOrderByCreatedAtAsc(requestId)
|
|
||||||
.stream()
|
|
||||||
.map(this::toContactRequestAttachmentDto)
|
|
||||||
.toList();
|
|
||||||
|
|
||||||
return toContactRequestDetailDto(saved, attachments);
|
|
||||||
}
|
|
||||||
|
|
||||||
public ResponseEntity<Resource> downloadContactRequestAttachment(UUID requestId, UUID attachmentId) {
|
|
||||||
CustomQuoteRequestAttachment attachment = customQuoteRequestAttachmentRepo.findById(attachmentId)
|
|
||||||
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "Attachment not found"));
|
|
||||||
|
|
||||||
if (!attachment.getRequest().getId().equals(requestId)) {
|
|
||||||
throw new ResponseStatusException(NOT_FOUND, "Attachment not found for request");
|
|
||||||
}
|
|
||||||
|
|
||||||
String relativePath = attachment.getStoredRelativePath();
|
|
||||||
if (relativePath == null || relativePath.isBlank() || "PENDING".equals(relativePath)) {
|
|
||||||
throw new ResponseStatusException(NOT_FOUND, "Attachment file not available");
|
|
||||||
}
|
|
||||||
|
|
||||||
String expectedPrefix = "quote-requests/" + requestId + "/attachments/" + attachmentId + "/";
|
|
||||||
if (!relativePath.startsWith(expectedPrefix)) {
|
|
||||||
throw new ResponseStatusException(NOT_FOUND, "Attachment file not available");
|
|
||||||
}
|
|
||||||
|
|
||||||
Path filePath = CONTACT_ATTACHMENTS_ROOT.resolve(relativePath).normalize();
|
|
||||||
if (!filePath.startsWith(CONTACT_ATTACHMENTS_ROOT)) {
|
|
||||||
throw new ResponseStatusException(NOT_FOUND, "Attachment file not available");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!Files.exists(filePath)) {
|
|
||||||
throw new ResponseStatusException(NOT_FOUND, "Attachment file not available");
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
Resource resource = new UrlResource(filePath.toUri());
|
|
||||||
if (!resource.exists() || !resource.isReadable()) {
|
|
||||||
throw new ResponseStatusException(NOT_FOUND, "Attachment file not available");
|
|
||||||
}
|
|
||||||
|
|
||||||
MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM;
|
|
||||||
String mimeType = attachment.getMimeType();
|
|
||||||
if (mimeType != null && !mimeType.isBlank()) {
|
|
||||||
try {
|
|
||||||
mediaType = MediaType.parseMediaType(mimeType);
|
|
||||||
} catch (Exception ignored) {
|
|
||||||
mediaType = MediaType.APPLICATION_OCTET_STREAM;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
String filename = attachment.getOriginalFilename();
|
|
||||||
if (filename == null || filename.isBlank()) {
|
|
||||||
filename = attachment.getStoredFilename() != null && !attachment.getStoredFilename().isBlank()
|
|
||||||
? attachment.getStoredFilename()
|
|
||||||
: "attachment-" + attachmentId;
|
|
||||||
}
|
|
||||||
|
|
||||||
return ResponseEntity.ok()
|
|
||||||
.contentType(mediaType)
|
|
||||||
.header(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.attachment()
|
|
||||||
.filename(filename, StandardCharsets.UTF_8)
|
|
||||||
.build()
|
|
||||||
.toString())
|
|
||||||
.body(resource);
|
|
||||||
} catch (MalformedURLException e) {
|
|
||||||
throw new ResponseStatusException(NOT_FOUND, "Attachment file not available");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<AdminQuoteSessionDto> getQuoteSessions() {
|
|
||||||
return quoteSessionRepo.findAll(Sort.by(Sort.Direction.DESC, "createdAt"))
|
|
||||||
.stream()
|
|
||||||
.map(this::toQuoteSessionDto)
|
|
||||||
.toList();
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<AdminCadInvoiceDto> getCadInvoices() {
|
|
||||||
return quoteSessionRepo.findByStatusInOrderByCreatedAtDesc(List.of("CAD_ACTIVE", "CONVERTED"))
|
|
||||||
.stream()
|
|
||||||
.filter(this::isCadSessionRecord)
|
|
||||||
.map(this::toCadInvoiceDto)
|
|
||||||
.toList();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public AdminCadInvoiceDto createOrUpdateCadInvoice(AdminCadInvoiceCreateRequest payload) {
|
|
||||||
if (payload == null || payload.getCadHours() == null) {
|
|
||||||
throw new ResponseStatusException(BAD_REQUEST, "cadHours is required");
|
|
||||||
}
|
|
||||||
|
|
||||||
BigDecimal cadHours = payload.getCadHours().setScale(2, RoundingMode.HALF_UP);
|
|
||||||
if (cadHours.compareTo(BigDecimal.ZERO) <= 0) {
|
|
||||||
throw new ResponseStatusException(BAD_REQUEST, "cadHours must be > 0");
|
|
||||||
}
|
|
||||||
|
|
||||||
BigDecimal cadRate = payload.getCadHourlyRateChf();
|
|
||||||
if (cadRate == null || cadRate.compareTo(BigDecimal.ZERO) <= 0) {
|
|
||||||
var policy = pricingRepo.findFirstByIsActiveTrueOrderByValidFromDesc();
|
|
||||||
cadRate = policy != null && policy.getCadCostChfPerHour() != null
|
|
||||||
? policy.getCadCostChfPerHour()
|
|
||||||
: BigDecimal.ZERO;
|
|
||||||
}
|
|
||||||
cadRate = cadRate.setScale(2, RoundingMode.HALF_UP);
|
|
||||||
|
|
||||||
QuoteSession session;
|
|
||||||
if (payload.getSessionId() != null) {
|
|
||||||
session = quoteSessionRepo.findById(payload.getSessionId())
|
|
||||||
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "Session not found"));
|
|
||||||
} else {
|
|
||||||
session = new QuoteSession();
|
|
||||||
session.setStatus("CAD_ACTIVE");
|
|
||||||
session.setSessionType("PRINT_QUOTE");
|
|
||||||
session.setPricingVersion("v1");
|
|
||||||
session.setMaterialCode("PLA");
|
|
||||||
session.setNozzleDiameterMm(BigDecimal.valueOf(0.4));
|
|
||||||
session.setLayerHeightMm(BigDecimal.valueOf(0.2));
|
|
||||||
session.setInfillPattern("grid");
|
|
||||||
session.setInfillPercent(20);
|
|
||||||
session.setSupportsEnabled(false);
|
|
||||||
session.setSetupCostChf(BigDecimal.ZERO);
|
|
||||||
session.setCreatedAt(OffsetDateTime.now());
|
|
||||||
session.setExpiresAt(OffsetDateTime.now().plusDays(30));
|
|
||||||
}
|
|
||||||
|
|
||||||
if ("CONVERTED".equals(session.getStatus())) {
|
|
||||||
throw new ResponseStatusException(CONFLICT, "Session already converted to order");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (payload.getSourceRequestId() != null) {
|
|
||||||
if (!customQuoteRequestRepo.existsById(payload.getSourceRequestId())) {
|
|
||||||
throw new ResponseStatusException(NOT_FOUND, "Source request not found");
|
|
||||||
}
|
|
||||||
session.setSourceRequestId(payload.getSourceRequestId());
|
|
||||||
} else {
|
|
||||||
session.setSourceRequestId(null);
|
|
||||||
}
|
|
||||||
|
|
||||||
session.setStatus("CAD_ACTIVE");
|
|
||||||
session.setCadHours(cadHours);
|
|
||||||
session.setCadHourlyRateChf(cadRate);
|
|
||||||
if (payload.getNotes() != null) {
|
|
||||||
String trimmedNotes = payload.getNotes().trim();
|
|
||||||
session.setNotes(trimmedNotes.isEmpty() ? null : trimmedNotes);
|
|
||||||
}
|
|
||||||
|
|
||||||
QuoteSession saved = quoteSessionRepo.save(session);
|
|
||||||
return toCadInvoiceDto(saved);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public void deleteQuoteSession(UUID sessionId) {
|
|
||||||
QuoteSession session = quoteSessionRepo.findById(sessionId)
|
|
||||||
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "Session not found"));
|
|
||||||
|
|
||||||
if (orderRepo.existsBySourceQuoteSession_Id(sessionId)) {
|
|
||||||
throw new ResponseStatusException(CONFLICT, "Cannot delete session already linked to an order");
|
|
||||||
}
|
|
||||||
|
|
||||||
deleteSessionFiles(sessionId);
|
|
||||||
quoteSessionRepo.delete(session);
|
|
||||||
}
|
|
||||||
|
|
||||||
private AdminContactRequestDto toContactRequestDto(CustomQuoteRequest request) {
|
|
||||||
AdminContactRequestDto dto = new AdminContactRequestDto();
|
|
||||||
dto.setId(request.getId());
|
|
||||||
dto.setRequestType(request.getRequestType());
|
|
||||||
dto.setCustomerType(request.getCustomerType());
|
|
||||||
dto.setEmail(request.getEmail());
|
|
||||||
dto.setPhone(request.getPhone());
|
|
||||||
dto.setName(request.getName());
|
|
||||||
dto.setCompanyName(request.getCompanyName());
|
|
||||||
dto.setStatus(request.getStatus());
|
|
||||||
dto.setCreatedAt(request.getCreatedAt());
|
|
||||||
return dto;
|
|
||||||
}
|
|
||||||
|
|
||||||
private AdminContactRequestAttachmentDto toContactRequestAttachmentDto(CustomQuoteRequestAttachment attachment) {
|
|
||||||
AdminContactRequestAttachmentDto dto = new AdminContactRequestAttachmentDto();
|
|
||||||
dto.setId(attachment.getId());
|
|
||||||
dto.setOriginalFilename(attachment.getOriginalFilename());
|
|
||||||
dto.setMimeType(attachment.getMimeType());
|
|
||||||
dto.setFileSizeBytes(attachment.getFileSizeBytes());
|
|
||||||
dto.setCreatedAt(attachment.getCreatedAt());
|
|
||||||
return dto;
|
|
||||||
}
|
|
||||||
|
|
||||||
private AdminContactRequestDetailDto toContactRequestDetailDto(CustomQuoteRequest request,
|
|
||||||
List<AdminContactRequestAttachmentDto> attachments) {
|
|
||||||
AdminContactRequestDetailDto dto = new AdminContactRequestDetailDto();
|
|
||||||
dto.setId(request.getId());
|
|
||||||
dto.setRequestType(request.getRequestType());
|
|
||||||
dto.setCustomerType(request.getCustomerType());
|
|
||||||
dto.setEmail(request.getEmail());
|
|
||||||
dto.setPhone(request.getPhone());
|
|
||||||
dto.setName(request.getName());
|
|
||||||
dto.setCompanyName(request.getCompanyName());
|
|
||||||
dto.setContactPerson(request.getContactPerson());
|
|
||||||
dto.setMessage(request.getMessage());
|
|
||||||
dto.setStatus(request.getStatus());
|
|
||||||
dto.setCreatedAt(request.getCreatedAt());
|
|
||||||
dto.setUpdatedAt(request.getUpdatedAt());
|
|
||||||
dto.setAttachments(attachments);
|
|
||||||
return dto;
|
|
||||||
}
|
|
||||||
|
|
||||||
private AdminQuoteSessionDto toQuoteSessionDto(QuoteSession session) {
|
|
||||||
AdminQuoteSessionDto dto = new AdminQuoteSessionDto();
|
|
||||||
dto.setId(session.getId());
|
|
||||||
dto.setStatus(session.getStatus());
|
|
||||||
dto.setSessionType(session.getSessionType() != null ? session.getSessionType() : "PRINT_QUOTE");
|
|
||||||
dto.setMaterialCode(session.getMaterialCode());
|
|
||||||
dto.setCreatedAt(session.getCreatedAt());
|
|
||||||
dto.setExpiresAt(session.getExpiresAt());
|
|
||||||
dto.setConvertedOrderId(session.getConvertedOrderId());
|
|
||||||
dto.setSourceRequestId(session.getSourceRequestId());
|
|
||||||
dto.setCadHours(session.getCadHours());
|
|
||||||
dto.setCadHourlyRateChf(session.getCadHourlyRateChf());
|
|
||||||
dto.setCadTotalChf(quoteSessionTotalsService.calculateCadTotal(session));
|
|
||||||
return dto;
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean isCadSessionRecord(QuoteSession session) {
|
|
||||||
if ("CAD_ACTIVE".equals(session.getStatus())) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (!"CONVERTED".equals(session.getStatus())) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
BigDecimal cadHours = session.getCadHours() != null ? session.getCadHours() : BigDecimal.ZERO;
|
|
||||||
return cadHours.compareTo(BigDecimal.ZERO) > 0 || session.getSourceRequestId() != null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private AdminCadInvoiceDto toCadInvoiceDto(QuoteSession session) {
|
|
||||||
List<QuoteLineItem> items = quoteLineItemRepo.findByQuoteSessionId(session.getId());
|
|
||||||
QuoteSessionTotalsService.QuoteSessionTotals totals = quoteSessionTotalsService.compute(session, items);
|
|
||||||
|
|
||||||
AdminCadInvoiceDto dto = new AdminCadInvoiceDto();
|
|
||||||
dto.setSessionId(session.getId());
|
|
||||||
dto.setSessionStatus(session.getStatus());
|
|
||||||
dto.setSourceRequestId(session.getSourceRequestId());
|
|
||||||
dto.setCadHours(session.getCadHours() != null ? session.getCadHours() : BigDecimal.ZERO);
|
|
||||||
dto.setCadHourlyRateChf(session.getCadHourlyRateChf() != null ? session.getCadHourlyRateChf() : BigDecimal.ZERO);
|
|
||||||
dto.setCadTotalChf(totals.cadTotalChf());
|
|
||||||
dto.setPrintItemsTotalChf(totals.printItemsTotalChf());
|
|
||||||
dto.setSetupCostChf(totals.setupCostChf());
|
|
||||||
dto.setShippingCostChf(totals.shippingCostChf());
|
|
||||||
dto.setGrandTotalChf(totals.grandTotalChf());
|
|
||||||
dto.setConvertedOrderId(session.getConvertedOrderId());
|
|
||||||
dto.setCheckoutPath("/checkout/cad?session=" + session.getId());
|
|
||||||
dto.setNotes(session.getNotes());
|
|
||||||
dto.setCreatedAt(session.getCreatedAt());
|
|
||||||
|
|
||||||
if (session.getConvertedOrderId() != null) {
|
|
||||||
Order order = orderRepo.findById(session.getConvertedOrderId()).orElse(null);
|
|
||||||
dto.setConvertedOrderStatus(order != null ? order.getStatus() : null);
|
|
||||||
}
|
|
||||||
return dto;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void deleteSessionFiles(UUID sessionId) {
|
|
||||||
Path sessionDir = Paths.get("storage_quotes", sessionId.toString());
|
|
||||||
if (!Files.exists(sessionDir)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try (Stream<Path> walk = Files.walk(sessionDir)) {
|
|
||||||
walk.sorted(Comparator.reverseOrder()).forEach(path -> {
|
|
||||||
try {
|
|
||||||
Files.deleteIfExists(path);
|
|
||||||
} catch (IOException e) {
|
|
||||||
throw new UncheckedIOException(e);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} catch (IOException | UncheckedIOException e) {
|
|
||||||
logger.error("Failed to delete files for session {}", sessionId, e);
|
|
||||||
throw new ResponseStatusException(INTERNAL_SERVER_ERROR, "Unable to delete session files");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,467 +0,0 @@
|
|||||||
package com.printcalculator.service.admin;
|
|
||||||
|
|
||||||
import com.printcalculator.dto.AdminShopCategoryDto;
|
|
||||||
import com.printcalculator.dto.AdminShopCategoryRefDto;
|
|
||||||
import com.printcalculator.dto.AdminUpsertShopCategoryRequest;
|
|
||||||
import com.printcalculator.entity.ShopCategory;
|
|
||||||
import com.printcalculator.entity.ShopProduct;
|
|
||||||
import com.printcalculator.repository.ShopCategoryRepository;
|
|
||||||
import com.printcalculator.repository.ShopProductRepository;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
|
||||||
import org.springframework.web.server.ResponseStatusException;
|
|
||||||
|
|
||||||
import java.text.Normalizer;
|
|
||||||
import java.time.OffsetDateTime;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.Comparator;
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Locale;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.UUID;
|
|
||||||
import java.util.regex.Pattern;
|
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
import static org.springframework.http.HttpStatus.BAD_REQUEST;
|
|
||||||
import static org.springframework.http.HttpStatus.CONFLICT;
|
|
||||||
import static org.springframework.http.HttpStatus.NOT_FOUND;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public class AdminShopCategoryControllerService {
|
|
||||||
private static final String SHOP_CATEGORY_MEDIA_USAGE_TYPE = "SHOP_CATEGORY";
|
|
||||||
private static final Pattern DIACRITICS_PATTERN = Pattern.compile("\\p{M}+");
|
|
||||||
private static final Pattern NON_ALPHANUMERIC_PATTERN = Pattern.compile("[^a-z0-9]+");
|
|
||||||
private static final Pattern EDGE_DASH_PATTERN = Pattern.compile("(^-+|-+$)");
|
|
||||||
|
|
||||||
private final ShopCategoryRepository shopCategoryRepository;
|
|
||||||
private final ShopProductRepository shopProductRepository;
|
|
||||||
|
|
||||||
public AdminShopCategoryControllerService(ShopCategoryRepository shopCategoryRepository,
|
|
||||||
ShopProductRepository shopProductRepository) {
|
|
||||||
this.shopCategoryRepository = shopCategoryRepository;
|
|
||||||
this.shopProductRepository = shopProductRepository;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<AdminShopCategoryDto> getCategories() {
|
|
||||||
CategoryContext context = buildContext();
|
|
||||||
List<AdminShopCategoryDto> result = new ArrayList<>();
|
|
||||||
appendFlatCategories(null, 0, context, result);
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<AdminShopCategoryDto> getCategoryTree() {
|
|
||||||
return buildCategoryTree(null, 0, buildContext());
|
|
||||||
}
|
|
||||||
|
|
||||||
public AdminShopCategoryDto getCategory(UUID categoryId) {
|
|
||||||
CategoryContext context = buildContext();
|
|
||||||
ShopCategory category = context.categoriesById().get(categoryId);
|
|
||||||
if (category == null) {
|
|
||||||
throw new ResponseStatusException(NOT_FOUND, "Shop category not found");
|
|
||||||
}
|
|
||||||
return toDto(category, resolveDepth(category), context, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public AdminShopCategoryDto createCategory(AdminUpsertShopCategoryRequest payload) {
|
|
||||||
ensurePayload(payload);
|
|
||||||
LocalizedCategoryContent localizedContent = normalizeLocalizedCategoryContent(payload);
|
|
||||||
String normalizedSlug = normalizeAndValidateSlug(payload.getSlug(), localizedContent.defaultName());
|
|
||||||
ensureSlugAvailable(normalizedSlug, null);
|
|
||||||
|
|
||||||
ShopCategory category = new ShopCategory();
|
|
||||||
category.setCreatedAt(OffsetDateTime.now());
|
|
||||||
applyPayload(category, payload, localizedContent, normalizedSlug, null);
|
|
||||||
|
|
||||||
ShopCategory saved = shopCategoryRepository.save(category);
|
|
||||||
return getCategory(saved.getId());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public AdminShopCategoryDto updateCategory(UUID categoryId, AdminUpsertShopCategoryRequest payload) {
|
|
||||||
ensurePayload(payload);
|
|
||||||
|
|
||||||
ShopCategory category = shopCategoryRepository.findById(categoryId)
|
|
||||||
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "Shop category not found"));
|
|
||||||
|
|
||||||
LocalizedCategoryContent localizedContent = normalizeLocalizedCategoryContent(payload);
|
|
||||||
String normalizedSlug = normalizeAndValidateSlug(payload.getSlug(), localizedContent.defaultName());
|
|
||||||
ensureSlugAvailable(normalizedSlug, category.getId());
|
|
||||||
|
|
||||||
applyPayload(category, payload, localizedContent, normalizedSlug, category.getId());
|
|
||||||
ShopCategory saved = shopCategoryRepository.save(category);
|
|
||||||
return getCategory(saved.getId());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public void deleteCategory(UUID categoryId) {
|
|
||||||
ShopCategory category = shopCategoryRepository.findById(categoryId)
|
|
||||||
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "Shop category not found"));
|
|
||||||
|
|
||||||
if (shopCategoryRepository.existsByParentCategory_Id(categoryId)) {
|
|
||||||
throw new ResponseStatusException(CONFLICT, "Category has child categories and cannot be deleted");
|
|
||||||
}
|
|
||||||
if (shopProductRepository.existsByCategory_Id(categoryId)) {
|
|
||||||
throw new ResponseStatusException(CONFLICT, "Category has products and cannot be deleted");
|
|
||||||
}
|
|
||||||
|
|
||||||
shopCategoryRepository.delete(category);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void applyPayload(ShopCategory category,
|
|
||||||
AdminUpsertShopCategoryRequest payload,
|
|
||||||
LocalizedCategoryContent localizedContent,
|
|
||||||
String normalizedSlug,
|
|
||||||
UUID currentCategoryId) {
|
|
||||||
ShopCategory parentCategory = resolveParentCategory(payload.getParentCategoryId(), currentCategoryId);
|
|
||||||
|
|
||||||
category.setParentCategory(parentCategory);
|
|
||||||
category.setSlug(normalizedSlug);
|
|
||||||
category.setName(localizedContent.defaultName());
|
|
||||||
category.setNameIt(localizedContent.names().get("it"));
|
|
||||||
category.setNameEn(localizedContent.names().get("en"));
|
|
||||||
category.setNameDe(localizedContent.names().get("de"));
|
|
||||||
category.setNameFr(localizedContent.names().get("fr"));
|
|
||||||
category.setDescription(localizedContent.defaultDescription());
|
|
||||||
category.setDescriptionIt(localizedContent.descriptions().get("it"));
|
|
||||||
category.setDescriptionEn(localizedContent.descriptions().get("en"));
|
|
||||||
category.setDescriptionDe(localizedContent.descriptions().get("de"));
|
|
||||||
category.setDescriptionFr(localizedContent.descriptions().get("fr"));
|
|
||||||
category.setSeoTitle(localizedContent.defaultSeoTitle());
|
|
||||||
category.setSeoTitleIt(localizedContent.seoTitles().get("it"));
|
|
||||||
category.setSeoTitleEn(localizedContent.seoTitles().get("en"));
|
|
||||||
category.setSeoTitleDe(localizedContent.seoTitles().get("de"));
|
|
||||||
category.setSeoTitleFr(localizedContent.seoTitles().get("fr"));
|
|
||||||
category.setSeoDescription(localizedContent.defaultSeoDescription());
|
|
||||||
category.setSeoDescriptionIt(localizedContent.seoDescriptions().get("it"));
|
|
||||||
category.setSeoDescriptionEn(localizedContent.seoDescriptions().get("en"));
|
|
||||||
category.setSeoDescriptionDe(localizedContent.seoDescriptions().get("de"));
|
|
||||||
category.setSeoDescriptionFr(localizedContent.seoDescriptions().get("fr"));
|
|
||||||
category.setOgTitle(normalizeOptional(payload.getOgTitle()));
|
|
||||||
category.setOgDescription(normalizeOptional(payload.getOgDescription()));
|
|
||||||
category.setIndexable(payload.getIndexable() == null || payload.getIndexable());
|
|
||||||
category.setIsActive(payload.getIsActive() == null || payload.getIsActive());
|
|
||||||
category.setSortOrder(payload.getSortOrder() != null ? payload.getSortOrder() : 0);
|
|
||||||
category.setUpdatedAt(OffsetDateTime.now());
|
|
||||||
}
|
|
||||||
|
|
||||||
private ShopCategory resolveParentCategory(UUID parentCategoryId, UUID currentCategoryId) {
|
|
||||||
if (parentCategoryId == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
if (currentCategoryId != null && currentCategoryId.equals(parentCategoryId)) {
|
|
||||||
throw new ResponseStatusException(BAD_REQUEST, "Category cannot be its own parent");
|
|
||||||
}
|
|
||||||
|
|
||||||
ShopCategory parentCategory = shopCategoryRepository.findById(parentCategoryId)
|
|
||||||
.orElseThrow(() -> new ResponseStatusException(BAD_REQUEST, "Parent category not found"));
|
|
||||||
|
|
||||||
if (currentCategoryId != null) {
|
|
||||||
ShopCategory ancestor = parentCategory;
|
|
||||||
while (ancestor != null) {
|
|
||||||
if (currentCategoryId.equals(ancestor.getId())) {
|
|
||||||
throw new ResponseStatusException(BAD_REQUEST, "Category hierarchy would create a cycle");
|
|
||||||
}
|
|
||||||
ancestor = ancestor.getParentCategory();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return parentCategory;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void ensurePayload(AdminUpsertShopCategoryRequest payload) {
|
|
||||||
if (payload == null) {
|
|
||||||
throw new ResponseStatusException(BAD_REQUEST, "Payload is required");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeAndValidateSlug(String slug, String fallbackName) {
|
|
||||||
String source = normalizeOptional(slug);
|
|
||||||
if (source == null) {
|
|
||||||
source = fallbackName;
|
|
||||||
}
|
|
||||||
|
|
||||||
String normalized = Normalizer.normalize(source, Normalizer.Form.NFD);
|
|
||||||
normalized = DIACRITICS_PATTERN.matcher(normalized).replaceAll("");
|
|
||||||
normalized = normalized.toLowerCase(Locale.ROOT);
|
|
||||||
normalized = NON_ALPHANUMERIC_PATTERN.matcher(normalized).replaceAll("-");
|
|
||||||
normalized = EDGE_DASH_PATTERN.matcher(normalized).replaceAll("");
|
|
||||||
|
|
||||||
if (normalized.isBlank()) {
|
|
||||||
throw new ResponseStatusException(BAD_REQUEST, "Slug is invalid");
|
|
||||||
}
|
|
||||||
return normalized;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void ensureSlugAvailable(String slug, UUID currentCategoryId) {
|
|
||||||
shopCategoryRepository.findBySlugIgnoreCase(slug).ifPresent(existing -> {
|
|
||||||
if (currentCategoryId == null || !existing.getId().equals(currentCategoryId)) {
|
|
||||||
throw new ResponseStatusException(BAD_REQUEST, "Category slug already exists");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeOptional(String value) {
|
|
||||||
if (value == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
String normalized = value.trim();
|
|
||||||
return normalized.isBlank() ? null : normalized;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeRequired(String value, String message) {
|
|
||||||
String normalized = normalizeOptional(value);
|
|
||||||
if (normalized == null) {
|
|
||||||
throw new ResponseStatusException(BAD_REQUEST, message);
|
|
||||||
}
|
|
||||||
return normalized;
|
|
||||||
}
|
|
||||||
|
|
||||||
private LocalizedCategoryContent normalizeLocalizedCategoryContent(AdminUpsertShopCategoryRequest payload) {
|
|
||||||
String legacyName = normalizeOptional(payload.getName());
|
|
||||||
String fallbackName = firstNonBlank(
|
|
||||||
legacyName,
|
|
||||||
normalizeOptional(payload.getNameIt()),
|
|
||||||
normalizeOptional(payload.getNameEn()),
|
|
||||||
normalizeOptional(payload.getNameDe()),
|
|
||||||
normalizeOptional(payload.getNameFr())
|
|
||||||
);
|
|
||||||
if (fallbackName == null) {
|
|
||||||
throw new ResponseStatusException(BAD_REQUEST, "Category name is required");
|
|
||||||
}
|
|
||||||
|
|
||||||
Map<String, String> names = new LinkedHashMap<>();
|
|
||||||
names.put("it", normalizeRequired(firstNonBlank(normalizeOptional(payload.getNameIt()), fallbackName), "Italian category name is required"));
|
|
||||||
names.put("en", normalizeRequired(firstNonBlank(normalizeOptional(payload.getNameEn()), fallbackName), "English category name is required"));
|
|
||||||
names.put("de", normalizeRequired(firstNonBlank(normalizeOptional(payload.getNameDe()), fallbackName), "German category name is required"));
|
|
||||||
names.put("fr", normalizeRequired(firstNonBlank(normalizeOptional(payload.getNameFr()), fallbackName), "French category name is required"));
|
|
||||||
|
|
||||||
String fallbackDescription = firstNonBlank(
|
|
||||||
normalizeOptional(payload.getDescription()),
|
|
||||||
normalizeOptional(payload.getDescriptionIt()),
|
|
||||||
normalizeOptional(payload.getDescriptionEn()),
|
|
||||||
normalizeOptional(payload.getDescriptionDe()),
|
|
||||||
normalizeOptional(payload.getDescriptionFr())
|
|
||||||
);
|
|
||||||
Map<String, String> descriptions = new LinkedHashMap<>();
|
|
||||||
descriptions.put("it", firstNonBlank(normalizeOptional(payload.getDescriptionIt()), fallbackDescription));
|
|
||||||
descriptions.put("en", firstNonBlank(normalizeOptional(payload.getDescriptionEn()), fallbackDescription));
|
|
||||||
descriptions.put("de", firstNonBlank(normalizeOptional(payload.getDescriptionDe()), fallbackDescription));
|
|
||||||
descriptions.put("fr", firstNonBlank(normalizeOptional(payload.getDescriptionFr()), fallbackDescription));
|
|
||||||
|
|
||||||
String fallbackSeoTitle = firstNonBlank(
|
|
||||||
normalizeOptional(payload.getSeoTitle()),
|
|
||||||
normalizeOptional(payload.getSeoTitleIt()),
|
|
||||||
normalizeOptional(payload.getSeoTitleEn()),
|
|
||||||
normalizeOptional(payload.getSeoTitleDe()),
|
|
||||||
normalizeOptional(payload.getSeoTitleFr())
|
|
||||||
);
|
|
||||||
Map<String, String> seoTitles = new LinkedHashMap<>();
|
|
||||||
seoTitles.put("it", firstNonBlank(normalizeOptional(payload.getSeoTitleIt()), fallbackSeoTitle));
|
|
||||||
seoTitles.put("en", firstNonBlank(normalizeOptional(payload.getSeoTitleEn()), fallbackSeoTitle));
|
|
||||||
seoTitles.put("de", firstNonBlank(normalizeOptional(payload.getSeoTitleDe()), fallbackSeoTitle));
|
|
||||||
seoTitles.put("fr", firstNonBlank(normalizeOptional(payload.getSeoTitleFr()), fallbackSeoTitle));
|
|
||||||
|
|
||||||
String fallbackSeoDescription = firstNonBlank(
|
|
||||||
normalizeOptional(payload.getSeoDescription()),
|
|
||||||
normalizeOptional(payload.getSeoDescriptionIt()),
|
|
||||||
normalizeOptional(payload.getSeoDescriptionEn()),
|
|
||||||
normalizeOptional(payload.getSeoDescriptionDe()),
|
|
||||||
normalizeOptional(payload.getSeoDescriptionFr())
|
|
||||||
);
|
|
||||||
Map<String, String> seoDescriptions = new LinkedHashMap<>();
|
|
||||||
seoDescriptions.put("it", validateSeoDescriptionLength(firstNonBlank(normalizeOptional(payload.getSeoDescriptionIt()), fallbackSeoDescription), "Italian"));
|
|
||||||
seoDescriptions.put("en", validateSeoDescriptionLength(firstNonBlank(normalizeOptional(payload.getSeoDescriptionEn()), fallbackSeoDescription), "English"));
|
|
||||||
seoDescriptions.put("de", validateSeoDescriptionLength(firstNonBlank(normalizeOptional(payload.getSeoDescriptionDe()), fallbackSeoDescription), "German"));
|
|
||||||
seoDescriptions.put("fr", validateSeoDescriptionLength(firstNonBlank(normalizeOptional(payload.getSeoDescriptionFr()), fallbackSeoDescription), "French"));
|
|
||||||
|
|
||||||
return new LocalizedCategoryContent(
|
|
||||||
names.get("it"),
|
|
||||||
firstNonBlank(descriptions.get("it"), fallbackDescription),
|
|
||||||
firstNonBlank(seoTitles.get("it"), fallbackSeoTitle),
|
|
||||||
firstNonBlank(seoDescriptions.get("it"), fallbackSeoDescription),
|
|
||||||
names,
|
|
||||||
descriptions,
|
|
||||||
seoTitles,
|
|
||||||
seoDescriptions
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String validateSeoDescriptionLength(String value, String languageLabel) {
|
|
||||||
if (value != null && value.length() > 160) {
|
|
||||||
throw new ResponseStatusException(BAD_REQUEST, languageLabel + " SEO description must be at most 160 characters");
|
|
||||||
}
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String firstNonBlank(String... values) {
|
|
||||||
if (values == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
for (String value : values) {
|
|
||||||
if (value != null && !value.isBlank()) {
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private CategoryContext buildContext() {
|
|
||||||
List<ShopCategory> categories = shopCategoryRepository.findAllByOrderBySortOrderAscNameAsc();
|
|
||||||
List<ShopProduct> products = shopProductRepository.findAll();
|
|
||||||
|
|
||||||
Map<UUID, ShopCategory> categoriesById = categories.stream()
|
|
||||||
.collect(Collectors.toMap(ShopCategory::getId, category -> category, (left, right) -> left, LinkedHashMap::new));
|
|
||||||
Map<UUID, List<ShopCategory>> childrenByParentId = new LinkedHashMap<>();
|
|
||||||
for (ShopCategory category : categories) {
|
|
||||||
UUID parentId = category.getParentCategory() != null ? category.getParentCategory().getId() : null;
|
|
||||||
childrenByParentId.computeIfAbsent(parentId, ignored -> new ArrayList<>()).add(category);
|
|
||||||
}
|
|
||||||
Comparator<ShopCategory> comparator = Comparator
|
|
||||||
.comparing(ShopCategory::getSortOrder, Comparator.nullsLast(Integer::compareTo))
|
|
||||||
.thenComparing(ShopCategory::getName, Comparator.nullsLast(String.CASE_INSENSITIVE_ORDER));
|
|
||||||
childrenByParentId.values().forEach(children -> children.sort(comparator));
|
|
||||||
|
|
||||||
Map<UUID, Integer> directProductCounts = new LinkedHashMap<>();
|
|
||||||
for (ShopProduct product : products) {
|
|
||||||
if (product.getCategory() == null || product.getCategory().getId() == null) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
directProductCounts.merge(product.getCategory().getId(), 1, Integer::sum);
|
|
||||||
}
|
|
||||||
|
|
||||||
Map<UUID, Integer> descendantProductCounts = new LinkedHashMap<>();
|
|
||||||
for (ShopCategory category : categories) {
|
|
||||||
resolveDescendantProductCount(category.getId(), childrenByParentId, directProductCounts, descendantProductCounts);
|
|
||||||
}
|
|
||||||
|
|
||||||
return new CategoryContext(categoriesById, childrenByParentId, directProductCounts, descendantProductCounts);
|
|
||||||
}
|
|
||||||
|
|
||||||
private int resolveDescendantProductCount(UUID categoryId,
|
|
||||||
Map<UUID, List<ShopCategory>> childrenByParentId,
|
|
||||||
Map<UUID, Integer> directProductCounts,
|
|
||||||
Map<UUID, Integer> descendantProductCounts) {
|
|
||||||
Integer cached = descendantProductCounts.get(categoryId);
|
|
||||||
if (cached != null) {
|
|
||||||
return cached;
|
|
||||||
}
|
|
||||||
|
|
||||||
int total = directProductCounts.getOrDefault(categoryId, 0);
|
|
||||||
for (ShopCategory child : childrenByParentId.getOrDefault(categoryId, List.of())) {
|
|
||||||
total += resolveDescendantProductCount(child.getId(), childrenByParentId, directProductCounts, descendantProductCounts);
|
|
||||||
}
|
|
||||||
descendantProductCounts.put(categoryId, total);
|
|
||||||
return total;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void appendFlatCategories(UUID parentId,
|
|
||||||
int depth,
|
|
||||||
CategoryContext context,
|
|
||||||
List<AdminShopCategoryDto> result) {
|
|
||||||
for (ShopCategory category : context.childrenByParentId().getOrDefault(parentId, List.of())) {
|
|
||||||
result.add(toDto(category, depth, context, false));
|
|
||||||
appendFlatCategories(category.getId(), depth + 1, context, result);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<AdminShopCategoryDto> buildCategoryTree(UUID parentId, int depth, CategoryContext context) {
|
|
||||||
return context.childrenByParentId().getOrDefault(parentId, List.of()).stream()
|
|
||||||
.map(category -> toDto(category, depth, context, true))
|
|
||||||
.toList();
|
|
||||||
}
|
|
||||||
|
|
||||||
private AdminShopCategoryDto toDto(ShopCategory category,
|
|
||||||
int depth,
|
|
||||||
CategoryContext context,
|
|
||||||
boolean includeChildren) {
|
|
||||||
AdminShopCategoryDto dto = new AdminShopCategoryDto();
|
|
||||||
dto.setId(category.getId());
|
|
||||||
dto.setParentCategoryId(category.getParentCategory() != null ? category.getParentCategory().getId() : null);
|
|
||||||
dto.setParentCategoryName(category.getParentCategory() != null ? category.getParentCategory().getName() : null);
|
|
||||||
dto.setSlug(category.getSlug());
|
|
||||||
dto.setName(category.getName());
|
|
||||||
dto.setNameIt(category.getNameIt());
|
|
||||||
dto.setNameEn(category.getNameEn());
|
|
||||||
dto.setNameDe(category.getNameDe());
|
|
||||||
dto.setNameFr(category.getNameFr());
|
|
||||||
dto.setDescription(category.getDescription());
|
|
||||||
dto.setDescriptionIt(category.getDescriptionIt());
|
|
||||||
dto.setDescriptionEn(category.getDescriptionEn());
|
|
||||||
dto.setDescriptionDe(category.getDescriptionDe());
|
|
||||||
dto.setDescriptionFr(category.getDescriptionFr());
|
|
||||||
dto.setSeoTitle(category.getSeoTitle());
|
|
||||||
dto.setSeoTitleIt(category.getSeoTitleIt());
|
|
||||||
dto.setSeoTitleEn(category.getSeoTitleEn());
|
|
||||||
dto.setSeoTitleDe(category.getSeoTitleDe());
|
|
||||||
dto.setSeoTitleFr(category.getSeoTitleFr());
|
|
||||||
dto.setSeoDescription(category.getSeoDescription());
|
|
||||||
dto.setSeoDescriptionIt(category.getSeoDescriptionIt());
|
|
||||||
dto.setSeoDescriptionEn(category.getSeoDescriptionEn());
|
|
||||||
dto.setSeoDescriptionDe(category.getSeoDescriptionDe());
|
|
||||||
dto.setSeoDescriptionFr(category.getSeoDescriptionFr());
|
|
||||||
dto.setOgTitle(category.getOgTitle());
|
|
||||||
dto.setOgDescription(category.getOgDescription());
|
|
||||||
dto.setIndexable(category.getIndexable());
|
|
||||||
dto.setIsActive(category.getIsActive());
|
|
||||||
dto.setSortOrder(category.getSortOrder());
|
|
||||||
dto.setDepth(depth);
|
|
||||||
dto.setChildCount(context.childrenByParentId().getOrDefault(category.getId(), List.of()).size());
|
|
||||||
dto.setDirectProductCount(context.directProductCounts().getOrDefault(category.getId(), 0));
|
|
||||||
dto.setDescendantProductCount(context.descendantProductCounts().getOrDefault(category.getId(), 0));
|
|
||||||
dto.setMediaUsageType(SHOP_CATEGORY_MEDIA_USAGE_TYPE);
|
|
||||||
dto.setMediaUsageKey(category.getId().toString());
|
|
||||||
dto.setBreadcrumbs(buildBreadcrumbs(category));
|
|
||||||
dto.setChildren(includeChildren ? buildCategoryTree(category.getId(), depth + 1, context) : List.of());
|
|
||||||
dto.setCreatedAt(category.getCreatedAt());
|
|
||||||
dto.setUpdatedAt(category.getUpdatedAt());
|
|
||||||
return dto;
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<AdminShopCategoryRefDto> buildBreadcrumbs(ShopCategory category) {
|
|
||||||
List<AdminShopCategoryRefDto> breadcrumbs = new ArrayList<>();
|
|
||||||
ShopCategory current = category;
|
|
||||||
while (current != null) {
|
|
||||||
AdminShopCategoryRefDto ref = new AdminShopCategoryRefDto();
|
|
||||||
ref.setId(current.getId());
|
|
||||||
ref.setSlug(current.getSlug());
|
|
||||||
ref.setName(current.getName());
|
|
||||||
breadcrumbs.add(ref);
|
|
||||||
current = current.getParentCategory();
|
|
||||||
}
|
|
||||||
java.util.Collections.reverse(breadcrumbs);
|
|
||||||
return breadcrumbs;
|
|
||||||
}
|
|
||||||
|
|
||||||
private int resolveDepth(ShopCategory category) {
|
|
||||||
int depth = 0;
|
|
||||||
ShopCategory current = category != null ? category.getParentCategory() : null;
|
|
||||||
while (current != null) {
|
|
||||||
depth++;
|
|
||||||
current = current.getParentCategory();
|
|
||||||
}
|
|
||||||
return depth;
|
|
||||||
}
|
|
||||||
|
|
||||||
private record CategoryContext(
|
|
||||||
Map<UUID, ShopCategory> categoriesById,
|
|
||||||
Map<UUID, List<ShopCategory>> childrenByParentId,
|
|
||||||
Map<UUID, Integer> directProductCounts,
|
|
||||||
Map<UUID, Integer> descendantProductCounts
|
|
||||||
) {
|
|
||||||
}
|
|
||||||
|
|
||||||
private record LocalizedCategoryContent(
|
|
||||||
String defaultName,
|
|
||||||
String defaultDescription,
|
|
||||||
String defaultSeoTitle,
|
|
||||||
String defaultSeoDescription,
|
|
||||||
Map<String, String> names,
|
|
||||||
Map<String, String> descriptions,
|
|
||||||
Map<String, String> seoTitles,
|
|
||||||
Map<String, String> seoDescriptions
|
|
||||||
) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,907 +0,0 @@
|
|||||||
package com.printcalculator.service.admin;
|
|
||||||
|
|
||||||
import com.printcalculator.dto.AdminMediaUsageDto;
|
|
||||||
import com.printcalculator.dto.AdminShopProductDto;
|
|
||||||
import com.printcalculator.dto.AdminShopProductVariantDto;
|
|
||||||
import com.printcalculator.dto.AdminUpsertShopProductRequest;
|
|
||||||
import com.printcalculator.dto.AdminUpsertShopProductVariantRequest;
|
|
||||||
import com.printcalculator.dto.PublicMediaUsageDto;
|
|
||||||
import com.printcalculator.dto.ShopProductModelDto;
|
|
||||||
import com.printcalculator.entity.ShopCategory;
|
|
||||||
import com.printcalculator.entity.ShopProduct;
|
|
||||||
import com.printcalculator.entity.ShopProductModelAsset;
|
|
||||||
import com.printcalculator.entity.ShopProductVariant;
|
|
||||||
import com.printcalculator.model.ModelDimensions;
|
|
||||||
import com.printcalculator.repository.OrderItemRepository;
|
|
||||||
import com.printcalculator.repository.QuoteLineItemRepository;
|
|
||||||
import com.printcalculator.repository.ShopCategoryRepository;
|
|
||||||
import com.printcalculator.repository.ShopProductModelAssetRepository;
|
|
||||||
import com.printcalculator.repository.ShopProductRepository;
|
|
||||||
import com.printcalculator.repository.ShopProductVariantRepository;
|
|
||||||
import com.printcalculator.service.SlicerService;
|
|
||||||
import com.printcalculator.service.media.PublicMediaQueryService;
|
|
||||||
import com.printcalculator.service.shop.ShopStorageService;
|
|
||||||
import com.printcalculator.service.storage.ClamAVService;
|
|
||||||
import org.jsoup.Jsoup;
|
|
||||||
import org.jsoup.nodes.Document;
|
|
||||||
import org.jsoup.safety.Safelist;
|
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
|
||||||
import org.springframework.http.HttpStatus;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
|
||||||
import org.springframework.util.StringUtils;
|
|
||||||
import org.springframework.web.multipart.MultipartFile;
|
|
||||||
import org.springframework.web.server.ResponseStatusException;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.InputStream;
|
|
||||||
import java.math.BigDecimal;
|
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.nio.file.StandardCopyOption;
|
|
||||||
import java.security.MessageDigest;
|
|
||||||
import java.security.NoSuchAlgorithmException;
|
|
||||||
import java.text.Normalizer;
|
|
||||||
import java.time.OffsetDateTime;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.Collection;
|
|
||||||
import java.util.Comparator;
|
|
||||||
import java.util.HexFormat;
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.LinkedHashSet;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Locale;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Objects;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.UUID;
|
|
||||||
import java.util.regex.Pattern;
|
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public class AdminShopProductControllerService {
|
|
||||||
private static final String SHOP_PRODUCT_MEDIA_USAGE_TYPE = "SHOP_PRODUCT";
|
|
||||||
private static final Set<String> SUPPORTED_MODEL_EXTENSIONS = Set.of("stl", "3mf");
|
|
||||||
private static final Pattern HEX_COLOR_PATTERN = Pattern.compile("^#[0-9A-Fa-f]{6}$");
|
|
||||||
private static final Pattern DIACRITICS_PATTERN = Pattern.compile("\\p{M}+");
|
|
||||||
private static final Pattern NON_ALPHANUMERIC_PATTERN = Pattern.compile("[^a-z0-9]+");
|
|
||||||
private static final Pattern EDGE_DASH_PATTERN = Pattern.compile("(^-+|-+$)");
|
|
||||||
private static final Safelist PRODUCT_DESCRIPTION_SAFELIST = Safelist.none()
|
|
||||||
.addTags("p", "div", "br", "strong", "b", "em", "i", "u", "ul", "ol", "li", "a")
|
|
||||||
.addAttributes("a", "href")
|
|
||||||
.addProtocols("a", "href", "http", "https", "mailto", "tel");
|
|
||||||
|
|
||||||
private final ShopProductRepository shopProductRepository;
|
|
||||||
private final ShopCategoryRepository shopCategoryRepository;
|
|
||||||
private final ShopProductVariantRepository shopProductVariantRepository;
|
|
||||||
private final ShopProductModelAssetRepository shopProductModelAssetRepository;
|
|
||||||
private final QuoteLineItemRepository quoteLineItemRepository;
|
|
||||||
private final OrderItemRepository orderItemRepository;
|
|
||||||
private final PublicMediaQueryService publicMediaQueryService;
|
|
||||||
private final AdminMediaControllerService adminMediaControllerService;
|
|
||||||
private final ShopStorageService shopStorageService;
|
|
||||||
private final SlicerService slicerService;
|
|
||||||
private final ClamAVService clamAVService;
|
|
||||||
private final long maxModelFileSizeBytes;
|
|
||||||
|
|
||||||
public AdminShopProductControllerService(ShopProductRepository shopProductRepository,
|
|
||||||
ShopCategoryRepository shopCategoryRepository,
|
|
||||||
ShopProductVariantRepository shopProductVariantRepository,
|
|
||||||
ShopProductModelAssetRepository shopProductModelAssetRepository,
|
|
||||||
QuoteLineItemRepository quoteLineItemRepository,
|
|
||||||
OrderItemRepository orderItemRepository,
|
|
||||||
PublicMediaQueryService publicMediaQueryService,
|
|
||||||
AdminMediaControllerService adminMediaControllerService,
|
|
||||||
ShopStorageService shopStorageService,
|
|
||||||
SlicerService slicerService,
|
|
||||||
ClamAVService clamAVService,
|
|
||||||
@Value("${shop.model.max-file-size-bytes:104857600}") long maxModelFileSizeBytes) {
|
|
||||||
this.shopProductRepository = shopProductRepository;
|
|
||||||
this.shopCategoryRepository = shopCategoryRepository;
|
|
||||||
this.shopProductVariantRepository = shopProductVariantRepository;
|
|
||||||
this.shopProductModelAssetRepository = shopProductModelAssetRepository;
|
|
||||||
this.quoteLineItemRepository = quoteLineItemRepository;
|
|
||||||
this.orderItemRepository = orderItemRepository;
|
|
||||||
this.publicMediaQueryService = publicMediaQueryService;
|
|
||||||
this.adminMediaControllerService = adminMediaControllerService;
|
|
||||||
this.shopStorageService = shopStorageService;
|
|
||||||
this.slicerService = slicerService;
|
|
||||||
this.clamAVService = clamAVService;
|
|
||||||
this.maxModelFileSizeBytes = maxModelFileSizeBytes;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<AdminShopProductDto> getProducts() {
|
|
||||||
return toProductDtos(shopProductRepository.findAllByOrderByIsFeaturedDescSortOrderAscNameAsc());
|
|
||||||
}
|
|
||||||
|
|
||||||
public AdminShopProductDto getProduct(UUID productId) {
|
|
||||||
ShopProduct product = shopProductRepository.findById(productId)
|
|
||||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Shop product not found"));
|
|
||||||
return toProductDtos(List.of(product)).get(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public AdminShopProductDto createProduct(AdminUpsertShopProductRequest payload) {
|
|
||||||
ensurePayload(payload);
|
|
||||||
LocalizedProductContent localizedContent = normalizeLocalizedProductContent(payload);
|
|
||||||
String normalizedSlug = normalizeAndValidateSlug(payload.getSlug(), localizedContent.defaultName());
|
|
||||||
ensureSlugAvailable(normalizedSlug, null);
|
|
||||||
|
|
||||||
ShopProduct product = new ShopProduct();
|
|
||||||
product.setCreatedAt(OffsetDateTime.now());
|
|
||||||
applyProductPayload(product, payload, localizedContent, normalizedSlug, resolveCategory(payload.getCategoryId()));
|
|
||||||
ShopProduct saved = shopProductRepository.save(product);
|
|
||||||
syncVariants(saved, payload.getVariants());
|
|
||||||
return getProduct(saved.getId());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public AdminShopProductDto updateProduct(UUID productId, AdminUpsertShopProductRequest payload) {
|
|
||||||
ensurePayload(payload);
|
|
||||||
ShopProduct product = shopProductRepository.findById(productId)
|
|
||||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Shop product not found"));
|
|
||||||
|
|
||||||
LocalizedProductContent localizedContent = normalizeLocalizedProductContent(payload);
|
|
||||||
String normalizedSlug = normalizeAndValidateSlug(payload.getSlug(), localizedContent.defaultName());
|
|
||||||
ensureSlugAvailable(normalizedSlug, productId);
|
|
||||||
|
|
||||||
applyProductPayload(product, payload, localizedContent, normalizedSlug, resolveCategory(payload.getCategoryId()));
|
|
||||||
ShopProduct saved = shopProductRepository.save(product);
|
|
||||||
syncVariants(saved, payload.getVariants());
|
|
||||||
return getProduct(saved.getId());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public void deleteProduct(UUID productId) {
|
|
||||||
ShopProduct product = shopProductRepository.findById(productId)
|
|
||||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Shop product not found"));
|
|
||||||
|
|
||||||
if (quoteLineItemRepository.existsByShopProduct_Id(productId)
|
|
||||||
|| orderItemRepository.existsByShopProduct_Id(productId)) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.CONFLICT, "Product is already used in carts or orders and cannot be deleted");
|
|
||||||
}
|
|
||||||
|
|
||||||
List<ShopProductVariant> variants = shopProductVariantRepository.findByProduct_IdOrderBySortOrderAscColorNameAsc(productId);
|
|
||||||
for (ShopProductVariant variant : variants) {
|
|
||||||
if (quoteLineItemRepository.existsByShopProductVariant_Id(variant.getId())
|
|
||||||
|| orderItemRepository.existsByShopProductVariant_Id(variant.getId())) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.CONFLICT, "One or more variants are already used in carts or orders and cannot be deleted");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
shopProductModelAssetRepository.findByProduct_Id(productId).ifPresent(asset -> {
|
|
||||||
deleteExistingModelFile(asset, productId);
|
|
||||||
shopProductModelAssetRepository.delete(asset);
|
|
||||||
});
|
|
||||||
if (!variants.isEmpty()) {
|
|
||||||
shopProductVariantRepository.deleteAll(variants);
|
|
||||||
}
|
|
||||||
shopProductRepository.delete(product);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public AdminShopProductDto uploadProductModel(UUID productId, MultipartFile file) throws IOException {
|
|
||||||
ShopProduct product = shopProductRepository.findById(productId)
|
|
||||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Shop product not found"));
|
|
||||||
validateModelUpload(file);
|
|
||||||
|
|
||||||
Path tempDirectory = Files.createTempDirectory("shop-product-model-");
|
|
||||||
Path destination = null;
|
|
||||||
try {
|
|
||||||
String cleanedFilename = sanitizeOriginalFilename(file.getOriginalFilename());
|
|
||||||
String extension = resolveExtension(cleanedFilename);
|
|
||||||
Path uploadPath = tempDirectory.resolve("upload." + extension);
|
|
||||||
file.transferTo(uploadPath);
|
|
||||||
|
|
||||||
try (InputStream inputStream = Files.newInputStream(uploadPath)) {
|
|
||||||
clamAVService.scan(inputStream);
|
|
||||||
}
|
|
||||||
|
|
||||||
Path storageDir = shopStorageService.productModelStorageDir(productId);
|
|
||||||
destination = storageDir.resolve(UUID.randomUUID() + ".stl");
|
|
||||||
if ("3mf".equals(extension)) {
|
|
||||||
slicerService.convert3mfToPersistentStl(uploadPath.toFile(), destination);
|
|
||||||
} else {
|
|
||||||
Files.copy(uploadPath, destination, StandardCopyOption.REPLACE_EXISTING);
|
|
||||||
}
|
|
||||||
|
|
||||||
ModelDimensions dimensions = slicerService.inspectModelDimensions(destination.toFile())
|
|
||||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "Unable to extract model dimensions"));
|
|
||||||
|
|
||||||
ShopProductModelAsset asset = shopProductModelAssetRepository.findByProduct_Id(productId)
|
|
||||||
.orElseGet(ShopProductModelAsset::new);
|
|
||||||
String previousStoredRelativePath = asset.getStoredRelativePath();
|
|
||||||
|
|
||||||
asset.setProduct(product);
|
|
||||||
asset.setOriginalFilename(buildDownloadFilename(cleanedFilename));
|
|
||||||
asset.setStoredFilename(destination.getFileName().toString());
|
|
||||||
asset.setStoredRelativePath(shopStorageService.toStoredPath(destination));
|
|
||||||
asset.setMimeType("model/stl");
|
|
||||||
asset.setFileSizeBytes(Files.size(destination));
|
|
||||||
asset.setSha256Hex(computeSha256(destination));
|
|
||||||
asset.setBoundingBoxXMm(BigDecimal.valueOf(dimensions.xMm()));
|
|
||||||
asset.setBoundingBoxYMm(BigDecimal.valueOf(dimensions.yMm()));
|
|
||||||
asset.setBoundingBoxZMm(BigDecimal.valueOf(dimensions.zMm()));
|
|
||||||
if (asset.getCreatedAt() == null) {
|
|
||||||
asset.setCreatedAt(OffsetDateTime.now());
|
|
||||||
}
|
|
||||||
asset.setUpdatedAt(OffsetDateTime.now());
|
|
||||||
shopProductModelAssetRepository.save(asset);
|
|
||||||
deleteStoredRelativePath(previousStoredRelativePath, productId, asset.getStoredRelativePath());
|
|
||||||
|
|
||||||
return getProduct(productId);
|
|
||||||
} catch (IOException | RuntimeException e) {
|
|
||||||
deletePathQuietly(destination);
|
|
||||||
throw e;
|
|
||||||
} finally {
|
|
||||||
deleteRecursively(tempDirectory);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public void deleteProductModel(UUID productId) {
|
|
||||||
shopProductRepository.findById(productId)
|
|
||||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Shop product not found"));
|
|
||||||
ShopProductModelAsset asset = shopProductModelAssetRepository.findByProduct_Id(productId)
|
|
||||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Shop product model not found"));
|
|
||||||
|
|
||||||
deleteExistingModelFile(asset, productId);
|
|
||||||
shopProductModelAssetRepository.delete(asset);
|
|
||||||
}
|
|
||||||
|
|
||||||
public ProductModelDownload getProductModel(UUID productId) {
|
|
||||||
ShopProduct product = shopProductRepository.findById(productId)
|
|
||||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Shop product not found"));
|
|
||||||
ShopProductModelAsset asset = shopProductModelAssetRepository.findByProduct_Id(productId)
|
|
||||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Shop product model not found"));
|
|
||||||
|
|
||||||
Path path = shopStorageService.resolveStoredProductPath(asset.getStoredRelativePath(), product.getId());
|
|
||||||
if (path == null || !Files.exists(path)) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Shop product model not found");
|
|
||||||
}
|
|
||||||
|
|
||||||
return new ProductModelDownload(path, asset.getOriginalFilename(), asset.getMimeType());
|
|
||||||
}
|
|
||||||
|
|
||||||
private void syncVariants(ShopProduct product, List<AdminUpsertShopProductVariantRequest> variantPayloads) {
|
|
||||||
List<AdminUpsertShopProductVariantRequest> normalizedPayloads = normalizeVariantPayloads(variantPayloads);
|
|
||||||
List<ShopProductVariant> existingVariants = shopProductVariantRepository.findByProduct_IdOrderBySortOrderAscColorNameAsc(product.getId());
|
|
||||||
Map<UUID, ShopProductVariant> existingById = existingVariants.stream()
|
|
||||||
.collect(Collectors.toMap(ShopProductVariant::getId, variant -> variant, (left, right) -> left, LinkedHashMap::new));
|
|
||||||
|
|
||||||
Set<UUID> retainedIds = new LinkedHashSet<>();
|
|
||||||
List<ShopProductVariant> variantsToSave = new ArrayList<>();
|
|
||||||
|
|
||||||
for (AdminUpsertShopProductVariantRequest payload : normalizedPayloads) {
|
|
||||||
ShopProductVariant variant;
|
|
||||||
if (payload.getId() != null) {
|
|
||||||
variant = existingById.get(payload.getId());
|
|
||||||
if (variant == null) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Variant does not belong to the product");
|
|
||||||
}
|
|
||||||
retainedIds.add(variant.getId());
|
|
||||||
} else {
|
|
||||||
variant = new ShopProductVariant();
|
|
||||||
variant.setCreatedAt(OffsetDateTime.now());
|
|
||||||
}
|
|
||||||
|
|
||||||
applyVariantPayload(variant, product, payload);
|
|
||||||
variantsToSave.add(variant);
|
|
||||||
}
|
|
||||||
|
|
||||||
List<ShopProductVariant> variantsToDelete = existingVariants.stream()
|
|
||||||
.filter(variant -> !retainedIds.contains(variant.getId()))
|
|
||||||
.toList();
|
|
||||||
for (ShopProductVariant variant : variantsToDelete) {
|
|
||||||
if (quoteLineItemRepository.existsByShopProductVariant_Id(variant.getId())
|
|
||||||
|| orderItemRepository.existsByShopProductVariant_Id(variant.getId())) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.CONFLICT, "Variant is already used in carts or orders and cannot be removed");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!variantsToDelete.isEmpty()) {
|
|
||||||
shopProductVariantRepository.deleteAll(variantsToDelete);
|
|
||||||
}
|
|
||||||
shopProductVariantRepository.saveAll(variantsToSave);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void applyProductPayload(ShopProduct product,
|
|
||||||
AdminUpsertShopProductRequest payload,
|
|
||||||
LocalizedProductContent localizedContent,
|
|
||||||
String normalizedSlug,
|
|
||||||
ShopCategory category) {
|
|
||||||
product.setCategory(category);
|
|
||||||
product.setSlug(normalizedSlug);
|
|
||||||
product.setName(localizedContent.defaultName());
|
|
||||||
product.setNameIt(localizedContent.names().get("it"));
|
|
||||||
product.setNameEn(localizedContent.names().get("en"));
|
|
||||||
product.setNameDe(localizedContent.names().get("de"));
|
|
||||||
product.setNameFr(localizedContent.names().get("fr"));
|
|
||||||
product.setExcerpt(localizedContent.defaultExcerpt());
|
|
||||||
product.setExcerptIt(localizedContent.excerpts().get("it"));
|
|
||||||
product.setExcerptEn(localizedContent.excerpts().get("en"));
|
|
||||||
product.setExcerptDe(localizedContent.excerpts().get("de"));
|
|
||||||
product.setExcerptFr(localizedContent.excerpts().get("fr"));
|
|
||||||
product.setDescription(localizedContent.defaultDescription());
|
|
||||||
product.setDescriptionIt(localizedContent.descriptions().get("it"));
|
|
||||||
product.setDescriptionEn(localizedContent.descriptions().get("en"));
|
|
||||||
product.setDescriptionDe(localizedContent.descriptions().get("de"));
|
|
||||||
product.setDescriptionFr(localizedContent.descriptions().get("fr"));
|
|
||||||
product.setSeoTitle(localizedContent.defaultSeoTitle());
|
|
||||||
product.setSeoTitleIt(localizedContent.seoTitles().get("it"));
|
|
||||||
product.setSeoTitleEn(localizedContent.seoTitles().get("en"));
|
|
||||||
product.setSeoTitleDe(localizedContent.seoTitles().get("de"));
|
|
||||||
product.setSeoTitleFr(localizedContent.seoTitles().get("fr"));
|
|
||||||
product.setSeoDescription(localizedContent.defaultSeoDescription());
|
|
||||||
product.setSeoDescriptionIt(localizedContent.seoDescriptions().get("it"));
|
|
||||||
product.setSeoDescriptionEn(localizedContent.seoDescriptions().get("en"));
|
|
||||||
product.setSeoDescriptionDe(localizedContent.seoDescriptions().get("de"));
|
|
||||||
product.setSeoDescriptionFr(localizedContent.seoDescriptions().get("fr"));
|
|
||||||
product.setOgTitle(localizedContent.defaultSeoTitle());
|
|
||||||
product.setOgDescription(localizedContent.defaultSeoDescription());
|
|
||||||
product.setIndexable(payload.getIndexable() == null || payload.getIndexable());
|
|
||||||
product.setIsFeatured(Boolean.TRUE.equals(payload.getIsFeatured()));
|
|
||||||
product.setIsActive(payload.getIsActive() == null || payload.getIsActive());
|
|
||||||
product.setSortOrder(payload.getSortOrder() != null ? payload.getSortOrder() : 0);
|
|
||||||
product.setUpdatedAt(OffsetDateTime.now());
|
|
||||||
}
|
|
||||||
|
|
||||||
private void applyVariantPayload(ShopProductVariant variant,
|
|
||||||
ShopProduct product,
|
|
||||||
AdminUpsertShopProductVariantRequest payload) {
|
|
||||||
String normalizedColorName = normalizeRequired(payload.getColorName(), "Variant colorName is required");
|
|
||||||
String normalizedVariantLabel = normalizeOptional(payload.getVariantLabel());
|
|
||||||
String normalizedSku = normalizeOptional(payload.getSku());
|
|
||||||
String fallbackColorLabel = firstNonBlank(
|
|
||||||
normalizeOptional(payload.getColorLabelIt()),
|
|
||||||
normalizeOptional(payload.getColorLabelEn()),
|
|
||||||
normalizeOptional(payload.getColorLabelDe()),
|
|
||||||
normalizeOptional(payload.getColorLabelFr()),
|
|
||||||
normalizedColorName
|
|
||||||
);
|
|
||||||
String normalizedMaterialCode = normalizeRequired(
|
|
||||||
payload.getInternalMaterialCode(),
|
|
||||||
"Variant internalMaterialCode is required"
|
|
||||||
).toUpperCase(Locale.ROOT);
|
|
||||||
|
|
||||||
BigDecimal price = payload.getPriceChf();
|
|
||||||
if (price == null || price.compareTo(BigDecimal.ZERO) < 0) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Variant priceChf must be >= 0");
|
|
||||||
}
|
|
||||||
if (price.scale() > 2) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Variant priceChf must have at most 2 decimal places");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (normalizedSku != null) {
|
|
||||||
if (variant.getId() == null) {
|
|
||||||
if (shopProductVariantRepository.existsBySkuIgnoreCase(normalizedSku)) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Variant SKU already exists");
|
|
||||||
}
|
|
||||||
} else if (shopProductVariantRepository.existsBySkuIgnoreCaseAndIdNot(normalizedSku, variant.getId())) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Variant SKU already exists");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
variant.setProduct(product);
|
|
||||||
variant.setSku(normalizedSku);
|
|
||||||
variant.setVariantLabel(normalizedVariantLabel != null ? normalizedVariantLabel : normalizedColorName);
|
|
||||||
variant.setColorName(normalizedColorName);
|
|
||||||
variant.setColorLabelIt(firstNonBlank(normalizeOptional(payload.getColorLabelIt()), fallbackColorLabel));
|
|
||||||
variant.setColorLabelEn(firstNonBlank(normalizeOptional(payload.getColorLabelEn()), fallbackColorLabel));
|
|
||||||
variant.setColorLabelDe(firstNonBlank(normalizeOptional(payload.getColorLabelDe()), fallbackColorLabel));
|
|
||||||
variant.setColorLabelFr(firstNonBlank(normalizeOptional(payload.getColorLabelFr()), fallbackColorLabel));
|
|
||||||
variant.setColorHex(normalizeColorHex(payload.getColorHex()));
|
|
||||||
variant.setInternalMaterialCode(normalizedMaterialCode);
|
|
||||||
variant.setPriceChf(price);
|
|
||||||
variant.setIsDefault(Boolean.TRUE.equals(payload.getIsDefault()));
|
|
||||||
variant.setIsActive(payload.getIsActive() == null || payload.getIsActive());
|
|
||||||
variant.setSortOrder(payload.getSortOrder() != null ? payload.getSortOrder() : 0);
|
|
||||||
variant.setUpdatedAt(OffsetDateTime.now());
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<AdminUpsertShopProductVariantRequest> normalizeVariantPayloads(List<AdminUpsertShopProductVariantRequest> payloads) {
|
|
||||||
if (payloads == null || payloads.isEmpty()) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "At least one variant is required");
|
|
||||||
}
|
|
||||||
|
|
||||||
List<AdminUpsertShopProductVariantRequest> normalized = new ArrayList<>(payloads);
|
|
||||||
Set<String> variantKeys = new LinkedHashSet<>();
|
|
||||||
int defaultCount = 0;
|
|
||||||
for (AdminUpsertShopProductVariantRequest payload : normalized) {
|
|
||||||
if (payload == null) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Variant payload is required");
|
|
||||||
}
|
|
||||||
String colorName = normalizeRequired(payload.getColorName(), "Variant colorName is required");
|
|
||||||
String materialCode = normalizeRequired(
|
|
||||||
payload.getInternalMaterialCode(),
|
|
||||||
"Variant internalMaterialCode is required"
|
|
||||||
).toUpperCase(Locale.ROOT);
|
|
||||||
String variantKey = materialCode + "|" + colorName.toLowerCase(Locale.ROOT);
|
|
||||||
if (!variantKeys.add(variantKey)) {
|
|
||||||
throw new ResponseStatusException(
|
|
||||||
HttpStatus.BAD_REQUEST,
|
|
||||||
"Duplicate variant combination: " + materialCode + " / " + colorName
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (Boolean.TRUE.equals(payload.getIsDefault())) {
|
|
||||||
defaultCount++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (defaultCount > 1) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Only one variant can be default");
|
|
||||||
}
|
|
||||||
if (defaultCount == 0) {
|
|
||||||
AdminUpsertShopProductVariantRequest fallbackDefault = normalized.stream()
|
|
||||||
.filter(payload -> payload.getIsActive() == null || payload.getIsActive())
|
|
||||||
.findFirst()
|
|
||||||
.orElse(normalized.get(0));
|
|
||||||
fallbackDefault.setIsDefault(true);
|
|
||||||
}
|
|
||||||
return normalized;
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<AdminShopProductDto> toProductDtos(List<ShopProduct> products) {
|
|
||||||
if (products == null || products.isEmpty()) {
|
|
||||||
return List.of();
|
|
||||||
}
|
|
||||||
|
|
||||||
List<UUID> productIds = products.stream().map(ShopProduct::getId).toList();
|
|
||||||
Map<UUID, List<ShopProductVariant>> variantsByProductId = shopProductVariantRepository
|
|
||||||
.findByProduct_IdInOrderBySortOrderAscColorNameAsc(productIds)
|
|
||||||
.stream()
|
|
||||||
.collect(Collectors.groupingBy(
|
|
||||||
variant -> variant.getProduct().getId(),
|
|
||||||
LinkedHashMap::new,
|
|
||||||
Collectors.toList()
|
|
||||||
));
|
|
||||||
Map<UUID, ShopProductModelAsset> modelAssetsByProductId = shopProductModelAssetRepository.findByProduct_IdIn(productIds)
|
|
||||||
.stream()
|
|
||||||
.collect(Collectors.toMap(asset -> asset.getProduct().getId(), asset -> asset, (left, right) -> left, LinkedHashMap::new));
|
|
||||||
Map<String, List<PublicMediaUsageDto>> publicImagesByUsageKey = publicMediaQueryService.getUsageMediaMap(
|
|
||||||
SHOP_PRODUCT_MEDIA_USAGE_TYPE,
|
|
||||||
products.stream().map(this::mediaUsageKey).toList(),
|
|
||||||
null
|
|
||||||
);
|
|
||||||
|
|
||||||
return products.stream()
|
|
||||||
.map(product -> {
|
|
||||||
String usageKey = mediaUsageKey(product);
|
|
||||||
return toProductDto(
|
|
||||||
product,
|
|
||||||
variantsByProductId.getOrDefault(product.getId(), List.of()),
|
|
||||||
modelAssetsByProductId.get(product.getId()),
|
|
||||||
publicImagesByUsageKey.getOrDefault(usageKey, List.of()),
|
|
||||||
adminMediaControllerService.getUsages(SHOP_PRODUCT_MEDIA_USAGE_TYPE, usageKey, null)
|
|
||||||
);
|
|
||||||
})
|
|
||||||
.toList();
|
|
||||||
}
|
|
||||||
|
|
||||||
private AdminShopProductDto toProductDto(ShopProduct product,
|
|
||||||
List<ShopProductVariant> variants,
|
|
||||||
ShopProductModelAsset modelAsset,
|
|
||||||
List<PublicMediaUsageDto> images,
|
|
||||||
List<AdminMediaUsageDto> mediaUsages) {
|
|
||||||
AdminShopProductDto dto = new AdminShopProductDto();
|
|
||||||
dto.setId(product.getId());
|
|
||||||
dto.setCategoryId(product.getCategory() != null ? product.getCategory().getId() : null);
|
|
||||||
dto.setCategoryName(product.getCategory() != null ? product.getCategory().getName() : null);
|
|
||||||
dto.setCategorySlug(product.getCategory() != null ? product.getCategory().getSlug() : null);
|
|
||||||
dto.setSlug(product.getSlug());
|
|
||||||
dto.setName(product.getName());
|
|
||||||
dto.setNameIt(product.getNameIt());
|
|
||||||
dto.setNameEn(product.getNameEn());
|
|
||||||
dto.setNameDe(product.getNameDe());
|
|
||||||
dto.setNameFr(product.getNameFr());
|
|
||||||
dto.setExcerpt(product.getExcerpt());
|
|
||||||
dto.setExcerptIt(product.getExcerptIt());
|
|
||||||
dto.setExcerptEn(product.getExcerptEn());
|
|
||||||
dto.setExcerptDe(product.getExcerptDe());
|
|
||||||
dto.setExcerptFr(product.getExcerptFr());
|
|
||||||
dto.setDescription(product.getDescription());
|
|
||||||
dto.setDescriptionIt(product.getDescriptionIt());
|
|
||||||
dto.setDescriptionEn(product.getDescriptionEn());
|
|
||||||
dto.setDescriptionDe(product.getDescriptionDe());
|
|
||||||
dto.setDescriptionFr(product.getDescriptionFr());
|
|
||||||
dto.setSeoTitle(product.getSeoTitle());
|
|
||||||
dto.setSeoTitleIt(product.getSeoTitleIt());
|
|
||||||
dto.setSeoTitleEn(product.getSeoTitleEn());
|
|
||||||
dto.setSeoTitleDe(product.getSeoTitleDe());
|
|
||||||
dto.setSeoTitleFr(product.getSeoTitleFr());
|
|
||||||
dto.setSeoDescription(product.getSeoDescription());
|
|
||||||
dto.setSeoDescriptionIt(product.getSeoDescriptionIt());
|
|
||||||
dto.setSeoDescriptionEn(product.getSeoDescriptionEn());
|
|
||||||
dto.setSeoDescriptionDe(product.getSeoDescriptionDe());
|
|
||||||
dto.setSeoDescriptionFr(product.getSeoDescriptionFr());
|
|
||||||
dto.setOgTitle(product.getOgTitle());
|
|
||||||
dto.setOgDescription(product.getOgDescription());
|
|
||||||
dto.setIndexable(product.getIndexable());
|
|
||||||
dto.setIsFeatured(product.getIsFeatured());
|
|
||||||
dto.setIsActive(product.getIsActive());
|
|
||||||
dto.setSortOrder(product.getSortOrder());
|
|
||||||
dto.setVariantCount(variants.size());
|
|
||||||
dto.setActiveVariantCount((int) variants.stream().filter(variant -> Boolean.TRUE.equals(variant.getIsActive())).count());
|
|
||||||
dto.setPriceFromChf(resolvePriceFrom(variants));
|
|
||||||
dto.setPriceToChf(resolvePriceTo(variants));
|
|
||||||
dto.setMediaUsageType(SHOP_PRODUCT_MEDIA_USAGE_TYPE);
|
|
||||||
dto.setMediaUsageKey(mediaUsageKey(product));
|
|
||||||
dto.setMediaUsages(mediaUsages);
|
|
||||||
dto.setImages(images);
|
|
||||||
dto.setModel3d(toModelDto(product, modelAsset));
|
|
||||||
dto.setVariants(variants.stream().map(this::toVariantDto).toList());
|
|
||||||
dto.setCreatedAt(product.getCreatedAt());
|
|
||||||
dto.setUpdatedAt(product.getUpdatedAt());
|
|
||||||
return dto;
|
|
||||||
}
|
|
||||||
|
|
||||||
private AdminShopProductVariantDto toVariantDto(ShopProductVariant variant) {
|
|
||||||
AdminShopProductVariantDto dto = new AdminShopProductVariantDto();
|
|
||||||
dto.setId(variant.getId());
|
|
||||||
dto.setSku(variant.getSku());
|
|
||||||
dto.setVariantLabel(variant.getVariantLabel());
|
|
||||||
dto.setColorName(variant.getColorName());
|
|
||||||
dto.setColorLabelIt(variant.getColorLabelIt());
|
|
||||||
dto.setColorLabelEn(variant.getColorLabelEn());
|
|
||||||
dto.setColorLabelDe(variant.getColorLabelDe());
|
|
||||||
dto.setColorLabelFr(variant.getColorLabelFr());
|
|
||||||
dto.setColorHex(variant.getColorHex());
|
|
||||||
dto.setInternalMaterialCode(variant.getInternalMaterialCode());
|
|
||||||
dto.setPriceChf(variant.getPriceChf());
|
|
||||||
dto.setIsDefault(variant.getIsDefault());
|
|
||||||
dto.setIsActive(variant.getIsActive());
|
|
||||||
dto.setSortOrder(variant.getSortOrder());
|
|
||||||
dto.setCreatedAt(variant.getCreatedAt());
|
|
||||||
dto.setUpdatedAt(variant.getUpdatedAt());
|
|
||||||
return dto;
|
|
||||||
}
|
|
||||||
|
|
||||||
private ShopProductModelDto toModelDto(ShopProduct product, ShopProductModelAsset asset) {
|
|
||||||
if (asset == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return new ShopProductModelDto(
|
|
||||||
"/api/admin/shop/products/" + product.getId() + "/model",
|
|
||||||
asset.getOriginalFilename(),
|
|
||||||
asset.getMimeType(),
|
|
||||||
asset.getFileSizeBytes(),
|
|
||||||
asset.getBoundingBoxXMm(),
|
|
||||||
asset.getBoundingBoxYMm(),
|
|
||||||
asset.getBoundingBoxZMm()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private BigDecimal resolvePriceFrom(List<ShopProductVariant> variants) {
|
|
||||||
return variants.stream()
|
|
||||||
.map(ShopProductVariant::getPriceChf)
|
|
||||||
.filter(Objects::nonNull)
|
|
||||||
.min(BigDecimal::compareTo)
|
|
||||||
.orElse(BigDecimal.ZERO);
|
|
||||||
}
|
|
||||||
|
|
||||||
private BigDecimal resolvePriceTo(List<ShopProductVariant> variants) {
|
|
||||||
return variants.stream()
|
|
||||||
.map(ShopProductVariant::getPriceChf)
|
|
||||||
.filter(Objects::nonNull)
|
|
||||||
.max(BigDecimal::compareTo)
|
|
||||||
.orElse(BigDecimal.ZERO);
|
|
||||||
}
|
|
||||||
|
|
||||||
private ShopCategory resolveCategory(UUID categoryId) {
|
|
||||||
if (categoryId == null) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "categoryId is required");
|
|
||||||
}
|
|
||||||
return shopCategoryRepository.findById(categoryId)
|
|
||||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "Category not found"));
|
|
||||||
}
|
|
||||||
|
|
||||||
private void ensurePayload(AdminUpsertShopProductRequest payload) {
|
|
||||||
if (payload == null) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Payload is required");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private LocalizedProductContent normalizeLocalizedProductContent(AdminUpsertShopProductRequest payload) {
|
|
||||||
String legacyName = normalizeOptional(payload.getName());
|
|
||||||
String fallbackName = firstNonBlank(
|
|
||||||
legacyName,
|
|
||||||
normalizeOptional(payload.getNameIt()),
|
|
||||||
normalizeOptional(payload.getNameEn()),
|
|
||||||
normalizeOptional(payload.getNameDe()),
|
|
||||||
normalizeOptional(payload.getNameFr())
|
|
||||||
);
|
|
||||||
if (fallbackName == null) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Product name is required");
|
|
||||||
}
|
|
||||||
|
|
||||||
Map<String, String> names = new LinkedHashMap<>();
|
|
||||||
names.put("it", normalizeRequired(firstNonBlank(normalizeOptional(payload.getNameIt()), fallbackName), "Italian product name is required"));
|
|
||||||
names.put("en", normalizeRequired(firstNonBlank(normalizeOptional(payload.getNameEn()), fallbackName), "English product name is required"));
|
|
||||||
names.put("de", normalizeRequired(firstNonBlank(normalizeOptional(payload.getNameDe()), fallbackName), "German product name is required"));
|
|
||||||
names.put("fr", normalizeRequired(firstNonBlank(normalizeOptional(payload.getNameFr()), fallbackName), "French product name is required"));
|
|
||||||
|
|
||||||
String fallbackExcerpt = firstNonBlank(
|
|
||||||
normalizeOptional(payload.getExcerpt()),
|
|
||||||
normalizeOptional(payload.getExcerptIt()),
|
|
||||||
normalizeOptional(payload.getExcerptEn()),
|
|
||||||
normalizeOptional(payload.getExcerptDe()),
|
|
||||||
normalizeOptional(payload.getExcerptFr())
|
|
||||||
);
|
|
||||||
Map<String, String> excerpts = new LinkedHashMap<>();
|
|
||||||
excerpts.put("it", firstNonBlank(normalizeOptional(payload.getExcerptIt()), fallbackExcerpt));
|
|
||||||
excerpts.put("en", firstNonBlank(normalizeOptional(payload.getExcerptEn()), fallbackExcerpt));
|
|
||||||
excerpts.put("de", firstNonBlank(normalizeOptional(payload.getExcerptDe()), fallbackExcerpt));
|
|
||||||
excerpts.put("fr", firstNonBlank(normalizeOptional(payload.getExcerptFr()), fallbackExcerpt));
|
|
||||||
|
|
||||||
String fallbackDescription = firstNonBlank(
|
|
||||||
normalizeRichTextOptional(payload.getDescription()),
|
|
||||||
normalizeRichTextOptional(payload.getDescriptionIt()),
|
|
||||||
normalizeRichTextOptional(payload.getDescriptionEn()),
|
|
||||||
normalizeRichTextOptional(payload.getDescriptionDe()),
|
|
||||||
normalizeRichTextOptional(payload.getDescriptionFr())
|
|
||||||
);
|
|
||||||
Map<String, String> descriptions = new LinkedHashMap<>();
|
|
||||||
descriptions.put("it", firstNonBlank(normalizeRichTextOptional(payload.getDescriptionIt()), fallbackDescription));
|
|
||||||
descriptions.put("en", firstNonBlank(normalizeRichTextOptional(payload.getDescriptionEn()), fallbackDescription));
|
|
||||||
descriptions.put("de", firstNonBlank(normalizeRichTextOptional(payload.getDescriptionDe()), fallbackDescription));
|
|
||||||
descriptions.put("fr", firstNonBlank(normalizeRichTextOptional(payload.getDescriptionFr()), fallbackDescription));
|
|
||||||
|
|
||||||
String fallbackSeoTitle = firstNonBlank(
|
|
||||||
normalizeOptional(payload.getSeoTitle()),
|
|
||||||
normalizeOptional(payload.getSeoTitleIt()),
|
|
||||||
normalizeOptional(payload.getSeoTitleEn()),
|
|
||||||
normalizeOptional(payload.getSeoTitleDe()),
|
|
||||||
normalizeOptional(payload.getSeoTitleFr())
|
|
||||||
);
|
|
||||||
Map<String, String> seoTitles = new LinkedHashMap<>();
|
|
||||||
seoTitles.put("it", firstNonBlank(normalizeOptional(payload.getSeoTitleIt()), fallbackSeoTitle));
|
|
||||||
seoTitles.put("en", firstNonBlank(normalizeOptional(payload.getSeoTitleEn()), fallbackSeoTitle));
|
|
||||||
seoTitles.put("de", firstNonBlank(normalizeOptional(payload.getSeoTitleDe()), fallbackSeoTitle));
|
|
||||||
seoTitles.put("fr", firstNonBlank(normalizeOptional(payload.getSeoTitleFr()), fallbackSeoTitle));
|
|
||||||
|
|
||||||
String fallbackSeoDescription = firstNonBlank(
|
|
||||||
normalizeOptional(payload.getSeoDescription()),
|
|
||||||
normalizeOptional(payload.getSeoDescriptionIt()),
|
|
||||||
normalizeOptional(payload.getSeoDescriptionEn()),
|
|
||||||
normalizeOptional(payload.getSeoDescriptionDe()),
|
|
||||||
normalizeOptional(payload.getSeoDescriptionFr())
|
|
||||||
);
|
|
||||||
Map<String, String> seoDescriptions = new LinkedHashMap<>();
|
|
||||||
seoDescriptions.put("it", validateSeoDescriptionLength(firstNonBlank(normalizeOptional(payload.getSeoDescriptionIt()), fallbackSeoDescription), "Italian"));
|
|
||||||
seoDescriptions.put("en", validateSeoDescriptionLength(firstNonBlank(normalizeOptional(payload.getSeoDescriptionEn()), fallbackSeoDescription), "English"));
|
|
||||||
seoDescriptions.put("de", validateSeoDescriptionLength(firstNonBlank(normalizeOptional(payload.getSeoDescriptionDe()), fallbackSeoDescription), "German"));
|
|
||||||
seoDescriptions.put("fr", validateSeoDescriptionLength(firstNonBlank(normalizeOptional(payload.getSeoDescriptionFr()), fallbackSeoDescription), "French"));
|
|
||||||
|
|
||||||
return new LocalizedProductContent(
|
|
||||||
names.get("it"),
|
|
||||||
firstNonBlank(excerpts.get("it"), fallbackExcerpt),
|
|
||||||
firstNonBlank(descriptions.get("it"), fallbackDescription),
|
|
||||||
firstNonBlank(seoTitles.get("it"), fallbackSeoTitle),
|
|
||||||
firstNonBlank(seoDescriptions.get("it"), fallbackSeoDescription),
|
|
||||||
names,
|
|
||||||
excerpts,
|
|
||||||
descriptions,
|
|
||||||
seoTitles,
|
|
||||||
seoDescriptions
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void ensureSlugAvailable(String slug, UUID currentProductId) {
|
|
||||||
shopProductRepository.findBySlugIgnoreCase(slug).ifPresent(existing -> {
|
|
||||||
if (currentProductId == null || !existing.getId().equals(currentProductId)) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Product slug already exists");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeRequired(String value, String message) {
|
|
||||||
String normalized = normalizeOptional(value);
|
|
||||||
if (normalized == null) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, message);
|
|
||||||
}
|
|
||||||
return normalized;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeOptional(String value) {
|
|
||||||
if (value == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
String normalized = value.trim();
|
|
||||||
return normalized.isBlank() ? null : normalized;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeRichTextOptional(String value) {
|
|
||||||
String normalized = normalizeOptional(value);
|
|
||||||
if (normalized == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
String sanitized = Jsoup.clean(
|
|
||||||
normalized,
|
|
||||||
"",
|
|
||||||
PRODUCT_DESCRIPTION_SAFELIST,
|
|
||||||
new Document.OutputSettings().prettyPrint(false)
|
|
||||||
).trim();
|
|
||||||
|
|
||||||
if (sanitized.isBlank()) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
String plainText = Jsoup.parse(sanitized).text();
|
|
||||||
return plainText != null && !plainText.trim().isEmpty() ? sanitized : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String firstNonBlank(String... values) {
|
|
||||||
if (values == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
for (String value : values) {
|
|
||||||
if (value != null && !value.isBlank()) {
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeAndValidateSlug(String slug, String fallbackName) {
|
|
||||||
String source = normalizeOptional(slug);
|
|
||||||
if (source == null) {
|
|
||||||
source = fallbackName;
|
|
||||||
}
|
|
||||||
|
|
||||||
String normalized = Normalizer.normalize(source, Normalizer.Form.NFD);
|
|
||||||
normalized = DIACRITICS_PATTERN.matcher(normalized).replaceAll("");
|
|
||||||
normalized = normalized.toLowerCase(Locale.ROOT);
|
|
||||||
normalized = NON_ALPHANUMERIC_PATTERN.matcher(normalized).replaceAll("-");
|
|
||||||
normalized = EDGE_DASH_PATTERN.matcher(normalized).replaceAll("");
|
|
||||||
if (normalized.isBlank()) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Slug is invalid");
|
|
||||||
}
|
|
||||||
return normalized;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeColorHex(String value) {
|
|
||||||
String normalized = normalizeOptional(value);
|
|
||||||
if (normalized == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
if (!HEX_COLOR_PATTERN.matcher(normalized).matches()) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Variant colorHex must be in format #RRGGBB");
|
|
||||||
}
|
|
||||||
return normalized.toUpperCase(Locale.ROOT);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String validateSeoDescriptionLength(String value, String languageLabel) {
|
|
||||||
if (value != null && value.length() > 160) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, languageLabel + " SEO description must be at most 160 characters");
|
|
||||||
}
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void validateModelUpload(MultipartFile file) {
|
|
||||||
if (file == null || file.isEmpty()) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "3D model file is required");
|
|
||||||
}
|
|
||||||
if (maxModelFileSizeBytes > 0 && file.getSize() > maxModelFileSizeBytes) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "3D model file exceeds size limit");
|
|
||||||
}
|
|
||||||
String extension = resolveExtension(sanitizeOriginalFilename(file.getOriginalFilename()));
|
|
||||||
if (!SUPPORTED_MODEL_EXTENSIONS.contains(extension)) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Unsupported 3D model type. Allowed: stl, 3mf");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private String sanitizeOriginalFilename(String originalFilename) {
|
|
||||||
String cleaned = StringUtils.cleanPath(originalFilename == null ? "" : originalFilename);
|
|
||||||
int separatorIndex = Math.max(cleaned.lastIndexOf('/'), cleaned.lastIndexOf('\\'));
|
|
||||||
String basename = separatorIndex >= 0 ? cleaned.substring(separatorIndex + 1) : cleaned;
|
|
||||||
basename = basename.replace("\r", "_").replace("\n", "_");
|
|
||||||
return basename.isBlank() ? "model.stl" : basename;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String resolveExtension(String filename) {
|
|
||||||
int dotIndex = filename.lastIndexOf('.');
|
|
||||||
if (dotIndex < 0 || dotIndex == filename.length() - 1) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
return filename.substring(dotIndex + 1).toLowerCase(Locale.ROOT);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String buildDownloadFilename(String originalFilename) {
|
|
||||||
int dotIndex = originalFilename.lastIndexOf('.');
|
|
||||||
String base = dotIndex > 0 ? originalFilename.substring(0, dotIndex) : originalFilename;
|
|
||||||
return base + ".stl";
|
|
||||||
}
|
|
||||||
|
|
||||||
private String mediaUsageKey(ShopProduct product) {
|
|
||||||
return product.getId().toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void deleteExistingModelFile(ShopProductModelAsset asset, UUID productId) {
|
|
||||||
if (asset == null || asset.getStoredRelativePath() == null || asset.getStoredRelativePath().isBlank()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
Path existingPath = shopStorageService.resolveStoredProductPath(asset.getStoredRelativePath(), productId);
|
|
||||||
if (existingPath == null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
Files.deleteIfExists(existingPath);
|
|
||||||
} catch (IOException ignored) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void deleteStoredRelativePath(String storedRelativePath, UUID productId, String excludeStoredRelativePath) {
|
|
||||||
if (storedRelativePath == null || storedRelativePath.isBlank()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (Objects.equals(storedRelativePath, excludeStoredRelativePath)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
Path existingPath = shopStorageService.resolveStoredProductPath(storedRelativePath, productId);
|
|
||||||
deletePathQuietly(existingPath);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String computeSha256(Path file) throws IOException {
|
|
||||||
MessageDigest digest;
|
|
||||||
try {
|
|
||||||
digest = MessageDigest.getInstance("SHA-256");
|
|
||||||
} catch (NoSuchAlgorithmException e) {
|
|
||||||
throw new IOException("SHA-256 digest unavailable", e);
|
|
||||||
}
|
|
||||||
|
|
||||||
try (InputStream inputStream = Files.newInputStream(file)) {
|
|
||||||
byte[] buffer = new byte[8192];
|
|
||||||
int read;
|
|
||||||
while ((read = inputStream.read(buffer)) >= 0) {
|
|
||||||
if (read > 0) {
|
|
||||||
digest.update(buffer, 0, read);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return HexFormat.of().formatHex(digest.digest());
|
|
||||||
}
|
|
||||||
|
|
||||||
private void deletePathQuietly(Path path) {
|
|
||||||
if (path == null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
Files.deleteIfExists(path);
|
|
||||||
} catch (IOException ignored) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void deleteRecursively(Path path) {
|
|
||||||
if (path == null || !Files.exists(path)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try (var walk = Files.walk(path)) {
|
|
||||||
walk.sorted(Comparator.reverseOrder()).forEach(current -> {
|
|
||||||
try {
|
|
||||||
Files.deleteIfExists(current);
|
|
||||||
} catch (IOException ignored) {
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} catch (IOException ignored) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public record ProductModelDownload(Path path, String filename, String mimeType) {
|
|
||||||
}
|
|
||||||
|
|
||||||
private record LocalizedProductContent(
|
|
||||||
String defaultName,
|
|
||||||
String defaultExcerpt,
|
|
||||||
String defaultDescription,
|
|
||||||
String defaultSeoTitle,
|
|
||||||
String defaultSeoDescription,
|
|
||||||
Map<String, String> names,
|
|
||||||
Map<String, String> excerpts,
|
|
||||||
Map<String, String> descriptions,
|
|
||||||
Map<String, String> seoTitles,
|
|
||||||
Map<String, String> seoDescriptions
|
|
||||||
) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,685 +0,0 @@
|
|||||||
package com.printcalculator.service.admin;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
||||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
|
||||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
|
||||||
import com.printcalculator.dto.AdminTranslateShopProductRequest;
|
|
||||||
import com.printcalculator.dto.AdminTranslateShopProductResponse;
|
|
||||||
import com.printcalculator.entity.ShopCategory;
|
|
||||||
import com.printcalculator.repository.ShopCategoryRepository;
|
|
||||||
import org.jsoup.Jsoup;
|
|
||||||
import org.jsoup.nodes.Document;
|
|
||||||
import org.jsoup.safety.Safelist;
|
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
|
||||||
import org.springframework.http.HttpStatus;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
|
||||||
import org.springframework.web.server.ResponseStatusException;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.net.URI;
|
|
||||||
import java.net.http.HttpClient;
|
|
||||||
import java.net.http.HttpRequest;
|
|
||||||
import java.net.http.HttpResponse;
|
|
||||||
import java.time.Duration;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.LinkedHashSet;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Locale;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public class AdminShopProductTranslationService {
|
|
||||||
private static final List<String> SUPPORTED_LANGUAGES = List.of("it", "en", "de", "fr");
|
|
||||||
private static final Safelist PRODUCT_DESCRIPTION_SAFELIST = Safelist.none()
|
|
||||||
.addTags("p", "div", "br", "strong", "b", "em", "i", "u", "ul", "ol", "li", "a")
|
|
||||||
.addAttributes("a", "href")
|
|
||||||
.addProtocols("a", "href", "http", "https", "mailto", "tel");
|
|
||||||
private static final String DEFAULT_SHOP_CONTEXT = """
|
|
||||||
3D fab is a Swiss-based 3D printing shop and technical service.
|
|
||||||
The tone must be practical, clear, technical, and trustworthy.
|
|
||||||
Avoid hype, avoid invented claims, and avoid vague marketing filler.
|
|
||||||
Preserve all brand names, measurements, materials, SKUs, codes, and technical terminology exactly when they should not be translated.
|
|
||||||
When the source field is empty, return an empty string rather than inventing content.
|
|
||||||
For descriptions, preserve safe HTML structure when present and keep output ready for an ecommerce/admin form.
|
|
||||||
For SEO, prefer concise, natural phrases suitable for ecommerce and search snippets.
|
|
||||||
""";
|
|
||||||
|
|
||||||
private final ShopCategoryRepository shopCategoryRepository;
|
|
||||||
private final ObjectMapper objectMapper;
|
|
||||||
private final HttpClient httpClient;
|
|
||||||
private final String apiKey;
|
|
||||||
private final String baseUrl;
|
|
||||||
private final String model;
|
|
||||||
private final Duration timeout;
|
|
||||||
private final String promptCacheKeyPrefix;
|
|
||||||
private final String additionalBusinessContext;
|
|
||||||
|
|
||||||
public AdminShopProductTranslationService(ShopCategoryRepository shopCategoryRepository,
|
|
||||||
ObjectMapper objectMapper,
|
|
||||||
@Value("${openai.translation.api-key:}") String apiKey,
|
|
||||||
@Value("${openai.translation.base-url:https://api.openai.com/v1}") String baseUrl,
|
|
||||||
@Value("${openai.translation.model:gpt-5.4}") String model,
|
|
||||||
@Value("${openai.translation.timeout-seconds:45}") long timeoutSeconds,
|
|
||||||
@Value("${openai.translation.prompt-cache-key-prefix:printcalc-shop-product-translation-v1}") String promptCacheKeyPrefix,
|
|
||||||
@Value("${openai.translation.business-context:}") String additionalBusinessContext) {
|
|
||||||
this.shopCategoryRepository = shopCategoryRepository;
|
|
||||||
this.objectMapper = objectMapper;
|
|
||||||
this.apiKey = apiKey != null ? apiKey.trim() : "";
|
|
||||||
this.baseUrl = normalizeBaseUrl(baseUrl);
|
|
||||||
this.model = model != null ? model.trim() : "";
|
|
||||||
this.timeout = Duration.ofSeconds(Math.max(timeoutSeconds, 5));
|
|
||||||
this.promptCacheKeyPrefix = promptCacheKeyPrefix != null && !promptCacheKeyPrefix.isBlank()
|
|
||||||
? promptCacheKeyPrefix.trim()
|
|
||||||
: "printcalc-shop-product-translation-v1";
|
|
||||||
this.additionalBusinessContext = additionalBusinessContext != null ? additionalBusinessContext.trim() : "";
|
|
||||||
this.httpClient = HttpClient.newBuilder()
|
|
||||||
.connectTimeout(this.timeout)
|
|
||||||
.build();
|
|
||||||
}
|
|
||||||
|
|
||||||
public AdminTranslateShopProductResponse translateProduct(AdminTranslateShopProductRequest payload) {
|
|
||||||
ensureConfigured();
|
|
||||||
NormalizedTranslationRequest normalizedRequest = normalizeRequest(payload);
|
|
||||||
List<String> targetLanguages = resolveTargetLanguages(normalizedRequest);
|
|
||||||
if (targetLanguages.isEmpty()) {
|
|
||||||
return emptyResponse(normalizedRequest.sourceLanguage());
|
|
||||||
}
|
|
||||||
|
|
||||||
CategoryContext categoryContext = loadCategoryContext(normalizedRequest.categoryId());
|
|
||||||
String businessContext = buildBusinessContext(categoryContext, normalizedRequest.materialCodes());
|
|
||||||
|
|
||||||
TranslationBundle generated = callOpenAiFunction(
|
|
||||||
"generate_product_translations",
|
|
||||||
"Generate translated product copy for the requested target languages.",
|
|
||||||
buildInstructions("Generate the first-pass translations.", businessContext),
|
|
||||||
buildGenerationInput(normalizedRequest, targetLanguages, categoryContext),
|
|
||||||
buildTranslationToolSchema(targetLanguages),
|
|
||||||
"generate"
|
|
||||||
);
|
|
||||||
|
|
||||||
TranslationBundle normalizedGenerated = sanitizeBundle(generated, targetLanguages);
|
|
||||||
List<String> validationNotes = buildValidationNotes(normalizedGenerated, targetLanguages);
|
|
||||||
|
|
||||||
TranslationBundle reviewed = callOpenAiFunction(
|
|
||||||
"review_product_translations",
|
|
||||||
"Review and correct translated product copy while preserving meaning, SEO limits, and technical terminology.",
|
|
||||||
buildInstructions("Review and correct the generated translations.", businessContext),
|
|
||||||
buildReviewInput(normalizedRequest, normalizedGenerated, targetLanguages, categoryContext, validationNotes),
|
|
||||||
buildTranslationToolSchema(targetLanguages),
|
|
||||||
"review"
|
|
||||||
);
|
|
||||||
|
|
||||||
TranslationBundle finalBundle = sanitizeBundle(reviewed, targetLanguages);
|
|
||||||
ensureRequiredTranslations(finalBundle, targetLanguages);
|
|
||||||
return toResponse(normalizedRequest.sourceLanguage(), targetLanguages, finalBundle);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void ensureConfigured() {
|
|
||||||
if (apiKey.isBlank() || model.isBlank()) {
|
|
||||||
throw new ResponseStatusException(
|
|
||||||
HttpStatus.SERVICE_UNAVAILABLE,
|
|
||||||
"OpenAI translation is not configured on the backend"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private NormalizedTranslationRequest normalizeRequest(AdminTranslateShopProductRequest payload) {
|
|
||||||
if (payload == null) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Translation payload is required");
|
|
||||||
}
|
|
||||||
|
|
||||||
String sourceLanguage = normalizeLanguage(payload.getSourceLanguage());
|
|
||||||
if (!SUPPORTED_LANGUAGES.contains(sourceLanguage)) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Unsupported source language");
|
|
||||||
}
|
|
||||||
|
|
||||||
Map<String, String> names = normalizeLocalizedMap(payload.getNames(), false);
|
|
||||||
Map<String, String> excerpts = normalizeLocalizedMap(payload.getExcerpts(), false);
|
|
||||||
Map<String, String> descriptions = normalizeLocalizedMap(payload.getDescriptions(), true);
|
|
||||||
Map<String, String> seoTitles = normalizeLocalizedMap(payload.getSeoTitles(), false);
|
|
||||||
Map<String, String> seoDescriptions = normalizeLocalizedMap(payload.getSeoDescriptions(), false);
|
|
||||||
|
|
||||||
if (names.get(sourceLanguage).isBlank()) {
|
|
||||||
throw new ResponseStatusException(
|
|
||||||
HttpStatus.BAD_REQUEST,
|
|
||||||
"The active source language must have a product name before translation"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Set<String> materialCodes = new LinkedHashSet<>();
|
|
||||||
if (payload.getMaterialCodes() != null) {
|
|
||||||
for (String materialCode : payload.getMaterialCodes()) {
|
|
||||||
String normalizedCode = normalizeOptional(materialCode);
|
|
||||||
if (normalizedCode != null) {
|
|
||||||
materialCodes.add(normalizedCode.toUpperCase(Locale.ROOT));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return new NormalizedTranslationRequest(
|
|
||||||
payload.getCategoryId(),
|
|
||||||
sourceLanguage,
|
|
||||||
Boolean.TRUE.equals(payload.getOverwriteExisting()),
|
|
||||||
List.copyOf(materialCodes),
|
|
||||||
names,
|
|
||||||
excerpts,
|
|
||||||
descriptions,
|
|
||||||
seoTitles,
|
|
||||||
seoDescriptions
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<String> resolveTargetLanguages(NormalizedTranslationRequest request) {
|
|
||||||
List<String> targetLanguages = new ArrayList<>();
|
|
||||||
for (String language : SUPPORTED_LANGUAGES) {
|
|
||||||
if (language.equals(request.sourceLanguage())) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (request.overwriteExisting() || needsTranslation(request, language)) {
|
|
||||||
targetLanguages.add(language);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return targetLanguages;
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean needsTranslation(NormalizedTranslationRequest request, String language) {
|
|
||||||
return request.names().get(language).isBlank()
|
|
||||||
|| request.excerpts().get(language).isBlank()
|
|
||||||
|| normalizeRichTextOptional(request.descriptions().get(language)) == null
|
|
||||||
|| request.seoTitles().get(language).isBlank()
|
|
||||||
|| request.seoDescriptions().get(language).isBlank();
|
|
||||||
}
|
|
||||||
|
|
||||||
private CategoryContext loadCategoryContext(UUID categoryId) {
|
|
||||||
if (categoryId == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
ShopCategory category = shopCategoryRepository.findById(categoryId).orElse(null);
|
|
||||||
if (category == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return new CategoryContext(
|
|
||||||
category.getSlug(),
|
|
||||||
Map.of(
|
|
||||||
"it", safeValue(category.getNameIt()),
|
|
||||||
"en", safeValue(category.getNameEn()),
|
|
||||||
"de", safeValue(category.getNameDe()),
|
|
||||||
"fr", safeValue(category.getNameFr())
|
|
||||||
),
|
|
||||||
Map.of(
|
|
||||||
"it", safeValue(category.getDescriptionIt()),
|
|
||||||
"en", safeValue(category.getDescriptionEn()),
|
|
||||||
"de", safeValue(category.getDescriptionDe()),
|
|
||||||
"fr", safeValue(category.getDescriptionFr())
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String buildBusinessContext(CategoryContext categoryContext, List<String> materialCodes) {
|
|
||||||
StringBuilder context = new StringBuilder(DEFAULT_SHOP_CONTEXT);
|
|
||||||
if (!additionalBusinessContext.isBlank()) {
|
|
||||||
context.append('\n').append(additionalBusinessContext.trim());
|
|
||||||
}
|
|
||||||
if (categoryContext != null) {
|
|
||||||
context.append("\nCategory slug: ").append(categoryContext.slug());
|
|
||||||
context.append("\nCategory names: ").append(writeJson(categoryContext.names()));
|
|
||||||
if (categoryContext.descriptions().values().stream().anyMatch(value -> !value.isBlank())) {
|
|
||||||
context.append("\nCategory descriptions: ").append(writeJson(categoryContext.descriptions()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (materialCodes != null && !materialCodes.isEmpty()) {
|
|
||||||
context.append("\nMaterial codes present in the product: ").append(String.join(", ", materialCodes));
|
|
||||||
}
|
|
||||||
return context.toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
private String buildInstructions(String task, String businessContext) {
|
|
||||||
return """
|
|
||||||
You are a senior ecommerce localization editor.
|
|
||||||
Task: %s
|
|
||||||
Return only the function call arguments that match the provided schema.
|
|
||||||
Always preserve meaning, HTML safety, and technical precision.
|
|
||||||
Never invent specifications or marketing claims not present in the source.
|
|
||||||
If a source field is empty, return an empty string for that field.
|
|
||||||
General context:
|
|
||||||
%s
|
|
||||||
""".formatted(task, businessContext);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String buildGenerationInput(NormalizedTranslationRequest request,
|
|
||||||
List<String> targetLanguages,
|
|
||||||
CategoryContext categoryContext) {
|
|
||||||
ObjectNode input = objectMapper.createObjectNode();
|
|
||||||
input.put("sourceLanguage", request.sourceLanguage());
|
|
||||||
input.set("targetLanguages", objectMapper.valueToTree(targetLanguages));
|
|
||||||
input.put("overwriteExisting", request.overwriteExisting());
|
|
||||||
input.set("source", localizedFieldNode(request, request.sourceLanguage()));
|
|
||||||
input.set("existingTranslations", existingTranslationsNode(request, targetLanguages));
|
|
||||||
input.set("materialCodes", objectMapper.valueToTree(request.materialCodes()));
|
|
||||||
if (categoryContext != null) {
|
|
||||||
input.put("categorySlug", categoryContext.slug());
|
|
||||||
input.set("categoryNames", objectMapper.valueToTree(categoryContext.names()));
|
|
||||||
}
|
|
||||||
return writeJson(input);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String buildReviewInput(NormalizedTranslationRequest request,
|
|
||||||
TranslationBundle generated,
|
|
||||||
List<String> targetLanguages,
|
|
||||||
CategoryContext categoryContext,
|
|
||||||
List<String> validationNotes) {
|
|
||||||
ObjectNode input = objectMapper.createObjectNode();
|
|
||||||
input.put("sourceLanguage", request.sourceLanguage());
|
|
||||||
input.set("targetLanguages", objectMapper.valueToTree(targetLanguages));
|
|
||||||
input.set("source", localizedFieldNode(request, request.sourceLanguage()));
|
|
||||||
input.set("generatedTranslations", generated.toJsonNode(objectMapper));
|
|
||||||
input.set("validationNotes", objectMapper.valueToTree(validationNotes));
|
|
||||||
input.set("materialCodes", objectMapper.valueToTree(request.materialCodes()));
|
|
||||||
if (categoryContext != null) {
|
|
||||||
input.put("categorySlug", categoryContext.slug());
|
|
||||||
input.set("categoryNames", objectMapper.valueToTree(categoryContext.names()));
|
|
||||||
}
|
|
||||||
return writeJson(input);
|
|
||||||
}
|
|
||||||
|
|
||||||
private ObjectNode localizedFieldNode(NormalizedTranslationRequest request, String language) {
|
|
||||||
ObjectNode node = objectMapper.createObjectNode();
|
|
||||||
node.put("name", request.names().get(language));
|
|
||||||
node.put("excerpt", request.excerpts().get(language));
|
|
||||||
node.put("description", request.descriptions().get(language));
|
|
||||||
node.put("seoTitle", request.seoTitles().get(language));
|
|
||||||
node.put("seoDescription", request.seoDescriptions().get(language));
|
|
||||||
return node;
|
|
||||||
}
|
|
||||||
|
|
||||||
private ObjectNode existingTranslationsNode(NormalizedTranslationRequest request, List<String> targetLanguages) {
|
|
||||||
ObjectNode node = objectMapper.createObjectNode();
|
|
||||||
for (String language : targetLanguages) {
|
|
||||||
node.set(language, localizedFieldNode(request, language));
|
|
||||||
}
|
|
||||||
return node;
|
|
||||||
}
|
|
||||||
|
|
||||||
private ObjectNode buildTranslationToolSchema(List<String> targetLanguages) {
|
|
||||||
ObjectNode root = objectMapper.createObjectNode();
|
|
||||||
root.put("type", "object");
|
|
||||||
root.put("additionalProperties", false);
|
|
||||||
|
|
||||||
ObjectNode properties = root.putObject("properties");
|
|
||||||
ObjectNode translations = properties.putObject("translations");
|
|
||||||
translations.put("type", "object");
|
|
||||||
translations.put("additionalProperties", false);
|
|
||||||
|
|
||||||
ObjectNode translationProperties = translations.putObject("properties");
|
|
||||||
ArrayNode requiredTranslations = translations.putArray("required");
|
|
||||||
for (String language : targetLanguages) {
|
|
||||||
translationProperties.set(language, buildTranslationSchemaForLanguage(language));
|
|
||||||
requiredTranslations.add(language);
|
|
||||||
}
|
|
||||||
|
|
||||||
ArrayNode required = root.putArray("required");
|
|
||||||
required.add("translations");
|
|
||||||
return root;
|
|
||||||
}
|
|
||||||
|
|
||||||
private ObjectNode buildTranslationSchemaForLanguage(String language) {
|
|
||||||
ObjectNode languageSchema = objectMapper.createObjectNode();
|
|
||||||
languageSchema.put("type", "object");
|
|
||||||
languageSchema.put("additionalProperties", false);
|
|
||||||
languageSchema.put("description", "Localized product copy for language " + language);
|
|
||||||
|
|
||||||
ObjectNode properties = languageSchema.putObject("properties");
|
|
||||||
addSchemaString(properties, "name", "Translated product name. Never empty.");
|
|
||||||
addSchemaString(properties, "excerpt", "Short excerpt. Empty string if source excerpt is empty.");
|
|
||||||
addSchemaString(properties, "description", "Product description as safe HTML or empty string if source description is empty.");
|
|
||||||
addSchemaString(properties, "seoTitle", "SEO title. Empty string if source SEO title is empty.");
|
|
||||||
addSchemaString(properties, "seoDescription", "SEO description, ideally under 160 characters. Empty string if source SEO description is empty.");
|
|
||||||
|
|
||||||
ArrayNode required = languageSchema.putArray("required");
|
|
||||||
required.add("name");
|
|
||||||
required.add("excerpt");
|
|
||||||
required.add("description");
|
|
||||||
required.add("seoTitle");
|
|
||||||
required.add("seoDescription");
|
|
||||||
return languageSchema;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void addSchemaString(ObjectNode properties, String name, String description) {
|
|
||||||
ObjectNode property = properties.putObject(name);
|
|
||||||
property.put("type", "string");
|
|
||||||
property.put("description", description);
|
|
||||||
}
|
|
||||||
|
|
||||||
private TranslationBundle callOpenAiFunction(String functionName,
|
|
||||||
String functionDescription,
|
|
||||||
String instructions,
|
|
||||||
String input,
|
|
||||||
ObjectNode parametersSchema,
|
|
||||||
String cacheSuffix) {
|
|
||||||
ObjectNode requestPayload = objectMapper.createObjectNode();
|
|
||||||
requestPayload.put("model", model);
|
|
||||||
requestPayload.put("instructions", instructions);
|
|
||||||
requestPayload.put("input", input);
|
|
||||||
requestPayload.put("tool_choice", "required");
|
|
||||||
requestPayload.put("temperature", 0.2);
|
|
||||||
requestPayload.put("store", false);
|
|
||||||
requestPayload.put("prompt_cache_key", promptCacheKeyPrefix + ":" + cacheSuffix);
|
|
||||||
|
|
||||||
ArrayNode tools = requestPayload.putArray("tools");
|
|
||||||
ObjectNode tool = tools.addObject();
|
|
||||||
tool.put("type", "function");
|
|
||||||
tool.put("name", functionName);
|
|
||||||
tool.put("description", functionDescription);
|
|
||||||
tool.put("strict", true);
|
|
||||||
tool.set("parameters", parametersSchema);
|
|
||||||
|
|
||||||
JsonNode responseNode = postResponsesRequest(requestPayload);
|
|
||||||
JsonNode output = responseNode.path("output");
|
|
||||||
if (output.isArray()) {
|
|
||||||
for (JsonNode item : output) {
|
|
||||||
if ("function_call".equals(item.path("type").asText())) {
|
|
||||||
String arguments = item.path("arguments").asText("");
|
|
||||||
if (arguments.isBlank()) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
JsonNode argumentsNode = objectMapper.readTree(arguments);
|
|
||||||
JsonNode translationsNode = argumentsNode.path("translations");
|
|
||||||
if (!translationsNode.isObject()) {
|
|
||||||
throw new ResponseStatusException(
|
|
||||||
HttpStatus.BAD_GATEWAY,
|
|
||||||
"OpenAI returned a function call without translations"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return TranslationBundle.fromJson(translationsNode);
|
|
||||||
} catch (JsonProcessingException exception) {
|
|
||||||
throw new ResponseStatusException(
|
|
||||||
HttpStatus.BAD_GATEWAY,
|
|
||||||
"OpenAI returned invalid JSON arguments",
|
|
||||||
exception
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new ResponseStatusException(
|
|
||||||
HttpStatus.BAD_GATEWAY,
|
|
||||||
"OpenAI did not return the expected function call"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private JsonNode postResponsesRequest(ObjectNode requestPayload) {
|
|
||||||
HttpRequest request = HttpRequest.newBuilder()
|
|
||||||
.uri(URI.create(baseUrl + "/responses"))
|
|
||||||
.timeout(timeout)
|
|
||||||
.header("Authorization", "Bearer " + apiKey)
|
|
||||||
.header("Content-Type", "application/json")
|
|
||||||
.POST(HttpRequest.BodyPublishers.ofString(writeJson(requestPayload)))
|
|
||||||
.build();
|
|
||||||
|
|
||||||
try {
|
|
||||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
|
||||||
JsonNode body = readJson(response.body());
|
|
||||||
if (response.statusCode() >= 400) {
|
|
||||||
String message = body.path("error").path("message").asText("").trim();
|
|
||||||
throw new ResponseStatusException(
|
|
||||||
HttpStatus.BAD_GATEWAY,
|
|
||||||
message.isBlank() ? "OpenAI translation request failed" : message
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return body;
|
|
||||||
} catch (IOException exception) {
|
|
||||||
throw new ResponseStatusException(
|
|
||||||
HttpStatus.BAD_GATEWAY,
|
|
||||||
"Unable to read the OpenAI translation response",
|
|
||||||
exception
|
|
||||||
);
|
|
||||||
} catch (InterruptedException exception) {
|
|
||||||
Thread.currentThread().interrupt();
|
|
||||||
throw new ResponseStatusException(
|
|
||||||
HttpStatus.BAD_GATEWAY,
|
|
||||||
"The OpenAI translation request was interrupted",
|
|
||||||
exception
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<String> buildValidationNotes(TranslationBundle bundle, List<String> targetLanguages) {
|
|
||||||
List<String> notes = new ArrayList<>();
|
|
||||||
for (String language : targetLanguages) {
|
|
||||||
if (bundle.names().getOrDefault(language, "").isBlank()) {
|
|
||||||
notes.add(language + ": translated name is empty and must be fixed");
|
|
||||||
}
|
|
||||||
String seoDescription = bundle.seoDescriptions().getOrDefault(language, "");
|
|
||||||
if (seoDescription.length() > 160) {
|
|
||||||
notes.add(language + ": seoDescription exceeds 160 characters and must be shortened");
|
|
||||||
}
|
|
||||||
String description = bundle.descriptions().getOrDefault(language, "");
|
|
||||||
if (!description.isBlank() && normalizeRichTextOptional(description) == null) {
|
|
||||||
notes.add(language + ": description lost meaningful text during sanitization");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (notes.isEmpty()) {
|
|
||||||
notes.add("No structural validation issues were found. Review naturalness, terminology, SEO clarity, and consistency.");
|
|
||||||
}
|
|
||||||
return notes;
|
|
||||||
}
|
|
||||||
|
|
||||||
private TranslationBundle sanitizeBundle(TranslationBundle bundle, List<String> targetLanguages) {
|
|
||||||
Map<String, String> names = new LinkedHashMap<>();
|
|
||||||
Map<String, String> excerpts = new LinkedHashMap<>();
|
|
||||||
Map<String, String> descriptions = new LinkedHashMap<>();
|
|
||||||
Map<String, String> seoTitles = new LinkedHashMap<>();
|
|
||||||
Map<String, String> seoDescriptions = new LinkedHashMap<>();
|
|
||||||
|
|
||||||
for (String language : targetLanguages) {
|
|
||||||
names.put(language, safeValue(bundle.names().get(language)));
|
|
||||||
excerpts.put(language, safeValue(bundle.excerpts().get(language)));
|
|
||||||
descriptions.put(language, safeDescription(bundle.descriptions().get(language)));
|
|
||||||
seoTitles.put(language, safeValue(bundle.seoTitles().get(language)));
|
|
||||||
seoDescriptions.put(language, limitSeoDescription(safeValue(bundle.seoDescriptions().get(language))));
|
|
||||||
}
|
|
||||||
|
|
||||||
return new TranslationBundle(names, excerpts, descriptions, seoTitles, seoDescriptions);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void ensureRequiredTranslations(TranslationBundle bundle, List<String> targetLanguages) {
|
|
||||||
for (String language : targetLanguages) {
|
|
||||||
if (bundle.names().getOrDefault(language, "").isBlank()) {
|
|
||||||
throw new ResponseStatusException(
|
|
||||||
HttpStatus.BAD_GATEWAY,
|
|
||||||
"OpenAI did not return a valid translated name for " + language.toUpperCase(Locale.ROOT)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private AdminTranslateShopProductResponse toResponse(String sourceLanguage,
|
|
||||||
List<String> targetLanguages,
|
|
||||||
TranslationBundle bundle) {
|
|
||||||
AdminTranslateShopProductResponse response = new AdminTranslateShopProductResponse();
|
|
||||||
response.setSourceLanguage(sourceLanguage);
|
|
||||||
response.setTargetLanguages(targetLanguages);
|
|
||||||
response.setNames(bundle.names());
|
|
||||||
response.setExcerpts(bundle.excerpts());
|
|
||||||
response.setDescriptions(bundle.descriptions());
|
|
||||||
response.setSeoTitles(bundle.seoTitles());
|
|
||||||
response.setSeoDescriptions(bundle.seoDescriptions());
|
|
||||||
return response;
|
|
||||||
}
|
|
||||||
|
|
||||||
private AdminTranslateShopProductResponse emptyResponse(String sourceLanguage) {
|
|
||||||
AdminTranslateShopProductResponse response = new AdminTranslateShopProductResponse();
|
|
||||||
response.setSourceLanguage(sourceLanguage);
|
|
||||||
response.setTargetLanguages(List.of());
|
|
||||||
response.setNames(Map.of());
|
|
||||||
response.setExcerpts(Map.of());
|
|
||||||
response.setDescriptions(Map.of());
|
|
||||||
response.setSeoTitles(Map.of());
|
|
||||||
response.setSeoDescriptions(Map.of());
|
|
||||||
return response;
|
|
||||||
}
|
|
||||||
|
|
||||||
private Map<String, String> normalizeLocalizedMap(Map<String, String> rawValues, boolean richText) {
|
|
||||||
Map<String, String> normalized = new LinkedHashMap<>();
|
|
||||||
for (String language : SUPPORTED_LANGUAGES) {
|
|
||||||
String value = rawValues != null ? rawValues.get(language) : null;
|
|
||||||
if (richText) {
|
|
||||||
normalized.put(language, normalizeRichTextOptional(value) != null ? normalizeRichTextOptional(value) : "");
|
|
||||||
} else {
|
|
||||||
normalized.put(language, safeValue(value));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return normalized;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String safeValue(String value) {
|
|
||||||
return value == null ? "" : value.trim();
|
|
||||||
}
|
|
||||||
|
|
||||||
private String safeDescription(String value) {
|
|
||||||
String normalized = normalizeRichTextOptional(value);
|
|
||||||
return normalized != null ? normalized : "";
|
|
||||||
}
|
|
||||||
|
|
||||||
private String limitSeoDescription(String value) {
|
|
||||||
String normalized = safeValue(value);
|
|
||||||
if (normalized.length() <= 160) {
|
|
||||||
return normalized;
|
|
||||||
}
|
|
||||||
int lastSpace = normalized.lastIndexOf(' ', 157);
|
|
||||||
if (lastSpace >= 120) {
|
|
||||||
return normalized.substring(0, lastSpace).trim();
|
|
||||||
}
|
|
||||||
return normalized.substring(0, 160).trim();
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeOptional(String value) {
|
|
||||||
if (value == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
String normalized = value.trim();
|
|
||||||
return normalized.isBlank() ? null : normalized;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeLanguage(String language) {
|
|
||||||
if (language == null) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
String normalized = language.trim().toLowerCase(Locale.ROOT);
|
|
||||||
int separatorIndex = normalized.indexOf('-');
|
|
||||||
if (separatorIndex > 0) {
|
|
||||||
normalized = normalized.substring(0, separatorIndex);
|
|
||||||
}
|
|
||||||
return normalized;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeRichTextOptional(String value) {
|
|
||||||
String normalized = normalizeOptional(value);
|
|
||||||
if (normalized == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
String sanitized = Jsoup.clean(
|
|
||||||
normalized,
|
|
||||||
"",
|
|
||||||
PRODUCT_DESCRIPTION_SAFELIST,
|
|
||||||
new Document.OutputSettings().prettyPrint(false)
|
|
||||||
).trim();
|
|
||||||
if (sanitized.isBlank()) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
String plainText = Jsoup.parse(sanitized).text();
|
|
||||||
return plainText != null && !plainText.trim().isEmpty() ? sanitized : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeBaseUrl(String rawBaseUrl) {
|
|
||||||
String normalized = rawBaseUrl != null && !rawBaseUrl.isBlank()
|
|
||||||
? rawBaseUrl.trim()
|
|
||||||
: "https://api.openai.com/v1";
|
|
||||||
while (normalized.endsWith("/")) {
|
|
||||||
normalized = normalized.substring(0, normalized.length() - 1);
|
|
||||||
}
|
|
||||||
return normalized;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String writeJson(Object value) {
|
|
||||||
try {
|
|
||||||
return objectMapper.writeValueAsString(value);
|
|
||||||
} catch (JsonProcessingException exception) {
|
|
||||||
throw new ResponseStatusException(
|
|
||||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
|
||||||
"Unable to serialize translation payload",
|
|
||||||
exception
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private JsonNode readJson(String rawJson) throws IOException {
|
|
||||||
return objectMapper.readTree(rawJson);
|
|
||||||
}
|
|
||||||
|
|
||||||
private record NormalizedTranslationRequest(UUID categoryId,
|
|
||||||
String sourceLanguage,
|
|
||||||
boolean overwriteExisting,
|
|
||||||
List<String> materialCodes,
|
|
||||||
Map<String, String> names,
|
|
||||||
Map<String, String> excerpts,
|
|
||||||
Map<String, String> descriptions,
|
|
||||||
Map<String, String> seoTitles,
|
|
||||||
Map<String, String> seoDescriptions) {
|
|
||||||
}
|
|
||||||
|
|
||||||
private record CategoryContext(String slug,
|
|
||||||
Map<String, String> names,
|
|
||||||
Map<String, String> descriptions) {
|
|
||||||
}
|
|
||||||
|
|
||||||
private record TranslationBundle(Map<String, String> names,
|
|
||||||
Map<String, String> excerpts,
|
|
||||||
Map<String, String> descriptions,
|
|
||||||
Map<String, String> seoTitles,
|
|
||||||
Map<String, String> seoDescriptions) {
|
|
||||||
static TranslationBundle fromJson(JsonNode translationsNode) {
|
|
||||||
Map<String, String> names = new LinkedHashMap<>();
|
|
||||||
Map<String, String> excerpts = new LinkedHashMap<>();
|
|
||||||
Map<String, String> descriptions = new LinkedHashMap<>();
|
|
||||||
Map<String, String> seoTitles = new LinkedHashMap<>();
|
|
||||||
Map<String, String> seoDescriptions = new LinkedHashMap<>();
|
|
||||||
|
|
||||||
translationsNode.fieldNames().forEachRemaining(language -> {
|
|
||||||
JsonNode localizedNode = translationsNode.path(language);
|
|
||||||
names.put(language, localizedNode.path("name").asText(""));
|
|
||||||
excerpts.put(language, localizedNode.path("excerpt").asText(""));
|
|
||||||
descriptions.put(language, localizedNode.path("description").asText(""));
|
|
||||||
seoTitles.put(language, localizedNode.path("seoTitle").asText(""));
|
|
||||||
seoDescriptions.put(language, localizedNode.path("seoDescription").asText(""));
|
|
||||||
});
|
|
||||||
|
|
||||||
return new TranslationBundle(names, excerpts, descriptions, seoTitles, seoDescriptions);
|
|
||||||
}
|
|
||||||
|
|
||||||
ObjectNode toJsonNode(ObjectMapper objectMapper) {
|
|
||||||
ObjectNode root = objectMapper.createObjectNode();
|
|
||||||
ObjectNode translations = root.putObject("translations");
|
|
||||||
for (String language : names.keySet()) {
|
|
||||||
ObjectNode languageNode = translations.putObject(language);
|
|
||||||
languageNode.put("name", names.getOrDefault(language, ""));
|
|
||||||
languageNode.put("excerpt", excerpts.getOrDefault(language, ""));
|
|
||||||
languageNode.put("description", descriptions.getOrDefault(language, ""));
|
|
||||||
languageNode.put("seoTitle", seoTitles.getOrDefault(language, ""));
|
|
||||||
languageNode.put("seoDescription", seoDescriptions.getOrDefault(language, ""));
|
|
||||||
}
|
|
||||||
return root;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,347 +0,0 @@
|
|||||||
package com.printcalculator.service.media;
|
|
||||||
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.InputStream;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.nio.file.InvalidPathException;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.Collections;
|
|
||||||
import java.util.LinkedHashSet;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Locale;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Set;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
public class MediaFfmpegService {
|
|
||||||
|
|
||||||
private static final Logger logger = LoggerFactory.getLogger(MediaFfmpegService.class);
|
|
||||||
|
|
||||||
private static final Map<String, List<String>> ENCODER_CANDIDATES = Map.of(
|
|
||||||
"JPEG", List.of("mjpeg"),
|
|
||||||
"WEBP", List.of("libwebp", "webp"),
|
|
||||||
"AVIF", List.of("libaom-av1", "librav1e", "libsvtav1")
|
|
||||||
);
|
|
||||||
private static final Map<String, List<String>> REQUIRED_MUXERS = Map.of(
|
|
||||||
"AVIF", List.of("avif")
|
|
||||||
);
|
|
||||||
|
|
||||||
private final String ffmpegExecutable;
|
|
||||||
private final Set<String> availableEncoders;
|
|
||||||
private final Set<String> availableMuxers;
|
|
||||||
|
|
||||||
public MediaFfmpegService(@Value("${media.ffmpeg.path:ffmpeg}") String ffmpegPath) {
|
|
||||||
this.ffmpegExecutable = resolveExecutable(ffmpegPath);
|
|
||||||
this.availableEncoders = Collections.unmodifiableSet(loadAvailableEncoders());
|
|
||||||
this.availableMuxers = Collections.unmodifiableSet(loadAvailableMuxers());
|
|
||||||
}
|
|
||||||
|
|
||||||
public void generateVariant(Path source, Path target, int widthPx, int heightPx, String format) throws IOException {
|
|
||||||
if (widthPx <= 0 || heightPx <= 0) {
|
|
||||||
throw new IllegalArgumentException("Variant dimensions must be positive.");
|
|
||||||
}
|
|
||||||
|
|
||||||
Path sourcePath = sanitizeMediaPath(source, "source", true);
|
|
||||||
Path targetPath = sanitizeMediaPath(target, "target", false);
|
|
||||||
Files.createDirectories(targetPath.getParent());
|
|
||||||
|
|
||||||
String normalizedFormat = normalizeFormat(format);
|
|
||||||
String encoder = resolveEncoder(normalizedFormat);
|
|
||||||
if (encoder == null) {
|
|
||||||
throw new IOException("FFmpeg encoder not available for media format " + normalizedFormat + ".");
|
|
||||||
}
|
|
||||||
if (!hasRequiredMuxer(normalizedFormat)) {
|
|
||||||
throw new IOException("FFmpeg muxer not available for media format " + normalizedFormat + ".");
|
|
||||||
}
|
|
||||||
|
|
||||||
List<String> command = new ArrayList<>();
|
|
||||||
command.add(ffmpegExecutable);
|
|
||||||
command.add("-y");
|
|
||||||
command.add("-hide_banner");
|
|
||||||
command.add("-loglevel");
|
|
||||||
command.add("error");
|
|
||||||
command.add("-i");
|
|
||||||
command.add(sourcePath.toString());
|
|
||||||
command.add("-vf");
|
|
||||||
command.add("scale=" + widthPx + ":" + heightPx + ":flags=lanczos,setsar=1");
|
|
||||||
command.add("-frames:v");
|
|
||||||
command.add("1");
|
|
||||||
command.add("-an");
|
|
||||||
|
|
||||||
switch (normalizedFormat) {
|
|
||||||
case "JPEG" -> {
|
|
||||||
command.add("-c:v");
|
|
||||||
command.add(encoder);
|
|
||||||
command.add("-q:v");
|
|
||||||
command.add("2");
|
|
||||||
}
|
|
||||||
case "WEBP" -> {
|
|
||||||
command.add("-c:v");
|
|
||||||
command.add(encoder);
|
|
||||||
command.add("-quality");
|
|
||||||
command.add("82");
|
|
||||||
}
|
|
||||||
case "AVIF" -> {
|
|
||||||
command.add("-c:v");
|
|
||||||
command.add(encoder);
|
|
||||||
command.add("-crf");
|
|
||||||
command.add("30");
|
|
||||||
command.add("-b:v");
|
|
||||||
command.add("0");
|
|
||||||
command.add("-f");
|
|
||||||
command.add("avif");
|
|
||||||
}
|
|
||||||
default -> throw new IllegalArgumentException("Unsupported media format: " + normalizedFormat);
|
|
||||||
}
|
|
||||||
|
|
||||||
command.add(targetPath.toString());
|
|
||||||
|
|
||||||
Process process = startValidatedProcess(command);
|
|
||||||
String output;
|
|
||||||
try (InputStream processStream = process.getInputStream()) {
|
|
||||||
output = new String(processStream.readAllBytes(), StandardCharsets.UTF_8);
|
|
||||||
}
|
|
||||||
|
|
||||||
int exitCode;
|
|
||||||
try {
|
|
||||||
exitCode = process.waitFor();
|
|
||||||
} catch (InterruptedException e) {
|
|
||||||
Thread.currentThread().interrupt();
|
|
||||||
throw new IOException("FFmpeg execution interrupted.", e);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (exitCode != 0 || !Files.exists(targetPath) || Files.size(targetPath) == 0) {
|
|
||||||
throw new IOException("FFmpeg failed to generate media variant. " + truncate(output));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean canEncode(String format) {
|
|
||||||
String normalizedFormat = normalizeFormat(format);
|
|
||||||
return resolveEncoder(normalizedFormat) != null && hasRequiredMuxer(normalizedFormat);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String resolveEncoder(String format) {
|
|
||||||
String normalizedFormat = normalizeFormat(format);
|
|
||||||
if (normalizedFormat == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
List<String> candidates = ENCODER_CANDIDATES.get(normalizedFormat);
|
|
||||||
if (candidates == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return candidates.stream()
|
|
||||||
.filter(availableEncoders::contains)
|
|
||||||
.findFirst()
|
|
||||||
.orElse(null);
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean hasRequiredMuxer(String format) {
|
|
||||||
List<String> requiredMuxers = REQUIRED_MUXERS.get(format);
|
|
||||||
if (requiredMuxers == null || requiredMuxers.isEmpty()) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return requiredMuxers.stream().anyMatch(availableMuxers::contains);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeFormat(String format) {
|
|
||||||
if (format == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return format.trim().toUpperCase(Locale.ROOT);
|
|
||||||
}
|
|
||||||
|
|
||||||
private Set<String> loadAvailableEncoders() {
|
|
||||||
List<String> command = List.of(ffmpegExecutable, "-hide_banner", "-encoders");
|
|
||||||
try {
|
|
||||||
Process process = startValidatedProcess(command);
|
|
||||||
String output;
|
|
||||||
try (InputStream processStream = process.getInputStream()) {
|
|
||||||
output = new String(processStream.readAllBytes(), StandardCharsets.UTF_8);
|
|
||||||
}
|
|
||||||
|
|
||||||
int exitCode = process.waitFor();
|
|
||||||
if (exitCode != 0) {
|
|
||||||
logger.warn("Unable to inspect FFmpeg encoders. Falling back to empty encoder list.");
|
|
||||||
return Set.of();
|
|
||||||
}
|
|
||||||
return parseAvailableEncoders(output);
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.warn(
|
|
||||||
"Unable to inspect FFmpeg encoders for executable '{}'. Falling back to empty encoder list. {}",
|
|
||||||
ffmpegExecutable,
|
|
||||||
e.getMessage()
|
|
||||||
);
|
|
||||||
return Set.of();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private Set<String> loadAvailableMuxers() {
|
|
||||||
List<String> command = List.of(ffmpegExecutable, "-hide_banner", "-muxers");
|
|
||||||
try {
|
|
||||||
Process process = startValidatedProcess(command);
|
|
||||||
String output;
|
|
||||||
try (InputStream processStream = process.getInputStream()) {
|
|
||||||
output = new String(processStream.readAllBytes(), StandardCharsets.UTF_8);
|
|
||||||
}
|
|
||||||
|
|
||||||
int exitCode = process.waitFor();
|
|
||||||
if (exitCode != 0) {
|
|
||||||
logger.warn("Unable to inspect FFmpeg muxers. Falling back to empty muxer list.");
|
|
||||||
return Set.of();
|
|
||||||
}
|
|
||||||
return parseAvailableMuxers(output);
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.warn(
|
|
||||||
"Unable to inspect FFmpeg muxers for executable '{}'. Falling back to empty muxer list. {}",
|
|
||||||
ffmpegExecutable,
|
|
||||||
e.getMessage()
|
|
||||||
);
|
|
||||||
return Set.of();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private Process startValidatedProcess(List<String> command) throws IOException {
|
|
||||||
// nosemgrep: java.lang.security.audit.command-injection-process-builder.command-injection-process-builder
|
|
||||||
return new ProcessBuilder(List.copyOf(command))
|
|
||||||
.redirectErrorStream(true)
|
|
||||||
.start();
|
|
||||||
}
|
|
||||||
|
|
||||||
static String sanitizeExecutable(String configuredExecutable) {
|
|
||||||
if (configuredExecutable == null) {
|
|
||||||
throw new IllegalArgumentException("media.ffmpeg.path must not be null.");
|
|
||||||
}
|
|
||||||
|
|
||||||
String candidate = configuredExecutable.trim();
|
|
||||||
if (candidate.isEmpty()) {
|
|
||||||
throw new IllegalArgumentException("media.ffmpeg.path must point to an FFmpeg executable.");
|
|
||||||
}
|
|
||||||
if (candidate.chars().anyMatch(Character::isISOControl)) {
|
|
||||||
throw new IllegalArgumentException("media.ffmpeg.path contains control characters.");
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
Path executablePath = Path.of(candidate);
|
|
||||||
Path filename = executablePath.getFileName();
|
|
||||||
String executableName = filename == null ? candidate : filename.toString();
|
|
||||||
if (executableName.isBlank() || executableName.startsWith("-")) {
|
|
||||||
throw new IllegalArgumentException("media.ffmpeg.path must be an executable path, not an option.");
|
|
||||||
}
|
|
||||||
|
|
||||||
return executablePath.normalize().toString();
|
|
||||||
} catch (InvalidPathException e) {
|
|
||||||
throw new IllegalArgumentException("media.ffmpeg.path is not a valid executable path.", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static String resolveExecutable(String configuredExecutable) {
|
|
||||||
String candidate = sanitizeExecutable(configuredExecutable);
|
|
||||||
|
|
||||||
try {
|
|
||||||
Path configuredPath = Path.of(candidate);
|
|
||||||
if (!configuredPath.isAbsolute()) {
|
|
||||||
return candidate;
|
|
||||||
}
|
|
||||||
if (Files.isExecutable(configuredPath)) {
|
|
||||||
return configuredPath.toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
Path filename = configuredPath.getFileName();
|
|
||||||
String fallbackExecutable = filename == null ? null : filename.toString();
|
|
||||||
if (fallbackExecutable != null && !fallbackExecutable.isBlank()) {
|
|
||||||
logger.warn(
|
|
||||||
"Configured FFmpeg executable '{}' not found or not executable. Falling back to '{}' from PATH.",
|
|
||||||
configuredPath,
|
|
||||||
fallbackExecutable
|
|
||||||
);
|
|
||||||
return fallbackExecutable;
|
|
||||||
}
|
|
||||||
return candidate;
|
|
||||||
} catch (InvalidPathException e) {
|
|
||||||
throw new IllegalArgumentException("media.ffmpeg.path is not a valid executable path.", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private Path sanitizeMediaPath(Path path, String label, boolean requireExistingFile) throws IOException {
|
|
||||||
if (path == null) {
|
|
||||||
throw new IllegalArgumentException("Media " + label + " path is required.");
|
|
||||||
}
|
|
||||||
|
|
||||||
Path normalized = path.toAbsolutePath().normalize();
|
|
||||||
Path filename = normalized.getFileName();
|
|
||||||
if (filename == null || filename.toString().isBlank()) {
|
|
||||||
throw new IOException("Media " + label + " path must include a file name.");
|
|
||||||
}
|
|
||||||
if (filename.toString().startsWith("-")) {
|
|
||||||
throw new IOException("Media " + label + " file name must not start with '-'.");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (requireExistingFile) {
|
|
||||||
if (!Files.isRegularFile(normalized) || !Files.isReadable(normalized)) {
|
|
||||||
throw new IOException("Media " + label + " file is not readable.");
|
|
||||||
}
|
|
||||||
} else if (normalized.getParent() == null) {
|
|
||||||
throw new IOException("Media " + label + " path must include a parent directory.");
|
|
||||||
}
|
|
||||||
|
|
||||||
return normalized;
|
|
||||||
}
|
|
||||||
|
|
||||||
private Set<String> parseAvailableEncoders(String output) {
|
|
||||||
if (output == null || output.isBlank()) {
|
|
||||||
return Set.of();
|
|
||||||
}
|
|
||||||
|
|
||||||
Set<String> encoders = new LinkedHashSet<>();
|
|
||||||
for (String line : output.split("\\R")) {
|
|
||||||
String trimmed = line.trim();
|
|
||||||
if (trimmed.isBlank() || trimmed.startsWith("--") || trimmed.startsWith("Encoders:")) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (trimmed.length() < 7) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
String[] parts = trimmed.split("\\s+", 3);
|
|
||||||
if (parts.length < 2) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
encoders.add(parts[1]);
|
|
||||||
}
|
|
||||||
return encoders;
|
|
||||||
}
|
|
||||||
|
|
||||||
private Set<String> parseAvailableMuxers(String output) {
|
|
||||||
if (output == null || output.isBlank()) {
|
|
||||||
return Set.of();
|
|
||||||
}
|
|
||||||
|
|
||||||
Set<String> muxers = new LinkedHashSet<>();
|
|
||||||
for (String line : output.split("\\R")) {
|
|
||||||
String trimmed = line.trim();
|
|
||||||
if (trimmed.isBlank() || trimmed.startsWith("--") || trimmed.startsWith("Muxers:")) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
String[] parts = trimmed.split("\\s+", 3);
|
|
||||||
if (parts.length < 2) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
muxers.add(parts[1]);
|
|
||||||
}
|
|
||||||
return muxers;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String truncate(String output) {
|
|
||||||
if (output == null || output.isBlank()) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
String normalized = output.trim().replace('\n', ' ');
|
|
||||||
return normalized.length() <= 300 ? normalized : normalized.substring(0, 300);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,122 +0,0 @@
|
|||||||
package com.printcalculator.service.media;
|
|
||||||
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
|
|
||||||
import javax.imageio.ImageIO;
|
|
||||||
import java.awt.image.BufferedImage;
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.InputStream;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
public class MediaImageInspector {
|
|
||||||
|
|
||||||
private static final byte[] PNG_SIGNATURE = new byte[]{
|
|
||||||
(byte) 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A
|
|
||||||
};
|
|
||||||
|
|
||||||
public ImageMetadata inspect(Path file) throws IOException {
|
|
||||||
try (InputStream inputStream = Files.newInputStream(file)) {
|
|
||||||
byte[] header = inputStream.readNBytes(64);
|
|
||||||
if (isJpeg(header)) {
|
|
||||||
return readWithImageIo(file, "image/jpeg", "jpg");
|
|
||||||
}
|
|
||||||
if (isPng(header)) {
|
|
||||||
return readWithImageIo(file, "image/png", "png");
|
|
||||||
}
|
|
||||||
if (isWebp(header)) {
|
|
||||||
Dimensions dimensions = readWebpDimensions(header);
|
|
||||||
return new ImageMetadata("image/webp", "webp", dimensions.width(), dimensions.height());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new IllegalArgumentException("Unsupported image type. Allowed: jpg, jpeg, png, webp.");
|
|
||||||
}
|
|
||||||
|
|
||||||
private ImageMetadata readWithImageIo(Path file, String mimeType, String extension) throws IOException {
|
|
||||||
BufferedImage image = ImageIO.read(file.toFile());
|
|
||||||
if (image == null || image.getWidth() <= 0 || image.getHeight() <= 0) {
|
|
||||||
throw new IllegalArgumentException("Uploaded image is invalid or unreadable.");
|
|
||||||
}
|
|
||||||
return new ImageMetadata(mimeType, extension, image.getWidth(), image.getHeight());
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean isJpeg(byte[] header) {
|
|
||||||
return header.length >= 3
|
|
||||||
&& (header[0] & 0xFF) == 0xFF
|
|
||||||
&& (header[1] & 0xFF) == 0xD8
|
|
||||||
&& (header[2] & 0xFF) == 0xFF;
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean isPng(byte[] header) {
|
|
||||||
if (header.length < PNG_SIGNATURE.length) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
for (int i = 0; i < PNG_SIGNATURE.length; i++) {
|
|
||||||
if (header[i] != PNG_SIGNATURE[i]) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean isWebp(byte[] header) {
|
|
||||||
return header.length >= 16
|
|
||||||
&& "RIFF".equals(ascii(header, 0, 4))
|
|
||||||
&& "WEBP".equals(ascii(header, 8, 4));
|
|
||||||
}
|
|
||||||
|
|
||||||
private Dimensions readWebpDimensions(byte[] header) {
|
|
||||||
if (header.length < 30) {
|
|
||||||
throw new IllegalArgumentException("Uploaded WebP image is invalid.");
|
|
||||||
}
|
|
||||||
|
|
||||||
String chunkType = ascii(header, 12, 4);
|
|
||||||
return switch (chunkType) {
|
|
||||||
case "VP8X" -> new Dimensions(
|
|
||||||
littleEndian24(header, 24) + 1,
|
|
||||||
littleEndian24(header, 27) + 1
|
|
||||||
);
|
|
||||||
case "VP8 " -> new Dimensions(
|
|
||||||
littleEndian16(header, 26) & 0x3FFF,
|
|
||||||
littleEndian16(header, 28) & 0x3FFF
|
|
||||||
);
|
|
||||||
case "VP8L" -> {
|
|
||||||
int packed = littleEndian32(header, 21);
|
|
||||||
int width = (packed & 0x3FFF) + 1;
|
|
||||||
int height = ((packed >> 14) & 0x3FFF) + 1;
|
|
||||||
yield new Dimensions(width, height);
|
|
||||||
}
|
|
||||||
default -> throw new IllegalArgumentException("Uploaded WebP image is invalid.");
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private String ascii(byte[] header, int offset, int length) {
|
|
||||||
return new String(header, offset, length, StandardCharsets.US_ASCII);
|
|
||||||
}
|
|
||||||
|
|
||||||
private int littleEndian16(byte[] header, int offset) {
|
|
||||||
return (header[offset] & 0xFF) | ((header[offset + 1] & 0xFF) << 8);
|
|
||||||
}
|
|
||||||
|
|
||||||
private int littleEndian24(byte[] header, int offset) {
|
|
||||||
return (header[offset] & 0xFF)
|
|
||||||
| ((header[offset + 1] & 0xFF) << 8)
|
|
||||||
| ((header[offset + 2] & 0xFF) << 16);
|
|
||||||
}
|
|
||||||
|
|
||||||
private int littleEndian32(byte[] header, int offset) {
|
|
||||||
return (header[offset] & 0xFF)
|
|
||||||
| ((header[offset + 1] & 0xFF) << 8)
|
|
||||||
| ((header[offset + 2] & 0xFF) << 16)
|
|
||||||
| ((header[offset + 3] & 0xFF) << 24);
|
|
||||||
}
|
|
||||||
|
|
||||||
private record Dimensions(int width, int height) {
|
|
||||||
}
|
|
||||||
|
|
||||||
public record ImageMetadata(String mimeType, String fileExtension, int widthPx, int heightPx) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,145 +0,0 @@
|
|||||||
package com.printcalculator.service.media;
|
|
||||||
|
|
||||||
import com.printcalculator.exception.StorageException;
|
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.nio.file.Paths;
|
|
||||||
import java.nio.file.StandardCopyOption;
|
|
||||||
import java.util.Locale;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
public class MediaStorageService {
|
|
||||||
|
|
||||||
private final Path normalizedRootLocation;
|
|
||||||
private final Path originalRootLocation;
|
|
||||||
private final Path publicRootLocation;
|
|
||||||
private final Path privateRootLocation;
|
|
||||||
private final String frontendBaseUrl;
|
|
||||||
|
|
||||||
public MediaStorageService(@Value("${media.storage.root:storage_media}") String storageRoot,
|
|
||||||
@Value("${app.frontend.base-url:${APP_FRONTEND_BASE_URL:http://localhost:8081}}") String frontendBaseUrl) {
|
|
||||||
this.normalizedRootLocation = Paths.get(storageRoot).toAbsolutePath().normalize();
|
|
||||||
this.originalRootLocation = normalizedRootLocation.resolve("original").normalize();
|
|
||||||
this.publicRootLocation = normalizedRootLocation.resolve("public").normalize();
|
|
||||||
this.privateRootLocation = normalizedRootLocation.resolve("private").normalize();
|
|
||||||
this.frontendBaseUrl = frontendBaseUrl;
|
|
||||||
init();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void init() {
|
|
||||||
try {
|
|
||||||
Files.createDirectories(originalRootLocation);
|
|
||||||
Files.createDirectories(publicRootLocation);
|
|
||||||
Files.createDirectories(privateRootLocation);
|
|
||||||
} catch (IOException e) {
|
|
||||||
throw new StorageException("Could not initialize media storage.", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void storeOriginal(Path source, String storageKey) throws IOException {
|
|
||||||
copy(source, resolveOriginal(storageKey));
|
|
||||||
}
|
|
||||||
|
|
||||||
public void storePublic(Path source, String storageKey) throws IOException {
|
|
||||||
copy(source, resolvePublic(storageKey));
|
|
||||||
}
|
|
||||||
|
|
||||||
public void storePrivate(Path source, String storageKey) throws IOException {
|
|
||||||
copy(source, resolvePrivate(storageKey));
|
|
||||||
}
|
|
||||||
|
|
||||||
public void deleteGenerated(String visibility, String storageKey) throws IOException {
|
|
||||||
Files.deleteIfExists(resolve(resolveVariantRoot(normalizeVisibility(visibility)), storageKey));
|
|
||||||
}
|
|
||||||
|
|
||||||
public void moveGenerated(String storageKey, String fromVisibility, String toVisibility) throws IOException {
|
|
||||||
String normalizedFrom = normalizeVisibility(fromVisibility);
|
|
||||||
String normalizedTo = normalizeVisibility(toVisibility);
|
|
||||||
if (normalizedFrom.equals(normalizedTo)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
Path source = resolve(resolveVariantRoot(normalizedFrom), storageKey);
|
|
||||||
Path target = resolve(resolveVariantRoot(normalizedTo), storageKey);
|
|
||||||
Files.createDirectories(target.getParent());
|
|
||||||
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
|
|
||||||
}
|
|
||||||
|
|
||||||
public String buildPublicUrl(String storageKey) {
|
|
||||||
if (storageKey == null || storageKey.isBlank()) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
String mediaBaseUrl = buildMediaBaseUrl();
|
|
||||||
String normalizedKey = storageKey.startsWith("/") ? storageKey.substring(1) : storageKey;
|
|
||||||
if (mediaBaseUrl.endsWith("/")) {
|
|
||||||
return mediaBaseUrl + normalizedKey;
|
|
||||||
}
|
|
||||||
return mediaBaseUrl + "/" + normalizedKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void copy(Path source, Path destination) throws IOException {
|
|
||||||
Files.createDirectories(destination.getParent());
|
|
||||||
Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
|
|
||||||
}
|
|
||||||
|
|
||||||
private Path resolveOriginal(String storageKey) {
|
|
||||||
return resolve(originalRootLocation, storageKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
private Path resolvePublic(String storageKey) {
|
|
||||||
return resolve(publicRootLocation, storageKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
private Path resolvePrivate(String storageKey) {
|
|
||||||
return resolve(privateRootLocation, storageKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
private Path resolveVariantRoot(String visibility) {
|
|
||||||
return switch (visibility) {
|
|
||||||
case "PUBLIC" -> publicRootLocation;
|
|
||||||
case "PRIVATE" -> privateRootLocation;
|
|
||||||
default -> throw new StorageException("Unsupported media visibility: " + visibility);
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private Path resolve(Path baseRoot, String storageKey) {
|
|
||||||
if (storageKey == null || storageKey.isBlank()) {
|
|
||||||
throw new StorageException("Storage key is required.");
|
|
||||||
}
|
|
||||||
Path relativePath = Paths.get(storageKey).normalize();
|
|
||||||
if (relativePath.isAbsolute()) {
|
|
||||||
throw new StorageException("Absolute paths are not allowed.");
|
|
||||||
}
|
|
||||||
|
|
||||||
Path resolved = baseRoot.resolve(relativePath).normalize();
|
|
||||||
if (!resolved.startsWith(baseRoot)) {
|
|
||||||
throw new StorageException("Cannot access files outside media storage root.");
|
|
||||||
}
|
|
||||||
return resolved;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeVisibility(String visibility) {
|
|
||||||
if (visibility == null || visibility.isBlank()) {
|
|
||||||
throw new StorageException("Visibility is required.");
|
|
||||||
}
|
|
||||||
return visibility.trim().toUpperCase(Locale.ROOT);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String buildMediaBaseUrl() {
|
|
||||||
String normalized = frontendBaseUrl != null ? frontendBaseUrl.trim() : "";
|
|
||||||
if (normalized.contains("localhost")){
|
|
||||||
return "http://localhost:8081";
|
|
||||||
}
|
|
||||||
if (normalized.isBlank()) {
|
|
||||||
normalized = "http://localhost:8081";
|
|
||||||
}
|
|
||||||
if (normalized.endsWith("/")) {
|
|
||||||
normalized = normalized.substring(0, normalized.length() - 1);
|
|
||||||
}
|
|
||||||
return normalized + "/media";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,192 +0,0 @@
|
|||||||
package com.printcalculator.service.media;
|
|
||||||
|
|
||||||
import com.printcalculator.dto.PublicMediaUsageDto;
|
|
||||||
import com.printcalculator.dto.PublicMediaVariantDto;
|
|
||||||
import com.printcalculator.entity.MediaAsset;
|
|
||||||
import com.printcalculator.entity.MediaUsage;
|
|
||||||
import com.printcalculator.entity.MediaVariant;
|
|
||||||
import com.printcalculator.repository.MediaUsageRepository;
|
|
||||||
import com.printcalculator.repository.MediaVariantRepository;
|
|
||||||
import org.springframework.http.HttpStatus;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
|
||||||
import org.springframework.web.server.ResponseStatusException;
|
|
||||||
|
|
||||||
import java.time.OffsetDateTime;
|
|
||||||
import java.util.Comparator;
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Locale;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Objects;
|
|
||||||
import java.util.UUID;
|
|
||||||
import java.util.function.Function;
|
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public class PublicMediaQueryService {
|
|
||||||
|
|
||||||
private static final String STATUS_READY = "READY";
|
|
||||||
private static final String VISIBILITY_PUBLIC = "PUBLIC";
|
|
||||||
private static final String FORMAT_JPEG = "JPEG";
|
|
||||||
private static final String FORMAT_WEBP = "WEBP";
|
|
||||||
private static final String FORMAT_AVIF = "AVIF";
|
|
||||||
private static final List<String> SUPPORTED_MEDIA_LANGUAGES = List.of("it", "en", "de", "fr");
|
|
||||||
|
|
||||||
private final MediaUsageRepository mediaUsageRepository;
|
|
||||||
private final MediaVariantRepository mediaVariantRepository;
|
|
||||||
private final MediaStorageService mediaStorageService;
|
|
||||||
|
|
||||||
public PublicMediaQueryService(MediaUsageRepository mediaUsageRepository,
|
|
||||||
MediaVariantRepository mediaVariantRepository,
|
|
||||||
MediaStorageService mediaStorageService) {
|
|
||||||
this.mediaUsageRepository = mediaUsageRepository;
|
|
||||||
this.mediaVariantRepository = mediaVariantRepository;
|
|
||||||
this.mediaStorageService = mediaStorageService;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<PublicMediaUsageDto> getUsageMedia(String usageType, String usageKey, String language) {
|
|
||||||
String normalizedUsageType = normalizeUsageType(usageType);
|
|
||||||
String normalizedUsageKey = normalizeUsageKey(usageKey);
|
|
||||||
return getUsageMediaMap(normalizedUsageType, List.of(normalizedUsageKey), language)
|
|
||||||
.getOrDefault(normalizedUsageKey, List.of());
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<String, List<PublicMediaUsageDto>> getUsageMediaMap(String usageType,
|
|
||||||
List<String> usageKeys,
|
|
||||||
String language) {
|
|
||||||
String normalizedUsageType = normalizeUsageType(usageType);
|
|
||||||
String normalizedLanguage = normalizeLanguage(language);
|
|
||||||
List<String> normalizedUsageKeys = (usageKeys == null
|
|
||||||
? List.<String>of()
|
|
||||||
: usageKeys)
|
|
||||||
.stream()
|
|
||||||
.filter(Objects::nonNull)
|
|
||||||
.map(this::normalizeUsageKey)
|
|
||||||
.distinct()
|
|
||||||
.toList();
|
|
||||||
|
|
||||||
if (normalizedUsageKeys.isEmpty()) {
|
|
||||||
return Map.of();
|
|
||||||
}
|
|
||||||
|
|
||||||
List<MediaUsage> usages = mediaUsageRepository
|
|
||||||
.findActiveByUsageTypeAndUsageKeys(normalizedUsageType, normalizedUsageKeys)
|
|
||||||
.stream()
|
|
||||||
.filter(this::isPublicReadyUsage)
|
|
||||||
.sorted(Comparator
|
|
||||||
.comparing(MediaUsage::getUsageKey, Comparator.nullsLast(String::compareTo))
|
|
||||||
.thenComparing(MediaUsage::getSortOrder, Comparator.nullsLast(Integer::compareTo))
|
|
||||||
.thenComparing(MediaUsage::getCreatedAt, Comparator.nullsLast(OffsetDateTime::compareTo)))
|
|
||||||
.toList();
|
|
||||||
|
|
||||||
if (usages.isEmpty()) {
|
|
||||||
return Map.of();
|
|
||||||
}
|
|
||||||
|
|
||||||
List<UUID> assetIds = usages.stream()
|
|
||||||
.map(MediaUsage::getMediaAsset)
|
|
||||||
.filter(Objects::nonNull)
|
|
||||||
.map(MediaAsset::getId)
|
|
||||||
.filter(Objects::nonNull)
|
|
||||||
.distinct()
|
|
||||||
.toList();
|
|
||||||
|
|
||||||
Map<UUID, List<MediaVariant>> variantsByAssetId = mediaVariantRepository.findByMediaAsset_IdIn(assetIds)
|
|
||||||
.stream()
|
|
||||||
.filter(variant -> !Objects.equals("ORIGINAL", variant.getFormat()))
|
|
||||||
.collect(Collectors.groupingBy(variant -> variant.getMediaAsset().getId()));
|
|
||||||
|
|
||||||
Map<String, List<PublicMediaUsageDto>> result = new LinkedHashMap<>();
|
|
||||||
for (MediaUsage usage : usages) {
|
|
||||||
result.computeIfAbsent(usage.getUsageKey(), ignored -> new java.util.ArrayList<>())
|
|
||||||
.add(toDto(
|
|
||||||
usage,
|
|
||||||
variantsByAssetId.getOrDefault(usage.getMediaAsset().getId(), List.of()),
|
|
||||||
normalizedLanguage
|
|
||||||
));
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean isPublicReadyUsage(MediaUsage usage) {
|
|
||||||
MediaAsset asset = usage.getMediaAsset();
|
|
||||||
return asset != null
|
|
||||||
&& STATUS_READY.equals(asset.getStatus())
|
|
||||||
&& VISIBILITY_PUBLIC.equals(asset.getVisibility());
|
|
||||||
}
|
|
||||||
|
|
||||||
private PublicMediaUsageDto toDto(MediaUsage usage, List<MediaVariant> variants, String language) {
|
|
||||||
Map<String, Map<String, MediaVariant>> variantsByPresetAndFormat = variants.stream()
|
|
||||||
.collect(Collectors.groupingBy(
|
|
||||||
MediaVariant::getVariantName,
|
|
||||||
Collectors.toMap(MediaVariant::getFormat, Function.identity(), (left, right) -> right)
|
|
||||||
));
|
|
||||||
|
|
||||||
PublicMediaUsageDto dto = new PublicMediaUsageDto();
|
|
||||||
dto.setMediaAssetId(usage.getMediaAsset().getId());
|
|
||||||
dto.setTitle(resolveLocalizedValue(usage.getTitleForLanguage(language), usage.getMediaAsset().getTitle()));
|
|
||||||
dto.setAltText(resolveLocalizedValue(usage.getAltTextForLanguage(language), usage.getMediaAsset().getAltText()));
|
|
||||||
dto.setUsageType(usage.getUsageType());
|
|
||||||
dto.setUsageKey(usage.getUsageKey());
|
|
||||||
dto.setSortOrder(usage.getSortOrder());
|
|
||||||
dto.setIsPrimary(usage.getIsPrimary());
|
|
||||||
dto.setThumb(buildPresetDto(variantsByPresetAndFormat.get("thumb")));
|
|
||||||
dto.setCard(buildPresetDto(variantsByPresetAndFormat.get("card")));
|
|
||||||
dto.setHero(buildPresetDto(variantsByPresetAndFormat.get("hero")));
|
|
||||||
return dto;
|
|
||||||
}
|
|
||||||
|
|
||||||
private PublicMediaVariantDto buildPresetDto(Map<String, MediaVariant> variantsByFormat) {
|
|
||||||
PublicMediaVariantDto dto = new PublicMediaVariantDto();
|
|
||||||
if (variantsByFormat == null || variantsByFormat.isEmpty()) {
|
|
||||||
return dto;
|
|
||||||
}
|
|
||||||
|
|
||||||
dto.setAvifUrl(buildVariantUrl(variantsByFormat.get(FORMAT_AVIF)));
|
|
||||||
dto.setWebpUrl(buildVariantUrl(variantsByFormat.get(FORMAT_WEBP)));
|
|
||||||
dto.setJpegUrl(buildVariantUrl(variantsByFormat.get(FORMAT_JPEG)));
|
|
||||||
return dto;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String buildVariantUrl(MediaVariant variant) {
|
|
||||||
if (variant == null || variant.getStorageKey() == null || variant.getStorageKey().isBlank()) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return mediaStorageService.buildPublicUrl(variant.getStorageKey());
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeUsageType(String usageType) {
|
|
||||||
if (usageType == null || usageType.isBlank()) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "usageType is required.");
|
|
||||||
}
|
|
||||||
return usageType.trim().toUpperCase(Locale.ROOT);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeUsageKey(String usageKey) {
|
|
||||||
if (usageKey == null || usageKey.isBlank()) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "usageKey is required.");
|
|
||||||
}
|
|
||||||
return usageKey.trim();
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeLanguage(String language) {
|
|
||||||
if (language == null || language.isBlank()) {
|
|
||||||
return "it";
|
|
||||||
}
|
|
||||||
|
|
||||||
String normalized = language.trim().toLowerCase(Locale.ROOT);
|
|
||||||
return SUPPORTED_MEDIA_LANGUAGES.contains(normalized) ? normalized : "it";
|
|
||||||
}
|
|
||||||
|
|
||||||
private String resolveLocalizedValue(String preferred, String fallback) {
|
|
||||||
if (preferred != null && !preferred.isBlank()) {
|
|
||||||
return preferred;
|
|
||||||
}
|
|
||||||
if (fallback != null && !fallback.isBlank()) {
|
|
||||||
return fallback.trim();
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,461 +0,0 @@
|
|||||||
package com.printcalculator.service.order;
|
|
||||||
|
|
||||||
import com.printcalculator.dto.AddressDto;
|
|
||||||
import com.printcalculator.dto.AdminOrderStatusUpdateRequest;
|
|
||||||
import com.printcalculator.dto.OrderDto;
|
|
||||||
import com.printcalculator.dto.OrderItemDto;
|
|
||||||
import com.printcalculator.entity.Order;
|
|
||||||
import com.printcalculator.entity.OrderItem;
|
|
||||||
import com.printcalculator.entity.Payment;
|
|
||||||
import com.printcalculator.entity.QuoteLineItem;
|
|
||||||
import com.printcalculator.entity.QuoteSession;
|
|
||||||
import com.printcalculator.event.OrderShippedEvent;
|
|
||||||
import com.printcalculator.repository.OrderItemRepository;
|
|
||||||
import com.printcalculator.repository.OrderRepository;
|
|
||||||
import com.printcalculator.repository.PaymentRepository;
|
|
||||||
import com.printcalculator.repository.QuoteLineItemRepository;
|
|
||||||
import com.printcalculator.service.payment.InvoicePdfRenderingService;
|
|
||||||
import com.printcalculator.service.payment.PaymentService;
|
|
||||||
import com.printcalculator.service.payment.QrBillService;
|
|
||||||
import com.printcalculator.service.storage.StorageService;
|
|
||||||
import org.springframework.context.ApplicationEventPublisher;
|
|
||||||
import org.springframework.core.io.Resource;
|
|
||||||
import org.springframework.core.io.UrlResource;
|
|
||||||
import org.springframework.http.ContentDisposition;
|
|
||||||
import org.springframework.http.HttpHeaders;
|
|
||||||
import org.springframework.http.MediaType;
|
|
||||||
import org.springframework.http.ResponseEntity;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
|
||||||
import org.springframework.web.server.ResponseStatusException;
|
|
||||||
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.nio.file.InvalidPathException;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.nio.file.Paths;
|
|
||||||
import java.util.Comparator;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Locale;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
import static org.springframework.http.HttpStatus.BAD_REQUEST;
|
|
||||||
import static org.springframework.http.HttpStatus.NOT_FOUND;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public class AdminOrderControllerService {
|
|
||||||
private static final Path QUOTE_STORAGE_ROOT = Paths.get("storage_quotes").toAbsolutePath().normalize();
|
|
||||||
private static final List<String> ALLOWED_ORDER_STATUSES = List.of(
|
|
||||||
"PENDING_PAYMENT",
|
|
||||||
"PAID",
|
|
||||||
"IN_PRODUCTION",
|
|
||||||
"SHIPPED",
|
|
||||||
"COMPLETED",
|
|
||||||
"CANCELLED"
|
|
||||||
);
|
|
||||||
|
|
||||||
private final OrderRepository orderRepo;
|
|
||||||
private final OrderItemRepository orderItemRepo;
|
|
||||||
private final PaymentRepository paymentRepo;
|
|
||||||
private final QuoteLineItemRepository quoteLineItemRepo;
|
|
||||||
private final PaymentService paymentService;
|
|
||||||
private final StorageService storageService;
|
|
||||||
private final InvoicePdfRenderingService invoiceService;
|
|
||||||
private final QrBillService qrBillService;
|
|
||||||
private final ApplicationEventPublisher eventPublisher;
|
|
||||||
|
|
||||||
public AdminOrderControllerService(OrderRepository orderRepo,
|
|
||||||
OrderItemRepository orderItemRepo,
|
|
||||||
PaymentRepository paymentRepo,
|
|
||||||
QuoteLineItemRepository quoteLineItemRepo,
|
|
||||||
PaymentService paymentService,
|
|
||||||
StorageService storageService,
|
|
||||||
InvoicePdfRenderingService invoiceService,
|
|
||||||
QrBillService qrBillService,
|
|
||||||
ApplicationEventPublisher eventPublisher) {
|
|
||||||
this.orderRepo = orderRepo;
|
|
||||||
this.orderItemRepo = orderItemRepo;
|
|
||||||
this.paymentRepo = paymentRepo;
|
|
||||||
this.quoteLineItemRepo = quoteLineItemRepo;
|
|
||||||
this.paymentService = paymentService;
|
|
||||||
this.storageService = storageService;
|
|
||||||
this.invoiceService = invoiceService;
|
|
||||||
this.qrBillService = qrBillService;
|
|
||||||
this.eventPublisher = eventPublisher;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<OrderDto> listOrders() {
|
|
||||||
return orderRepo.findAllByOrderByCreatedAtDesc()
|
|
||||||
.stream()
|
|
||||||
.map(this::toOrderDto)
|
|
||||||
.toList();
|
|
||||||
}
|
|
||||||
|
|
||||||
public OrderDto getOrder(UUID orderId) {
|
|
||||||
return toOrderDto(getOrderOrThrow(orderId));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public OrderDto updatePaymentMethod(UUID orderId, Map<String, String> payload) {
|
|
||||||
getOrderOrThrow(orderId);
|
|
||||||
String method = payload != null ? payload.get("method") : null;
|
|
||||||
if (method == null || method.isBlank()) {
|
|
||||||
throw new ResponseStatusException(BAD_REQUEST, "Payment method is required");
|
|
||||||
}
|
|
||||||
paymentService.updatePaymentMethod(orderId, method);
|
|
||||||
return toOrderDto(getOrderOrThrow(orderId));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public OrderDto updateOrderStatus(UUID orderId, AdminOrderStatusUpdateRequest payload) {
|
|
||||||
if (payload == null || payload.getStatus() == null || payload.getStatus().isBlank()) {
|
|
||||||
throw new ResponseStatusException(BAD_REQUEST, "Status is required");
|
|
||||||
}
|
|
||||||
|
|
||||||
Order order = getOrderOrThrow(orderId);
|
|
||||||
String normalizedStatus = payload.getStatus().trim().toUpperCase(Locale.ROOT);
|
|
||||||
if (!ALLOWED_ORDER_STATUSES.contains(normalizedStatus)) {
|
|
||||||
throw new ResponseStatusException(
|
|
||||||
BAD_REQUEST,
|
|
||||||
"Invalid order status. Allowed values: " + String.join(", ", ALLOWED_ORDER_STATUSES)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
String previousStatus = order.getStatus();
|
|
||||||
order.setStatus(normalizedStatus);
|
|
||||||
Order savedOrder = orderRepo.save(order);
|
|
||||||
|
|
||||||
if (!"SHIPPED".equals(previousStatus) && "SHIPPED".equals(normalizedStatus)) {
|
|
||||||
eventPublisher.publishEvent(new OrderShippedEvent(this, savedOrder));
|
|
||||||
}
|
|
||||||
|
|
||||||
return toOrderDto(savedOrder);
|
|
||||||
}
|
|
||||||
|
|
||||||
public ResponseEntity<Resource> downloadOrderItemFile(UUID orderId, UUID orderItemId) {
|
|
||||||
OrderItem item = orderItemRepo.findById(orderItemId)
|
|
||||||
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "Order item not found"));
|
|
||||||
|
|
||||||
if (!item.getOrder().getId().equals(orderId)) {
|
|
||||||
throw new ResponseStatusException(NOT_FOUND, "Order item not found for order");
|
|
||||||
}
|
|
||||||
|
|
||||||
String relativePath = item.getStoredRelativePath();
|
|
||||||
if (relativePath == null || relativePath.isBlank() || "PENDING".equals(relativePath)) {
|
|
||||||
throw new ResponseStatusException(NOT_FOUND, "File not available");
|
|
||||||
}
|
|
||||||
Path safeRelativePath = resolveOrderItemRelativePath(relativePath, orderId, orderItemId);
|
|
||||||
if (safeRelativePath == null) {
|
|
||||||
throw new ResponseStatusException(NOT_FOUND, "File not available");
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
Resource resource = loadOrderItemResourceWithRecovery(item, safeRelativePath);
|
|
||||||
MediaType contentType = MediaType.APPLICATION_OCTET_STREAM;
|
|
||||||
if (item.getMimeType() != null && !item.getMimeType().isBlank()) {
|
|
||||||
try {
|
|
||||||
contentType = MediaType.parseMediaType(item.getMimeType());
|
|
||||||
} catch (Exception ignored) {
|
|
||||||
contentType = MediaType.APPLICATION_OCTET_STREAM;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
String filename = item.getOriginalFilename() != null && !item.getOriginalFilename().isBlank()
|
|
||||||
? item.getOriginalFilename()
|
|
||||||
: "order-item-" + orderItemId;
|
|
||||||
|
|
||||||
return ResponseEntity.ok()
|
|
||||||
.contentType(contentType)
|
|
||||||
.header(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.attachment()
|
|
||||||
.filename(filename, StandardCharsets.UTF_8)
|
|
||||||
.build()
|
|
||||||
.toString())
|
|
||||||
.body(resource);
|
|
||||||
} catch (ResponseStatusException e) {
|
|
||||||
throw e;
|
|
||||||
} catch (Exception e) {
|
|
||||||
throw new ResponseStatusException(NOT_FOUND, "File not available");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public ResponseEntity<byte[]> downloadOrderConfirmation(UUID orderId) {
|
|
||||||
return generateDocument(getOrderOrThrow(orderId), true);
|
|
||||||
}
|
|
||||||
|
|
||||||
public ResponseEntity<byte[]> downloadOrderInvoice(UUID orderId) {
|
|
||||||
return generateDocument(getOrderOrThrow(orderId), false);
|
|
||||||
}
|
|
||||||
|
|
||||||
private Order getOrderOrThrow(UUID orderId) {
|
|
||||||
return orderRepo.findById(orderId)
|
|
||||||
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "Order not found"));
|
|
||||||
}
|
|
||||||
|
|
||||||
private OrderDto toOrderDto(Order order) {
|
|
||||||
List<OrderItem> items = orderItemRepo.findByOrder_Id(order.getId());
|
|
||||||
OrderDto dto = new OrderDto();
|
|
||||||
dto.setId(order.getId());
|
|
||||||
dto.setOrderNumber(getDisplayOrderNumber(order));
|
|
||||||
dto.setSourceType(order.getSourceType() != null ? order.getSourceType() : "CALCULATOR");
|
|
||||||
dto.setStatus(order.getStatus());
|
|
||||||
|
|
||||||
paymentRepo.findByOrder_Id(order.getId()).ifPresent(payment -> {
|
|
||||||
dto.setPaymentStatus(payment.getStatus());
|
|
||||||
dto.setPaymentMethod(payment.getMethod());
|
|
||||||
});
|
|
||||||
|
|
||||||
dto.setCustomerEmail(order.getCustomerEmail());
|
|
||||||
dto.setCustomerPhone(order.getCustomerPhone());
|
|
||||||
dto.setPreferredLanguage(order.getPreferredLanguage());
|
|
||||||
dto.setBillingCustomerType(order.getBillingCustomerType());
|
|
||||||
dto.setCurrency(order.getCurrency());
|
|
||||||
dto.setSetupCostChf(order.getSetupCostChf());
|
|
||||||
dto.setShippingCostChf(order.getShippingCostChf());
|
|
||||||
dto.setDiscountChf(order.getDiscountChf());
|
|
||||||
dto.setSubtotalChf(order.getSubtotalChf());
|
|
||||||
dto.setIsCadOrder(order.getIsCadOrder());
|
|
||||||
dto.setSourceRequestId(order.getSourceRequestId());
|
|
||||||
dto.setCadHours(order.getCadHours());
|
|
||||||
dto.setCadHourlyRateChf(order.getCadHourlyRateChf());
|
|
||||||
dto.setCadTotalChf(order.getCadTotalChf());
|
|
||||||
dto.setTotalChf(order.getTotalChf());
|
|
||||||
dto.setCreatedAt(order.getCreatedAt());
|
|
||||||
dto.setShippingSameAsBilling(order.getShippingSameAsBilling());
|
|
||||||
QuoteSession sourceSession = order.getSourceQuoteSession();
|
|
||||||
if (sourceSession != null) {
|
|
||||||
dto.setPrintMaterialCode(sourceSession.getMaterialCode());
|
|
||||||
dto.setPrintNozzleDiameterMm(sourceSession.getNozzleDiameterMm());
|
|
||||||
dto.setPrintLayerHeightMm(sourceSession.getLayerHeightMm());
|
|
||||||
dto.setPrintInfillPattern(sourceSession.getInfillPattern());
|
|
||||||
dto.setPrintInfillPercent(sourceSession.getInfillPercent());
|
|
||||||
dto.setPrintSupportsEnabled(sourceSession.getSupportsEnabled());
|
|
||||||
}
|
|
||||||
|
|
||||||
AddressDto billing = new AddressDto();
|
|
||||||
billing.setFirstName(order.getBillingFirstName());
|
|
||||||
billing.setLastName(order.getBillingLastName());
|
|
||||||
billing.setCompanyName(order.getBillingCompanyName());
|
|
||||||
billing.setContactPerson(order.getBillingContactPerson());
|
|
||||||
billing.setAddressLine1(order.getBillingAddressLine1());
|
|
||||||
billing.setAddressLine2(order.getBillingAddressLine2());
|
|
||||||
billing.setZip(order.getBillingZip());
|
|
||||||
billing.setCity(order.getBillingCity());
|
|
||||||
billing.setCountryCode(order.getBillingCountryCode());
|
|
||||||
dto.setBillingAddress(billing);
|
|
||||||
|
|
||||||
if (!Boolean.TRUE.equals(order.getShippingSameAsBilling())) {
|
|
||||||
AddressDto shipping = new AddressDto();
|
|
||||||
shipping.setFirstName(order.getShippingFirstName());
|
|
||||||
shipping.setLastName(order.getShippingLastName());
|
|
||||||
shipping.setCompanyName(order.getShippingCompanyName());
|
|
||||||
shipping.setContactPerson(order.getShippingContactPerson());
|
|
||||||
shipping.setAddressLine1(order.getShippingAddressLine1());
|
|
||||||
shipping.setAddressLine2(order.getShippingAddressLine2());
|
|
||||||
shipping.setZip(order.getShippingZip());
|
|
||||||
shipping.setCity(order.getShippingCity());
|
|
||||||
shipping.setCountryCode(order.getShippingCountryCode());
|
|
||||||
dto.setShippingAddress(shipping);
|
|
||||||
}
|
|
||||||
|
|
||||||
List<OrderItemDto> itemDtos = items.stream().map(item -> {
|
|
||||||
OrderItemDto itemDto = new OrderItemDto();
|
|
||||||
itemDto.setId(item.getId());
|
|
||||||
itemDto.setItemType(item.getItemType() != null ? item.getItemType() : "PRINT_FILE");
|
|
||||||
itemDto.setOriginalFilename(item.getOriginalFilename());
|
|
||||||
itemDto.setDisplayName(
|
|
||||||
item.getDisplayName() != null && !item.getDisplayName().isBlank()
|
|
||||||
? item.getDisplayName()
|
|
||||||
: item.getOriginalFilename()
|
|
||||||
);
|
|
||||||
itemDto.setMaterialCode(item.getMaterialCode());
|
|
||||||
itemDto.setColorCode(item.getColorCode());
|
|
||||||
if (item.getShopProduct() != null) {
|
|
||||||
itemDto.setShopProductId(item.getShopProduct().getId());
|
|
||||||
}
|
|
||||||
if (item.getShopProductVariant() != null) {
|
|
||||||
itemDto.setShopProductVariantId(item.getShopProductVariant().getId());
|
|
||||||
}
|
|
||||||
itemDto.setShopProductSlug(item.getShopProductSlug());
|
|
||||||
itemDto.setShopProductName(item.getShopProductName());
|
|
||||||
itemDto.setShopVariantLabel(item.getShopVariantLabel());
|
|
||||||
itemDto.setShopVariantColorName(item.getShopVariantColorName());
|
|
||||||
itemDto.setShopVariantColorLabelIt(item.getShopProductVariant() != null ? item.getShopProductVariant().getColorLabelIt() : null);
|
|
||||||
itemDto.setShopVariantColorLabelEn(item.getShopProductVariant() != null ? item.getShopProductVariant().getColorLabelEn() : null);
|
|
||||||
itemDto.setShopVariantColorLabelDe(item.getShopProductVariant() != null ? item.getShopProductVariant().getColorLabelDe() : null);
|
|
||||||
itemDto.setShopVariantColorLabelFr(item.getShopProductVariant() != null ? item.getShopProductVariant().getColorLabelFr() : null);
|
|
||||||
itemDto.setShopVariantColorHex(item.getShopVariantColorHex());
|
|
||||||
if (item.getFilamentVariant() != null) {
|
|
||||||
itemDto.setFilamentVariantId(item.getFilamentVariant().getId());
|
|
||||||
itemDto.setFilamentVariantDisplayName(item.getFilamentVariant().getVariantDisplayName());
|
|
||||||
itemDto.setFilamentColorName(item.getFilamentVariant().getColorName());
|
|
||||||
itemDto.setFilamentColorLabelIt(item.getFilamentVariant().getColorLabelIt());
|
|
||||||
itemDto.setFilamentColorLabelEn(item.getFilamentVariant().getColorLabelEn());
|
|
||||||
itemDto.setFilamentColorLabelDe(item.getFilamentVariant().getColorLabelDe());
|
|
||||||
itemDto.setFilamentColorLabelFr(item.getFilamentVariant().getColorLabelFr());
|
|
||||||
itemDto.setFilamentColorHex(item.getFilamentVariant().getColorHex());
|
|
||||||
}
|
|
||||||
itemDto.setQuality(item.getQuality());
|
|
||||||
itemDto.setNozzleDiameterMm(item.getNozzleDiameterMm());
|
|
||||||
itemDto.setLayerHeightMm(item.getLayerHeightMm());
|
|
||||||
itemDto.setInfillPercent(item.getInfillPercent());
|
|
||||||
itemDto.setInfillPattern(item.getInfillPattern());
|
|
||||||
itemDto.setSupportsEnabled(item.getSupportsEnabled());
|
|
||||||
itemDto.setQuantity(item.getQuantity());
|
|
||||||
itemDto.setPrintTimeSeconds(item.getPrintTimeSeconds());
|
|
||||||
itemDto.setMaterialGrams(item.getMaterialGrams());
|
|
||||||
itemDto.setUnitPriceChf(item.getUnitPriceChf());
|
|
||||||
itemDto.setLineTotalChf(item.getLineTotalChf());
|
|
||||||
return itemDto;
|
|
||||||
}).toList();
|
|
||||||
dto.setItems(itemDtos);
|
|
||||||
|
|
||||||
return dto;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String getDisplayOrderNumber(Order order) {
|
|
||||||
String orderNumber = order.getOrderNumber();
|
|
||||||
if (orderNumber != null && !orderNumber.isBlank()) {
|
|
||||||
return orderNumber;
|
|
||||||
}
|
|
||||||
return order.getId() != null ? order.getId().toString() : "unknown";
|
|
||||||
}
|
|
||||||
|
|
||||||
private ResponseEntity<byte[]> generateDocument(Order order, boolean isConfirmation) {
|
|
||||||
String displayOrderNumber = getDisplayOrderNumber(order);
|
|
||||||
if (isConfirmation) {
|
|
||||||
Path relativePath = buildConfirmationPdfRelativePath(order.getId(), displayOrderNumber);
|
|
||||||
try {
|
|
||||||
byte[] existingPdf = storageService.loadAsResource(relativePath).getInputStream().readAllBytes();
|
|
||||||
return ResponseEntity.ok()
|
|
||||||
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"confirmation-" + displayOrderNumber + ".pdf\"")
|
|
||||||
.contentType(MediaType.APPLICATION_PDF)
|
|
||||||
.body(existingPdf);
|
|
||||||
} catch (Exception ignored) {
|
|
||||||
// fallback to generated confirmation document
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
List<OrderItem> items = orderItemRepo.findByOrder_Id(order.getId());
|
|
||||||
Payment payment = paymentRepo.findByOrder_Id(order.getId()).orElse(null);
|
|
||||||
byte[] pdf = invoiceService.generateDocumentPdf(order, items, isConfirmation, qrBillService, payment);
|
|
||||||
|
|
||||||
String prefix = isConfirmation ? "confirmation-" : "invoice-";
|
|
||||||
return ResponseEntity.ok()
|
|
||||||
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + prefix + displayOrderNumber + ".pdf\"")
|
|
||||||
.contentType(MediaType.APPLICATION_PDF)
|
|
||||||
.body(pdf);
|
|
||||||
}
|
|
||||||
|
|
||||||
private Path resolveOrderItemRelativePath(String storedRelativePath, UUID orderId, UUID orderItemId) {
|
|
||||||
try {
|
|
||||||
Path candidate = Path.of(storedRelativePath).normalize();
|
|
||||||
if (candidate.isAbsolute()) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
Path expectedPrefix = Path.of("orders", orderId.toString(), "3d-files", orderItemId.toString());
|
|
||||||
if (!candidate.startsWith(expectedPrefix)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return candidate;
|
|
||||||
} catch (InvalidPathException e) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private Resource loadOrderItemResourceWithRecovery(OrderItem item, Path safeRelativePath) {
|
|
||||||
try {
|
|
||||||
return storageService.loadAsResource(safeRelativePath);
|
|
||||||
} catch (Exception primaryFailure) {
|
|
||||||
Path sourceQuotePath = resolveFallbackQuoteItemPath(item);
|
|
||||||
if (sourceQuotePath == null) {
|
|
||||||
throw new ResponseStatusException(NOT_FOUND, "File not available");
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
storageService.store(sourceQuotePath, safeRelativePath);
|
|
||||||
return storageService.loadAsResource(safeRelativePath);
|
|
||||||
} catch (Exception copyFailure) {
|
|
||||||
try {
|
|
||||||
Resource quoteResource = new UrlResource(sourceQuotePath.toUri());
|
|
||||||
if (quoteResource.exists() || quoteResource.isReadable()) {
|
|
||||||
return quoteResource;
|
|
||||||
}
|
|
||||||
} catch (Exception ignored) {
|
|
||||||
// fall through to 404
|
|
||||||
}
|
|
||||||
throw new ResponseStatusException(NOT_FOUND, "File not available");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private Path resolveFallbackQuoteItemPath(OrderItem orderItem) {
|
|
||||||
Order order = orderItem.getOrder();
|
|
||||||
QuoteSession sourceSession = order != null ? order.getSourceQuoteSession() : null;
|
|
||||||
UUID sourceSessionId = sourceSession != null ? sourceSession.getId() : null;
|
|
||||||
if (sourceSessionId == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
String targetFilename = normalizeFilename(orderItem.getOriginalFilename());
|
|
||||||
if (targetFilename == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return quoteLineItemRepo.findByQuoteSessionId(sourceSessionId).stream()
|
|
||||||
.filter(quoteItem -> targetFilename.equals(normalizeFilename(quoteItem.getOriginalFilename())))
|
|
||||||
.sorted(Comparator.comparingInt((QuoteLineItem quoteItem) -> scoreQuoteMatch(orderItem, quoteItem)).reversed())
|
|
||||||
.map(quoteItem -> resolveStoredQuotePath(quoteItem.getStoredPath(), sourceSessionId))
|
|
||||||
.filter(path -> path != null && Files.exists(path))
|
|
||||||
.findFirst()
|
|
||||||
.orElse(null);
|
|
||||||
}
|
|
||||||
|
|
||||||
private int scoreQuoteMatch(OrderItem orderItem, QuoteLineItem quoteItem) {
|
|
||||||
int score = 0;
|
|
||||||
if (orderItem.getQuantity() != null && orderItem.getQuantity().equals(quoteItem.getQuantity())) {
|
|
||||||
score += 4;
|
|
||||||
}
|
|
||||||
if (orderItem.getPrintTimeSeconds() != null && orderItem.getPrintTimeSeconds().equals(quoteItem.getPrintTimeSeconds())) {
|
|
||||||
score += 3;
|
|
||||||
}
|
|
||||||
if (orderItem.getMaterialCode() != null
|
|
||||||
&& quoteItem.getMaterialCode() != null
|
|
||||||
&& orderItem.getMaterialCode().equalsIgnoreCase(quoteItem.getMaterialCode())) {
|
|
||||||
score += 3;
|
|
||||||
}
|
|
||||||
if (orderItem.getMaterialGrams() != null
|
|
||||||
&& quoteItem.getMaterialGrams() != null
|
|
||||||
&& orderItem.getMaterialGrams().compareTo(quoteItem.getMaterialGrams()) == 0) {
|
|
||||||
score += 2;
|
|
||||||
}
|
|
||||||
return score;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeFilename(String filename) {
|
|
||||||
if (filename == null || filename.isBlank()) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return filename.trim();
|
|
||||||
}
|
|
||||||
|
|
||||||
private Path resolveStoredQuotePath(String storedPath, UUID expectedSessionId) {
|
|
||||||
if (storedPath == null || storedPath.isBlank()) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
Path raw = Path.of(storedPath).normalize();
|
|
||||||
Path resolved = raw.isAbsolute() ? raw : QUOTE_STORAGE_ROOT.resolve(raw).normalize();
|
|
||||||
Path expectedSessionRoot = QUOTE_STORAGE_ROOT.resolve(expectedSessionId.toString()).normalize();
|
|
||||||
if (!resolved.startsWith(expectedSessionRoot)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return resolved;
|
|
||||||
} catch (InvalidPathException e) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private Path buildConfirmationPdfRelativePath(UUID orderId, String orderNumber) {
|
|
||||||
return Path.of("orders", orderId.toString(), "documents", "confirmation-" + orderNumber + ".pdf");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,384 +0,0 @@
|
|||||||
package com.printcalculator.service.order;
|
|
||||||
|
|
||||||
import com.printcalculator.dto.AddressDto;
|
|
||||||
import com.printcalculator.dto.CreateOrderRequest;
|
|
||||||
import com.printcalculator.dto.OrderDto;
|
|
||||||
import com.printcalculator.dto.OrderItemDto;
|
|
||||||
import com.printcalculator.entity.Order;
|
|
||||||
import com.printcalculator.entity.OrderItem;
|
|
||||||
import com.printcalculator.entity.Payment;
|
|
||||||
import com.printcalculator.repository.OrderItemRepository;
|
|
||||||
import com.printcalculator.repository.OrderRepository;
|
|
||||||
import com.printcalculator.repository.PaymentRepository;
|
|
||||||
import com.printcalculator.service.OrderService;
|
|
||||||
import com.printcalculator.service.payment.InvoicePdfRenderingService;
|
|
||||||
import com.printcalculator.service.payment.PaymentService;
|
|
||||||
import com.printcalculator.service.payment.QrBillService;
|
|
||||||
import com.printcalculator.service.payment.TwintPaymentService;
|
|
||||||
import com.printcalculator.service.storage.StorageService;
|
|
||||||
import org.springframework.http.MediaType;
|
|
||||||
import org.springframework.http.ResponseEntity;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
|
||||||
import org.springframework.util.StringUtils;
|
|
||||||
import org.springframework.web.multipart.MultipartFile;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.net.URI;
|
|
||||||
import java.nio.file.InvalidPathException;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.util.Base64;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Locale;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Optional;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.UUID;
|
|
||||||
import java.util.regex.Pattern;
|
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public class OrderControllerService {
|
|
||||||
private static final Pattern SAFE_EXTENSION_PATTERN = Pattern.compile("^[a-z0-9]{1,10}$");
|
|
||||||
private static final Set<String> PERSONAL_DATA_REDACTED_STATUSES = Set.of(
|
|
||||||
"IN_PRODUCTION",
|
|
||||||
"SHIPPED",
|
|
||||||
"COMPLETED"
|
|
||||||
);
|
|
||||||
|
|
||||||
private final OrderService orderService;
|
|
||||||
private final OrderRepository orderRepo;
|
|
||||||
private final OrderItemRepository orderItemRepo;
|
|
||||||
private final StorageService storageService;
|
|
||||||
private final InvoicePdfRenderingService invoiceService;
|
|
||||||
private final QrBillService qrBillService;
|
|
||||||
private final TwintPaymentService twintPaymentService;
|
|
||||||
private final PaymentService paymentService;
|
|
||||||
private final PaymentRepository paymentRepo;
|
|
||||||
|
|
||||||
public OrderControllerService(OrderService orderService,
|
|
||||||
OrderRepository orderRepo,
|
|
||||||
OrderItemRepository orderItemRepo,
|
|
||||||
StorageService storageService,
|
|
||||||
InvoicePdfRenderingService invoiceService,
|
|
||||||
QrBillService qrBillService,
|
|
||||||
TwintPaymentService twintPaymentService,
|
|
||||||
PaymentService paymentService,
|
|
||||||
PaymentRepository paymentRepo) {
|
|
||||||
this.orderService = orderService;
|
|
||||||
this.orderRepo = orderRepo;
|
|
||||||
this.orderItemRepo = orderItemRepo;
|
|
||||||
this.storageService = storageService;
|
|
||||||
this.invoiceService = invoiceService;
|
|
||||||
this.qrBillService = qrBillService;
|
|
||||||
this.twintPaymentService = twintPaymentService;
|
|
||||||
this.paymentService = paymentService;
|
|
||||||
this.paymentRepo = paymentRepo;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public OrderDto createOrderFromQuote(UUID quoteSessionId, CreateOrderRequest request) {
|
|
||||||
Order order = orderService.createOrderFromQuote(quoteSessionId, request);
|
|
||||||
List<OrderItem> items = orderItemRepo.findByOrder_Id(order.getId());
|
|
||||||
return convertToDto(order, items);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public boolean uploadOrderItemFile(UUID orderId, UUID orderItemId, MultipartFile file) throws IOException {
|
|
||||||
OrderItem item = orderItemRepo.findById(orderItemId)
|
|
||||||
.orElseThrow(() -> new RuntimeException("OrderItem not found"));
|
|
||||||
|
|
||||||
if (!item.getOrder().getId().equals(orderId)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
String relativePath = item.getStoredRelativePath();
|
|
||||||
Path destinationRelativePath;
|
|
||||||
if (relativePath == null || relativePath.equals("PENDING")) {
|
|
||||||
String ext = getExtension(file.getOriginalFilename());
|
|
||||||
String storedFilename = UUID.randomUUID() + "." + ext;
|
|
||||||
destinationRelativePath = Path.of("orders", orderId.toString(), "3d-files", orderItemId.toString(), storedFilename);
|
|
||||||
item.setStoredRelativePath(destinationRelativePath.toString());
|
|
||||||
item.setStoredFilename(storedFilename);
|
|
||||||
} else {
|
|
||||||
destinationRelativePath = resolveOrderItemRelativePath(relativePath, orderId, orderItemId);
|
|
||||||
if (destinationRelativePath == null) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
storageService.store(file, destinationRelativePath);
|
|
||||||
item.setFileSizeBytes(file.getSize());
|
|
||||||
item.setMimeType(file.getContentType());
|
|
||||||
orderItemRepo.save(item);
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Optional<OrderDto> getOrder(UUID orderId) {
|
|
||||||
return orderRepo.findById(orderId)
|
|
||||||
.map(order -> {
|
|
||||||
List<OrderItem> items = orderItemRepo.findByOrder_Id(order.getId());
|
|
||||||
return convertToDto(order, items);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public Optional<OrderDto> reportPayment(UUID orderId, String method) {
|
|
||||||
paymentService.reportPayment(orderId, method);
|
|
||||||
return getOrder(orderId);
|
|
||||||
}
|
|
||||||
|
|
||||||
public ResponseEntity<byte[]> getConfirmation(UUID orderId) {
|
|
||||||
return generateDocument(orderId, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
public ResponseEntity<Map<String, String>> getTwintPayment(UUID orderId) {
|
|
||||||
Order order = orderRepo.findById(orderId).orElse(null);
|
|
||||||
if (order == null) {
|
|
||||||
return ResponseEntity.notFound().build();
|
|
||||||
}
|
|
||||||
|
|
||||||
byte[] qrPng = twintPaymentService.generateQrPng(order, 360);
|
|
||||||
String qrDataUri = "data:image/png;base64," + Base64.getEncoder().encodeToString(qrPng);
|
|
||||||
|
|
||||||
Map<String, String> data = new HashMap<>();
|
|
||||||
data.put("paymentUrl", twintPaymentService.getTwintPaymentUrl(order));
|
|
||||||
data.put("openUrl", "/api/orders/" + orderId + "/twint/open");
|
|
||||||
data.put("qrImageUrl", "/api/orders/" + orderId + "/twint/qr");
|
|
||||||
data.put("qrImageDataUri", qrDataUri);
|
|
||||||
return ResponseEntity.ok(data);
|
|
||||||
}
|
|
||||||
|
|
||||||
public ResponseEntity<Void> openTwintPayment(UUID orderId) {
|
|
||||||
Order order = orderRepo.findById(orderId).orElse(null);
|
|
||||||
if (order == null) {
|
|
||||||
return ResponseEntity.notFound().build();
|
|
||||||
}
|
|
||||||
|
|
||||||
return ResponseEntity.status(302)
|
|
||||||
.location(URI.create(twintPaymentService.getTwintPaymentUrl(order)))
|
|
||||||
.build();
|
|
||||||
}
|
|
||||||
|
|
||||||
public ResponseEntity<byte[]> getTwintQr(UUID orderId, int size) {
|
|
||||||
Order order = orderRepo.findById(orderId).orElse(null);
|
|
||||||
if (order == null) {
|
|
||||||
return ResponseEntity.notFound().build();
|
|
||||||
}
|
|
||||||
|
|
||||||
int normalizedSize = Math.max(200, Math.min(size, 600));
|
|
||||||
byte[] png = twintPaymentService.generateQrPng(order, normalizedSize);
|
|
||||||
|
|
||||||
return ResponseEntity.ok()
|
|
||||||
.contentType(MediaType.IMAGE_PNG)
|
|
||||||
.body(png);
|
|
||||||
}
|
|
||||||
|
|
||||||
private ResponseEntity<byte[]> generateDocument(UUID orderId, boolean isConfirmation) {
|
|
||||||
Order order = orderRepo.findById(orderId)
|
|
||||||
.orElseThrow(() -> new RuntimeException("Order not found"));
|
|
||||||
|
|
||||||
if (isConfirmation) {
|
|
||||||
Path relativePath = buildConfirmationPdfRelativePath(order);
|
|
||||||
try {
|
|
||||||
byte[] existingPdf = storageService.loadAsResource(relativePath).getInputStream().readAllBytes();
|
|
||||||
return ResponseEntity.ok()
|
|
||||||
.header("Content-Disposition", "attachment; filename=\"confirmation-" + getDisplayOrderNumber(order) + ".pdf\"")
|
|
||||||
.contentType(MediaType.APPLICATION_PDF)
|
|
||||||
.body(existingPdf);
|
|
||||||
} catch (Exception ignored) {
|
|
||||||
// Fallback to on-the-fly generation if the stored file is missing or unreadable.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
List<OrderItem> items = orderItemRepo.findByOrder_Id(orderId);
|
|
||||||
Payment payment = paymentRepo.findByOrder_Id(orderId).orElse(null);
|
|
||||||
|
|
||||||
byte[] pdf = invoiceService.generateDocumentPdf(order, items, isConfirmation, qrBillService, payment);
|
|
||||||
String typePrefix = isConfirmation ? "confirmation-" : "invoice-";
|
|
||||||
String truncatedUuid = order.getId().toString().substring(0, 8);
|
|
||||||
return ResponseEntity.ok()
|
|
||||||
.header("Content-Disposition", "attachment; filename=\"" + typePrefix + truncatedUuid + ".pdf\"")
|
|
||||||
.contentType(MediaType.APPLICATION_PDF)
|
|
||||||
.body(pdf);
|
|
||||||
}
|
|
||||||
|
|
||||||
private Path buildConfirmationPdfRelativePath(Order order) {
|
|
||||||
return Path.of(
|
|
||||||
"orders",
|
|
||||||
order.getId().toString(),
|
|
||||||
"documents",
|
|
||||||
"confirmation-" + getDisplayOrderNumber(order) + ".pdf"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String getExtension(String filename) {
|
|
||||||
if (filename == null) {
|
|
||||||
return "stl";
|
|
||||||
}
|
|
||||||
String cleaned = StringUtils.cleanPath(filename);
|
|
||||||
if (cleaned.contains("..")) {
|
|
||||||
return "stl";
|
|
||||||
}
|
|
||||||
int i = cleaned.lastIndexOf('.');
|
|
||||||
if (i > 0 && i < cleaned.length() - 1) {
|
|
||||||
String ext = cleaned.substring(i + 1).toLowerCase(Locale.ROOT);
|
|
||||||
if (SAFE_EXTENSION_PATTERN.matcher(ext).matches()) {
|
|
||||||
return ext;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return "stl";
|
|
||||||
}
|
|
||||||
|
|
||||||
private Path resolveOrderItemRelativePath(String storedRelativePath, UUID orderId, UUID orderItemId) {
|
|
||||||
try {
|
|
||||||
Path candidate = Path.of(storedRelativePath).normalize();
|
|
||||||
if (candidate.isAbsolute()) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
Path expectedPrefix = Path.of("orders", orderId.toString(), "3d-files", orderItemId.toString());
|
|
||||||
if (!candidate.startsWith(expectedPrefix)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return candidate;
|
|
||||||
} catch (InvalidPathException e) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private OrderDto convertToDto(Order order, List<OrderItem> items) {
|
|
||||||
OrderDto dto = new OrderDto();
|
|
||||||
dto.setId(order.getId());
|
|
||||||
dto.setOrderNumber(getDisplayOrderNumber(order));
|
|
||||||
dto.setSourceType(order.getSourceType() != null ? order.getSourceType() : "CALCULATOR");
|
|
||||||
dto.setStatus(order.getStatus());
|
|
||||||
|
|
||||||
paymentRepo.findByOrder_Id(order.getId()).ifPresent(payment -> {
|
|
||||||
dto.setPaymentStatus(payment.getStatus());
|
|
||||||
dto.setPaymentMethod(payment.getMethod());
|
|
||||||
});
|
|
||||||
|
|
||||||
boolean redactPersonalData = shouldRedactPersonalData(order.getStatus());
|
|
||||||
if (!redactPersonalData) {
|
|
||||||
dto.setCustomerEmail(order.getCustomerEmail());
|
|
||||||
dto.setCustomerPhone(order.getCustomerPhone());
|
|
||||||
dto.setBillingCustomerType(order.getBillingCustomerType());
|
|
||||||
}
|
|
||||||
dto.setPreferredLanguage(order.getPreferredLanguage());
|
|
||||||
dto.setCurrency(order.getCurrency());
|
|
||||||
dto.setSetupCostChf(order.getSetupCostChf());
|
|
||||||
dto.setShippingCostChf(order.getShippingCostChf());
|
|
||||||
dto.setDiscountChf(order.getDiscountChf());
|
|
||||||
dto.setSubtotalChf(order.getSubtotalChf());
|
|
||||||
dto.setIsCadOrder(order.getIsCadOrder());
|
|
||||||
dto.setSourceRequestId(order.getSourceRequestId());
|
|
||||||
dto.setCadHours(order.getCadHours());
|
|
||||||
dto.setCadHourlyRateChf(order.getCadHourlyRateChf());
|
|
||||||
dto.setCadTotalChf(order.getCadTotalChf());
|
|
||||||
dto.setTotalChf(order.getTotalChf());
|
|
||||||
dto.setCreatedAt(order.getCreatedAt());
|
|
||||||
dto.setShippingSameAsBilling(order.getShippingSameAsBilling());
|
|
||||||
|
|
||||||
if (!redactPersonalData) {
|
|
||||||
AddressDto billing = new AddressDto();
|
|
||||||
billing.setFirstName(order.getBillingFirstName());
|
|
||||||
billing.setLastName(order.getBillingLastName());
|
|
||||||
billing.setCompanyName(order.getBillingCompanyName());
|
|
||||||
billing.setContactPerson(order.getBillingContactPerson());
|
|
||||||
billing.setAddressLine1(order.getBillingAddressLine1());
|
|
||||||
billing.setAddressLine2(order.getBillingAddressLine2());
|
|
||||||
billing.setZip(order.getBillingZip());
|
|
||||||
billing.setCity(order.getBillingCity());
|
|
||||||
billing.setCountryCode(order.getBillingCountryCode());
|
|
||||||
dto.setBillingAddress(billing);
|
|
||||||
|
|
||||||
if (!Boolean.TRUE.equals(order.getShippingSameAsBilling())) {
|
|
||||||
AddressDto shipping = new AddressDto();
|
|
||||||
shipping.setFirstName(order.getShippingFirstName());
|
|
||||||
shipping.setLastName(order.getShippingLastName());
|
|
||||||
shipping.setCompanyName(order.getShippingCompanyName());
|
|
||||||
shipping.setContactPerson(order.getShippingContactPerson());
|
|
||||||
shipping.setAddressLine1(order.getShippingAddressLine1());
|
|
||||||
shipping.setAddressLine2(order.getShippingAddressLine2());
|
|
||||||
shipping.setZip(order.getShippingZip());
|
|
||||||
shipping.setCity(order.getShippingCity());
|
|
||||||
shipping.setCountryCode(order.getShippingCountryCode());
|
|
||||||
dto.setShippingAddress(shipping);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
List<OrderItemDto> itemDtos = items.stream().map(item -> {
|
|
||||||
OrderItemDto itemDto = new OrderItemDto();
|
|
||||||
itemDto.setId(item.getId());
|
|
||||||
itemDto.setItemType(item.getItemType() != null ? item.getItemType() : "PRINT_FILE");
|
|
||||||
itemDto.setOriginalFilename(item.getOriginalFilename());
|
|
||||||
itemDto.setDisplayName(
|
|
||||||
item.getDisplayName() != null && !item.getDisplayName().isBlank()
|
|
||||||
? item.getDisplayName()
|
|
||||||
: item.getOriginalFilename()
|
|
||||||
);
|
|
||||||
itemDto.setMaterialCode(item.getMaterialCode());
|
|
||||||
itemDto.setColorCode(item.getColorCode());
|
|
||||||
if (item.getShopProduct() != null) {
|
|
||||||
itemDto.setShopProductId(item.getShopProduct().getId());
|
|
||||||
}
|
|
||||||
if (item.getShopProductVariant() != null) {
|
|
||||||
itemDto.setShopProductVariantId(item.getShopProductVariant().getId());
|
|
||||||
}
|
|
||||||
itemDto.setShopProductSlug(item.getShopProductSlug());
|
|
||||||
itemDto.setShopProductName(item.getShopProductName());
|
|
||||||
itemDto.setShopVariantLabel(item.getShopVariantLabel());
|
|
||||||
itemDto.setShopVariantColorName(item.getShopVariantColorName());
|
|
||||||
itemDto.setShopVariantColorLabelIt(item.getShopProductVariant() != null ? item.getShopProductVariant().getColorLabelIt() : null);
|
|
||||||
itemDto.setShopVariantColorLabelEn(item.getShopProductVariant() != null ? item.getShopProductVariant().getColorLabelEn() : null);
|
|
||||||
itemDto.setShopVariantColorLabelDe(item.getShopProductVariant() != null ? item.getShopProductVariant().getColorLabelDe() : null);
|
|
||||||
itemDto.setShopVariantColorLabelFr(item.getShopProductVariant() != null ? item.getShopProductVariant().getColorLabelFr() : null);
|
|
||||||
itemDto.setShopVariantColorHex(item.getShopVariantColorHex());
|
|
||||||
if (item.getFilamentVariant() != null) {
|
|
||||||
itemDto.setFilamentVariantId(item.getFilamentVariant().getId());
|
|
||||||
itemDto.setFilamentVariantDisplayName(item.getFilamentVariant().getVariantDisplayName());
|
|
||||||
itemDto.setFilamentColorName(item.getFilamentVariant().getColorName());
|
|
||||||
itemDto.setFilamentColorLabelIt(item.getFilamentVariant().getColorLabelIt());
|
|
||||||
itemDto.setFilamentColorLabelEn(item.getFilamentVariant().getColorLabelEn());
|
|
||||||
itemDto.setFilamentColorLabelDe(item.getFilamentVariant().getColorLabelDe());
|
|
||||||
itemDto.setFilamentColorLabelFr(item.getFilamentVariant().getColorLabelFr());
|
|
||||||
itemDto.setFilamentColorHex(item.getFilamentVariant().getColorHex());
|
|
||||||
}
|
|
||||||
itemDto.setQuality(item.getQuality());
|
|
||||||
itemDto.setNozzleDiameterMm(item.getNozzleDiameterMm());
|
|
||||||
itemDto.setLayerHeightMm(item.getLayerHeightMm());
|
|
||||||
itemDto.setInfillPercent(item.getInfillPercent());
|
|
||||||
itemDto.setInfillPattern(item.getInfillPattern());
|
|
||||||
itemDto.setSupportsEnabled(item.getSupportsEnabled());
|
|
||||||
itemDto.setQuantity(item.getQuantity());
|
|
||||||
itemDto.setPrintTimeSeconds(item.getPrintTimeSeconds());
|
|
||||||
itemDto.setMaterialGrams(item.getMaterialGrams());
|
|
||||||
itemDto.setUnitPriceChf(item.getUnitPriceChf());
|
|
||||||
itemDto.setLineTotalChf(item.getLineTotalChf());
|
|
||||||
return itemDto;
|
|
||||||
}).collect(Collectors.toList());
|
|
||||||
dto.setItems(itemDtos);
|
|
||||||
|
|
||||||
return dto;
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean shouldRedactPersonalData(String status) {
|
|
||||||
if (status == null || status.isBlank()) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return PERSONAL_DATA_REDACTED_STATUSES.contains(status.trim().toUpperCase(Locale.ROOT));
|
|
||||||
}
|
|
||||||
|
|
||||||
private String getDisplayOrderNumber(Order order) {
|
|
||||||
String orderNumber = order.getOrderNumber();
|
|
||||||
if (orderNumber != null && !orderNumber.isBlank()) {
|
|
||||||
return orderNumber;
|
|
||||||
}
|
|
||||||
return order.getId() != null ? order.getId().toString() : "unknown";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -88,9 +88,14 @@ public class InvoicePdfRenderingService {
|
|||||||
vars.put("shippingAddressLine2", order.getShippingZip() + " " + order.getShippingCity() + ", " + order.getShippingCountryCode());
|
vars.put("shippingAddressLine2", order.getShippingZip() + " " + order.getShippingCity() + ", " + order.getShippingCountryCode());
|
||||||
}
|
}
|
||||||
|
|
||||||
List<Map<String, Object>> invoiceLineItems = items.stream()
|
List<Map<String, Object>> invoiceLineItems = items.stream().map(i -> {
|
||||||
.map(this::toInvoiceLineItem)
|
Map<String, Object> line = new HashMap<>();
|
||||||
.collect(Collectors.toList());
|
line.put("description", "Stampa 3D: " + i.getOriginalFilename());
|
||||||
|
line.put("quantity", i.getQuantity());
|
||||||
|
line.put("unitPriceFormatted", String.format("CHF %.2f", i.getUnitPriceChf()));
|
||||||
|
line.put("lineTotalFormatted", String.format("CHF %.2f", i.getLineTotalChf()));
|
||||||
|
return line;
|
||||||
|
}).collect(Collectors.toList());
|
||||||
|
|
||||||
if (order.getCadTotalChf() != null && order.getCadTotalChf().compareTo(BigDecimal.ZERO) > 0) {
|
if (order.getCadTotalChf() != null && order.getCadTotalChf().compareTo(BigDecimal.ZERO) > 0) {
|
||||||
BigDecimal cadHours = order.getCadHours() != null ? order.getCadHours() : BigDecimal.ZERO;
|
BigDecimal cadHours = order.getCadHours() != null ? order.getCadHours() : BigDecimal.ZERO;
|
||||||
@@ -152,45 +157,4 @@ public class InvoicePdfRenderingService {
|
|||||||
private String formatCadHours(BigDecimal hours) {
|
private String formatCadHours(BigDecimal hours) {
|
||||||
return hours.setScale(2, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString();
|
return hours.setScale(2, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString();
|
||||||
}
|
}
|
||||||
|
|
||||||
private Map<String, Object> toInvoiceLineItem(OrderItem item) {
|
|
||||||
Map<String, Object> line = new HashMap<>();
|
|
||||||
line.put("description", buildLineDescription(item));
|
|
||||||
line.put("quantity", item.getQuantity());
|
|
||||||
line.put("unitPriceFormatted", String.format("CHF %.2f", item.getUnitPriceChf()));
|
|
||||||
line.put("lineTotalFormatted", String.format("CHF %.2f", item.getLineTotalChf()));
|
|
||||||
return line;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String buildLineDescription(OrderItem item) {
|
|
||||||
if (item == null) {
|
|
||||||
return "Articolo";
|
|
||||||
}
|
|
||||||
|
|
||||||
if ("SHOP_PRODUCT".equalsIgnoreCase(item.getItemType())) {
|
|
||||||
String productName = firstNonBlank(
|
|
||||||
item.getDisplayName(),
|
|
||||||
item.getShopProductName(),
|
|
||||||
item.getOriginalFilename(),
|
|
||||||
"Prodotto shop"
|
|
||||||
);
|
|
||||||
String variantLabel = firstNonBlank(item.getShopVariantLabel(), item.getShopVariantColorName(), null);
|
|
||||||
return variantLabel != null ? productName + " - " + variantLabel : productName;
|
|
||||||
}
|
|
||||||
|
|
||||||
String fileName = firstNonBlank(item.getDisplayName(), item.getOriginalFilename(), "File 3D");
|
|
||||||
return "Stampa 3D: " + fileName;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String firstNonBlank(String... values) {
|
|
||||||
if (values == null || values.length == 0) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
for (String value : values) {
|
|
||||||
if (value != null && !value.isBlank()) {
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ import com.printcalculator.model.QuoteResult;
|
|||||||
import com.printcalculator.repository.QuoteLineItemRepository;
|
import com.printcalculator.repository.QuoteLineItemRepository;
|
||||||
import com.printcalculator.repository.QuoteSessionRepository;
|
import com.printcalculator.repository.QuoteSessionRepository;
|
||||||
import com.printcalculator.service.OrcaProfileResolver;
|
import com.printcalculator.service.OrcaProfileResolver;
|
||||||
import com.printcalculator.service.ProfileManager;
|
|
||||||
import com.printcalculator.service.QuoteCalculator;
|
import com.printcalculator.service.QuoteCalculator;
|
||||||
import com.printcalculator.service.SlicerService;
|
import com.printcalculator.service.SlicerService;
|
||||||
import com.printcalculator.service.storage.ClamAVService;
|
import com.printcalculator.service.storage.ClamAVService;
|
||||||
@@ -42,7 +41,6 @@ public class QuoteSessionItemService {
|
|||||||
private final ClamAVService clamAVService;
|
private final ClamAVService clamAVService;
|
||||||
private final QuoteStorageService quoteStorageService;
|
private final QuoteStorageService quoteStorageService;
|
||||||
private final QuoteSessionSettingsService settingsService;
|
private final QuoteSessionSettingsService settingsService;
|
||||||
private final ProfileManager profileManager;
|
|
||||||
|
|
||||||
public QuoteSessionItemService(QuoteLineItemRepository lineItemRepo,
|
public QuoteSessionItemService(QuoteLineItemRepository lineItemRepo,
|
||||||
QuoteSessionRepository sessionRepo,
|
QuoteSessionRepository sessionRepo,
|
||||||
@@ -51,8 +49,7 @@ public class QuoteSessionItemService {
|
|||||||
OrcaProfileResolver orcaProfileResolver,
|
OrcaProfileResolver orcaProfileResolver,
|
||||||
ClamAVService clamAVService,
|
ClamAVService clamAVService,
|
||||||
QuoteStorageService quoteStorageService,
|
QuoteStorageService quoteStorageService,
|
||||||
QuoteSessionSettingsService settingsService,
|
QuoteSessionSettingsService settingsService) {
|
||||||
ProfileManager profileManager) {
|
|
||||||
this.lineItemRepo = lineItemRepo;
|
this.lineItemRepo = lineItemRepo;
|
||||||
this.sessionRepo = sessionRepo;
|
this.sessionRepo = sessionRepo;
|
||||||
this.slicerService = slicerService;
|
this.slicerService = slicerService;
|
||||||
@@ -61,7 +58,6 @@ public class QuoteSessionItemService {
|
|||||||
this.clamAVService = clamAVService;
|
this.clamAVService = clamAVService;
|
||||||
this.quoteStorageService = quoteStorageService;
|
this.quoteStorageService = quoteStorageService;
|
||||||
this.settingsService = settingsService;
|
this.settingsService = settingsService;
|
||||||
this.profileManager = profileManager;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public QuoteLineItem addItemToSession(QuoteSession session, MultipartFile file, PrintSettingsDto settings) throws IOException {
|
public QuoteLineItem addItemToSession(QuoteSession session, MultipartFile file, PrintSettingsDto settings) throws IOException {
|
||||||
@@ -72,14 +68,10 @@ public class QuoteSessionItemService {
|
|||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Cannot modify a converted session");
|
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Cannot modify a converted session");
|
||||||
}
|
}
|
||||||
|
|
||||||
String ext = quoteStorageService.getSafeExtension(file.getOriginalFilename(), "");
|
|
||||||
if (ext.isBlank()) {
|
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Unsupported file type. Allowed: stl, 3mf");
|
|
||||||
}
|
|
||||||
|
|
||||||
clamAVService.scan(file.getInputStream());
|
clamAVService.scan(file.getInputStream());
|
||||||
|
|
||||||
Path sessionStorageDir = quoteStorageService.sessionStorageDir(session.getId());
|
Path sessionStorageDir = quoteStorageService.sessionStorageDir(session.getId());
|
||||||
|
String ext = quoteStorageService.getSafeExtension(file.getOriginalFilename(), "stl");
|
||||||
String storedFilename = UUID.randomUUID() + "." + ext;
|
String storedFilename = UUID.randomUUID() + "." + ext;
|
||||||
Path persistentPath = quoteStorageService.resolveSessionPath(sessionStorageDir, storedFilename);
|
Path persistentPath = quoteStorageService.resolveSessionPath(sessionStorageDir, storedFilename);
|
||||||
|
|
||||||
@@ -117,12 +109,7 @@ public class QuoteSessionItemService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
OrcaProfileResolver.ResolvedProfiles profiles = orcaProfileResolver.resolve(machine, nozzleDiameter, selectedVariant);
|
OrcaProfileResolver.ResolvedProfiles profiles = orcaProfileResolver.resolve(machine, nozzleDiameter, selectedVariant);
|
||||||
String processProfile = resolveProcessProfile(
|
String processProfile = resolveProcessProfile(settings);
|
||||||
settings,
|
|
||||||
profiles.machineProfileName(),
|
|
||||||
nozzleDiameter,
|
|
||||||
layerHeight
|
|
||||||
);
|
|
||||||
|
|
||||||
Map<String, String> processOverrides = new HashMap<>();
|
Map<String, String> processOverrides = new HashMap<>();
|
||||||
processOverrides.put("layer_height", layerHeight.stripTrailingZeros().toPlainString());
|
processOverrides.put("layer_height", layerHeight.stripTrailingZeros().toPlainString());
|
||||||
@@ -193,29 +180,7 @@ public class QuoteSessionItemService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private String resolveProcessProfile(PrintSettingsDto settings,
|
private String resolveProcessProfile(PrintSettingsDto settings) {
|
||||||
String machineProfileName,
|
|
||||||
BigDecimal nozzleDiameter,
|
|
||||||
BigDecimal layerHeight) {
|
|
||||||
if (machineProfileName == null || machineProfileName.isBlank() || layerHeight == null) {
|
|
||||||
return resolveLegacyProcessProfile(settings);
|
|
||||||
}
|
|
||||||
|
|
||||||
String qualityHint = settingsService.resolveQuality(settings, layerHeight);
|
|
||||||
return profileManager
|
|
||||||
.findCompatibleProcessProfileName(machineProfileName, layerHeight, qualityHint)
|
|
||||||
.orElseThrow(() -> new ResponseStatusException(
|
|
||||||
HttpStatus.BAD_REQUEST,
|
|
||||||
"Layer height " + layerHeight.stripTrailingZeros().toPlainString()
|
|
||||||
+ " is not available for nozzle "
|
|
||||||
+ (nozzleDiameter != null
|
|
||||||
? nozzleDiameter.stripTrailingZeros().toPlainString()
|
|
||||||
: "-")
|
|
||||||
+ " on printer profile " + machineProfileName
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
private String resolveLegacyProcessProfile(PrintSettingsDto settings) {
|
|
||||||
if (settings.getLayerHeight() == null) {
|
if (settings.getLayerHeight() == null) {
|
||||||
return "standard";
|
return "standard";
|
||||||
}
|
}
|
||||||
@@ -241,11 +206,9 @@ public class QuoteSessionItemService {
|
|||||||
Path convertedPersistentPath) {
|
Path convertedPersistentPath) {
|
||||||
QuoteLineItem item = new QuoteLineItem();
|
QuoteLineItem item = new QuoteLineItem();
|
||||||
item.setQuoteSession(session);
|
item.setQuoteSession(session);
|
||||||
item.setLineItemType("PRINT_FILE");
|
|
||||||
item.setOriginalFilename(originalFilename);
|
item.setOriginalFilename(originalFilename);
|
||||||
item.setDisplayName(originalFilename);
|
|
||||||
item.setStoredPath(quoteStorageService.toStoredPath(persistentPath));
|
item.setStoredPath(quoteStorageService.toStoredPath(persistentPath));
|
||||||
item.setQuantity(normalizeQuantity(settings.getQuantity()));
|
item.setQuantity(1);
|
||||||
item.setColorCode(selectedVariant.getColorName());
|
item.setColorCode(selectedVariant.getColorName());
|
||||||
item.setFilamentVariant(selectedVariant);
|
item.setFilamentVariant(selectedVariant);
|
||||||
item.setMaterialCode(selectedVariant.getFilamentMaterialType() != null
|
item.setMaterialCode(selectedVariant.getFilamentMaterialType() != null
|
||||||
@@ -285,11 +248,4 @@ public class QuoteSessionItemService {
|
|||||||
item.setUpdatedAt(OffsetDateTime.now());
|
item.setUpdatedAt(OffsetDateTime.now());
|
||||||
return item;
|
return item;
|
||||||
}
|
}
|
||||||
|
|
||||||
private int normalizeQuantity(Integer quantity) {
|
|
||||||
if (quantity == null || quantity < 1) {
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
return quantity;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -34,62 +34,21 @@ public class QuoteSessionResponseAssembler {
|
|||||||
response.put("printItemsTotalChf", totals.printItemsTotalChf());
|
response.put("printItemsTotalChf", totals.printItemsTotalChf());
|
||||||
response.put("cadTotalChf", totals.cadTotalChf());
|
response.put("cadTotalChf", totals.cadTotalChf());
|
||||||
response.put("itemsTotalChf", totals.itemsTotalChf());
|
response.put("itemsTotalChf", totals.itemsTotalChf());
|
||||||
response.put("baseSetupCostChf", totals.baseSetupCostChf());
|
|
||||||
response.put("nozzleChangeCostChf", totals.nozzleChangeCostChf());
|
|
||||||
response.put("setupCostChf", totals.setupCostChf());
|
|
||||||
response.put("shippingCostChf", totals.shippingCostChf());
|
response.put("shippingCostChf", totals.shippingCostChf());
|
||||||
response.put("globalMachineCostChf", totals.globalMachineCostChf());
|
response.put("globalMachineCostChf", totals.globalMachineCostChf());
|
||||||
response.put("grandTotalChf", totals.grandTotalChf());
|
response.put("grandTotalChf", totals.grandTotalChf());
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Map<String, Object> emptyCart() {
|
|
||||||
Map<String, Object> response = new HashMap<>();
|
|
||||||
response.put("session", null);
|
|
||||||
response.put("items", List.of());
|
|
||||||
response.put("printItemsTotalChf", BigDecimal.ZERO);
|
|
||||||
response.put("cadTotalChf", BigDecimal.ZERO);
|
|
||||||
response.put("itemsTotalChf", BigDecimal.ZERO);
|
|
||||||
response.put("baseSetupCostChf", BigDecimal.ZERO);
|
|
||||||
response.put("nozzleChangeCostChf", BigDecimal.ZERO);
|
|
||||||
response.put("setupCostChf", BigDecimal.ZERO);
|
|
||||||
response.put("shippingCostChf", BigDecimal.ZERO);
|
|
||||||
response.put("globalMachineCostChf", BigDecimal.ZERO);
|
|
||||||
response.put("grandTotalChf", BigDecimal.ZERO);
|
|
||||||
return response;
|
|
||||||
}
|
|
||||||
|
|
||||||
private Map<String, Object> toItemDto(QuoteLineItem item, QuoteSessionTotalsService.QuoteSessionTotals totals) {
|
private Map<String, Object> toItemDto(QuoteLineItem item, QuoteSessionTotalsService.QuoteSessionTotals totals) {
|
||||||
Map<String, Object> dto = new HashMap<>();
|
Map<String, Object> dto = new HashMap<>();
|
||||||
dto.put("id", item.getId());
|
dto.put("id", item.getId());
|
||||||
dto.put("lineItemType", item.getLineItemType() != null ? item.getLineItemType() : "PRINT_FILE");
|
|
||||||
dto.put("originalFilename", item.getOriginalFilename());
|
dto.put("originalFilename", item.getOriginalFilename());
|
||||||
dto.put(
|
|
||||||
"displayName",
|
|
||||||
item.getDisplayName() != null && !item.getDisplayName().isBlank()
|
|
||||||
? item.getDisplayName()
|
|
||||||
: item.getOriginalFilename()
|
|
||||||
);
|
|
||||||
dto.put("quantity", item.getQuantity());
|
dto.put("quantity", item.getQuantity());
|
||||||
dto.put("printTimeSeconds", item.getPrintTimeSeconds());
|
dto.put("printTimeSeconds", item.getPrintTimeSeconds());
|
||||||
dto.put("materialGrams", item.getMaterialGrams());
|
dto.put("materialGrams", item.getMaterialGrams());
|
||||||
dto.put("colorCode", item.getColorCode());
|
dto.put("colorCode", item.getColorCode());
|
||||||
dto.put("filamentVariantId", item.getFilamentVariant() != null ? item.getFilamentVariant().getId() : null);
|
dto.put("filamentVariantId", item.getFilamentVariant() != null ? item.getFilamentVariant().getId() : null);
|
||||||
dto.put("shopProductId", item.getShopProduct() != null ? item.getShopProduct().getId() : null);
|
|
||||||
dto.put("shopProductVariantId", item.getShopProductVariant() != null ? item.getShopProductVariant().getId() : null);
|
|
||||||
dto.put("shopProductSlug", item.getShopProductSlug());
|
|
||||||
dto.put("shopProductName", item.getShopProductName());
|
|
||||||
dto.put("shopVariantLabel", item.getShopVariantLabel());
|
|
||||||
dto.put("shopVariantColorName", item.getShopVariantColorName());
|
|
||||||
dto.put("shopVariantColorLabelIt", item.getShopProductVariant() != null ? item.getShopProductVariant().getColorLabelIt() : null);
|
|
||||||
dto.put("shopVariantColorLabelEn", item.getShopProductVariant() != null ? item.getShopProductVariant().getColorLabelEn() : null);
|
|
||||||
dto.put("shopVariantColorLabelDe", item.getShopProductVariant() != null ? item.getShopProductVariant().getColorLabelDe() : null);
|
|
||||||
dto.put("shopVariantColorLabelFr", item.getShopProductVariant() != null ? item.getShopProductVariant().getColorLabelFr() : null);
|
|
||||||
dto.put("shopVariantColorHex", item.getShopVariantColorHex());
|
|
||||||
dto.put("filamentColorLabelIt", item.getFilamentVariant() != null ? item.getFilamentVariant().getColorLabelIt() : null);
|
|
||||||
dto.put("filamentColorLabelEn", item.getFilamentVariant() != null ? item.getFilamentVariant().getColorLabelEn() : null);
|
|
||||||
dto.put("filamentColorLabelDe", item.getFilamentVariant() != null ? item.getFilamentVariant().getColorLabelDe() : null);
|
|
||||||
dto.put("filamentColorLabelFr", item.getFilamentVariant() != null ? item.getFilamentVariant().getColorLabelFr() : null);
|
|
||||||
dto.put("materialCode", item.getMaterialCode());
|
dto.put("materialCode", item.getMaterialCode());
|
||||||
dto.put("quality", item.getQuality());
|
dto.put("quality", item.getQuality());
|
||||||
dto.put("nozzleDiameterMm", item.getNozzleDiameterMm());
|
dto.put("nozzleDiameterMm", item.getNozzleDiameterMm());
|
||||||
|
|||||||
@@ -54,6 +54,7 @@ public class QuoteStorageService {
|
|||||||
return switch (ext) {
|
return switch (ext) {
|
||||||
case "stl" -> "stl";
|
case "stl" -> "stl";
|
||||||
case "3mf" -> "3mf";
|
case "3mf" -> "3mf";
|
||||||
|
case "step", "stp" -> "step";
|
||||||
default -> fallback;
|
default -> fallback;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user