Compare commits
73 Commits
feat/cad-b
...
77d7bdb265
| Author | SHA1 | Date | |
|---|---|---|---|
| 77d7bdb265 | |||
| cd2666d8e2 | |||
| 2f34c52b6f | |||
|
|
2606b22185 | ||
| 038e1634eb | |||
| f03f111d5e | |||
| aaa58346d3 | |||
| 506762c538 | |||
|
|
492d474c82 | ||
| 225995c892 | |||
| dfe109ac8d | |||
| ca22c0c461 | |||
| 8afab3e58e | |||
| b4462dcd9d | |||
|
|
f598e376a6 | ||
| e8ebef926e | |||
| 85598dee3b | |||
| 2dbf7e9c09 | |||
|
|
210820185b | ||
| 7615b8b601 | |||
| 17df0c6b9b | |||
| 9e306ea1d1 | |||
| 63804e7561 | |||
| 0c4800443f | |||
| 72c0c2c098 | |||
| b517373538 | |||
| 1bd6a43614 | |||
|
|
575a540a70 | ||
| 47c442aba9 | |||
| 042c254691 | |||
| 7a699d2adf | |||
| 00825b1002 | |||
|
|
811e0f441b | ||
| 235fe7780d | |||
| 93b0b55f43 | |||
| cdd0d22d9a | |||
| 0a3510e996 | |||
| 819ac01d44 | |||
|
|
aa6322e928 | ||
| a7491130fb | |||
| 8e23bd97e6 | |||
| 71424f086e | |||
| b2edf5ec4c | |||
| 8c61990827 | |||
| 54b50028b1 | |||
| 40da5ff1b7 | |||
| 9facf05c10 | |||
| fe3951b6c3 | |||
| 1effd4926f | |||
|
|
d061f21d79 | ||
| 266fab5e17 | |||
| a4b85b01bd | |||
| 30e28cb019 | |||
| 1a36808d9f | |||
| 8a57aa78fb | |||
| de9e473cca | |||
| a7f58175fa | |||
| 460b878fbb | |||
| 4a8925df13 | |||
| db3619e889 | |||
|
|
5e5a3949d4 | ||
| 0ef97eeb9b | |||
| 6149e4ac43 | |||
|
|
57360bacd0 | ||
| db3708aef6 | |||
| 2050ff35f4 | |||
| 038e79e52a | |||
| 6f47d02813 | |||
| 3916f3ace6 | |||
| df3fecf722 | |||
| 2c4fa570e1 | |||
| ab2229ec8b | |||
| d9931a6fae |
@@ -41,25 +41,38 @@ jobs:
|
||||
cache: "npm"
|
||||
cache-dependency-path: "frontend/package-lock.json"
|
||||
|
||||
- name: Install Chromium
|
||||
- name: Resolve Chrome binary
|
||||
shell: bash
|
||||
run: |
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends chromium
|
||||
set -euo pipefail
|
||||
if command -v chromium >/dev/null 2>&1; then
|
||||
CHROME_PATH="$(command -v chromium)"
|
||||
elif command -v chromium-browser >/dev/null 2>&1; then
|
||||
CHROME_PATH="$(command -v chromium-browser)"
|
||||
elif command -v google-chrome >/dev/null 2>&1; then
|
||||
CHROME_PATH="$(command -v google-chrome)"
|
||||
else
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends chromium
|
||||
CHROME_PATH="$(command -v chromium)"
|
||||
fi
|
||||
|
||||
echo "CHROME_BIN=$CHROME_PATH" >> "$GITHUB_ENV"
|
||||
echo "Using CHROME_BIN=$CHROME_PATH"
|
||||
|
||||
- name: Install frontend dependencies
|
||||
shell: bash
|
||||
run: |
|
||||
cd frontend
|
||||
npm ci --no-audit --no-fund
|
||||
npm ci --no-audit --no-fund --prefer-offline
|
||||
|
||||
- name: Run frontend tests (headless)
|
||||
shell: bash
|
||||
env:
|
||||
CHROME_BIN: /usr/bin/chromium
|
||||
CI: "true"
|
||||
run: |
|
||||
cd frontend
|
||||
echo "Karma CHROME_BIN=$CHROME_BIN"
|
||||
npm run test -- --watch=false --browsers=ChromeHeadlessNoSandbox
|
||||
|
||||
build-and-push:
|
||||
|
||||
@@ -150,23 +150,36 @@ jobs:
|
||||
cache: "npm"
|
||||
cache-dependency-path: "frontend/package-lock.json"
|
||||
|
||||
- name: Install Chromium
|
||||
- name: Resolve Chrome binary
|
||||
shell: bash
|
||||
run: |
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends chromium
|
||||
set -euo pipefail
|
||||
if command -v chromium >/dev/null 2>&1; then
|
||||
CHROME_PATH="$(command -v chromium)"
|
||||
elif command -v chromium-browser >/dev/null 2>&1; then
|
||||
CHROME_PATH="$(command -v chromium-browser)"
|
||||
elif command -v google-chrome >/dev/null 2>&1; then
|
||||
CHROME_PATH="$(command -v google-chrome)"
|
||||
else
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends chromium
|
||||
CHROME_PATH="$(command -v chromium)"
|
||||
fi
|
||||
|
||||
echo "CHROME_BIN=$CHROME_PATH" >> "$GITHUB_ENV"
|
||||
echo "Using CHROME_BIN=$CHROME_PATH"
|
||||
|
||||
- name: Install frontend dependencies
|
||||
shell: bash
|
||||
run: |
|
||||
cd frontend
|
||||
npm ci --no-audit --no-fund
|
||||
npm ci --no-audit --no-fund --prefer-offline
|
||||
|
||||
- name: Run frontend tests (headless)
|
||||
shell: bash
|
||||
env:
|
||||
CHROME_BIN: /usr/bin/chromium
|
||||
CI: "true"
|
||||
run: |
|
||||
cd frontend
|
||||
echo "Karma CHROME_BIN=$CHROME_BIN"
|
||||
npm run test -- --watch=false --browsers=ChromeHeadlessNoSandbox
|
||||
|
||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -44,8 +44,12 @@ build/
|
||||
|
||||
./storage_orders
|
||||
./storage_quotes
|
||||
./storage_requests
|
||||
./storage_media
|
||||
storage_orders
|
||||
storage_quotes
|
||||
storage_requests
|
||||
storage_media
|
||||
|
||||
# Qodana local reports/artifacts
|
||||
backend/.qodana/
|
||||
|
||||
51
README.md
51
README.md
@@ -11,7 +11,7 @@ Un'applicazione Full Stack (Angular + Spring Boot) per calcolare preventivi di s
|
||||
|
||||
## Stack Tecnologico
|
||||
|
||||
- **Backend**: Java 21, Spring Boot 3.4, PostgreSQL, Flyway.
|
||||
- **Backend**: Java 21, Spring Boot 3.4, PostgreSQL.
|
||||
- **Frontend**: Angular 19, Angular Material, Three.js.
|
||||
- **Slicer**: OrcaSlicer (invocato via CLI).
|
||||
|
||||
@@ -21,14 +21,20 @@ Un'applicazione Full Stack (Angular + Spring Boot) per calcolare preventivi di s
|
||||
* **Node.js 22** e **npm** installati.
|
||||
* **PostgreSQL** attivo.
|
||||
* **OrcaSlicer** installato sul sistema.
|
||||
* **FFmpeg** installato sul sistema o presente nell'immagine Docker del backend.
|
||||
|
||||
## Avvio Rapido
|
||||
|
||||
### 1. Database
|
||||
Crea un database PostgreSQL chiamato `printcalc`. Le tabelle verranno create automaticamente al primo avvio tramite Flyway.
|
||||
Crea un database PostgreSQL chiamato `printcalc`. Lo schema viene gestito dal progetto tramite configurazione JPA/SQL del repository.
|
||||
|
||||
### 2. Backend
|
||||
Configura il percorso di OrcaSlicer in `backend/src/main/resources/application.properties` o tramite la variabile d'ambiente `SLICER_PATH`.
|
||||
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:
|
||||
|
||||
- `MEDIA_STORAGE_ROOT` per la root `storage_media` usata dal backend (`original/`, `public/`, `private/`)
|
||||
- `MEDIA_PUBLIC_BASE_URL` per gli URL assoluti restituiti dalle API admin, ad esempio `https://example.com/media`
|
||||
- `MEDIA_FFMPEG_PATH` per il binario `ffmpeg`
|
||||
- `MEDIA_UPLOAD_MAX_FILE_SIZE_BYTES` per il limite per asset immagine
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
@@ -57,11 +63,50 @@ I prezzi non sono più gestiti tramite variabili d'ambiente fisse ma tramite tab
|
||||
* `/backend`: API Spring Boot.
|
||||
* `/frontend`: Applicazione Angular.
|
||||
* `/backend/profiles`: Contiene i file di configurazione per OrcaSlicer.
|
||||
* `/storage_media`: Originali e varianti media pubbliche/private su filesystem.
|
||||
|
||||
## 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 il volume media atteso è `/mnt/cache/appdata/print-calculator/${ENV}/storage_media:/app/storage_media`.
|
||||
|
||||
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
|
||||
|
||||
### 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).
|
||||
|
||||
### FFmpeg e media pubblici
|
||||
Verifica che `MEDIA_FFMPEG_PATH` punti a un `ffmpeg` con supporto JPEG, WebP e AVIF. Se gli URL media restituiti dalle API admin non sono raggiungibili, controlla che `MEDIA_PUBLIC_BASE_URL` corrisponda al `location /media/` esposto da Nginx e che il volume `storage_media` sia montato correttamente.
|
||||
|
||||
### Database connection
|
||||
Verifica le credenziali in `application.properties`. Se usi Docker, puoi passare `DB_URL`, `DB_USERNAME` e `DB_PASSWORD` come variabili d'ambiente.
|
||||
|
||||
@@ -13,16 +13,25 @@ FROM eclipse-temurin:21-jre-jammy
|
||||
ARG ORCA_VERSION=2.3.1
|
||||
ARG ORCA_DOWNLOAD_URL
|
||||
|
||||
# Install system dependencies for OrcaSlicer (same as before)
|
||||
RUN apt-get update && apt-get install -y \
|
||||
# Install system dependencies for OrcaSlicer and media processing.
|
||||
# The build fails fast if the packaged ffmpeg lacks JPEG/WebP/AVIF encoders.
|
||||
RUN set -eux; \
|
||||
apt-get update; \
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
|
||||
ffmpeg \
|
||||
wget \
|
||||
assimp-utils \
|
||||
libgl1 \
|
||||
libglib2.0-0 \
|
||||
libgtk-3-0 \
|
||||
libdbus-1-3 \
|
||||
libwebkit2gtk-4.0-37 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
libwebkit2gtk-4.0-37; \
|
||||
ffmpeg -hide_banner -encoders > /tmp/ffmpeg-encoders.txt; \
|
||||
grep -Eq '[[:space:]]mjpeg[[:space:]]' /tmp/ffmpeg-encoders.txt; \
|
||||
grep -Eq '[[:space:]](libwebp|webp)[[:space:]]' /tmp/ffmpeg-encoders.txt; \
|
||||
grep -Eq '[[:space:]](libaom-av1|librav1e|libsvtav1)[[:space:]]' /tmp/ffmpeg-encoders.txt; \
|
||||
rm -f /tmp/ffmpeg-encoders.txt; \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Install OrcaSlicer
|
||||
WORKDIR /opt
|
||||
|
||||
@@ -2,519 +2,46 @@ package com.printcalculator.controller;
|
||||
|
||||
import com.printcalculator.dto.QuoteRequestDto;
|
||||
import com.printcalculator.entity.CustomQuoteRequest;
|
||||
import com.printcalculator.entity.CustomQuoteRequestAttachment;
|
||||
import com.printcalculator.repository.CustomQuoteRequestAttachmentRepository;
|
||||
import com.printcalculator.repository.CustomQuoteRequestRepository;
|
||||
import com.printcalculator.service.ClamAVService;
|
||||
import com.printcalculator.service.email.EmailNotificationService;
|
||||
import com.printcalculator.service.request.CustomQuoteRequestControllerService;
|
||||
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.ResponseEntity;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
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.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestPart;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
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.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/custom-quote-requests")
|
||||
public class CustomQuoteRequestController {
|
||||
|
||||
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;
|
||||
private final CustomQuoteRequestControllerService customQuoteRequestControllerService;
|
||||
|
||||
@Value("${app.mail.contact-request.admin.enabled:true}")
|
||||
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;
|
||||
public CustomQuoteRequestController(CustomQuoteRequestControllerService customQuoteRequestControllerService) {
|
||||
this.customQuoteRequestControllerService = customQuoteRequestControllerService;
|
||||
}
|
||||
|
||||
// 1. Create Custom Quote Request
|
||||
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
@Transactional
|
||||
public ResponseEntity<CustomQuoteRequest> createCustomQuoteRequest(
|
||||
@Valid @RequestPart("request") QuoteRequestDto requestDto,
|
||||
@RequestPart(value = "files", required = false) List<MultipartFile> files
|
||||
) throws IOException {
|
||||
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);
|
||||
return ResponseEntity.ok(customQuoteRequestControllerService.createCustomQuoteRequest(requestDto, files));
|
||||
}
|
||||
|
||||
// 2. Get Request
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public ResponseEntity<CustomQuoteRequest> getCustomQuoteRequest(@PathVariable UUID id) {
|
||||
return requestRepo.findById(id)
|
||||
return customQuoteRequestControllerService.getCustomQuoteRequest(id)
|
||||
.map(ResponseEntity::ok)
|
||||
.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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,18 +3,19 @@ package com.printcalculator.controller;
|
||||
import com.printcalculator.dto.OptionsResponse;
|
||||
import com.printcalculator.entity.FilamentMaterialType;
|
||||
import com.printcalculator.entity.FilamentVariant;
|
||||
import com.printcalculator.entity.LayerHeightOption;
|
||||
import com.printcalculator.entity.MaterialOrcaProfileMap;
|
||||
import com.printcalculator.entity.NozzleOption;
|
||||
import com.printcalculator.entity.PrinterMachine;
|
||||
import com.printcalculator.entity.PrinterMachineProfile;
|
||||
import com.printcalculator.repository.FilamentMaterialTypeRepository;
|
||||
import com.printcalculator.repository.FilamentVariantRepository;
|
||||
import com.printcalculator.repository.LayerHeightOptionRepository;
|
||||
import com.printcalculator.repository.MaterialOrcaProfileMapRepository;
|
||||
import com.printcalculator.repository.NozzleOptionRepository;
|
||||
import com.printcalculator.repository.PrinterMachineRepository;
|
||||
import com.printcalculator.repository.PrinterMachineProfileRepository;
|
||||
import com.printcalculator.service.NozzleLayerHeightPolicyService;
|
||||
import com.printcalculator.service.OrcaProfileResolver;
|
||||
import com.printcalculator.service.ProfileManager;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
@@ -23,7 +24,11 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Comparator;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -32,26 +37,32 @@ public class OptionsController {
|
||||
|
||||
private final FilamentMaterialTypeRepository materialRepo;
|
||||
private final FilamentVariantRepository variantRepo;
|
||||
private final LayerHeightOptionRepository layerHeightRepo;
|
||||
private final NozzleOptionRepository nozzleRepo;
|
||||
private final PrinterMachineRepository printerMachineRepo;
|
||||
private final PrinterMachineProfileRepository printerMachineProfileRepo;
|
||||
private final MaterialOrcaProfileMapRepository materialOrcaMapRepo;
|
||||
private final OrcaProfileResolver orcaProfileResolver;
|
||||
private final ProfileManager profileManager;
|
||||
private final NozzleLayerHeightPolicyService nozzleLayerHeightPolicyService;
|
||||
|
||||
public OptionsController(FilamentMaterialTypeRepository materialRepo,
|
||||
FilamentVariantRepository variantRepo,
|
||||
LayerHeightOptionRepository layerHeightRepo,
|
||||
NozzleOptionRepository nozzleRepo,
|
||||
PrinterMachineRepository printerMachineRepo,
|
||||
PrinterMachineProfileRepository printerMachineProfileRepo,
|
||||
MaterialOrcaProfileMapRepository materialOrcaMapRepo,
|
||||
OrcaProfileResolver orcaProfileResolver) {
|
||||
OrcaProfileResolver orcaProfileResolver,
|
||||
ProfileManager profileManager,
|
||||
NozzleLayerHeightPolicyService nozzleLayerHeightPolicyService) {
|
||||
this.materialRepo = materialRepo;
|
||||
this.variantRepo = variantRepo;
|
||||
this.layerHeightRepo = layerHeightRepo;
|
||||
this.nozzleRepo = nozzleRepo;
|
||||
this.printerMachineRepo = printerMachineRepo;
|
||||
this.printerMachineProfileRepo = printerMachineProfileRepo;
|
||||
this.materialOrcaMapRepo = materialOrcaMapRepo;
|
||||
this.orcaProfileResolver = orcaProfileResolver;
|
||||
this.profileManager = profileManager;
|
||||
this.nozzleLayerHeightPolicyService = nozzleLayerHeightPolicyService;
|
||||
}
|
||||
|
||||
@GetMapping("/api/calculator/options")
|
||||
@@ -116,17 +127,27 @@ public class OptionsController {
|
||||
new OptionsResponse.InfillPatternOption("cubic", "Cubic")
|
||||
);
|
||||
|
||||
List<OptionsResponse.LayerHeightOptionDTO> layers = layerHeightRepo.findAll().stream()
|
||||
.filter(l -> Boolean.TRUE.equals(l.getIsActive()))
|
||||
.sorted(Comparator.comparing(LayerHeightOption::getLayerHeightMm))
|
||||
.map(l -> new OptionsResponse.LayerHeightOptionDTO(
|
||||
l.getLayerHeightMm().doubleValue(),
|
||||
String.format("%.2f mm", l.getLayerHeightMm())
|
||||
))
|
||||
.toList();
|
||||
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()
|
||||
.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))
|
||||
.map(n -> new OptionsResponse.NozzleOptionDTO(
|
||||
n.getNozzleDiameterMm().doubleValue(),
|
||||
@@ -137,24 +158,88 @@ public class OptionsController {
|
||||
))
|
||||
.toList();
|
||||
|
||||
return ResponseEntity.ok(new OptionsResponse(materialOptions, qualities, patterns, layers, nozzles));
|
||||
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(
|
||||
nozzleDiameter != null ? BigDecimal.valueOf(nozzleDiameter) : null
|
||||
);
|
||||
if (!visibleNozzles.isEmpty() && !visibleNozzles.contains(selectedNozzle)) {
|
||||
selectedNozzle = visibleNozzles.iterator().next();
|
||||
}
|
||||
|
||||
List<OptionsResponse.LayerHeightOptionDTO> layers = toLayerDtos(
|
||||
effectiveRulesByNozzle.getOrDefault(selectedNozzle, List.of())
|
||||
);
|
||||
if (layers.isEmpty()) {
|
||||
if (!visibleNozzles.isEmpty()) {
|
||||
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()
|
||||
.map(entry -> new OptionsResponse.NozzleLayerHeightOptionsDTO(
|
||||
entry.getKey().doubleValue(),
|
||||
toLayerDtos(entry.getValue())
|
||||
))
|
||||
.toList();
|
||||
|
||||
return ResponseEntity.ok(new OptionsResponse(
|
||||
materialOptions,
|
||||
qualities,
|
||||
patterns,
|
||||
layers,
|
||||
nozzles,
|
||||
layerHeightsByNozzle
|
||||
));
|
||||
}
|
||||
|
||||
private Set<Long> resolveCompatibleMaterialTypeIds(Long printerMachineId, Double nozzleDiameter) {
|
||||
PrinterMachine machine = null;
|
||||
if (printerMachineId != null) {
|
||||
machine = printerMachineRepo.findById(printerMachineId).orElse(null);
|
||||
}
|
||||
if (machine == null) {
|
||||
machine = printerMachineRepo.findFirstByIsActiveTrue().orElse(null);
|
||||
}
|
||||
PrinterMachine machine = resolveMachine(printerMachineId);
|
||||
if (machine == null) {
|
||||
return Set.of();
|
||||
}
|
||||
|
||||
BigDecimal nozzle = nozzleDiameter != null
|
||||
? BigDecimal.valueOf(nozzleDiameter)
|
||||
: BigDecimal.valueOf(0.40);
|
||||
BigDecimal nozzle = nozzleLayerHeightPolicyService.resolveNozzle(
|
||||
nozzleDiameter != null ? BigDecimal.valueOf(nozzleDiameter) : null
|
||||
);
|
||||
|
||||
PrinterMachineProfile machineProfile = orcaProfileResolver
|
||||
.resolveMachineProfile(machine, nozzle)
|
||||
@@ -172,6 +257,73 @@ public class OptionsController {
|
||||
.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) {
|
||||
return layers.stream()
|
||||
.sorted(Comparator.naturalOrder())
|
||||
.map(layer -> new OptionsResponse.LayerHeightOptionDTO(
|
||||
layer.doubleValue(),
|
||||
String.format("%.2f mm", layer)
|
||||
))
|
||||
.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) {
|
||||
if (variant.getColorHex() != null && !variant.getColorHex().isBlank()) {
|
||||
return variant.getColorHex();
|
||||
|
||||
@@ -1,140 +1,62 @@
|
||||
package com.printcalculator.controller;
|
||||
|
||||
import com.printcalculator.dto.*;
|
||||
import com.printcalculator.entity.*;
|
||||
import com.printcalculator.repository.*;
|
||||
import com.printcalculator.service.InvoicePdfRenderingService;
|
||||
import com.printcalculator.service.OrderService;
|
||||
import com.printcalculator.service.PaymentService;
|
||||
import com.printcalculator.service.QrBillService;
|
||||
import com.printcalculator.service.StorageService;
|
||||
import com.printcalculator.service.TwintPaymentService;
|
||||
import com.printcalculator.dto.CreateOrderRequest;
|
||||
import com.printcalculator.dto.OrderDto;
|
||||
import com.printcalculator.service.order.OrderControllerService;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
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.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 jakarta.validation.Valid;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import java.nio.file.InvalidPathException;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
import java.util.Base64;
|
||||
import java.util.stream.Collectors;
|
||||
import java.net.URI;
|
||||
import java.util.Locale;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.UUID;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/orders")
|
||||
public class OrderController {
|
||||
private static final Pattern SAFE_EXTENSION_PATTERN = Pattern.compile("^[a-z0-9]{1,10}$");
|
||||
|
||||
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;
|
||||
private final 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;
|
||||
public OrderController(OrderControllerService orderControllerService) {
|
||||
this.orderControllerService = orderControllerService;
|
||||
}
|
||||
|
||||
|
||||
// 1. Create Order from Quote
|
||||
@PostMapping("/from-quote/{quoteSessionId}")
|
||||
@Transactional
|
||||
public ResponseEntity<OrderDto> createOrderFromQuote(
|
||||
@PathVariable UUID quoteSessionId,
|
||||
@Valid @RequestBody com.printcalculator.dto.CreateOrderRequest request
|
||||
@Valid @RequestBody CreateOrderRequest request
|
||||
) {
|
||||
Order order = orderService.createOrderFromQuote(quoteSessionId, request);
|
||||
List<OrderItem> items = orderItemRepo.findByOrder_Id(order.getId());
|
||||
return ResponseEntity.ok(convertToDto(order, items));
|
||||
return ResponseEntity.ok(orderControllerService.createOrderFromQuote(quoteSessionId, request));
|
||||
}
|
||||
|
||||
|
||||
@PostMapping(value = "/{orderId}/items/{orderItemId}/file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
@Transactional
|
||||
public ResponseEntity<Void> uploadOrderItemFile(
|
||||
@PathVariable UUID orderId,
|
||||
@PathVariable UUID orderItemId,
|
||||
@RequestParam("file") MultipartFile file
|
||||
@PathVariable UUID orderId,
|
||||
@PathVariable UUID orderItemId,
|
||||
@RequestParam("file") MultipartFile file
|
||||
) throws IOException {
|
||||
|
||||
OrderItem item = orderItemRepo.findById(orderItemId)
|
||||
.orElseThrow(() -> new RuntimeException("OrderItem not found"));
|
||||
|
||||
if (!item.getOrder().getId().equals(orderId)) {
|
||||
boolean uploaded = orderControllerService.uploadOrderItemFile(orderId, orderItemId, file);
|
||||
if (!uploaded) {
|
||||
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();
|
||||
}
|
||||
|
||||
@GetMapping("/{orderId}")
|
||||
public ResponseEntity<OrderDto> getOrder(@PathVariable UUID orderId) {
|
||||
return orderRepo.findById(orderId)
|
||||
.map(o -> {
|
||||
List<OrderItem> items = orderItemRepo.findByOrder_Id(o.getId());
|
||||
return ResponseEntity.ok(convertToDto(o, items));
|
||||
})
|
||||
return orderControllerService.getOrder(orderId)
|
||||
.map(ResponseEntity::ok)
|
||||
.orElse(ResponseEntity.notFound().build());
|
||||
}
|
||||
|
||||
@@ -144,89 +66,29 @@ public class OrderController {
|
||||
@PathVariable UUID orderId,
|
||||
@RequestBody Map<String, String> payload
|
||||
) {
|
||||
String method = payload.get("method");
|
||||
paymentService.reportPayment(orderId, method);
|
||||
return getOrder(orderId);
|
||||
return orderControllerService.reportPayment(orderId, payload.get("method"))
|
||||
.map(ResponseEntity::ok)
|
||||
.orElse(ResponseEntity.notFound().build());
|
||||
}
|
||||
|
||||
@GetMapping("/{orderId}/confirmation")
|
||||
public ResponseEntity<byte[]> getConfirmation(@PathVariable UUID orderId) {
|
||||
return generateDocument(orderId, true);
|
||||
return orderControllerService.getConfirmation(orderId);
|
||||
}
|
||||
|
||||
@GetMapping("/{orderId}/invoice")
|
||||
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();
|
||||
}
|
||||
|
||||
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")
|
||||
public ResponseEntity<Map<String, String>> getTwintPayment(@PathVariable 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);
|
||||
return orderControllerService.getTwintPayment(orderId);
|
||||
}
|
||||
|
||||
@GetMapping("/{orderId}/twint/open")
|
||||
public ResponseEntity<Void> openTwintPayment(@PathVariable 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();
|
||||
return orderControllerService.openTwintPayment(orderId);
|
||||
}
|
||||
|
||||
@GetMapping("/{orderId}/twint/qr")
|
||||
@@ -234,132 +96,6 @@ public class OrderController {
|
||||
@PathVariable UUID orderId,
|
||||
@RequestParam(defaultValue = "320") 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);
|
||||
return orderControllerService.getTwintQr(orderId, size);
|
||||
}
|
||||
|
||||
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());
|
||||
});
|
||||
|
||||
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());
|
||||
|
||||
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.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 String getDisplayOrderNumber(Order order) {
|
||||
String orderNumber = order.getOrderNumber();
|
||||
if (orderNumber != null && !orderNumber.isBlank()) {
|
||||
return orderNumber;
|
||||
}
|
||||
return order.getId() != null ? order.getId().toString() : "unknown";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -4,17 +4,23 @@ import com.printcalculator.entity.PrinterMachine;
|
||||
import com.printcalculator.model.PrintStats;
|
||||
import com.printcalculator.model.QuoteResult;
|
||||
import com.printcalculator.repository.PrinterMachineRepository;
|
||||
import com.printcalculator.service.NozzleLayerHeightPolicyService;
|
||||
import com.printcalculator.service.QuoteCalculator;
|
||||
import com.printcalculator.service.SlicerService;
|
||||
import com.printcalculator.service.storage.ClamAVService;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.springframework.http.HttpStatus.BAD_REQUEST;
|
||||
|
||||
@RestController
|
||||
public class QuoteController {
|
||||
@@ -22,17 +28,23 @@ public class QuoteController {
|
||||
private final SlicerService slicerService;
|
||||
private final QuoteCalculator quoteCalculator;
|
||||
private final PrinterMachineRepository machineRepo;
|
||||
private final com.printcalculator.service.ClamAVService clamAVService;
|
||||
private final ClamAVService clamAVService;
|
||||
private final NozzleLayerHeightPolicyService nozzleLayerHeightPolicyService;
|
||||
|
||||
// Defaults (using aliases defined in ProfileManager)
|
||||
private static final String DEFAULT_FILAMENT = "pla_basic";
|
||||
private static final String DEFAULT_PROCESS = "standard";
|
||||
|
||||
public QuoteController(SlicerService slicerService, QuoteCalculator quoteCalculator, PrinterMachineRepository machineRepo, com.printcalculator.service.ClamAVService clamAVService) {
|
||||
public QuoteController(SlicerService slicerService,
|
||||
QuoteCalculator quoteCalculator,
|
||||
PrinterMachineRepository machineRepo,
|
||||
ClamAVService clamAVService,
|
||||
NozzleLayerHeightPolicyService nozzleLayerHeightPolicyService) {
|
||||
this.slicerService = slicerService;
|
||||
this.quoteCalculator = quoteCalculator;
|
||||
this.machineRepo = machineRepo;
|
||||
this.clamAVService = clamAVService;
|
||||
this.nozzleLayerHeightPolicyService = nozzleLayerHeightPolicyService;
|
||||
}
|
||||
|
||||
@PostMapping("/api/quote")
|
||||
@@ -69,15 +81,27 @@ public class QuoteController {
|
||||
if (infillPattern != null && !infillPattern.isEmpty()) {
|
||||
processOverrides.put("sparse_infill_pattern", infillPattern);
|
||||
}
|
||||
BigDecimal normalizedNozzle = nozzleLayerHeightPolicyService.resolveNozzle(
|
||||
nozzleDiameter != null ? BigDecimal.valueOf(nozzleDiameter) : null
|
||||
);
|
||||
if (layerHeight != null) {
|
||||
processOverrides.put("layer_height", String.valueOf(layerHeight));
|
||||
BigDecimal normalizedLayer = nozzleLayerHeightPolicyService.normalizeLayer(BigDecimal.valueOf(layerHeight));
|
||||
if (!nozzleLayerHeightPolicyService.isAllowed(normalizedNozzle, normalizedLayer)) {
|
||||
throw new ResponseStatusException(
|
||||
BAD_REQUEST,
|
||||
"Layer height " + normalizedLayer.stripTrailingZeros().toPlainString()
|
||||
+ " is not allowed for nozzle " + normalizedNozzle.stripTrailingZeros().toPlainString()
|
||||
+ ". Allowed: " + nozzleLayerHeightPolicyService.allowedLayersLabel(normalizedNozzle)
|
||||
);
|
||||
}
|
||||
processOverrides.put("layer_height", normalizedLayer.stripTrailingZeros().toPlainString());
|
||||
}
|
||||
if (supportEnabled != null) {
|
||||
processOverrides.put("enable_support", supportEnabled ? "1" : "0");
|
||||
}
|
||||
|
||||
if (nozzleDiameter != null) {
|
||||
machineOverrides.put("nozzle_diameter", String.valueOf(nozzleDiameter));
|
||||
machineOverrides.put("nozzle_diameter", normalizedNozzle.stripTrailingZeros().toPlainString());
|
||||
// Also need to ensure the printer profile is compatible or just override?
|
||||
// Usually nozzle diameter changes require a different printer profile or deep overrides.
|
||||
// For now, we trust the override key works on the base profile.
|
||||
|
||||
@@ -1,386 +1,217 @@
|
||||
package com.printcalculator.controller;
|
||||
|
||||
import com.printcalculator.entity.FilamentMaterialType;
|
||||
import com.printcalculator.entity.FilamentVariant;
|
||||
import com.printcalculator.entity.PrinterMachine;
|
||||
import com.printcalculator.dto.PrintSettingsDto;
|
||||
import com.printcalculator.entity.QuoteLineItem;
|
||||
import com.printcalculator.entity.QuoteSession;
|
||||
import com.printcalculator.model.ModelDimensions;
|
||||
import com.printcalculator.model.PrintStats;
|
||||
import com.printcalculator.model.QuoteResult;
|
||||
import com.printcalculator.repository.FilamentMaterialTypeRepository;
|
||||
import com.printcalculator.repository.FilamentVariantRepository;
|
||||
import com.printcalculator.repository.PrinterMachineRepository;
|
||||
import com.printcalculator.repository.QuoteLineItemRepository;
|
||||
import com.printcalculator.repository.QuoteSessionRepository;
|
||||
import com.printcalculator.service.OrcaProfileResolver;
|
||||
import com.printcalculator.service.QuoteCalculator;
|
||||
import com.printcalculator.service.QuoteSessionTotalsService;
|
||||
import com.printcalculator.service.SlicerService;
|
||||
import com.printcalculator.service.quote.QuoteSessionItemService;
|
||||
import com.printcalculator.service.quote.QuoteSessionResponseAssembler;
|
||||
import com.printcalculator.service.quote.QuoteStorageService;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.io.UrlResource;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
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.math.RoundingMode;
|
||||
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.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.Optional;
|
||||
import java.util.Locale;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.io.UrlResource;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import static org.springframework.http.HttpStatus.BAD_REQUEST;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/quote-sessions")
|
||||
|
||||
public class QuoteSessionController {
|
||||
private static final Path QUOTE_STORAGE_ROOT = Paths.get("storage_quotes").toAbsolutePath().normalize();
|
||||
|
||||
private final QuoteSessionRepository sessionRepo;
|
||||
private final QuoteLineItemRepository lineItemRepo;
|
||||
private final SlicerService slicerService;
|
||||
private final QuoteCalculator quoteCalculator;
|
||||
private final PrinterMachineRepository machineRepo;
|
||||
private final FilamentMaterialTypeRepository materialRepo;
|
||||
private final FilamentVariantRepository variantRepo;
|
||||
private final OrcaProfileResolver orcaProfileResolver;
|
||||
private final com.printcalculator.repository.PricingPolicyRepository pricingRepo;
|
||||
private final com.printcalculator.service.ClamAVService clamAVService;
|
||||
private final QuoteSessionTotalsService quoteSessionTotalsService;
|
||||
private final QuoteSessionItemService quoteSessionItemService;
|
||||
private final QuoteStorageService quoteStorageService;
|
||||
private final QuoteSessionResponseAssembler quoteSessionResponseAssembler;
|
||||
|
||||
public QuoteSessionController(QuoteSessionRepository sessionRepo,
|
||||
QuoteLineItemRepository lineItemRepo,
|
||||
SlicerService slicerService,
|
||||
QuoteCalculator quoteCalculator,
|
||||
PrinterMachineRepository machineRepo,
|
||||
FilamentMaterialTypeRepository materialRepo,
|
||||
FilamentVariantRepository variantRepo,
|
||||
OrcaProfileResolver orcaProfileResolver,
|
||||
com.printcalculator.repository.PricingPolicyRepository pricingRepo,
|
||||
com.printcalculator.service.ClamAVService clamAVService,
|
||||
QuoteSessionTotalsService quoteSessionTotalsService) {
|
||||
QuoteSessionTotalsService quoteSessionTotalsService,
|
||||
QuoteSessionItemService quoteSessionItemService,
|
||||
QuoteStorageService quoteStorageService,
|
||||
QuoteSessionResponseAssembler quoteSessionResponseAssembler) {
|
||||
this.sessionRepo = sessionRepo;
|
||||
this.lineItemRepo = lineItemRepo;
|
||||
this.slicerService = slicerService;
|
||||
this.quoteCalculator = quoteCalculator;
|
||||
this.machineRepo = machineRepo;
|
||||
this.materialRepo = materialRepo;
|
||||
this.variantRepo = variantRepo;
|
||||
this.orcaProfileResolver = orcaProfileResolver;
|
||||
this.pricingRepo = pricingRepo;
|
||||
this.clamAVService = clamAVService;
|
||||
this.quoteSessionTotalsService = quoteSessionTotalsService;
|
||||
this.quoteSessionItemService = quoteSessionItemService;
|
||||
this.quoteStorageService = quoteStorageService;
|
||||
this.quoteSessionResponseAssembler = quoteSessionResponseAssembler;
|
||||
}
|
||||
|
||||
// 1. Start a new empty session
|
||||
@PostMapping(value = "")
|
||||
@Transactional
|
||||
public ResponseEntity<QuoteSession> createSession() {
|
||||
QuoteSession session = new QuoteSession();
|
||||
session.setStatus("ACTIVE");
|
||||
session.setPricingVersion("v1");
|
||||
// Default material/settings will be set when items are added or updated?
|
||||
// For now set safe defaults
|
||||
session.setMaterialCode("PLA");
|
||||
session.setMaterialCode("PLA");
|
||||
session.setSupportsEnabled(false);
|
||||
session.setCreatedAt(OffsetDateTime.now());
|
||||
session.setExpiresAt(OffsetDateTime.now().plusDays(30));
|
||||
|
||||
session.setExpiresAt(OffsetDateTime.now().plusDays(30));
|
||||
|
||||
var policy = pricingRepo.findFirstByIsActiveTrueOrderByValidFromDesc();
|
||||
session.setSetupCostChf(quoteCalculator.calculateSessionSetupFee(policy));
|
||||
|
||||
|
||||
session = sessionRepo.save(session);
|
||||
return ResponseEntity.ok(session);
|
||||
}
|
||||
|
||||
// 2. Add item to existing session
|
||||
|
||||
@PostMapping(value = "/{id}/line-items", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
@Transactional
|
||||
public ResponseEntity<QuoteLineItem> addItemToExistingSession(
|
||||
@PathVariable UUID id,
|
||||
@RequestPart("settings") com.printcalculator.dto.PrintSettingsDto settings,
|
||||
@RequestPart("file") MultipartFile file
|
||||
) throws IOException {
|
||||
public ResponseEntity<QuoteLineItem> addItemToExistingSession(@PathVariable UUID id,
|
||||
@RequestPart("settings") PrintSettingsDto settings,
|
||||
@RequestPart("file") MultipartFile file) throws IOException {
|
||||
QuoteSession session = sessionRepo.findById(id)
|
||||
.orElseThrow(() -> new RuntimeException("Session not found"));
|
||||
|
||||
QuoteLineItem item = addItemToSession(session, file, settings);
|
||||
QuoteLineItem item = quoteSessionItemService.addItemToSession(session, file, settings);
|
||||
return ResponseEntity.ok(item);
|
||||
}
|
||||
|
||||
// Helper to add item
|
||||
private QuoteLineItem addItemToSession(QuoteSession session, MultipartFile file, com.printcalculator.dto.PrintSettingsDto settings) throws IOException {
|
||||
if (file.isEmpty()) throw new IllegalArgumentException("File is empty");
|
||||
@PatchMapping("/line-items/{lineItemId}")
|
||||
@Transactional
|
||||
public ResponseEntity<QuoteLineItem> updateLineItem(@PathVariable UUID lineItemId,
|
||||
@RequestBody Map<String, Object> updates) {
|
||||
QuoteLineItem item = lineItemRepo.findById(lineItemId)
|
||||
.orElseThrow(() -> new RuntimeException("Item not found"));
|
||||
|
||||
QuoteSession session = item.getQuoteSession();
|
||||
if ("CONVERTED".equals(session.getStatus())) {
|
||||
throw new ResponseStatusException(BAD_REQUEST, "Cannot modify a converted session");
|
||||
}
|
||||
|
||||
// Scan for virus
|
||||
clamAVService.scan(file.getInputStream());
|
||||
|
||||
// 1. Define Persistent Storage Path
|
||||
// Structure: storage_quotes/{sessionId}/{uuid}.{ext}
|
||||
Path sessionStorageDir = QUOTE_STORAGE_ROOT.resolve(session.getId().toString()).normalize();
|
||||
if (!sessionStorageDir.startsWith(QUOTE_STORAGE_ROOT)) {
|
||||
throw new IOException("Invalid quote session storage path");
|
||||
if (updates.containsKey("quantity")) {
|
||||
item.setQuantity(parsePositiveQuantity(updates.get("quantity")));
|
||||
}
|
||||
Files.createDirectories(sessionStorageDir);
|
||||
|
||||
String originalFilename = file.getOriginalFilename();
|
||||
String ext = getSafeExtension(originalFilename, "stl");
|
||||
String storedFilename = UUID.randomUUID() + "." + ext;
|
||||
Path persistentPath = sessionStorageDir.resolve(storedFilename).normalize();
|
||||
if (!persistentPath.startsWith(sessionStorageDir)) {
|
||||
throw new IOException("Invalid quote line-item storage path");
|
||||
if (updates.containsKey("color_code")) {
|
||||
Object colorValue = updates.get("color_code");
|
||||
if (colorValue != null) {
|
||||
item.setColorCode(String.valueOf(colorValue));
|
||||
}
|
||||
}
|
||||
|
||||
// Save file
|
||||
try (InputStream inputStream = file.getInputStream()) {
|
||||
Files.copy(inputStream, persistentPath, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
|
||||
Path convertedPersistentPath = null;
|
||||
try {
|
||||
boolean cadSession = "CAD_ACTIVE".equals(session.getStatus());
|
||||
|
||||
// In CAD sessions, print settings are locked server-side.
|
||||
if (cadSession) {
|
||||
enforceCadPrintSettings(session, settings);
|
||||
} else {
|
||||
applyPrintSettings(settings);
|
||||
}
|
||||
|
||||
BigDecimal nozzleDiameter = BigDecimal.valueOf(settings.getNozzleDiameter() != null ? settings.getNozzleDiameter() : 0.4);
|
||||
|
||||
// Pick machine (selected machine if provided, otherwise first active)
|
||||
PrinterMachine machine = resolvePrinterMachine(settings.getPrinterMachineId());
|
||||
|
||||
// Resolve selected filament variant
|
||||
FilamentVariant selectedVariant = resolveFilamentVariant(settings);
|
||||
|
||||
if (cadSession
|
||||
&& session.getMaterialCode() != null
|
||||
&& selectedVariant.getFilamentMaterialType() != null
|
||||
&& selectedVariant.getFilamentMaterialType().getMaterialCode() != null) {
|
||||
String lockedMaterial = normalizeRequestedMaterialCode(session.getMaterialCode());
|
||||
String selectedMaterial = normalizeRequestedMaterialCode(selectedVariant.getFilamentMaterialType().getMaterialCode());
|
||||
if (!lockedMaterial.equals(selectedMaterial)) {
|
||||
throw new ResponseStatusException(BAD_REQUEST, "Selected filament does not match locked CAD material");
|
||||
}
|
||||
}
|
||||
|
||||
// Update session global settings from the most recent item added
|
||||
if (!cadSession) {
|
||||
session.setMaterialCode(selectedVariant.getFilamentMaterialType().getMaterialCode());
|
||||
session.setNozzleDiameterMm(nozzleDiameter);
|
||||
session.setLayerHeightMm(BigDecimal.valueOf(settings.getLayerHeight() != null ? settings.getLayerHeight() : 0.2));
|
||||
session.setInfillPattern(settings.getInfillPattern());
|
||||
session.setInfillPercent(settings.getInfillDensity() != null ? settings.getInfillDensity().intValue() : 20);
|
||||
session.setSupportsEnabled(settings.getSupportsEnabled() != null ? settings.getSupportsEnabled() : false);
|
||||
sessionRepo.save(session);
|
||||
}
|
||||
|
||||
OrcaProfileResolver.ResolvedProfiles profiles = orcaProfileResolver.resolve(machine, nozzleDiameter, selectedVariant);
|
||||
String machineProfile = profiles.machineProfileName();
|
||||
String filamentProfile = profiles.filamentProfileName();
|
||||
|
||||
String processProfile = "standard";
|
||||
if (settings.getLayerHeight() != null) {
|
||||
if (settings.getLayerHeight() >= 0.28) processProfile = "draft";
|
||||
else if (settings.getLayerHeight() <= 0.12) processProfile = "extra_fine";
|
||||
}
|
||||
|
||||
// Build overrides map from settings
|
||||
Map<String, String> processOverrides = new HashMap<>();
|
||||
if (settings.getLayerHeight() != null) processOverrides.put("layer_height", String.valueOf(settings.getLayerHeight()));
|
||||
if (settings.getInfillDensity() != null) processOverrides.put("sparse_infill_density", settings.getInfillDensity() + "%");
|
||||
if (settings.getInfillPattern() != null) processOverrides.put("sparse_infill_pattern", settings.getInfillPattern());
|
||||
|
||||
Path slicerInputPath = persistentPath;
|
||||
if ("3mf".equals(ext)) {
|
||||
String convertedFilename = UUID.randomUUID() + "-converted.stl";
|
||||
convertedPersistentPath = sessionStorageDir.resolve(convertedFilename).normalize();
|
||||
if (!convertedPersistentPath.startsWith(sessionStorageDir)) {
|
||||
throw new IOException("Invalid converted STL storage path");
|
||||
}
|
||||
slicerService.convert3mfToPersistentStl(persistentPath.toFile(), convertedPersistentPath);
|
||||
slicerInputPath = convertedPersistentPath;
|
||||
}
|
||||
|
||||
// 3. Slice (Use persistent path)
|
||||
PrintStats stats = slicerService.slice(
|
||||
slicerInputPath.toFile(),
|
||||
machineProfile,
|
||||
filamentProfile,
|
||||
processProfile,
|
||||
null, // machine overrides
|
||||
processOverrides
|
||||
);
|
||||
|
||||
Optional<ModelDimensions> modelDimensions = slicerService.inspectModelDimensions(slicerInputPath.toFile());
|
||||
|
||||
// 4. Calculate Quote
|
||||
QuoteResult result = quoteCalculator.calculate(stats, machine.getPrinterDisplayName(), selectedVariant);
|
||||
|
||||
// 5. Create Line Item
|
||||
QuoteLineItem item = new QuoteLineItem();
|
||||
item.setQuoteSession(session);
|
||||
item.setOriginalFilename(file.getOriginalFilename());
|
||||
item.setStoredPath(QUOTE_STORAGE_ROOT.relativize(persistentPath).toString()); // SAVE PATH (relative to root)
|
||||
item.setQuantity(1);
|
||||
item.setColorCode(selectedVariant.getColorName());
|
||||
item.setFilamentVariant(selectedVariant);
|
||||
item.setStatus("READY"); // or CALCULATED
|
||||
|
||||
item.setPrintTimeSeconds((int) stats.printTimeSeconds());
|
||||
item.setMaterialGrams(BigDecimal.valueOf(stats.filamentWeightGrams()));
|
||||
item.setUnitPriceChf(BigDecimal.valueOf(result.getTotalPrice()));
|
||||
|
||||
// Store breakdown
|
||||
Map<String, Object> breakdown = new HashMap<>();
|
||||
breakdown.put("machine_cost", result.getTotalPrice()); // Excludes setup fee which is at session level
|
||||
breakdown.put("setup_fee", 0);
|
||||
if (convertedPersistentPath != null) {
|
||||
breakdown.put("convertedStoredPath", QUOTE_STORAGE_ROOT.relativize(convertedPersistentPath).toString());
|
||||
}
|
||||
item.setPricingBreakdown(breakdown);
|
||||
|
||||
// Dimensions for shipping/package checks are computed server-side from the uploaded model.
|
||||
item.setBoundingBoxXMm(modelDimensions
|
||||
.map(dim -> BigDecimal.valueOf(dim.xMm()))
|
||||
.orElseGet(() -> settings.getBoundingBoxX() != null ? BigDecimal.valueOf(settings.getBoundingBoxX()) : BigDecimal.ZERO));
|
||||
item.setBoundingBoxYMm(modelDimensions
|
||||
.map(dim -> BigDecimal.valueOf(dim.yMm()))
|
||||
.orElseGet(() -> settings.getBoundingBoxY() != null ? BigDecimal.valueOf(settings.getBoundingBoxY()) : BigDecimal.ZERO));
|
||||
item.setBoundingBoxZMm(modelDimensions
|
||||
.map(dim -> BigDecimal.valueOf(dim.zMm()))
|
||||
.orElseGet(() -> settings.getBoundingBoxZ() != null ? BigDecimal.valueOf(settings.getBoundingBoxZ()) : BigDecimal.ZERO));
|
||||
|
||||
item.setCreatedAt(OffsetDateTime.now());
|
||||
item.setUpdatedAt(OffsetDateTime.now());
|
||||
|
||||
return lineItemRepo.save(item);
|
||||
|
||||
} catch (Exception e) {
|
||||
// Cleanup if failed
|
||||
Files.deleteIfExists(persistentPath);
|
||||
if (convertedPersistentPath != null) {
|
||||
Files.deleteIfExists(convertedPersistentPath);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
item.setUpdatedAt(OffsetDateTime.now());
|
||||
return ResponseEntity.ok(lineItemRepo.save(item));
|
||||
}
|
||||
|
||||
private void applyPrintSettings(com.printcalculator.dto.PrintSettingsDto settings) {
|
||||
if ("BASIC".equalsIgnoreCase(settings.getComplexityMode())) {
|
||||
// Set defaults based on Quality
|
||||
String quality = settings.getQuality() != null ? settings.getQuality().toLowerCase() : "standard";
|
||||
|
||||
switch (quality) {
|
||||
case "draft":
|
||||
settings.setLayerHeight(0.28);
|
||||
settings.setInfillDensity(15.0);
|
||||
settings.setInfillPattern("grid");
|
||||
break;
|
||||
case "high":
|
||||
settings.setLayerHeight(0.12);
|
||||
settings.setInfillDensity(20.0);
|
||||
settings.setInfillPattern("gyroid");
|
||||
break;
|
||||
case "standard":
|
||||
default:
|
||||
settings.setLayerHeight(0.20);
|
||||
settings.setInfillDensity(15.0);
|
||||
settings.setInfillPattern("grid");
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
// ADVANCED Mode: Use values from Frontend, set defaults if missing
|
||||
if (settings.getLayerHeight() == null) settings.setLayerHeight(0.20);
|
||||
if (settings.getInfillDensity() == null) settings.setInfillDensity(20.0);
|
||||
if (settings.getInfillPattern() == null) settings.setInfillPattern("grid");
|
||||
}
|
||||
}
|
||||
@DeleteMapping("/{sessionId}/line-items/{lineItemId}")
|
||||
@Transactional
|
||||
public ResponseEntity<Void> deleteLineItem(@PathVariable UUID sessionId,
|
||||
@PathVariable UUID lineItemId) {
|
||||
QuoteLineItem item = lineItemRepo.findById(lineItemId)
|
||||
.orElseThrow(() -> new RuntimeException("Item not found"));
|
||||
|
||||
private void enforceCadPrintSettings(QuoteSession session, com.printcalculator.dto.PrintSettingsDto settings) {
|
||||
settings.setComplexityMode("ADVANCED");
|
||||
settings.setMaterial(session.getMaterialCode() != null ? session.getMaterialCode() : "PLA");
|
||||
settings.setNozzleDiameter(session.getNozzleDiameterMm() != null ? session.getNozzleDiameterMm().doubleValue() : 0.4);
|
||||
settings.setLayerHeight(session.getLayerHeightMm() != null ? session.getLayerHeightMm().doubleValue() : 0.2);
|
||||
settings.setInfillPattern(session.getInfillPattern() != null ? session.getInfillPattern() : "grid");
|
||||
settings.setInfillDensity(session.getInfillPercent() != null ? session.getInfillPercent().doubleValue() : 20.0);
|
||||
settings.setSupportsEnabled(Boolean.TRUE.equals(session.getSupportsEnabled()));
|
||||
}
|
||||
|
||||
private PrinterMachine resolvePrinterMachine(Long printerMachineId) {
|
||||
if (printerMachineId != null) {
|
||||
PrinterMachine selected = machineRepo.findById(printerMachineId)
|
||||
.orElseThrow(() -> new RuntimeException("Printer machine not found: " + printerMachineId));
|
||||
if (!Boolean.TRUE.equals(selected.getIsActive())) {
|
||||
throw new RuntimeException("Selected printer machine is not active");
|
||||
}
|
||||
return selected;
|
||||
if (!item.getQuoteSession().getId().equals(sessionId)) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
return machineRepo.findFirstByIsActiveTrue()
|
||||
.orElseThrow(() -> new RuntimeException("No active printer found"));
|
||||
lineItemRepo.delete(item);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
private FilamentVariant resolveFilamentVariant(com.printcalculator.dto.PrintSettingsDto settings) {
|
||||
if (settings.getFilamentVariantId() != null) {
|
||||
FilamentVariant variant = variantRepo.findById(settings.getFilamentVariantId())
|
||||
.orElseThrow(() -> new RuntimeException("Filament variant not found: " + settings.getFilamentVariantId()));
|
||||
if (!Boolean.TRUE.equals(variant.getIsActive())) {
|
||||
throw new RuntimeException("Selected filament variant is not active");
|
||||
}
|
||||
return variant;
|
||||
@GetMapping("/{id}")
|
||||
public ResponseEntity<Map<String, Object>> getQuoteSession(@PathVariable UUID id) {
|
||||
QuoteSession session = sessionRepo.findById(id)
|
||||
.orElseThrow(() -> new RuntimeException("Session not found"));
|
||||
|
||||
List<QuoteLineItem> items = lineItemRepo.findByQuoteSessionId(id);
|
||||
QuoteSessionTotalsService.QuoteSessionTotals totals = quoteSessionTotalsService.compute(session, items);
|
||||
return ResponseEntity.ok(quoteSessionResponseAssembler.assemble(session, items, totals));
|
||||
}
|
||||
|
||||
@GetMapping(value = "/{sessionId}/line-items/{lineItemId}/content")
|
||||
public ResponseEntity<Resource> downloadLineItemContent(@PathVariable UUID sessionId,
|
||||
@PathVariable UUID lineItemId,
|
||||
@RequestParam(name = "preview", required = false, defaultValue = "false") boolean preview)
|
||||
throws IOException {
|
||||
QuoteLineItem item = lineItemRepo.findById(lineItemId)
|
||||
.orElseThrow(() -> new RuntimeException("Item not found"));
|
||||
|
||||
if (!item.getQuoteSession().getId().equals(sessionId)) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
String requestedMaterialCode = normalizeRequestedMaterialCode(settings.getMaterial());
|
||||
|
||||
FilamentMaterialType materialType = materialRepo.findByMaterialCode(requestedMaterialCode)
|
||||
.orElseGet(() -> materialRepo.findByMaterialCode("PLA")
|
||||
.orElseThrow(() -> new RuntimeException("Fallback material PLA not configured")));
|
||||
|
||||
String requestedColor = settings.getColor() != null ? settings.getColor().trim() : null;
|
||||
if (requestedColor != null && !requestedColor.isBlank()) {
|
||||
Optional<FilamentVariant> byColor = variantRepo.findByFilamentMaterialTypeAndColorName(materialType, requestedColor);
|
||||
if (byColor.isPresent() && Boolean.TRUE.equals(byColor.get().getIsActive())) {
|
||||
return byColor.get();
|
||||
String targetStoredPath = item.getStoredPath();
|
||||
if (preview) {
|
||||
String convertedPath = quoteStorageService.extractConvertedStoredPath(item);
|
||||
if (convertedPath != null && !convertedPath.isBlank()) {
|
||||
targetStoredPath = convertedPath;
|
||||
}
|
||||
}
|
||||
|
||||
return variantRepo.findFirstByFilamentMaterialTypeAndIsActiveTrue(materialType)
|
||||
.orElseThrow(() -> new RuntimeException("No active variant for material: " + requestedMaterialCode));
|
||||
}
|
||||
|
||||
private String normalizeRequestedMaterialCode(String value) {
|
||||
if (value == null || value.isBlank()) {
|
||||
return "PLA";
|
||||
if (targetStoredPath == null) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
|
||||
return value.trim()
|
||||
.toUpperCase(Locale.ROOT)
|
||||
.replace('_', ' ')
|
||||
.replace('-', ' ')
|
||||
.replaceAll("\\s+", " ");
|
||||
java.nio.file.Path path = quoteStorageService.resolveStoredQuotePath(targetStoredPath, sessionId);
|
||||
if (path == null || !java.nio.file.Files.exists(path)) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
|
||||
Resource resource = new UrlResource(path.toUri());
|
||||
String downloadName = preview ? path.getFileName().toString() : item.getOriginalFilename();
|
||||
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.APPLICATION_OCTET_STREAM)
|
||||
.header(org.springframework.http.HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + downloadName + "\"")
|
||||
.body(resource);
|
||||
}
|
||||
|
||||
@GetMapping(value = "/{sessionId}/line-items/{lineItemId}/stl-preview")
|
||||
public ResponseEntity<Resource> downloadLineItemStlPreview(@PathVariable UUID sessionId,
|
||||
@PathVariable UUID lineItemId)
|
||||
throws IOException {
|
||||
QuoteLineItem item = lineItemRepo.findById(lineItemId)
|
||||
.orElseThrow(() -> new RuntimeException("Item not found"));
|
||||
|
||||
if (!item.getQuoteSession().getId().equals(sessionId)) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
if (!"stl".equals(quoteStorageService.getSafeExtension(item.getOriginalFilename(), ""))) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
|
||||
String targetStoredPath = item.getStoredPath();
|
||||
if (targetStoredPath == null || targetStoredPath.isBlank()) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
|
||||
java.nio.file.Path path = quoteStorageService.resolveStoredQuotePath(targetStoredPath, sessionId);
|
||||
if (path == null || !java.nio.file.Files.exists(path)) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
|
||||
if (!"stl".equals(quoteStorageService.getSafeExtension(path.getFileName().toString(), ""))) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
|
||||
Resource resource = new UrlResource(path.toUri());
|
||||
String downloadName = path.getFileName().toString();
|
||||
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType("model/stl"))
|
||||
.header(org.springframework.http.HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + downloadName + "\"")
|
||||
.body(resource);
|
||||
}
|
||||
|
||||
private int parsePositiveQuantity(Object raw) {
|
||||
@@ -408,198 +239,4 @@ public class QuoteSessionController {
|
||||
}
|
||||
return quantity;
|
||||
}
|
||||
|
||||
// 3. Update Line Item
|
||||
@PatchMapping("/line-items/{lineItemId}")
|
||||
@Transactional
|
||||
public ResponseEntity<QuoteLineItem> updateLineItem(
|
||||
@PathVariable UUID lineItemId,
|
||||
@RequestBody Map<String, Object> updates
|
||||
) {
|
||||
QuoteLineItem item = lineItemRepo.findById(lineItemId)
|
||||
.orElseThrow(() -> new RuntimeException("Item not found"));
|
||||
|
||||
QuoteSession session = item.getQuoteSession();
|
||||
if ("CONVERTED".equals(session.getStatus())) {
|
||||
throw new ResponseStatusException(BAD_REQUEST, "Cannot modify a converted session");
|
||||
}
|
||||
|
||||
if (updates.containsKey("quantity")) {
|
||||
item.setQuantity(parsePositiveQuantity(updates.get("quantity")));
|
||||
}
|
||||
if (updates.containsKey("color_code")) {
|
||||
Object colorValue = updates.get("color_code");
|
||||
if (colorValue != null) {
|
||||
item.setColorCode(String.valueOf(colorValue));
|
||||
}
|
||||
}
|
||||
|
||||
// Recalculate price if needed?
|
||||
// For now, unit price is fixed in mock. Total is calculated on GET.
|
||||
|
||||
item.setUpdatedAt(OffsetDateTime.now());
|
||||
return ResponseEntity.ok(lineItemRepo.save(item));
|
||||
}
|
||||
|
||||
// 4. Delete Line Item
|
||||
@DeleteMapping("/{sessionId}/line-items/{lineItemId}")
|
||||
@Transactional
|
||||
public ResponseEntity<Void> deleteLineItem(
|
||||
@PathVariable UUID sessionId,
|
||||
@PathVariable UUID lineItemId
|
||||
) {
|
||||
// Verify item belongs to session?
|
||||
QuoteLineItem item = lineItemRepo.findById(lineItemId)
|
||||
.orElseThrow(() -> new RuntimeException("Item not found"));
|
||||
|
||||
if (!item.getQuoteSession().getId().equals(sessionId)) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
lineItemRepo.delete(item);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
// 5. Get Session (Session + Items + Total)
|
||||
@GetMapping("/{id}")
|
||||
public ResponseEntity<Map<String, Object>> getQuoteSession(@PathVariable UUID id) {
|
||||
QuoteSession session = sessionRepo.findById(id)
|
||||
.orElseThrow(() -> new RuntimeException("Session not found"));
|
||||
|
||||
List<QuoteLineItem> items = lineItemRepo.findByQuoteSessionId(id);
|
||||
QuoteSessionTotalsService.QuoteSessionTotals totals = quoteSessionTotalsService.compute(session, items);
|
||||
|
||||
// Map items to DTO to embed distributed machine cost
|
||||
List<Map<String, Object>> itemsDto = new ArrayList<>();
|
||||
for (QuoteLineItem item : items) {
|
||||
Map<String, Object> dto = new HashMap<>();
|
||||
dto.put("id", item.getId());
|
||||
dto.put("originalFilename", item.getOriginalFilename());
|
||||
dto.put("quantity", item.getQuantity());
|
||||
dto.put("printTimeSeconds", item.getPrintTimeSeconds());
|
||||
dto.put("materialGrams", item.getMaterialGrams());
|
||||
dto.put("colorCode", item.getColorCode());
|
||||
dto.put("filamentVariantId", item.getFilamentVariant() != null ? item.getFilamentVariant().getId() : null);
|
||||
dto.put("status", item.getStatus());
|
||||
dto.put("convertedStoredPath", extractConvertedStoredPath(item));
|
||||
|
||||
BigDecimal unitPrice = item.getUnitPriceChf() != null ? item.getUnitPriceChf() : BigDecimal.ZERO;
|
||||
int quantity = item.getQuantity() != null && item.getQuantity() > 0 ? item.getQuantity() : 1;
|
||||
if (totals.totalPrintSeconds().compareTo(BigDecimal.ZERO) > 0 && item.getPrintTimeSeconds() != null) {
|
||||
BigDecimal itemSeconds = BigDecimal.valueOf(item.getPrintTimeSeconds()).multiply(BigDecimal.valueOf(quantity));
|
||||
BigDecimal share = itemSeconds.divide(totals.totalPrintSeconds(), 8, RoundingMode.HALF_UP);
|
||||
BigDecimal itemMachineCost = totals.globalMachineCostChf().multiply(share);
|
||||
BigDecimal unitMachineCost = itemMachineCost.divide(BigDecimal.valueOf(quantity), 2, RoundingMode.HALF_UP);
|
||||
unitPrice = unitPrice.add(unitMachineCost);
|
||||
}
|
||||
dto.put("unitPriceChf", unitPrice);
|
||||
itemsDto.add(dto);
|
||||
}
|
||||
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
response.put("session", session);
|
||||
response.put("items", itemsDto);
|
||||
response.put("printItemsTotalChf", totals.printItemsTotalChf());
|
||||
response.put("cadTotalChf", totals.cadTotalChf());
|
||||
response.put("itemsTotalChf", totals.itemsTotalChf());
|
||||
response.put("shippingCostChf", totals.shippingCostChf());
|
||||
response.put("globalMachineCostChf", totals.globalMachineCostChf());
|
||||
response.put("grandTotalChf", totals.grandTotalChf());
|
||||
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
|
||||
// 6. Download Line Item Content
|
||||
@GetMapping(value = "/{sessionId}/line-items/{lineItemId}/content")
|
||||
public ResponseEntity<org.springframework.core.io.Resource> downloadLineItemContent(
|
||||
@PathVariable UUID sessionId,
|
||||
@PathVariable UUID lineItemId,
|
||||
@RequestParam(name = "preview", required = false, defaultValue = "false") boolean preview
|
||||
) throws IOException {
|
||||
QuoteLineItem item = lineItemRepo.findById(lineItemId)
|
||||
.orElseThrow(() -> new RuntimeException("Item not found"));
|
||||
|
||||
if (!item.getQuoteSession().getId().equals(sessionId)) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
String targetStoredPath = item.getStoredPath();
|
||||
if (preview) {
|
||||
String convertedPath = extractConvertedStoredPath(item);
|
||||
if (convertedPath != null && !convertedPath.isBlank()) {
|
||||
targetStoredPath = convertedPath;
|
||||
}
|
||||
}
|
||||
|
||||
if (targetStoredPath == null) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
|
||||
Path path = resolveStoredQuotePath(targetStoredPath, sessionId);
|
||||
if (path == null || !Files.exists(path)) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
|
||||
org.springframework.core.io.Resource resource = new UrlResource(path.toUri());
|
||||
String downloadName = item.getOriginalFilename();
|
||||
if (preview) {
|
||||
downloadName = path.getFileName().toString();
|
||||
}
|
||||
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.APPLICATION_OCTET_STREAM)
|
||||
.header(org.springframework.http.HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + downloadName + "\"")
|
||||
.body(resource);
|
||||
}
|
||||
|
||||
private String getSafeExtension(String filename, String fallback) {
|
||||
if (filename == null) {
|
||||
return fallback;
|
||||
}
|
||||
String cleaned = StringUtils.cleanPath(filename);
|
||||
if (cleaned.contains("..")) {
|
||||
return fallback;
|
||||
}
|
||||
int index = cleaned.lastIndexOf('.');
|
||||
if (index <= 0 || index >= cleaned.length() - 1) {
|
||||
return fallback;
|
||||
}
|
||||
String ext = cleaned.substring(index + 1).toLowerCase(Locale.ROOT);
|
||||
return switch (ext) {
|
||||
case "stl" -> "stl";
|
||||
case "3mf" -> "3mf";
|
||||
case "step", "stp" -> "step";
|
||||
default -> fallback;
|
||||
};
|
||||
}
|
||||
|
||||
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 String extractConvertedStoredPath(QuoteLineItem item) {
|
||||
Map<String, Object> breakdown = item.getPricingBreakdown();
|
||||
if (breakdown == null) {
|
||||
return null;
|
||||
}
|
||||
Object converted = breakdown.get("convertedStoredPath");
|
||||
if (converted == null) {
|
||||
return null;
|
||||
}
|
||||
String path = String.valueOf(converted).trim();
|
||||
return path.isEmpty() ? null : path;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,77 +4,39 @@ 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 com.printcalculator.service.admin.AdminFilamentControllerService;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
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.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;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/admin/filaments")
|
||||
@Transactional(readOnly = true)
|
||||
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 FilamentMaterialTypeRepository materialRepo;
|
||||
private final FilamentVariantRepository variantRepo;
|
||||
private final QuoteLineItemRepository quoteLineItemRepo;
|
||||
private final OrderItemRepository orderItemRepo;
|
||||
private final AdminFilamentControllerService adminFilamentControllerService;
|
||||
|
||||
public AdminFilamentController(
|
||||
FilamentMaterialTypeRepository materialRepo,
|
||||
FilamentVariantRepository variantRepo,
|
||||
QuoteLineItemRepository quoteLineItemRepo,
|
||||
OrderItemRepository orderItemRepo
|
||||
) {
|
||||
this.materialRepo = materialRepo;
|
||||
this.variantRepo = variantRepo;
|
||||
this.quoteLineItemRepo = quoteLineItemRepo;
|
||||
this.orderItemRepo = orderItemRepo;
|
||||
public AdminFilamentController(AdminFilamentControllerService adminFilamentControllerService) {
|
||||
this.adminFilamentControllerService = adminFilamentControllerService;
|
||||
}
|
||||
|
||||
@GetMapping("/materials")
|
||||
public ResponseEntity<List<AdminFilamentMaterialTypeDto>> getMaterials() {
|
||||
List<AdminFilamentMaterialTypeDto> response = materialRepo.findAll().stream()
|
||||
.sorted(Comparator.comparing(FilamentMaterialType::getMaterialCode, String.CASE_INSENSITIVE_ORDER))
|
||||
.map(this::toMaterialDto)
|
||||
.toList();
|
||||
return ResponseEntity.ok(response);
|
||||
return ResponseEntity.ok(adminFilamentControllerService.getMaterials());
|
||||
}
|
||||
|
||||
@GetMapping("/variants")
|
||||
public ResponseEntity<List<AdminFilamentVariantDto>> 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);
|
||||
return ResponseEntity.ok(adminFilamentControllerService.getVariants());
|
||||
}
|
||||
|
||||
@PostMapping("/materials")
|
||||
@@ -82,13 +44,7 @@ public class AdminFilamentController {
|
||||
public ResponseEntity<AdminFilamentMaterialTypeDto> createMaterial(
|
||||
@RequestBody AdminUpsertFilamentMaterialTypeRequest 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));
|
||||
return ResponseEntity.ok(adminFilamentControllerService.createMaterial(payload));
|
||||
}
|
||||
|
||||
@PutMapping("/materials/{materialTypeId}")
|
||||
@@ -97,15 +53,7 @@ public class AdminFilamentController {
|
||||
@PathVariable Long materialTypeId,
|
||||
@RequestBody 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 ResponseEntity.ok(toMaterialDto(saved));
|
||||
return ResponseEntity.ok(adminFilamentControllerService.updateMaterial(materialTypeId, payload));
|
||||
}
|
||||
|
||||
@PostMapping("/variants")
|
||||
@@ -113,17 +61,7 @@ public class AdminFilamentController {
|
||||
public ResponseEntity<AdminFilamentVariantDto> createVariant(
|
||||
@RequestBody 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 ResponseEntity.ok(toVariantDto(saved));
|
||||
return ResponseEntity.ok(adminFilamentControllerService.createVariant(payload));
|
||||
}
|
||||
|
||||
@PutMapping("/variants/{variantId}")
|
||||
@@ -132,224 +70,13 @@ public class AdminFilamentController {
|
||||
@PathVariable Long variantId,
|
||||
@RequestBody 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 ResponseEntity.ok(toVariantDto(saved));
|
||||
return ResponseEntity.ok(adminFilamentControllerService.updateVariant(variantId, payload));
|
||||
}
|
||||
|
||||
@DeleteMapping("/variants/{variantId}")
|
||||
@Transactional
|
||||
public ResponseEntity<Void> deleteVariant(@PathVariable 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);
|
||||
adminFilamentControllerService.deleteVariant(variantId);
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
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));
|
||||
}
|
||||
|
||||
@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,37 +1,14 @@
|
||||
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.AdminCadInvoiceDto;
|
||||
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 com.printcalculator.service.admin.AdminOperationsControllerService;
|
||||
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.transaction.annotation.Transactional;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
@@ -42,148 +19,34 @@ 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 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;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/admin")
|
||||
@Transactional(readOnly = true)
|
||||
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 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;
|
||||
private final AdminOperationsControllerService adminOperationsControllerService;
|
||||
|
||||
public AdminOperationsController(
|
||||
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 AdminOperationsController(AdminOperationsControllerService adminOperationsControllerService) {
|
||||
this.adminOperationsControllerService = adminOperationsControllerService;
|
||||
}
|
||||
|
||||
@GetMapping("/filament-stock")
|
||||
public ResponseEntity<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));
|
||||
}
|
||||
|
||||
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);
|
||||
return ResponseEntity.ok(adminOperationsControllerService.getFilamentStock());
|
||||
}
|
||||
|
||||
@GetMapping("/contact-requests")
|
||||
public ResponseEntity<List<AdminContactRequestDto>> getContactRequests() {
|
||||
List<AdminContactRequestDto> response = customQuoteRequestRepo.findAll(
|
||||
Sort.by(Sort.Direction.DESC, "createdAt")
|
||||
)
|
||||
.stream()
|
||||
.map(this::toContactRequestDto)
|
||||
.toList();
|
||||
|
||||
return ResponseEntity.ok(response);
|
||||
return ResponseEntity.ok(adminOperationsControllerService.getContactRequests());
|
||||
}
|
||||
|
||||
@GetMapping("/contact-requests/{requestId}")
|
||||
public ResponseEntity<AdminContactRequestDetailDto> getContactRequestDetail(@PathVariable 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 ResponseEntity.ok(toContactRequestDetailDto(request, attachments));
|
||||
return ResponseEntity.ok(adminOperationsControllerService.getContactRequestDetail(requestId));
|
||||
}
|
||||
|
||||
@PatchMapping("/contact-requests/{requestId}/status")
|
||||
@@ -192,31 +55,7 @@ public class AdminOperationsController {
|
||||
@PathVariable UUID requestId,
|
||||
@RequestBody 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 ResponseEntity.ok(toContactRequestDetailDto(saved, attachments));
|
||||
return ResponseEntity.ok(adminOperationsControllerService.updateContactRequestStatus(requestId, payload));
|
||||
}
|
||||
|
||||
@GetMapping("/contact-requests/{requestId}/attachments/{attachmentId}/file")
|
||||
@@ -224,87 +63,17 @@ public class AdminOperationsController {
|
||||
@PathVariable UUID requestId,
|
||||
@PathVariable 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");
|
||||
}
|
||||
return adminOperationsControllerService.downloadContactRequestAttachment(requestId, attachmentId);
|
||||
}
|
||||
|
||||
@GetMapping("/sessions")
|
||||
public ResponseEntity<List<AdminQuoteSessionDto>> getQuoteSessions() {
|
||||
List<AdminQuoteSessionDto> response = quoteSessionRepo.findAll(
|
||||
Sort.by(Sort.Direction.DESC, "createdAt")
|
||||
)
|
||||
.stream()
|
||||
.map(this::toQuoteSessionDto)
|
||||
.toList();
|
||||
|
||||
return ResponseEntity.ok(response);
|
||||
return ResponseEntity.ok(adminOperationsControllerService.getQuoteSessions());
|
||||
}
|
||||
|
||||
@GetMapping("/cad-invoices")
|
||||
public ResponseEntity<List<AdminCadInvoiceDto>> getCadInvoices() {
|
||||
List<AdminCadInvoiceDto> response = quoteSessionRepo.findByStatusInOrderByCreatedAtDesc(List.of("CAD_ACTIVE", "CONVERTED"))
|
||||
.stream()
|
||||
.filter(this::isCadSessionRecord)
|
||||
.map(this::toCadInvoiceDto)
|
||||
.toList();
|
||||
return ResponseEntity.ok(response);
|
||||
return ResponseEntity.ok(adminOperationsControllerService.getCadInvoices());
|
||||
}
|
||||
|
||||
@PostMapping("/cad-invoices")
|
||||
@@ -312,198 +81,13 @@ public class AdminOperationsController {
|
||||
public ResponseEntity<AdminCadInvoiceDto> createOrUpdateCadInvoice(
|
||||
@RequestBody 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.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));
|
||||
return ResponseEntity.ok(adminOperationsControllerService.createOrUpdateCadInvoice(payload));
|
||||
}
|
||||
|
||||
@DeleteMapping("/sessions/{sessionId}")
|
||||
@Transactional
|
||||
public ResponseEntity<Void> deleteQuoteSession(@PathVariable 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);
|
||||
adminOperationsControllerService.deleteQuoteSession(sessionId);
|
||||
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,24 +1,9 @@
|
||||
package com.printcalculator.controller.admin;
|
||||
|
||||
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.QuoteSession;
|
||||
import com.printcalculator.repository.OrderItemRepository;
|
||||
import com.printcalculator.repository.OrderRepository;
|
||||
import com.printcalculator.repository.PaymentRepository;
|
||||
import com.printcalculator.service.InvoicePdfRenderingService;
|
||||
import com.printcalculator.service.PaymentService;
|
||||
import com.printcalculator.service.QrBillService;
|
||||
import com.printcalculator.service.StorageService;
|
||||
import com.printcalculator.service.order.AdminOrderControllerService;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.ContentDisposition;
|
||||
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;
|
||||
@@ -27,83 +12,39 @@ 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 org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.InvalidPathException;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
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;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/admin/orders")
|
||||
@Transactional(readOnly = true)
|
||||
public class AdminOrderController {
|
||||
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 PaymentService paymentService;
|
||||
private final StorageService storageService;
|
||||
private final InvoicePdfRenderingService invoiceService;
|
||||
private final QrBillService qrBillService;
|
||||
private final AdminOrderControllerService adminOrderControllerService;
|
||||
|
||||
public AdminOrderController(
|
||||
OrderRepository orderRepo,
|
||||
OrderItemRepository orderItemRepo,
|
||||
PaymentRepository paymentRepo,
|
||||
PaymentService paymentService,
|
||||
StorageService storageService,
|
||||
InvoicePdfRenderingService invoiceService,
|
||||
QrBillService qrBillService
|
||||
) {
|
||||
this.orderRepo = orderRepo;
|
||||
this.orderItemRepo = orderItemRepo;
|
||||
this.paymentRepo = paymentRepo;
|
||||
this.paymentService = paymentService;
|
||||
this.storageService = storageService;
|
||||
this.invoiceService = invoiceService;
|
||||
this.qrBillService = qrBillService;
|
||||
public AdminOrderController(AdminOrderControllerService adminOrderControllerService) {
|
||||
this.adminOrderControllerService = adminOrderControllerService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ResponseEntity<List<OrderDto>> listOrders() {
|
||||
List<OrderDto> response = orderRepo.findAllByOrderByCreatedAtDesc()
|
||||
.stream()
|
||||
.map(this::toOrderDto)
|
||||
.toList();
|
||||
return ResponseEntity.ok(response);
|
||||
return ResponseEntity.ok(adminOrderControllerService.listOrders());
|
||||
}
|
||||
|
||||
@GetMapping("/{orderId}")
|
||||
public ResponseEntity<OrderDto> getOrder(@PathVariable UUID orderId) {
|
||||
return ResponseEntity.ok(toOrderDto(getOrderOrThrow(orderId)));
|
||||
return ResponseEntity.ok(adminOrderControllerService.getOrder(orderId));
|
||||
}
|
||||
|
||||
@PostMapping("/{orderId}/payments/confirm")
|
||||
@Transactional
|
||||
public ResponseEntity<OrderDto> confirmPayment(
|
||||
public ResponseEntity<OrderDto> updatePaymentMethod(
|
||||
@PathVariable UUID orderId,
|
||||
@RequestBody(required = false) Map<String, String> payload
|
||||
) {
|
||||
getOrderOrThrow(orderId);
|
||||
String method = payload != null ? payload.get("method") : null;
|
||||
paymentService.confirmPayment(orderId, method);
|
||||
return ResponseEntity.ok(toOrderDto(getOrderOrThrow(orderId)));
|
||||
return ResponseEntity.ok(adminOrderControllerService.updatePaymentMethod(orderId, payload));
|
||||
}
|
||||
|
||||
@PostMapping("/{orderId}/status")
|
||||
@@ -112,22 +53,7 @@ public class AdminOrderController {
|
||||
@PathVariable UUID orderId,
|
||||
@RequestBody AdminOrderStatusUpdateRequest 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)
|
||||
);
|
||||
}
|
||||
order.setStatus(normalizedStatus);
|
||||
orderRepo.save(order);
|
||||
|
||||
return ResponseEntity.ok(toOrderDto(order));
|
||||
return ResponseEntity.ok(adminOrderControllerService.updateOrderStatus(orderId, payload));
|
||||
}
|
||||
|
||||
@GetMapping("/{orderId}/items/{orderItemId}/file")
|
||||
@@ -135,198 +61,16 @@ public class AdminOrderController {
|
||||
@PathVariable UUID orderId,
|
||||
@PathVariable 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 = 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");
|
||||
}
|
||||
return adminOrderControllerService.downloadOrderItemFile(orderId, orderItemId);
|
||||
}
|
||||
|
||||
@GetMapping("/{orderId}/documents/confirmation")
|
||||
public ResponseEntity<byte[]> downloadOrderConfirmation(@PathVariable UUID orderId) {
|
||||
return generateDocument(getOrderOrThrow(orderId), true);
|
||||
return adminOrderControllerService.downloadOrderConfirmation(orderId);
|
||||
}
|
||||
|
||||
@GetMapping("/{orderId}/documents/invoice")
|
||||
public ResponseEntity<byte[]> downloadOrderInvoice(@PathVariable 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.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 Path buildConfirmationPdfRelativePath(UUID orderId, String orderNumber) {
|
||||
return Path.of("orders", orderId.toString(), "documents", "confirmation-" + orderNumber + ".pdf");
|
||||
return adminOrderControllerService.downloadOrderInvoice(orderId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,8 @@ public record OptionsResponse(
|
||||
List<QualityOption> qualities,
|
||||
List<InfillPatternOption> infillPatterns,
|
||||
List<LayerHeightOptionDTO> layerHeights,
|
||||
List<NozzleOptionDTO> nozzleDiameters
|
||||
List<NozzleOptionDTO> nozzleDiameters,
|
||||
List<NozzleLayerHeightOptionsDTO> layerHeightsByNozzle
|
||||
) {
|
||||
public record MaterialOption(String code, String label, List<VariantOption> variants) {}
|
||||
public record VariantOption(
|
||||
@@ -24,4 +25,5 @@ public record OptionsResponse(
|
||||
public record InfillPatternOption(String id, String label) {}
|
||||
public record LayerHeightOptionDTO(double value, String label) {}
|
||||
public record NozzleOptionDTO(double value, String label) {}
|
||||
public record NozzleLayerHeightOptionsDTO(double nozzleDiameter, List<LayerHeightOptionDTO> layerHeights) {}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,16 @@ public class OrderItemDto {
|
||||
private String originalFilename;
|
||||
private String materialCode;
|
||||
private String colorCode;
|
||||
private Long filamentVariantId;
|
||||
private String filamentVariantDisplayName;
|
||||
private String filamentColorName;
|
||||
private String filamentColorHex;
|
||||
private String quality;
|
||||
private BigDecimal nozzleDiameterMm;
|
||||
private BigDecimal layerHeightMm;
|
||||
private Integer infillPercent;
|
||||
private String infillPattern;
|
||||
private Boolean supportsEnabled;
|
||||
private Integer quantity;
|
||||
private Integer printTimeSeconds;
|
||||
private BigDecimal materialGrams;
|
||||
@@ -27,6 +37,36 @@ public class OrderItemDto {
|
||||
public String getColorCode() { return colorCode; }
|
||||
public void setColorCode(String colorCode) { this.colorCode = colorCode; }
|
||||
|
||||
public Long getFilamentVariantId() { return filamentVariantId; }
|
||||
public void setFilamentVariantId(Long filamentVariantId) { this.filamentVariantId = filamentVariantId; }
|
||||
|
||||
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 getFilamentColorHex() { return filamentColorHex; }
|
||||
public void setFilamentColorHex(String filamentColorHex) { this.filamentColorHex = filamentColorHex; }
|
||||
|
||||
public String getQuality() { return quality; }
|
||||
public void setQuality(String quality) { this.quality = quality; }
|
||||
|
||||
public BigDecimal getNozzleDiameterMm() { return nozzleDiameterMm; }
|
||||
public void setNozzleDiameterMm(BigDecimal nozzleDiameterMm) { this.nozzleDiameterMm = nozzleDiameterMm; }
|
||||
|
||||
public BigDecimal getLayerHeightMm() { return layerHeightMm; }
|
||||
public void setLayerHeightMm(BigDecimal layerHeightMm) { this.layerHeightMm = layerHeightMm; }
|
||||
|
||||
public Integer getInfillPercent() { return infillPercent; }
|
||||
public void setInfillPercent(Integer infillPercent) { this.infillPercent = infillPercent; }
|
||||
|
||||
public String getInfillPattern() { return infillPattern; }
|
||||
public void setInfillPattern(String infillPattern) { this.infillPattern = infillPattern; }
|
||||
|
||||
public Boolean getSupportsEnabled() { return supportsEnabled; }
|
||||
public void setSupportsEnabled(Boolean supportsEnabled) { this.supportsEnabled = supportsEnabled; }
|
||||
|
||||
public Integer getQuantity() { return quantity; }
|
||||
public void setQuantity(Integer quantity) { this.quantity = quantity; }
|
||||
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
package com.printcalculator.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class PrintSettingsDto {
|
||||
// Mode: "BASIC" or "ADVANCED"
|
||||
private String complexityMode;
|
||||
@@ -10,6 +7,7 @@ public class PrintSettingsDto {
|
||||
// Common
|
||||
private String material; // e.g. "PLA", "PLA TOUGH", "PETG"
|
||||
private String color; // e.g. "White", "#FFFFFF"
|
||||
private Integer quantity;
|
||||
private Long filamentVariantId;
|
||||
private Long printerMachineId;
|
||||
|
||||
@@ -28,4 +26,132 @@ public class PrintSettingsDto {
|
||||
private Double boundingBoxX;
|
||||
private Double boundingBoxY;
|
||||
private Double boundingBoxZ;
|
||||
|
||||
public String getComplexityMode() {
|
||||
return complexityMode;
|
||||
}
|
||||
|
||||
public void setComplexityMode(String complexityMode) {
|
||||
this.complexityMode = complexityMode;
|
||||
}
|
||||
|
||||
public String getMaterial() {
|
||||
return material;
|
||||
}
|
||||
|
||||
public void setMaterial(String material) {
|
||||
this.material = material;
|
||||
}
|
||||
|
||||
public String getColor() {
|
||||
return color;
|
||||
}
|
||||
|
||||
public void setColor(String color) {
|
||||
this.color = color;
|
||||
}
|
||||
|
||||
public Long getFilamentVariantId() {
|
||||
return filamentVariantId;
|
||||
}
|
||||
|
||||
public void setFilamentVariantId(Long filamentVariantId) {
|
||||
this.filamentVariantId = filamentVariantId;
|
||||
}
|
||||
|
||||
public Integer getQuantity() {
|
||||
return quantity;
|
||||
}
|
||||
|
||||
public void setQuantity(Integer quantity) {
|
||||
this.quantity = quantity;
|
||||
}
|
||||
|
||||
public Long getPrinterMachineId() {
|
||||
return printerMachineId;
|
||||
}
|
||||
|
||||
public void setPrinterMachineId(Long printerMachineId) {
|
||||
this.printerMachineId = printerMachineId;
|
||||
}
|
||||
|
||||
public String getQuality() {
|
||||
return quality;
|
||||
}
|
||||
|
||||
public void setQuality(String quality) {
|
||||
this.quality = quality;
|
||||
}
|
||||
|
||||
public Double getNozzleDiameter() {
|
||||
return nozzleDiameter;
|
||||
}
|
||||
|
||||
public void setNozzleDiameter(Double nozzleDiameter) {
|
||||
this.nozzleDiameter = nozzleDiameter;
|
||||
}
|
||||
|
||||
public Double getLayerHeight() {
|
||||
return layerHeight;
|
||||
}
|
||||
|
||||
public void setLayerHeight(Double layerHeight) {
|
||||
this.layerHeight = layerHeight;
|
||||
}
|
||||
|
||||
public Double getInfillDensity() {
|
||||
return infillDensity;
|
||||
}
|
||||
|
||||
public void setInfillDensity(Double infillDensity) {
|
||||
this.infillDensity = infillDensity;
|
||||
}
|
||||
|
||||
public String getInfillPattern() {
|
||||
return infillPattern;
|
||||
}
|
||||
|
||||
public void setInfillPattern(String infillPattern) {
|
||||
this.infillPattern = infillPattern;
|
||||
}
|
||||
|
||||
public Boolean getSupportsEnabled() {
|
||||
return supportsEnabled;
|
||||
}
|
||||
|
||||
public void setSupportsEnabled(Boolean supportsEnabled) {
|
||||
this.supportsEnabled = supportsEnabled;
|
||||
}
|
||||
|
||||
public String getNotes() {
|
||||
return notes;
|
||||
}
|
||||
|
||||
public void setNotes(String notes) {
|
||||
this.notes = notes;
|
||||
}
|
||||
|
||||
public Double getBoundingBoxX() {
|
||||
return boundingBoxX;
|
||||
}
|
||||
|
||||
public void setBoundingBoxX(Double boundingBoxX) {
|
||||
this.boundingBoxX = boundingBoxX;
|
||||
}
|
||||
|
||||
public Double getBoundingBoxY() {
|
||||
return boundingBoxY;
|
||||
}
|
||||
|
||||
public void setBoundingBoxY(Double boundingBoxY) {
|
||||
this.boundingBoxY = boundingBoxY;
|
||||
}
|
||||
|
||||
public Double getBoundingBoxZ() {
|
||||
return boundingBoxZ;
|
||||
}
|
||||
|
||||
public void setBoundingBoxZ(Double boundingBoxZ) {
|
||||
this.boundingBoxZ = boundingBoxZ;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
177
backend/src/main/java/com/printcalculator/entity/MediaAsset.java
Normal file
177
backend/src/main/java/com/printcalculator/entity/MediaAsset.java
Normal file
@@ -0,0 +1,177 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
273
backend/src/main/java/com/printcalculator/entity/MediaUsage.java
Normal file
273
backend/src/main/java/com/printcalculator/entity/MediaUsage.java
Normal file
@@ -0,0 +1,273 @@
|
||||
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 -> {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.printcalculator.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import org.hibernate.annotations.ColumnDefault;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
@Entity
|
||||
@Table(
|
||||
name = "nozzle_layer_height_option",
|
||||
uniqueConstraints = @UniqueConstraint(
|
||||
name = "ux_nozzle_layer_height_option_nozzle_layer",
|
||||
columnNames = {"nozzle_diameter_mm", "layer_height_mm"}
|
||||
)
|
||||
)
|
||||
public class NozzleLayerHeightOption {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "nozzle_layer_height_option_id", nullable = false)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "nozzle_diameter_mm", nullable = false, precision = 4, scale = 2)
|
||||
private BigDecimal nozzleDiameterMm;
|
||||
|
||||
@Column(name = "layer_height_mm", nullable = false, precision = 5, scale = 3)
|
||||
private BigDecimal layerHeightMm;
|
||||
|
||||
@ColumnDefault("true")
|
||||
@Column(name = "is_active", nullable = false)
|
||||
private Boolean isActive;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public BigDecimal getNozzleDiameterMm() {
|
||||
return nozzleDiameterMm;
|
||||
}
|
||||
|
||||
public void setNozzleDiameterMm(BigDecimal nozzleDiameterMm) {
|
||||
this.nozzleDiameterMm = nozzleDiameterMm;
|
||||
}
|
||||
|
||||
public BigDecimal getLayerHeightMm() {
|
||||
return layerHeightMm;
|
||||
}
|
||||
|
||||
public void setLayerHeightMm(BigDecimal layerHeightMm) {
|
||||
this.layerHeightMm = layerHeightMm;
|
||||
}
|
||||
|
||||
public Boolean getIsActive() {
|
||||
return isActive;
|
||||
}
|
||||
|
||||
public void setIsActive(Boolean isActive) {
|
||||
this.isActive = isActive;
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,24 @@ public class OrderItem {
|
||||
@Column(name = "material_code", nullable = false, length = Integer.MAX_VALUE)
|
||||
private String materialCode;
|
||||
|
||||
@Column(name = "quality", length = Integer.MAX_VALUE)
|
||||
private String quality;
|
||||
|
||||
@Column(name = "nozzle_diameter_mm", precision = 4, scale = 2)
|
||||
private BigDecimal nozzleDiameterMm;
|
||||
|
||||
@Column(name = "layer_height_mm", precision = 5, scale = 3)
|
||||
private BigDecimal layerHeightMm;
|
||||
|
||||
@Column(name = "infill_percent")
|
||||
private Integer infillPercent;
|
||||
|
||||
@Column(name = "infill_pattern", length = Integer.MAX_VALUE)
|
||||
private String infillPattern;
|
||||
|
||||
@Column(name = "supports_enabled")
|
||||
private Boolean supportsEnabled;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "filament_variant_id")
|
||||
private FilamentVariant filamentVariant;
|
||||
@@ -162,6 +180,54 @@ public class OrderItem {
|
||||
this.materialCode = materialCode;
|
||||
}
|
||||
|
||||
public String getQuality() {
|
||||
return quality;
|
||||
}
|
||||
|
||||
public void setQuality(String quality) {
|
||||
this.quality = quality;
|
||||
}
|
||||
|
||||
public BigDecimal getNozzleDiameterMm() {
|
||||
return nozzleDiameterMm;
|
||||
}
|
||||
|
||||
public void setNozzleDiameterMm(BigDecimal nozzleDiameterMm) {
|
||||
this.nozzleDiameterMm = nozzleDiameterMm;
|
||||
}
|
||||
|
||||
public BigDecimal getLayerHeightMm() {
|
||||
return layerHeightMm;
|
||||
}
|
||||
|
||||
public void setLayerHeightMm(BigDecimal layerHeightMm) {
|
||||
this.layerHeightMm = layerHeightMm;
|
||||
}
|
||||
|
||||
public Integer getInfillPercent() {
|
||||
return infillPercent;
|
||||
}
|
||||
|
||||
public void setInfillPercent(Integer infillPercent) {
|
||||
this.infillPercent = infillPercent;
|
||||
}
|
||||
|
||||
public String getInfillPattern() {
|
||||
return infillPattern;
|
||||
}
|
||||
|
||||
public void setInfillPattern(String infillPattern) {
|
||||
this.infillPattern = infillPattern;
|
||||
}
|
||||
|
||||
public Boolean getSupportsEnabled() {
|
||||
return supportsEnabled;
|
||||
}
|
||||
|
||||
public void setSupportsEnabled(Boolean supportsEnabled) {
|
||||
this.supportsEnabled = supportsEnabled;
|
||||
}
|
||||
|
||||
public FilamentVariant getFilamentVariant() {
|
||||
return filamentVariant;
|
||||
}
|
||||
|
||||
@@ -45,6 +45,27 @@ public class QuoteLineItem {
|
||||
@com.fasterxml.jackson.annotation.JsonIgnore
|
||||
private FilamentVariant filamentVariant;
|
||||
|
||||
@Column(name = "material_code", length = Integer.MAX_VALUE)
|
||||
private String materialCode;
|
||||
|
||||
@Column(name = "quality", length = Integer.MAX_VALUE)
|
||||
private String quality;
|
||||
|
||||
@Column(name = "nozzle_diameter_mm", precision = 5, scale = 2)
|
||||
private BigDecimal nozzleDiameterMm;
|
||||
|
||||
@Column(name = "layer_height_mm", precision = 6, scale = 3)
|
||||
private BigDecimal layerHeightMm;
|
||||
|
||||
@Column(name = "infill_percent")
|
||||
private Integer infillPercent;
|
||||
|
||||
@Column(name = "infill_pattern", length = Integer.MAX_VALUE)
|
||||
private String infillPattern;
|
||||
|
||||
@Column(name = "supports_enabled")
|
||||
private Boolean supportsEnabled;
|
||||
|
||||
@Column(name = "bounding_box_x_mm", precision = 10, scale = 3)
|
||||
private BigDecimal boundingBoxXMm;
|
||||
|
||||
@@ -137,6 +158,62 @@ public class QuoteLineItem {
|
||||
this.filamentVariant = filamentVariant;
|
||||
}
|
||||
|
||||
public String getMaterialCode() {
|
||||
return materialCode;
|
||||
}
|
||||
|
||||
public void setMaterialCode(String materialCode) {
|
||||
this.materialCode = materialCode;
|
||||
}
|
||||
|
||||
public String getQuality() {
|
||||
return quality;
|
||||
}
|
||||
|
||||
public void setQuality(String quality) {
|
||||
this.quality = quality;
|
||||
}
|
||||
|
||||
public BigDecimal getNozzleDiameterMm() {
|
||||
return nozzleDiameterMm;
|
||||
}
|
||||
|
||||
public void setNozzleDiameterMm(BigDecimal nozzleDiameterMm) {
|
||||
this.nozzleDiameterMm = nozzleDiameterMm;
|
||||
}
|
||||
|
||||
public BigDecimal getLayerHeightMm() {
|
||||
return layerHeightMm;
|
||||
}
|
||||
|
||||
public void setLayerHeightMm(BigDecimal layerHeightMm) {
|
||||
this.layerHeightMm = layerHeightMm;
|
||||
}
|
||||
|
||||
public Integer getInfillPercent() {
|
||||
return infillPercent;
|
||||
}
|
||||
|
||||
public void setInfillPercent(Integer infillPercent) {
|
||||
this.infillPercent = infillPercent;
|
||||
}
|
||||
|
||||
public String getInfillPattern() {
|
||||
return infillPattern;
|
||||
}
|
||||
|
||||
public void setInfillPattern(String infillPattern) {
|
||||
this.infillPattern = infillPattern;
|
||||
}
|
||||
|
||||
public Boolean getSupportsEnabled() {
|
||||
return supportsEnabled;
|
||||
}
|
||||
|
||||
public void setSupportsEnabled(Boolean supportsEnabled) {
|
||||
this.supportsEnabled = supportsEnabled;
|
||||
}
|
||||
|
||||
public BigDecimal getBoundingBoxXMm() {
|
||||
return boundingBoxXMm;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.printcalculator.event;
|
||||
|
||||
import com.printcalculator.entity.Order;
|
||||
import lombok.Getter;
|
||||
import org.springframework.context.ApplicationEvent;
|
||||
|
||||
@Getter
|
||||
public class OrderShippedEvent extends ApplicationEvent {
|
||||
|
||||
private final Order order;
|
||||
|
||||
public OrderShippedEvent(Object source, Order order) {
|
||||
super(source);
|
||||
this.order = order;
|
||||
}
|
||||
}
|
||||
@@ -4,12 +4,13 @@ import com.printcalculator.entity.Order;
|
||||
import com.printcalculator.entity.OrderItem;
|
||||
import com.printcalculator.entity.Payment;
|
||||
import com.printcalculator.event.OrderCreatedEvent;
|
||||
import com.printcalculator.event.OrderShippedEvent;
|
||||
import com.printcalculator.event.PaymentConfirmedEvent;
|
||||
import com.printcalculator.event.PaymentReportedEvent;
|
||||
import com.printcalculator.repository.OrderItemRepository;
|
||||
import com.printcalculator.service.InvoicePdfRenderingService;
|
||||
import com.printcalculator.service.QrBillService;
|
||||
import com.printcalculator.service.StorageService;
|
||||
import com.printcalculator.service.payment.InvoicePdfRenderingService;
|
||||
import com.printcalculator.service.payment.QrBillService;
|
||||
import com.printcalculator.service.storage.StorageService;
|
||||
import com.printcalculator.service.email.EmailNotificationService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -95,6 +96,19 @@ public class OrderEmailListener {
|
||||
}
|
||||
}
|
||||
|
||||
@Async
|
||||
@EventListener
|
||||
public void handleOrderShippedEvent(OrderShippedEvent event) {
|
||||
Order order = event.getOrder();
|
||||
log.info("Processing OrderShippedEvent for order id: {}", order.getId());
|
||||
|
||||
try {
|
||||
sendOrderShippedEmail(order);
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to send order shipped email for order id: {}", order.getId(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private void sendCustomerConfirmationEmail(Order order) {
|
||||
String language = resolveLanguage(order.getPreferredLanguage());
|
||||
String orderNumber = getDisplayOrderNumber(order);
|
||||
@@ -153,6 +167,21 @@ public class OrderEmailListener {
|
||||
);
|
||||
}
|
||||
|
||||
private void sendOrderShippedEmail(Order order) {
|
||||
String language = resolveLanguage(order.getPreferredLanguage());
|
||||
String orderNumber = getDisplayOrderNumber(order);
|
||||
|
||||
Map<String, Object> templateData = buildBaseTemplateData(order, language);
|
||||
String subject = applyOrderShippedTexts(templateData, language, orderNumber);
|
||||
|
||||
emailNotificationService.sendEmail(
|
||||
order.getCustomer().getEmail(),
|
||||
subject,
|
||||
"order-shipped",
|
||||
templateData
|
||||
);
|
||||
}
|
||||
|
||||
private void sendAdminNotificationEmail(Order order) {
|
||||
String orderNumber = getDisplayOrderNumber(order);
|
||||
Map<String, Object> templateData = buildBaseTemplateData(order, DEFAULT_LANGUAGE);
|
||||
@@ -381,6 +410,63 @@ public class OrderEmailListener {
|
||||
};
|
||||
}
|
||||
|
||||
private String applyOrderShippedTexts(Map<String, Object> templateData, String language, String orderNumber) {
|
||||
return switch (language) {
|
||||
case "en" -> {
|
||||
templateData.put("emailTitle", "Order Shipped");
|
||||
templateData.put("headlineText", "Your order #" + orderNumber + " has been shipped");
|
||||
templateData.put("greetingText", "Hi " + templateData.get("customerName") + ",");
|
||||
templateData.put("introText", "Good news: your package has left our workshop and is on its way.");
|
||||
templateData.put("statusText", "Current status: Shipped.");
|
||||
templateData.put("orderDetailsCtaText", "View order status");
|
||||
templateData.put("supportText", "If you need assistance, reply to this email.");
|
||||
templateData.put("footerText", "Automated message from 3D-Fab.");
|
||||
templateData.put("labelOrderNumber", "Order number");
|
||||
templateData.put("labelTotal", "Total");
|
||||
yield "Your order has been shipped (Order #" + orderNumber + ") - 3D-Fab";
|
||||
}
|
||||
case "de" -> {
|
||||
templateData.put("emailTitle", "Bestellung versandt");
|
||||
templateData.put("headlineText", "Ihre Bestellung #" + orderNumber + " wurde versandt");
|
||||
templateData.put("greetingText", "Hallo " + templateData.get("customerName") + ",");
|
||||
templateData.put("introText", "Gute Nachricht: Ihr Paket hat unsere Werkstatt verlassen und ist unterwegs.");
|
||||
templateData.put("statusText", "Aktueller Status: Versandt.");
|
||||
templateData.put("orderDetailsCtaText", "Bestellstatus ansehen");
|
||||
templateData.put("supportText", "Wenn Sie Hilfe benoetigen, antworten Sie auf diese E-Mail.");
|
||||
templateData.put("footerText", "Automatische Nachricht von 3D-Fab.");
|
||||
templateData.put("labelOrderNumber", "Bestellnummer");
|
||||
templateData.put("labelTotal", "Gesamtbetrag");
|
||||
yield "Ihre Bestellung wurde versandt (Bestellung #" + orderNumber + ") - 3D-Fab";
|
||||
}
|
||||
case "fr" -> {
|
||||
templateData.put("emailTitle", "Commande expediee");
|
||||
templateData.put("headlineText", "Votre commande #" + orderNumber + " a ete expediee");
|
||||
templateData.put("greetingText", "Bonjour " + templateData.get("customerName") + ",");
|
||||
templateData.put("introText", "Bonne nouvelle: votre colis a quitte notre atelier et est en route.");
|
||||
templateData.put("statusText", "Statut actuel: Expediee.");
|
||||
templateData.put("orderDetailsCtaText", "Voir le statut de la commande");
|
||||
templateData.put("supportText", "Si vous avez besoin d'aide, repondez a cet email.");
|
||||
templateData.put("footerText", "Message automatique de 3D-Fab.");
|
||||
templateData.put("labelOrderNumber", "Numero de commande");
|
||||
templateData.put("labelTotal", "Total");
|
||||
yield "Votre commande a ete expediee (Commande #" + orderNumber + ") - 3D-Fab";
|
||||
}
|
||||
default -> {
|
||||
templateData.put("emailTitle", "Ordine spedito");
|
||||
templateData.put("headlineText", "Il tuo ordine #" + orderNumber + " e' stato spedito");
|
||||
templateData.put("greetingText", "Ciao " + templateData.get("customerName") + ",");
|
||||
templateData.put("introText", "Buone notizie: il tuo pacco e' partito dal nostro laboratorio ed e' in viaggio.");
|
||||
templateData.put("statusText", "Stato attuale: spedito.");
|
||||
templateData.put("orderDetailsCtaText", "Visualizza stato ordine");
|
||||
templateData.put("supportText", "Se hai bisogno di assistenza, rispondi a questa email.");
|
||||
templateData.put("footerText", "Messaggio automatico di 3D-Fab.");
|
||||
templateData.put("labelOrderNumber", "Numero ordine");
|
||||
templateData.put("labelTotal", "Totale");
|
||||
yield "Il tuo ordine e' stato spedito (Ordine #" + orderNumber + ") - 3D-Fab";
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private String getDisplayOrderNumber(Order order) {
|
||||
String orderNumber = order.getOrderNumber();
|
||||
if (orderNumber != null && !orderNumber.isBlank()) {
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
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();
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
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);
|
||||
|
||||
@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);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.printcalculator.repository;
|
||||
|
||||
import com.printcalculator.entity.NozzleLayerHeightOption;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface NozzleLayerHeightOptionRepository extends JpaRepository<NozzleLayerHeightOption, Long> {
|
||||
List<NozzleLayerHeightOption> findByIsActiveTrueOrderByNozzleDiameterMmAscLayerHeightMmAsc();
|
||||
}
|
||||
@@ -3,5 +3,9 @@ package com.printcalculator.repository;
|
||||
import com.printcalculator.entity.NozzleOption;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface NozzleOptionRepository extends JpaRepository<NozzleOption, Long> {
|
||||
}
|
||||
Optional<NozzleOption> findFirstByNozzleDiameterMmAndIsActiveTrue(BigDecimal nozzleDiameterMm);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
package com.printcalculator.service;
|
||||
|
||||
import com.printcalculator.entity.NozzleLayerHeightOption;
|
||||
import com.printcalculator.repository.NozzleLayerHeightOptionRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
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.logging.Logger;
|
||||
|
||||
@Service
|
||||
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_LAYER = BigDecimal.valueOf(0.20).setScale(3, RoundingMode.HALF_UP);
|
||||
|
||||
private final NozzleLayerHeightOptionRepository ruleRepo;
|
||||
|
||||
public NozzleLayerHeightPolicyService(NozzleLayerHeightOptionRepository ruleRepo) {
|
||||
this.ruleRepo = ruleRepo;
|
||||
}
|
||||
|
||||
public Map<BigDecimal, List<BigDecimal>> getActiveRulesByNozzle() {
|
||||
List<NozzleLayerHeightOption> rules = ruleRepo.findByIsActiveTrueOrderByNozzleDiameterMmAscLayerHeightMmAsc();
|
||||
if (rules.isEmpty()) {
|
||||
logger.warning("No active nozzle->layer rules found in DB (table nozzle_layer_height_option is empty)");
|
||||
return Map.of();
|
||||
}
|
||||
|
||||
Map<BigDecimal, List<BigDecimal>> byNozzle = new LinkedHashMap<>();
|
||||
for (NozzleLayerHeightOption rule : rules) {
|
||||
BigDecimal nozzle = normalizeNozzle(rule.getNozzleDiameterMm());
|
||||
BigDecimal layer = normalizeLayer(rule.getLayerHeightMm());
|
||||
if (nozzle == null || layer == null) {
|
||||
continue;
|
||||
}
|
||||
byNozzle.computeIfAbsent(nozzle, ignored -> new ArrayList<>()).add(layer);
|
||||
}
|
||||
|
||||
byNozzle.values().forEach(this::sortAndDeduplicate);
|
||||
return byNozzle;
|
||||
}
|
||||
|
||||
public BigDecimal normalizeNozzle(BigDecimal value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
return value.setScale(2, RoundingMode.HALF_UP);
|
||||
}
|
||||
|
||||
public BigDecimal normalizeLayer(BigDecimal value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
return value.setScale(3, RoundingMode.HALF_UP);
|
||||
}
|
||||
|
||||
public BigDecimal resolveNozzle(BigDecimal requestedNozzle) {
|
||||
return normalizeNozzle(requestedNozzle != null ? requestedNozzle : DEFAULT_NOZZLE);
|
||||
}
|
||||
|
||||
public BigDecimal resolveLayer(BigDecimal requestedLayer, BigDecimal nozzleDiameter) {
|
||||
if (requestedLayer != null) {
|
||||
return normalizeLayer(requestedLayer);
|
||||
}
|
||||
return defaultLayerForNozzle(nozzleDiameter);
|
||||
}
|
||||
|
||||
public List<BigDecimal> allowedLayersForNozzle(BigDecimal nozzleDiameter) {
|
||||
BigDecimal nozzle = resolveNozzle(nozzleDiameter);
|
||||
List<BigDecimal> allowed = getActiveRulesByNozzle().get(nozzle);
|
||||
return allowed != null ? allowed : List.of();
|
||||
}
|
||||
|
||||
public boolean isAllowed(BigDecimal nozzleDiameter, BigDecimal layerHeight) {
|
||||
BigDecimal layer = normalizeLayer(layerHeight);
|
||||
if (layer == null) {
|
||||
return false;
|
||||
}
|
||||
return allowedLayersForNozzle(nozzleDiameter)
|
||||
.stream()
|
||||
.anyMatch(allowed -> allowed.compareTo(layer) == 0);
|
||||
}
|
||||
|
||||
public BigDecimal defaultLayerForNozzle(BigDecimal nozzleDiameter) {
|
||||
List<BigDecimal> allowed = allowedLayersForNozzle(nozzleDiameter);
|
||||
if (allowed.isEmpty()) {
|
||||
return DEFAULT_LAYER;
|
||||
}
|
||||
|
||||
BigDecimal preferred = normalizeLayer(DEFAULT_LAYER);
|
||||
for (BigDecimal candidate : allowed) {
|
||||
if (candidate.compareTo(preferred) == 0) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
return allowed.get(0);
|
||||
}
|
||||
|
||||
public String allowedLayersLabel(BigDecimal nozzleDiameter) {
|
||||
List<BigDecimal> allowed = allowedLayersForNozzle(nozzleDiameter);
|
||||
if (allowed.isEmpty()) {
|
||||
return "none";
|
||||
}
|
||||
return allowed.stream()
|
||||
.map(value -> String.format(Locale.ROOT, "%.2f", value))
|
||||
.reduce((a, b) -> a + ", " + b)
|
||||
.orElse("none");
|
||||
}
|
||||
|
||||
private void sortAndDeduplicate(List<BigDecimal> values) {
|
||||
values.sort(Comparator.naturalOrder());
|
||||
for (int i = values.size() - 1; i > 0; i--) {
|
||||
if (values.get(i).compareTo(values.get(i - 1)) == 0) {
|
||||
values.remove(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -8,6 +8,10 @@ import com.printcalculator.repository.OrderRepository;
|
||||
import com.printcalculator.repository.QuoteLineItemRepository;
|
||||
import com.printcalculator.repository.QuoteSessionRepository;
|
||||
import com.printcalculator.event.OrderCreatedEvent;
|
||||
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.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
@@ -16,6 +20,7 @@ import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.InvalidPathException;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.OffsetDateTime;
|
||||
@@ -23,6 +28,7 @@ import java.util.*;
|
||||
|
||||
@Service
|
||||
public class OrderService {
|
||||
private static final Path QUOTE_STORAGE_ROOT = Paths.get("storage_quotes").toAbsolutePath().normalize();
|
||||
|
||||
private final OrderRepository orderRepo;
|
||||
private final OrderItemRepository orderItemRepo;
|
||||
@@ -151,7 +157,7 @@ public class OrderService {
|
||||
order.setSubtotalChf(BigDecimal.ZERO);
|
||||
order.setTotalChf(BigDecimal.ZERO);
|
||||
order.setDiscountChf(BigDecimal.ZERO);
|
||||
order.setSetupCostChf(session.getSetupCostChf() != null ? session.getSetupCostChf() : BigDecimal.ZERO);
|
||||
order.setSetupCostChf(totals.setupCostChf());
|
||||
order.setShippingCostChf(totals.shippingCostChf());
|
||||
order.setIsCadOrder(cadTotal.compareTo(BigDecimal.ZERO) > 0 || "CAD_ACTIVE".equals(session.getStatus()));
|
||||
order.setSourceRequestId(session.getSourceRequestId());
|
||||
@@ -178,6 +184,12 @@ public class OrderService {
|
||||
} else {
|
||||
oItem.setMaterialCode(session.getMaterialCode());
|
||||
}
|
||||
oItem.setQuality(qItem.getQuality());
|
||||
oItem.setNozzleDiameterMm(qItem.getNozzleDiameterMm());
|
||||
oItem.setLayerHeightMm(qItem.getLayerHeightMm());
|
||||
oItem.setInfillPercent(qItem.getInfillPercent());
|
||||
oItem.setInfillPattern(qItem.getInfillPattern());
|
||||
oItem.setSupportsEnabled(qItem.getSupportsEnabled());
|
||||
|
||||
BigDecimal distributedUnitPrice = qItem.getUnitPriceChf() != null ? qItem.getUnitPriceChf() : BigDecimal.ZERO;
|
||||
if (totals.totalPrintSeconds().compareTo(BigDecimal.ZERO) > 0 && qItem.getPrintTimeSeconds() != null) {
|
||||
@@ -210,16 +222,15 @@ public class OrderService {
|
||||
String relativePath = "orders/" + order.getId() + "/3d-files/" + oItem.getId() + "/" + storedFilename;
|
||||
oItem.setStoredRelativePath(relativePath);
|
||||
|
||||
if (qItem.getStoredPath() != null) {
|
||||
try {
|
||||
Path sourcePath = Paths.get(qItem.getStoredPath());
|
||||
if (Files.exists(sourcePath)) {
|
||||
storageService.store(sourcePath, Paths.get(relativePath));
|
||||
oItem.setFileSizeBytes(Files.size(sourcePath));
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
Path sourcePath = resolveStoredQuotePath(qItem.getStoredPath(), session.getId());
|
||||
if (sourcePath == null || !Files.exists(sourcePath)) {
|
||||
throw new IllegalStateException("Source file not available for quote line item " + qItem.getId());
|
||||
}
|
||||
try {
|
||||
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);
|
||||
@@ -291,6 +302,23 @@ public class OrderService {
|
||||
return "stl";
|
||||
}
|
||||
|
||||
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 String getDisplayOrderNumber(Order order) {
|
||||
String orderNumber = order.getOrderNumber();
|
||||
if (orderNumber != null && !orderNumber.isBlank()) {
|
||||
|
||||
@@ -7,10 +7,14 @@ import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.Collections;
|
||||
import java.util.Iterator;
|
||||
import java.util.Optional;
|
||||
import java.util.logging.Logger;
|
||||
@@ -20,16 +24,21 @@ import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Set;
|
||||
import java.util.Locale;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Service
|
||||
public class ProfileManager {
|
||||
|
||||
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 Path resolvedProfilesRoot;
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
private final Map<String, String> profileAliases;
|
||||
private volatile List<ProcessProfileMeta> cachedProcessProfiles;
|
||||
|
||||
public ProfileManager(@Value("${profiles.root:profiles}") String profilesRoot, ObjectMapper mapper) {
|
||||
this.profilesRoot = profilesRoot;
|
||||
@@ -68,6 +77,61 @@ public class ProfileManager {
|
||||
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) {
|
||||
if (!Files.isDirectory(resolvedProfilesRoot)) {
|
||||
logger.severe("Profiles root does not exist or is not a directory: " + resolvedProfilesRoot);
|
||||
@@ -215,4 +279,125 @@ public class ProfileManager {
|
||||
}
|
||||
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,22 +3,29 @@ package com.printcalculator.service;
|
||||
import com.printcalculator.entity.PricingPolicy;
|
||||
import com.printcalculator.entity.QuoteLineItem;
|
||||
import com.printcalculator.entity.QuoteSession;
|
||||
import com.printcalculator.repository.NozzleOptionRepository;
|
||||
import com.printcalculator.repository.PricingPolicyRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
@Service
|
||||
public class QuoteSessionTotalsService {
|
||||
private final PricingPolicyRepository pricingRepo;
|
||||
private final QuoteCalculator quoteCalculator;
|
||||
private final NozzleOptionRepository nozzleOptionRepo;
|
||||
|
||||
public QuoteSessionTotalsService(PricingPolicyRepository pricingRepo, QuoteCalculator quoteCalculator) {
|
||||
public QuoteSessionTotalsService(PricingPolicyRepository pricingRepo,
|
||||
QuoteCalculator quoteCalculator,
|
||||
NozzleOptionRepository nozzleOptionRepo) {
|
||||
this.pricingRepo = pricingRepo;
|
||||
this.quoteCalculator = quoteCalculator;
|
||||
this.nozzleOptionRepo = nozzleOptionRepo;
|
||||
}
|
||||
|
||||
public QuoteSessionTotals compute(QuoteSession session, List<QuoteLineItem> items) {
|
||||
@@ -43,7 +50,9 @@ public class QuoteSessionTotalsService {
|
||||
BigDecimal cadTotal = calculateCadTotal(session);
|
||||
BigDecimal itemsTotal = printItemsTotal.add(cadTotal);
|
||||
|
||||
BigDecimal setupFee = session.getSetupCostChf() != null ? session.getSetupCostChf() : BigDecimal.ZERO;
|
||||
BigDecimal baseSetupFee = 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 grandTotal = itemsTotal.add(setupFee).add(shippingCost);
|
||||
|
||||
@@ -52,6 +61,8 @@ public class QuoteSessionTotalsService {
|
||||
globalMachineCost,
|
||||
cadTotal,
|
||||
itemsTotal,
|
||||
baseSetupFee.setScale(2, RoundingMode.HALF_UP),
|
||||
nozzleChangeCost,
|
||||
setupFee,
|
||||
shippingCost,
|
||||
grandTotal,
|
||||
@@ -104,6 +115,36 @@ public class QuoteSessionTotalsService {
|
||||
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) {
|
||||
if (quantity == null || quantity < 1) {
|
||||
return 1;
|
||||
@@ -116,6 +157,8 @@ public class QuoteSessionTotalsService {
|
||||
BigDecimal globalMachineCostChf,
|
||||
BigDecimal cadTotalChf,
|
||||
BigDecimal itemsTotalChf,
|
||||
BigDecimal baseSetupCostChf,
|
||||
BigDecimal nozzleChangeCostChf,
|
||||
BigDecimal setupCostChf,
|
||||
BigDecimal shippingCostChf,
|
||||
BigDecimal grandTotalChf,
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
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());
|
||||
|
||||
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(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 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,858 @@
|
||||
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));
|
||||
}
|
||||
|
||||
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 encoders are 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) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,469 @@
|
||||
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.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.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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
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 final String ffmpegExecutable;
|
||||
private final Set<String> availableEncoders;
|
||||
|
||||
public MediaFfmpegService(@Value("${media.ffmpeg.path:ffmpeg}") String ffmpegPath) {
|
||||
this.ffmpegExecutable = resolveExecutable(ffmpegPath);
|
||||
this.availableEncoders = Collections.unmodifiableSet(loadAvailableEncoders());
|
||||
}
|
||||
|
||||
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 encoder = resolveEncoder(format);
|
||||
if (encoder == null) {
|
||||
throw new IOException("FFmpeg encoder not available for media format " + format + ".");
|
||||
}
|
||||
|
||||
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 (format) {
|
||||
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");
|
||||
}
|
||||
default -> throw new IllegalArgumentException("Unsupported media format: " + format);
|
||||
}
|
||||
|
||||
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) {
|
||||
return resolveEncoder(format) != null;
|
||||
}
|
||||
|
||||
private String resolveEncoder(String format) {
|
||||
if (format == null) {
|
||||
return null;
|
||||
}
|
||||
List<String> candidates = ENCODER_CANDIDATES.get(format.trim().toUpperCase(Locale.ROOT));
|
||||
if (candidates == null) {
|
||||
return null;
|
||||
}
|
||||
return candidates.stream()
|
||||
.filter(availableEncoders::contains)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
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 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 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
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) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
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 publicBaseUrl;
|
||||
|
||||
public MediaStorageService(@Value("${media.storage.root:storage_media}") String storageRoot,
|
||||
@Value("${media.public.base-url:http://localhost:8080/media}") String publicBaseUrl) {
|
||||
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.publicBaseUrl = publicBaseUrl;
|
||||
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 normalizedKey = storageKey.startsWith("/") ? storageKey.substring(1) : storageKey;
|
||||
if (publicBaseUrl.endsWith("/")) {
|
||||
return publicBaseUrl + normalizedKey;
|
||||
}
|
||||
return publicBaseUrl + "/" + 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
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.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);
|
||||
String normalizedLanguage = normalizeLanguage(language);
|
||||
|
||||
List<MediaUsage> usages = mediaUsageRepository
|
||||
.findByUsageTypeAndUsageKeyAndIsActiveTrueOrderBySortOrderAscCreatedAtAsc(
|
||||
normalizedUsageType,
|
||||
normalizedUsageKey
|
||||
)
|
||||
.stream()
|
||||
.filter(this::isPublicReadyUsage)
|
||||
.sorted(Comparator
|
||||
.comparing(MediaUsage::getSortOrder, Comparator.nullsLast(Integer::compareTo))
|
||||
.thenComparing(MediaUsage::getCreatedAt, Comparator.nullsLast(OffsetDateTime::compareTo)))
|
||||
.toList();
|
||||
|
||||
if (usages.isEmpty()) {
|
||||
return List.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()));
|
||||
|
||||
return usages.stream()
|
||||
.map(usage -> toDto(
|
||||
usage,
|
||||
variantsByAssetId.getOrDefault(usage.getMediaAsset().getId(), List.of()),
|
||||
normalizedLanguage
|
||||
))
|
||||
.toList();
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,435 @@
|
||||
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.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.setOriginalFilename(item.getOriginalFilename());
|
||||
itemDto.setMaterialCode(item.getMaterialCode());
|
||||
itemDto.setColorCode(item.getColorCode());
|
||||
if (item.getFilamentVariant() != null) {
|
||||
itemDto.setFilamentVariantId(item.getFilamentVariant().getId());
|
||||
itemDto.setFilamentVariantDisplayName(item.getFilamentVariant().getVariantDisplayName());
|
||||
itemDto.setFilamentColorName(item.getFilamentVariant().getColorName());
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
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.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.setOriginalFilename(item.getOriginalFilename());
|
||||
itemDto.setMaterialCode(item.getMaterialCode());
|
||||
itemDto.setColorCode(item.getColorCode());
|
||||
if (item.getFilamentVariant() != null) {
|
||||
itemDto.setFilamentVariantId(item.getFilamentVariant().getId());
|
||||
itemDto.setFilamentVariantDisplayName(item.getFilamentVariant().getVariantDisplayName());
|
||||
itemDto.setFilamentColorName(item.getFilamentVariant().getColorName());
|
||||
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";
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.printcalculator.service;
|
||||
package com.printcalculator.service.payment;
|
||||
|
||||
import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
|
||||
import com.openhtmltopdf.svgsupport.BatikSVGDrawer;
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.printcalculator.service;
|
||||
package com.printcalculator.service.payment;
|
||||
|
||||
import com.printcalculator.entity.Order;
|
||||
import com.printcalculator.entity.Payment;
|
||||
@@ -65,7 +65,7 @@ public class PaymentService {
|
||||
payment.setReportedAt(OffsetDateTime.now());
|
||||
|
||||
// We intentionally do not update the payment method here based on user input,
|
||||
// because the user cannot reliably determine the actual method without an integration.
|
||||
// because the system cannot reliably determine the actual method without an integration.
|
||||
// It will be updated by the backoffice admin manually.
|
||||
|
||||
payment = paymentRepo.save(payment);
|
||||
@@ -98,4 +98,20 @@ public class PaymentService {
|
||||
|
||||
return payment;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Payment updatePaymentMethod(UUID orderId, String method) {
|
||||
if (method == null || method.isBlank()) {
|
||||
throw new IllegalArgumentException("Payment method is required");
|
||||
}
|
||||
|
||||
Order order = orderRepo.findById(orderId)
|
||||
.orElseThrow(() -> new RuntimeException("Order not found with id " + orderId));
|
||||
|
||||
Payment payment = paymentRepo.findByOrder_Id(orderId)
|
||||
.orElseGet(() -> getOrCreatePaymentForOrder(order, "OTHER"));
|
||||
|
||||
payment.setMethod(method.trim().toUpperCase());
|
||||
return paymentRepo.save(payment);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,10 @@
|
||||
package com.printcalculator.service;
|
||||
package com.printcalculator.service.payment;
|
||||
|
||||
import com.printcalculator.entity.Order;
|
||||
import net.codecrete.qrbill.generator.Bill;
|
||||
import net.codecrete.qrbill.generator.GraphicsFormat;
|
||||
import net.codecrete.qrbill.generator.QRBill;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
@Service
|
||||
public class QrBillService {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.printcalculator.service;
|
||||
package com.printcalculator.service.payment;
|
||||
|
||||
import io.nayuki.qrcodegen.QrCode;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
@@ -0,0 +1,289 @@
|
||||
package com.printcalculator.service.quote;
|
||||
|
||||
import com.printcalculator.dto.PrintSettingsDto;
|
||||
import com.printcalculator.entity.FilamentVariant;
|
||||
import com.printcalculator.entity.PrinterMachine;
|
||||
import com.printcalculator.entity.QuoteLineItem;
|
||||
import com.printcalculator.entity.QuoteSession;
|
||||
import com.printcalculator.model.ModelDimensions;
|
||||
import com.printcalculator.model.PrintStats;
|
||||
import com.printcalculator.model.QuoteResult;
|
||||
import com.printcalculator.repository.QuoteLineItemRepository;
|
||||
import com.printcalculator.repository.QuoteSessionRepository;
|
||||
import com.printcalculator.service.OrcaProfileResolver;
|
||||
import com.printcalculator.service.ProfileManager;
|
||||
import com.printcalculator.service.QuoteCalculator;
|
||||
import com.printcalculator.service.SlicerService;
|
||||
import com.printcalculator.service.storage.ClamAVService;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
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.time.OffsetDateTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
|
||||
@Service
|
||||
public class QuoteSessionItemService {
|
||||
private final QuoteLineItemRepository lineItemRepo;
|
||||
private final QuoteSessionRepository sessionRepo;
|
||||
private final SlicerService slicerService;
|
||||
private final QuoteCalculator quoteCalculator;
|
||||
private final OrcaProfileResolver orcaProfileResolver;
|
||||
private final ClamAVService clamAVService;
|
||||
private final QuoteStorageService quoteStorageService;
|
||||
private final QuoteSessionSettingsService settingsService;
|
||||
private final ProfileManager profileManager;
|
||||
|
||||
public QuoteSessionItemService(QuoteLineItemRepository lineItemRepo,
|
||||
QuoteSessionRepository sessionRepo,
|
||||
SlicerService slicerService,
|
||||
QuoteCalculator quoteCalculator,
|
||||
OrcaProfileResolver orcaProfileResolver,
|
||||
ClamAVService clamAVService,
|
||||
QuoteStorageService quoteStorageService,
|
||||
QuoteSessionSettingsService settingsService,
|
||||
ProfileManager profileManager) {
|
||||
this.lineItemRepo = lineItemRepo;
|
||||
this.sessionRepo = sessionRepo;
|
||||
this.slicerService = slicerService;
|
||||
this.quoteCalculator = quoteCalculator;
|
||||
this.orcaProfileResolver = orcaProfileResolver;
|
||||
this.clamAVService = clamAVService;
|
||||
this.quoteStorageService = quoteStorageService;
|
||||
this.settingsService = settingsService;
|
||||
this.profileManager = profileManager;
|
||||
}
|
||||
|
||||
public QuoteLineItem addItemToSession(QuoteSession session, MultipartFile file, PrintSettingsDto settings) throws IOException {
|
||||
if (file.isEmpty()) {
|
||||
throw new IllegalArgumentException("File is empty");
|
||||
}
|
||||
if ("CONVERTED".equals(session.getStatus())) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Cannot modify a converted session");
|
||||
}
|
||||
|
||||
clamAVService.scan(file.getInputStream());
|
||||
|
||||
Path sessionStorageDir = quoteStorageService.sessionStorageDir(session.getId());
|
||||
String ext = quoteStorageService.getSafeExtension(file.getOriginalFilename(), "stl");
|
||||
String storedFilename = UUID.randomUUID() + "." + ext;
|
||||
Path persistentPath = quoteStorageService.resolveSessionPath(sessionStorageDir, storedFilename);
|
||||
|
||||
try (InputStream inputStream = file.getInputStream()) {
|
||||
Files.copy(inputStream, persistentPath, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
|
||||
Path convertedPersistentPath = null;
|
||||
try {
|
||||
boolean cadSession = "CAD_ACTIVE".equals(session.getStatus());
|
||||
|
||||
if (cadSession) {
|
||||
settingsService.enforceCadPrintSettings(session, settings);
|
||||
} else {
|
||||
settingsService.applyPrintSettings(settings);
|
||||
}
|
||||
|
||||
QuoteSessionSettingsService.NozzleLayerSettings nozzleAndLayer = settingsService.resolveNozzleAndLayer(settings);
|
||||
BigDecimal nozzleDiameter = nozzleAndLayer.nozzleDiameter();
|
||||
BigDecimal layerHeight = nozzleAndLayer.layerHeight();
|
||||
|
||||
PrinterMachine machine = settingsService.resolvePrinterMachine(settings.getPrinterMachineId());
|
||||
FilamentVariant selectedVariant = settingsService.resolveFilamentVariant(settings);
|
||||
|
||||
validateCadMaterialLock(session, cadSession, selectedVariant);
|
||||
|
||||
if (!cadSession) {
|
||||
session.setMaterialCode(selectedVariant.getFilamentMaterialType().getMaterialCode());
|
||||
session.setNozzleDiameterMm(nozzleDiameter);
|
||||
session.setLayerHeightMm(layerHeight);
|
||||
session.setInfillPattern(settings.getInfillPattern());
|
||||
session.setInfillPercent(settings.getInfillDensity() != null ? settings.getInfillDensity().intValue() : 20);
|
||||
session.setSupportsEnabled(settings.getSupportsEnabled() != null ? settings.getSupportsEnabled() : false);
|
||||
sessionRepo.save(session);
|
||||
}
|
||||
|
||||
OrcaProfileResolver.ResolvedProfiles profiles = orcaProfileResolver.resolve(machine, nozzleDiameter, selectedVariant);
|
||||
String processProfile = resolveProcessProfile(
|
||||
settings,
|
||||
profiles.machineProfileName(),
|
||||
nozzleDiameter,
|
||||
layerHeight
|
||||
);
|
||||
|
||||
Map<String, String> processOverrides = new HashMap<>();
|
||||
processOverrides.put("layer_height", layerHeight.stripTrailingZeros().toPlainString());
|
||||
if (settings.getInfillDensity() != null) {
|
||||
processOverrides.put("sparse_infill_density", settings.getInfillDensity() + "%");
|
||||
}
|
||||
if (settings.getInfillPattern() != null) {
|
||||
processOverrides.put("sparse_infill_pattern", settings.getInfillPattern());
|
||||
}
|
||||
|
||||
Path slicerInputPath = persistentPath;
|
||||
if ("3mf".equals(ext)) {
|
||||
String convertedFilename = UUID.randomUUID() + "-converted.stl";
|
||||
convertedPersistentPath = quoteStorageService.resolveSessionPath(sessionStorageDir, convertedFilename);
|
||||
slicerService.convert3mfToPersistentStl(persistentPath.toFile(), convertedPersistentPath);
|
||||
slicerInputPath = convertedPersistentPath;
|
||||
}
|
||||
|
||||
PrintStats stats = slicerService.slice(
|
||||
slicerInputPath.toFile(),
|
||||
profiles.machineProfileName(),
|
||||
profiles.filamentProfileName(),
|
||||
processProfile,
|
||||
null,
|
||||
processOverrides
|
||||
);
|
||||
|
||||
Optional<ModelDimensions> modelDimensions = slicerService.inspectModelDimensions(slicerInputPath.toFile());
|
||||
QuoteResult result = quoteCalculator.calculate(stats, machine.getPrinterDisplayName(), selectedVariant);
|
||||
|
||||
QuoteLineItem item = buildLineItem(
|
||||
session,
|
||||
file.getOriginalFilename(),
|
||||
settings,
|
||||
selectedVariant,
|
||||
nozzleDiameter,
|
||||
layerHeight,
|
||||
stats,
|
||||
result,
|
||||
modelDimensions,
|
||||
persistentPath,
|
||||
convertedPersistentPath
|
||||
);
|
||||
|
||||
return lineItemRepo.save(item);
|
||||
} catch (Exception e) {
|
||||
Files.deleteIfExists(persistentPath);
|
||||
if (convertedPersistentPath != null) {
|
||||
Files.deleteIfExists(convertedPersistentPath);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private void validateCadMaterialLock(QuoteSession session, boolean cadSession, FilamentVariant selectedVariant) {
|
||||
if (!cadSession
|
||||
|| session.getMaterialCode() == null
|
||||
|| selectedVariant.getFilamentMaterialType() == null
|
||||
|| selectedVariant.getFilamentMaterialType().getMaterialCode() == null) {
|
||||
return;
|
||||
}
|
||||
String lockedMaterial = settingsService.normalizeRequestedMaterialCode(session.getMaterialCode());
|
||||
String selectedMaterial = settingsService.normalizeRequestedMaterialCode(
|
||||
selectedVariant.getFilamentMaterialType().getMaterialCode()
|
||||
);
|
||||
if (!lockedMaterial.equals(selectedMaterial)) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Selected filament does not match locked CAD material");
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
return "standard";
|
||||
}
|
||||
if (settings.getLayerHeight() >= 0.28) {
|
||||
return "draft";
|
||||
}
|
||||
if (settings.getLayerHeight() <= 0.12) {
|
||||
return "extra_fine";
|
||||
}
|
||||
return "standard";
|
||||
}
|
||||
|
||||
private QuoteLineItem buildLineItem(QuoteSession session,
|
||||
String originalFilename,
|
||||
PrintSettingsDto settings,
|
||||
FilamentVariant selectedVariant,
|
||||
BigDecimal nozzleDiameter,
|
||||
BigDecimal layerHeight,
|
||||
PrintStats stats,
|
||||
QuoteResult result,
|
||||
Optional<ModelDimensions> modelDimensions,
|
||||
Path persistentPath,
|
||||
Path convertedPersistentPath) {
|
||||
QuoteLineItem item = new QuoteLineItem();
|
||||
item.setQuoteSession(session);
|
||||
item.setOriginalFilename(originalFilename);
|
||||
item.setStoredPath(quoteStorageService.toStoredPath(persistentPath));
|
||||
item.setQuantity(normalizeQuantity(settings.getQuantity()));
|
||||
item.setColorCode(selectedVariant.getColorName());
|
||||
item.setFilamentVariant(selectedVariant);
|
||||
item.setMaterialCode(selectedVariant.getFilamentMaterialType() != null
|
||||
? selectedVariant.getFilamentMaterialType().getMaterialCode()
|
||||
: settingsService.normalizeRequestedMaterialCode(settings.getMaterial()));
|
||||
item.setQuality(settingsService.resolveQuality(settings, layerHeight));
|
||||
item.setNozzleDiameterMm(nozzleDiameter);
|
||||
item.setLayerHeightMm(layerHeight);
|
||||
item.setInfillPercent(settings.getInfillDensity() != null ? settings.getInfillDensity().intValue() : 20);
|
||||
item.setInfillPattern(settings.getInfillPattern());
|
||||
item.setSupportsEnabled(settings.getSupportsEnabled() != null ? settings.getSupportsEnabled() : false);
|
||||
item.setStatus("READY");
|
||||
|
||||
item.setPrintTimeSeconds((int) stats.printTimeSeconds());
|
||||
item.setMaterialGrams(BigDecimal.valueOf(stats.filamentWeightGrams()));
|
||||
item.setUnitPriceChf(BigDecimal.valueOf(result.getTotalPrice()));
|
||||
|
||||
Map<String, Object> breakdown = new HashMap<>();
|
||||
breakdown.put("machine_cost", result.getTotalPrice());
|
||||
breakdown.put("setup_fee", 0);
|
||||
if (convertedPersistentPath != null) {
|
||||
breakdown.put("convertedStoredPath", quoteStorageService.toStoredPath(convertedPersistentPath));
|
||||
}
|
||||
item.setPricingBreakdown(breakdown);
|
||||
|
||||
item.setBoundingBoxXMm(modelDimensions
|
||||
.map(dim -> BigDecimal.valueOf(dim.xMm()))
|
||||
.orElseGet(() -> settings.getBoundingBoxX() != null ? BigDecimal.valueOf(settings.getBoundingBoxX()) : BigDecimal.ZERO));
|
||||
item.setBoundingBoxYMm(modelDimensions
|
||||
.map(dim -> BigDecimal.valueOf(dim.yMm()))
|
||||
.orElseGet(() -> settings.getBoundingBoxY() != null ? BigDecimal.valueOf(settings.getBoundingBoxY()) : BigDecimal.ZERO));
|
||||
item.setBoundingBoxZMm(modelDimensions
|
||||
.map(dim -> BigDecimal.valueOf(dim.zMm()))
|
||||
.orElseGet(() -> settings.getBoundingBoxZ() != null ? BigDecimal.valueOf(settings.getBoundingBoxZ()) : BigDecimal.ZERO));
|
||||
|
||||
item.setCreatedAt(OffsetDateTime.now());
|
||||
item.setUpdatedAt(OffsetDateTime.now());
|
||||
return item;
|
||||
}
|
||||
|
||||
private int normalizeQuantity(Integer quantity) {
|
||||
if (quantity == null || quantity < 1) {
|
||||
return 1;
|
||||
}
|
||||
return quantity;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.printcalculator.service.quote;
|
||||
|
||||
import com.printcalculator.entity.QuoteLineItem;
|
||||
import com.printcalculator.entity.QuoteSession;
|
||||
import com.printcalculator.service.QuoteSessionTotalsService;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
public class QuoteSessionResponseAssembler {
|
||||
private final QuoteStorageService quoteStorageService;
|
||||
|
||||
public QuoteSessionResponseAssembler(QuoteStorageService quoteStorageService) {
|
||||
this.quoteStorageService = quoteStorageService;
|
||||
}
|
||||
|
||||
public Map<String, Object> assemble(QuoteSession session,
|
||||
List<QuoteLineItem> items,
|
||||
QuoteSessionTotalsService.QuoteSessionTotals totals) {
|
||||
List<Map<String, Object>> itemsDto = new ArrayList<>();
|
||||
for (QuoteLineItem item : items) {
|
||||
itemsDto.add(toItemDto(item, totals));
|
||||
}
|
||||
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
response.put("session", session);
|
||||
response.put("items", itemsDto);
|
||||
response.put("printItemsTotalChf", totals.printItemsTotalChf());
|
||||
response.put("cadTotalChf", totals.cadTotalChf());
|
||||
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("globalMachineCostChf", totals.globalMachineCostChf());
|
||||
response.put("grandTotalChf", totals.grandTotalChf());
|
||||
return response;
|
||||
}
|
||||
|
||||
private Map<String, Object> toItemDto(QuoteLineItem item, QuoteSessionTotalsService.QuoteSessionTotals totals) {
|
||||
Map<String, Object> dto = new HashMap<>();
|
||||
dto.put("id", item.getId());
|
||||
dto.put("originalFilename", item.getOriginalFilename());
|
||||
dto.put("quantity", item.getQuantity());
|
||||
dto.put("printTimeSeconds", item.getPrintTimeSeconds());
|
||||
dto.put("materialGrams", item.getMaterialGrams());
|
||||
dto.put("colorCode", item.getColorCode());
|
||||
dto.put("filamentVariantId", item.getFilamentVariant() != null ? item.getFilamentVariant().getId() : null);
|
||||
dto.put("materialCode", item.getMaterialCode());
|
||||
dto.put("quality", item.getQuality());
|
||||
dto.put("nozzleDiameterMm", item.getNozzleDiameterMm());
|
||||
dto.put("layerHeightMm", item.getLayerHeightMm());
|
||||
dto.put("infillPercent", item.getInfillPercent());
|
||||
dto.put("infillPattern", item.getInfillPattern());
|
||||
dto.put("supportsEnabled", item.getSupportsEnabled());
|
||||
dto.put("status", item.getStatus());
|
||||
dto.put("convertedStoredPath", quoteStorageService.extractConvertedStoredPath(item));
|
||||
dto.put("unitPriceChf", resolveDistributedUnitPrice(item, totals));
|
||||
return dto;
|
||||
}
|
||||
|
||||
private BigDecimal resolveDistributedUnitPrice(QuoteLineItem item, QuoteSessionTotalsService.QuoteSessionTotals totals) {
|
||||
BigDecimal unitPrice = item.getUnitPriceChf() != null ? item.getUnitPriceChf() : BigDecimal.ZERO;
|
||||
int quantity = item.getQuantity() != null && item.getQuantity() > 0 ? item.getQuantity() : 1;
|
||||
if (totals.totalPrintSeconds().compareTo(BigDecimal.ZERO) > 0 && item.getPrintTimeSeconds() != null) {
|
||||
BigDecimal itemSeconds = BigDecimal.valueOf(item.getPrintTimeSeconds()).multiply(BigDecimal.valueOf(quantity));
|
||||
BigDecimal share = itemSeconds.divide(totals.totalPrintSeconds(), 8, RoundingMode.HALF_UP);
|
||||
BigDecimal itemMachineCost = totals.globalMachineCostChf().multiply(share);
|
||||
BigDecimal unitMachineCost = itemMachineCost.divide(BigDecimal.valueOf(quantity), 2, RoundingMode.HALF_UP);
|
||||
unitPrice = unitPrice.add(unitMachineCost);
|
||||
}
|
||||
return unitPrice;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package com.printcalculator.service.quote;
|
||||
|
||||
import com.printcalculator.dto.PrintSettingsDto;
|
||||
import com.printcalculator.entity.FilamentMaterialType;
|
||||
import com.printcalculator.entity.FilamentVariant;
|
||||
import com.printcalculator.entity.PrinterMachine;
|
||||
import com.printcalculator.entity.QuoteSession;
|
||||
import com.printcalculator.repository.FilamentMaterialTypeRepository;
|
||||
import com.printcalculator.repository.FilamentVariantRepository;
|
||||
import com.printcalculator.repository.PrinterMachineRepository;
|
||||
import com.printcalculator.service.NozzleLayerHeightPolicyService;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
public class QuoteSessionSettingsService {
|
||||
private final PrinterMachineRepository machineRepo;
|
||||
private final FilamentMaterialTypeRepository materialRepo;
|
||||
private final FilamentVariantRepository variantRepo;
|
||||
private final NozzleLayerHeightPolicyService nozzleLayerHeightPolicyService;
|
||||
|
||||
public QuoteSessionSettingsService(PrinterMachineRepository machineRepo,
|
||||
FilamentMaterialTypeRepository materialRepo,
|
||||
FilamentVariantRepository variantRepo,
|
||||
NozzleLayerHeightPolicyService nozzleLayerHeightPolicyService) {
|
||||
this.machineRepo = machineRepo;
|
||||
this.materialRepo = materialRepo;
|
||||
this.variantRepo = variantRepo;
|
||||
this.nozzleLayerHeightPolicyService = nozzleLayerHeightPolicyService;
|
||||
}
|
||||
|
||||
public void applyPrintSettings(PrintSettingsDto settings) {
|
||||
if (settings.getNozzleDiameter() == null) {
|
||||
settings.setNozzleDiameter(0.40);
|
||||
}
|
||||
|
||||
if ("BASIC".equalsIgnoreCase(settings.getComplexityMode())) {
|
||||
String quality = settings.getQuality() != null ? settings.getQuality().toLowerCase() : "standard";
|
||||
|
||||
switch (quality) {
|
||||
case "draft" -> {
|
||||
settings.setLayerHeight(0.28);
|
||||
settings.setInfillDensity(15.0);
|
||||
settings.setInfillPattern("grid");
|
||||
}
|
||||
case "extra_fine", "high_definition", "high" -> {
|
||||
settings.setLayerHeight(0.12);
|
||||
settings.setInfillDensity(20.0);
|
||||
settings.setInfillPattern("gyroid");
|
||||
}
|
||||
case "standard" -> {
|
||||
settings.setLayerHeight(0.20);
|
||||
settings.setInfillDensity(15.0);
|
||||
settings.setInfillPattern("grid");
|
||||
}
|
||||
default -> {
|
||||
settings.setLayerHeight(0.20);
|
||||
settings.setInfillDensity(15.0);
|
||||
settings.setInfillPattern("grid");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (settings.getInfillDensity() == null) {
|
||||
settings.setInfillDensity(20.0);
|
||||
}
|
||||
if (settings.getInfillPattern() == null) {
|
||||
settings.setInfillPattern("grid");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void enforceCadPrintSettings(QuoteSession session, PrintSettingsDto settings) {
|
||||
settings.setComplexityMode("ADVANCED");
|
||||
settings.setMaterial(session.getMaterialCode() != null ? session.getMaterialCode() : "PLA");
|
||||
settings.setNozzleDiameter(session.getNozzleDiameterMm() != null ? session.getNozzleDiameterMm().doubleValue() : 0.4);
|
||||
settings.setLayerHeight(session.getLayerHeightMm() != null ? session.getLayerHeightMm().doubleValue() : 0.2);
|
||||
settings.setInfillPattern(session.getInfillPattern() != null ? session.getInfillPattern() : "grid");
|
||||
settings.setInfillDensity(session.getInfillPercent() != null ? session.getInfillPercent().doubleValue() : 20.0);
|
||||
settings.setSupportsEnabled(Boolean.TRUE.equals(session.getSupportsEnabled()));
|
||||
}
|
||||
|
||||
public NozzleLayerSettings resolveNozzleAndLayer(PrintSettingsDto settings) {
|
||||
BigDecimal nozzleDiameter = nozzleLayerHeightPolicyService.resolveNozzle(
|
||||
settings.getNozzleDiameter() != null ? BigDecimal.valueOf(settings.getNozzleDiameter()) : null
|
||||
);
|
||||
BigDecimal layerHeight = nozzleLayerHeightPolicyService.resolveLayer(
|
||||
settings.getLayerHeight() != null ? BigDecimal.valueOf(settings.getLayerHeight()) : null,
|
||||
nozzleDiameter
|
||||
);
|
||||
if (!nozzleLayerHeightPolicyService.isAllowed(nozzleDiameter, layerHeight)) {
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.BAD_REQUEST,
|
||||
"Layer height " + layerHeight.stripTrailingZeros().toPlainString()
|
||||
+ " is not allowed for nozzle " + nozzleDiameter.stripTrailingZeros().toPlainString()
|
||||
+ ". Allowed: " + nozzleLayerHeightPolicyService.allowedLayersLabel(nozzleDiameter)
|
||||
);
|
||||
}
|
||||
settings.setNozzleDiameter(nozzleDiameter.doubleValue());
|
||||
settings.setLayerHeight(layerHeight.doubleValue());
|
||||
return new NozzleLayerSettings(nozzleDiameter, layerHeight);
|
||||
}
|
||||
|
||||
public PrinterMachine resolvePrinterMachine(Long printerMachineId) {
|
||||
if (printerMachineId != null) {
|
||||
PrinterMachine selected = machineRepo.findById(printerMachineId)
|
||||
.orElseThrow(() -> new RuntimeException("Printer machine not found: " + printerMachineId));
|
||||
if (!Boolean.TRUE.equals(selected.getIsActive())) {
|
||||
throw new RuntimeException("Selected printer machine is not active");
|
||||
}
|
||||
return selected;
|
||||
}
|
||||
|
||||
return machineRepo.findFirstByIsActiveTrue()
|
||||
.orElseThrow(() -> new RuntimeException("No active printer found"));
|
||||
}
|
||||
|
||||
public FilamentVariant resolveFilamentVariant(PrintSettingsDto settings) {
|
||||
if (settings.getFilamentVariantId() != null) {
|
||||
FilamentVariant variant = variantRepo.findById(settings.getFilamentVariantId())
|
||||
.orElseThrow(() -> new RuntimeException("Filament variant not found: " + settings.getFilamentVariantId()));
|
||||
if (!Boolean.TRUE.equals(variant.getIsActive())) {
|
||||
throw new RuntimeException("Selected filament variant is not active");
|
||||
}
|
||||
return variant;
|
||||
}
|
||||
|
||||
String requestedMaterialCode = normalizeRequestedMaterialCode(settings.getMaterial());
|
||||
FilamentMaterialType materialType = materialRepo.findByMaterialCode(requestedMaterialCode)
|
||||
.orElseGet(() -> materialRepo.findByMaterialCode("PLA")
|
||||
.orElseThrow(() -> new RuntimeException("Fallback material PLA not configured")));
|
||||
|
||||
String requestedColor = settings.getColor() != null ? settings.getColor().trim() : null;
|
||||
if (requestedColor != null && !requestedColor.isBlank()) {
|
||||
Optional<FilamentVariant> byColor = variantRepo.findByFilamentMaterialTypeAndColorName(materialType, requestedColor);
|
||||
if (byColor.isPresent() && Boolean.TRUE.equals(byColor.get().getIsActive())) {
|
||||
return byColor.get();
|
||||
}
|
||||
}
|
||||
|
||||
return variantRepo.findFirstByFilamentMaterialTypeAndIsActiveTrue(materialType)
|
||||
.orElseThrow(() -> new RuntimeException("No active variant for material: " + requestedMaterialCode));
|
||||
}
|
||||
|
||||
public String normalizeRequestedMaterialCode(String value) {
|
||||
if (value == null || value.isBlank()) {
|
||||
return "PLA";
|
||||
}
|
||||
|
||||
return value.trim()
|
||||
.toUpperCase(Locale.ROOT)
|
||||
.replace('_', ' ')
|
||||
.replace('-', ' ')
|
||||
.replaceAll("\\s+", " ");
|
||||
}
|
||||
|
||||
public String resolveQuality(PrintSettingsDto settings, BigDecimal layerHeight) {
|
||||
if (settings.getQuality() != null && !settings.getQuality().isBlank()) {
|
||||
return settings.getQuality().trim().toLowerCase(Locale.ROOT);
|
||||
}
|
||||
if (layerHeight == null) {
|
||||
return "standard";
|
||||
}
|
||||
if (layerHeight.compareTo(BigDecimal.valueOf(0.24)) >= 0) {
|
||||
return "draft";
|
||||
}
|
||||
if (layerHeight.compareTo(BigDecimal.valueOf(0.12)) <= 0) {
|
||||
return "extra_fine";
|
||||
}
|
||||
return "standard";
|
||||
}
|
||||
|
||||
public record NozzleLayerSettings(BigDecimal nozzleDiameter, BigDecimal layerHeight) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.printcalculator.service.quote;
|
||||
|
||||
import com.printcalculator.entity.QuoteLineItem;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.InvalidPathException;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
public class QuoteStorageService {
|
||||
private static final Path QUOTE_STORAGE_ROOT = Paths.get("storage_quotes").toAbsolutePath().normalize();
|
||||
|
||||
public Path sessionStorageDir(UUID sessionId) throws IOException {
|
||||
Path sessionStorageDir = QUOTE_STORAGE_ROOT.resolve(sessionId.toString()).normalize();
|
||||
if (!sessionStorageDir.startsWith(QUOTE_STORAGE_ROOT)) {
|
||||
throw new IOException("Invalid quote session storage path");
|
||||
}
|
||||
Files.createDirectories(sessionStorageDir);
|
||||
return sessionStorageDir;
|
||||
}
|
||||
|
||||
public Path resolveSessionPath(Path sessionStorageDir, String filename) throws IOException {
|
||||
Path resolved = sessionStorageDir.resolve(filename).normalize();
|
||||
if (!resolved.startsWith(sessionStorageDir)) {
|
||||
throw new IOException("Invalid quote line-item storage path");
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
public String toStoredPath(Path absolutePath) {
|
||||
return QUOTE_STORAGE_ROOT.relativize(absolutePath).toString();
|
||||
}
|
||||
|
||||
public String getSafeExtension(String filename, String fallback) {
|
||||
if (filename == null) {
|
||||
return fallback;
|
||||
}
|
||||
String cleaned = StringUtils.cleanPath(filename);
|
||||
if (cleaned.contains("..")) {
|
||||
return fallback;
|
||||
}
|
||||
int index = cleaned.lastIndexOf('.');
|
||||
if (index <= 0 || index >= cleaned.length() - 1) {
|
||||
return fallback;
|
||||
}
|
||||
String ext = cleaned.substring(index + 1).toLowerCase(Locale.ROOT);
|
||||
return switch (ext) {
|
||||
case "stl" -> "stl";
|
||||
case "3mf" -> "3mf";
|
||||
case "step", "stp" -> "step";
|
||||
default -> fallback;
|
||||
};
|
||||
}
|
||||
|
||||
public 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;
|
||||
}
|
||||
}
|
||||
|
||||
public String extractConvertedStoredPath(QuoteLineItem item) {
|
||||
Map<String, Object> breakdown = item.getPricingBreakdown();
|
||||
if (breakdown == null) {
|
||||
return null;
|
||||
}
|
||||
Object converted = breakdown.get("convertedStoredPath");
|
||||
if (converted == null) {
|
||||
return null;
|
||||
}
|
||||
String path = String.valueOf(converted).trim();
|
||||
return path.isEmpty() ? null : path;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
package com.printcalculator.service.request;
|
||||
|
||||
import com.printcalculator.entity.CustomQuoteRequest;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
public class ContactRequestLocalizationService {
|
||||
|
||||
public 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";
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public 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;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
public 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;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
public Locale localeForLanguage(String language) {
|
||||
return switch (language) {
|
||||
case "en" -> Locale.ENGLISH;
|
||||
case "de" -> Locale.GERMAN;
|
||||
case "fr" -> Locale.FRENCH;
|
||||
default -> Locale.ITALIAN;
|
||||
};
|
||||
}
|
||||
|
||||
public 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";
|
||||
}
|
||||
|
||||
public 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";
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package com.printcalculator.service.request;
|
||||
|
||||
import com.printcalculator.entity.CustomQuoteRequest;
|
||||
import com.printcalculator.entity.CustomQuoteRequestAttachment;
|
||||
import com.printcalculator.repository.CustomQuoteRequestAttachmentRepository;
|
||||
import com.printcalculator.service.storage.ClamAVService;
|
||||
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.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.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Service
|
||||
@Transactional(readOnly = true)
|
||||
public class CustomQuoteRequestAttachmentService {
|
||||
|
||||
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"
|
||||
);
|
||||
|
||||
private final CustomQuoteRequestAttachmentRepository attachmentRepo;
|
||||
private final ClamAVService clamAVService;
|
||||
|
||||
public CustomQuoteRequestAttachmentService(CustomQuoteRequestAttachmentRepository attachmentRepo,
|
||||
ClamAVService clamAVService) {
|
||||
this.attachmentRepo = attachmentRepo;
|
||||
this.clamAVService = clamAVService;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public int storeAttachments(CustomQuoteRequest request, List<MultipartFile> files) throws IOException {
|
||||
if (files == null || files.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
if (files.size() > 15) {
|
||||
throw new IOException("Too many files. Max 15 allowed.");
|
||||
}
|
||||
|
||||
int attachmentsCount = 0;
|
||||
for (MultipartFile file : files) {
|
||||
if (file.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
if (isCompressedFile(file)) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Compressed files are not allowed.");
|
||||
}
|
||||
|
||||
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());
|
||||
attachment.setStoredFilename(UUID.randomUUID() + ".upload");
|
||||
attachment.setStoredRelativePath("PENDING");
|
||||
|
||||
attachment = attachmentRepo.save(attachment);
|
||||
|
||||
Path relativePath = Path.of(
|
||||
"quote-requests",
|
||||
request.getId().toString(),
|
||||
"attachments",
|
||||
attachment.getId().toString(),
|
||||
attachment.getStoredFilename()
|
||||
);
|
||||
attachment.setStoredRelativePath(relativePath.toString());
|
||||
attachmentRepo.save(attachment);
|
||||
|
||||
Path absolutePath = resolveWithinStorageRoot(relativePath);
|
||||
Files.createDirectories(absolutePath.getParent());
|
||||
try (InputStream inputStream = file.getInputStream()) {
|
||||
Files.copy(inputStream, absolutePath, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
attachmentsCount++;
|
||||
}
|
||||
|
||||
return attachmentsCount;
|
||||
}
|
||||
|
||||
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(Locale.ROOT));
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.printcalculator.service.request;
|
||||
|
||||
import com.printcalculator.dto.QuoteRequestDto;
|
||||
import com.printcalculator.entity.CustomQuoteRequest;
|
||||
import com.printcalculator.repository.CustomQuoteRequestRepository;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
@Transactional(readOnly = true)
|
||||
public class CustomQuoteRequestControllerService {
|
||||
|
||||
private final CustomQuoteRequestRepository requestRepo;
|
||||
private final CustomQuoteRequestAttachmentService attachmentService;
|
||||
private final CustomQuoteRequestNotificationService notificationService;
|
||||
|
||||
public CustomQuoteRequestControllerService(CustomQuoteRequestRepository requestRepo,
|
||||
CustomQuoteRequestAttachmentService attachmentService,
|
||||
CustomQuoteRequestNotificationService notificationService) {
|
||||
this.requestRepo = requestRepo;
|
||||
this.attachmentService = attachmentService;
|
||||
this.notificationService = notificationService;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public CustomQuoteRequest createCustomQuoteRequest(QuoteRequestDto requestDto, List<MultipartFile> files) throws IOException {
|
||||
validateConsents(requestDto);
|
||||
|
||||
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);
|
||||
|
||||
int attachmentsCount = attachmentService.storeAttachments(request, files);
|
||||
notificationService.sendNotifications(request, attachmentsCount, requestDto.getLanguage());
|
||||
|
||||
return request;
|
||||
}
|
||||
|
||||
public Optional<CustomQuoteRequest> getCustomQuoteRequest(UUID id) {
|
||||
return requestRepo.findById(id);
|
||||
}
|
||||
|
||||
private void validateConsents(QuoteRequestDto requestDto) {
|
||||
if (!requestDto.isAcceptTerms() || !requestDto.isAcceptPrivacy()) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Accettazione Termini e Privacy obbligatoria.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package com.printcalculator.service.request;
|
||||
|
||||
import com.printcalculator.entity.CustomQuoteRequest;
|
||||
import com.printcalculator.service.email.EmailNotificationService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Year;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.FormatStyle;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
public class CustomQuoteRequestNotificationService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(CustomQuoteRequestNotificationService.class);
|
||||
|
||||
private final EmailNotificationService emailNotificationService;
|
||||
private final ContactRequestLocalizationService localizationService;
|
||||
|
||||
@Value("${app.mail.contact-request.admin.enabled:true}")
|
||||
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;
|
||||
|
||||
public CustomQuoteRequestNotificationService(EmailNotificationService emailNotificationService,
|
||||
ContactRequestLocalizationService localizationService) {
|
||||
this.emailNotificationService = emailNotificationService;
|
||||
this.localizationService = localizationService;
|
||||
}
|
||||
|
||||
public void sendNotifications(CustomQuoteRequest request, int attachmentsCount, String rawLanguage) {
|
||||
String language = localizationService.normalizeLanguage(rawLanguage);
|
||||
sendAdminContactRequestNotification(request, attachmentsCount);
|
||||
sendCustomerContactRequestConfirmation(request, attachmentsCount, language);
|
||||
}
|
||||
|
||||
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(localizationService.localeForLanguage(language))
|
||||
)
|
||||
);
|
||||
templateData.put("recipientName", localizationService.resolveRecipientName(request, language));
|
||||
templateData.put("requestType", localizationService.localizeRequestType(request.getRequestType(), language));
|
||||
templateData.put("customerType", localizationService.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 = localizationService.applyCustomerContactRequestTexts(templateData, language, request.getId());
|
||||
|
||||
emailNotificationService.sendEmail(
|
||||
request.getEmail(),
|
||||
subject,
|
||||
"contact-request-customer",
|
||||
templateData
|
||||
);
|
||||
}
|
||||
|
||||
private String safeValue(String value) {
|
||||
if (value == null || value.isBlank()) {
|
||||
return "-";
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.printcalculator.service;
|
||||
package com.printcalculator.service.storage;
|
||||
|
||||
import com.printcalculator.exception.VirusDetectedException;
|
||||
import org.slf4j.Logger;
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.printcalculator.service;
|
||||
package com.printcalculator.service.storage;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.core.io.Resource;
|
||||
@@ -7,7 +7,6 @@ import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import com.printcalculator.exception.StorageException;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.printcalculator.service;
|
||||
package com.printcalculator.service.storage;
|
||||
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
@@ -3,6 +3,11 @@ app.mail.admin.enabled=false
|
||||
app.mail.contact-request.admin.enabled=false
|
||||
|
||||
# Admin back-office local test credentials
|
||||
admin.password=local-admin-password
|
||||
admin.password=ciaociao
|
||||
admin.session.secret=local-session-secret-for-dev-only-000000000000000000000000
|
||||
admin.session.ttl-minutes=480
|
||||
|
||||
# Local media storage served by a local static server on port 8081.
|
||||
media.storage.root=/Users/joe/IdeaProjects/print-calculator/storage_media
|
||||
media.public.base-url=http://localhost:8081
|
||||
media.ffmpeg.path=ffmpeg
|
||||
|
||||
@@ -26,8 +26,14 @@ clamav.host=${CLAMAV_HOST:clamav}
|
||||
clamav.port=${CLAMAV_PORT:3310}
|
||||
clamav.enabled=${CLAMAV_ENABLED:false}
|
||||
|
||||
# Media configuration
|
||||
media.storage.root=${MEDIA_STORAGE_ROOT:storage_media}
|
||||
media.public.base-url=${MEDIA_PUBLIC_BASE_URL:http://localhost:8080/media}
|
||||
media.ffmpeg.path=${MEDIA_FFMPEG_PATH:ffmpeg}
|
||||
media.upload.max-file-size-bytes=${MEDIA_UPLOAD_MAX_FILE_SIZE_BYTES:26214400}
|
||||
|
||||
# TWINT Configuration
|
||||
payment.twint.url=${TWINT_PAYMENT_URL:}
|
||||
payment.twint.url=${TWINT_PAYMENT_URL:https://go.twint.ch/1/e/tw?tw=acq.gERQQytOTnyIMuQHUqn4hlxgciHE5X7nnqHnNSPAr2OF2K3uBlXJDr2n9JU3sgxa.}
|
||||
|
||||
# Mail Configuration
|
||||
spring.mail.host=${MAIL_HOST:mail.infomaniak.com}
|
||||
@@ -43,7 +49,7 @@ app.mail.from=${APP_MAIL_FROM:${MAIL_USERNAME:noreply@printcalculator.local}}
|
||||
app.mail.admin.enabled=${APP_MAIL_ADMIN_ENABLED:true}
|
||||
app.mail.admin.address=${APP_MAIL_ADMIN_ADDRESS:admin@printcalculator.local}
|
||||
app.mail.contact-request.admin.enabled=${APP_MAIL_CONTACT_REQUEST_ADMIN_ENABLED:true}
|
||||
app.mail.contact-request.admin.address=${APP_MAIL_CONTACT_REQUEST_ADMIN_ADDRESS:infog@3d-fab.ch}
|
||||
app.mail.contact-request.admin.address=${APP_MAIL_CONTACT_REQUEST_ADMIN_ADDRESS:info@3d-fab.ch}
|
||||
app.mail.contact-request.customer.enabled=${APP_MAIL_CONTACT_REQUEST_CUSTOMER_ENABLED:true}
|
||||
app.frontend.base-url=${APP_FRONTEND_BASE_URL:http://localhost:4200}
|
||||
|
||||
|
||||
110
backend/src/main/resources/templates/email/order-shipped.html
Normal file
110
backend/src/main/resources/templates/email/order-shipped.html
Normal file
@@ -0,0 +1,110 @@
|
||||
<!DOCTYPE html>
|
||||
<html xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title th:text="${emailTitle}">Order Shipped</title>
|
||||
<style>
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
background-color: #f4f4f4;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.container {
|
||||
max-width: 600px;
|
||||
margin: 20px auto;
|
||||
background-color: #ffffff;
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.header {
|
||||
text-align: center;
|
||||
border-bottom: 1px solid #eeeeee;
|
||||
padding-bottom: 20px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.header h1 {
|
||||
color: #333333;
|
||||
}
|
||||
|
||||
.content {
|
||||
color: #555555;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.status-box {
|
||||
background-color: #e9f3ff;
|
||||
border: 1px solid #a9c8ef;
|
||||
border-radius: 5px;
|
||||
padding: 12px;
|
||||
margin-top: 18px;
|
||||
}
|
||||
|
||||
.order-box {
|
||||
background-color: #f9f9f9;
|
||||
border-radius: 5px;
|
||||
padding: 12px;
|
||||
margin-top: 18px;
|
||||
}
|
||||
|
||||
.order-box th {
|
||||
text-align: left;
|
||||
padding-right: 18px;
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
.footer {
|
||||
text-align: center;
|
||||
font-size: 0.9em;
|
||||
color: #999999;
|
||||
margin-top: 30px;
|
||||
border-top: 1px solid #eeeeee;
|
||||
padding-top: 20px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1 th:text="${headlineText}">Your order #00000000 has been shipped</h1>
|
||||
</div>
|
||||
|
||||
<div class="content">
|
||||
<p th:text="${greetingText}">Hi Customer,</p>
|
||||
<p th:text="${introText}">Good news: your package is on its way.</p>
|
||||
|
||||
<div class="status-box">
|
||||
<strong th:text="${statusText}">Current status: Shipped.</strong>
|
||||
</div>
|
||||
|
||||
<div class="order-box">
|
||||
<table>
|
||||
<tr>
|
||||
<th th:text="${labelOrderNumber}">Order number</th>
|
||||
<td th:text="${orderNumber}">00000000</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th th:text="${labelTotal}">Total</th>
|
||||
<td th:text="${totalCost}">CHF 0.00</td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<p>
|
||||
<span th:text="${orderDetailsCtaText}">View order status</span>:
|
||||
<a th:href="${orderDetailsUrl}" th:text="${orderDetailsUrl}">https://example.com/en/co/00000000-0000-0000-0000-000000000000</a>
|
||||
</p>
|
||||
<p th:text="${supportText}">If you need assistance, reply to this email.</p>
|
||||
</div>
|
||||
|
||||
<div class="footer">
|
||||
<p>© <span th:text="${currentYear}">2026</span> 3D-Fab</p>
|
||||
<p th:text="${footerText}">Automated message.</p>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,130 @@
|
||||
package com.printcalculator.controller;
|
||||
|
||||
import com.printcalculator.dto.OrderDto;
|
||||
import com.printcalculator.entity.Order;
|
||||
import com.printcalculator.repository.OrderItemRepository;
|
||||
import com.printcalculator.repository.OrderRepository;
|
||||
import com.printcalculator.repository.PaymentRepository;
|
||||
import com.printcalculator.service.payment.InvoicePdfRenderingService;
|
||||
import com.printcalculator.service.OrderService;
|
||||
import com.printcalculator.service.order.OrderControllerService;
|
||||
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.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class OrderControllerPrivacyTest {
|
||||
|
||||
@Mock
|
||||
private OrderService orderService;
|
||||
@Mock
|
||||
private OrderRepository orderRepo;
|
||||
@Mock
|
||||
private OrderItemRepository orderItemRepo;
|
||||
@Mock
|
||||
private StorageService storageService;
|
||||
@Mock
|
||||
private InvoicePdfRenderingService invoiceService;
|
||||
@Mock
|
||||
private QrBillService qrBillService;
|
||||
@Mock
|
||||
private TwintPaymentService twintPaymentService;
|
||||
@Mock
|
||||
private PaymentService paymentService;
|
||||
@Mock
|
||||
private PaymentRepository paymentRepo;
|
||||
|
||||
private OrderController controller;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
OrderControllerService orderControllerService = new OrderControllerService(
|
||||
orderService,
|
||||
orderRepo,
|
||||
orderItemRepo,
|
||||
storageService,
|
||||
invoiceService,
|
||||
qrBillService,
|
||||
twintPaymentService,
|
||||
paymentService,
|
||||
paymentRepo
|
||||
);
|
||||
controller = new OrderController(orderControllerService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getOrder_pendingPayment_keepsPersonalData() {
|
||||
UUID orderId = UUID.randomUUID();
|
||||
Order order = buildOrder(orderId, "PENDING_PAYMENT");
|
||||
|
||||
when(orderRepo.findById(orderId)).thenReturn(Optional.of(order));
|
||||
when(orderItemRepo.findByOrder_Id(orderId)).thenReturn(List.of());
|
||||
when(paymentRepo.findByOrder_Id(orderId)).thenReturn(Optional.empty());
|
||||
|
||||
ResponseEntity<OrderDto> response = controller.getOrder(orderId);
|
||||
|
||||
assertEquals(HttpStatus.OK, response.getStatusCode());
|
||||
assertNotNull(response.getBody());
|
||||
assertEquals("customer@example.com", response.getBody().getCustomerEmail());
|
||||
assertEquals("+41790000000", response.getBody().getCustomerPhone());
|
||||
assertNotNull(response.getBody().getBillingAddress());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getOrder_advancedStatuses_redactsPersonalData() {
|
||||
List<String> statuses = List.of("IN_PRODUCTION", "SHIPPED", "COMPLETED");
|
||||
|
||||
for (String status : statuses) {
|
||||
UUID orderId = UUID.randomUUID();
|
||||
Order order = buildOrder(orderId, status);
|
||||
|
||||
when(orderRepo.findById(orderId)).thenReturn(Optional.of(order));
|
||||
when(orderItemRepo.findByOrder_Id(orderId)).thenReturn(List.of());
|
||||
when(paymentRepo.findByOrder_Id(orderId)).thenReturn(Optional.empty());
|
||||
|
||||
ResponseEntity<OrderDto> response = controller.getOrder(orderId);
|
||||
|
||||
assertEquals(HttpStatus.OK, response.getStatusCode());
|
||||
assertNotNull(response.getBody());
|
||||
assertNull(response.getBody().getCustomerEmail());
|
||||
assertNull(response.getBody().getCustomerPhone());
|
||||
assertNull(response.getBody().getBillingCustomerType());
|
||||
assertNull(response.getBody().getBillingAddress());
|
||||
assertNull(response.getBody().getShippingAddress());
|
||||
}
|
||||
}
|
||||
|
||||
private Order buildOrder(UUID orderId, String status) {
|
||||
Order order = new Order();
|
||||
order.setId(orderId);
|
||||
order.setStatus(status);
|
||||
order.setCustomerEmail("customer@example.com");
|
||||
order.setCustomerPhone("+41790000000");
|
||||
order.setBillingCustomerType("PRIVATE");
|
||||
order.setBillingFirstName("Joe");
|
||||
order.setBillingLastName("Kung");
|
||||
order.setBillingAddressLine1("Via G. Pioda 1");
|
||||
order.setBillingZip("6900");
|
||||
order.setBillingCity("Lugano");
|
||||
order.setBillingCountryCode("CH");
|
||||
order.setShippingSameAsBilling(true);
|
||||
return order;
|
||||
}
|
||||
}
|
||||
@@ -6,15 +6,18 @@ import com.printcalculator.entity.Order;
|
||||
import com.printcalculator.repository.OrderItemRepository;
|
||||
import com.printcalculator.repository.OrderRepository;
|
||||
import com.printcalculator.repository.PaymentRepository;
|
||||
import com.printcalculator.service.InvoicePdfRenderingService;
|
||||
import com.printcalculator.service.PaymentService;
|
||||
import com.printcalculator.service.QrBillService;
|
||||
import com.printcalculator.service.StorageService;
|
||||
import com.printcalculator.repository.QuoteLineItemRepository;
|
||||
import com.printcalculator.service.order.AdminOrderControllerService;
|
||||
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.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
@@ -40,6 +43,8 @@ class AdminOrderControllerStatusValidationTest {
|
||||
@Mock
|
||||
private PaymentRepository paymentRepository;
|
||||
@Mock
|
||||
private QuoteLineItemRepository quoteLineItemRepository;
|
||||
@Mock
|
||||
private PaymentService paymentService;
|
||||
@Mock
|
||||
private StorageService storageService;
|
||||
@@ -47,20 +52,25 @@ class AdminOrderControllerStatusValidationTest {
|
||||
private InvoicePdfRenderingService invoicePdfRenderingService;
|
||||
@Mock
|
||||
private QrBillService qrBillService;
|
||||
@Mock
|
||||
private ApplicationEventPublisher eventPublisher;
|
||||
|
||||
private AdminOrderController controller;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
controller = new AdminOrderController(
|
||||
AdminOrderControllerService adminOrderControllerService = new AdminOrderControllerService(
|
||||
orderRepository,
|
||||
orderItemRepository,
|
||||
paymentRepository,
|
||||
quoteLineItemRepository,
|
||||
paymentService,
|
||||
storageService,
|
||||
invoicePdfRenderingService,
|
||||
qrBillService
|
||||
qrBillService,
|
||||
eventPublisher
|
||||
);
|
||||
controller = new AdminOrderController(adminOrderControllerService);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -92,6 +102,7 @@ class AdminOrderControllerStatusValidationTest {
|
||||
order.setStatus("PENDING_PAYMENT");
|
||||
|
||||
when(orderRepository.findById(orderId)).thenReturn(Optional.of(order));
|
||||
when(orderRepository.save(any(Order.class))).thenAnswer(invocation -> invocation.getArgument(0));
|
||||
when(orderItemRepository.findByOrder_Id(orderId)).thenReturn(List.of());
|
||||
when(paymentRepository.findByOrder_Id(orderId)).thenReturn(Optional.empty());
|
||||
|
||||
|
||||
@@ -4,9 +4,9 @@ import com.printcalculator.entity.Customer;
|
||||
import com.printcalculator.entity.Order;
|
||||
import com.printcalculator.event.OrderCreatedEvent;
|
||||
import com.printcalculator.repository.OrderItemRepository;
|
||||
import com.printcalculator.service.InvoicePdfRenderingService;
|
||||
import com.printcalculator.service.QrBillService;
|
||||
import com.printcalculator.service.StorageService;
|
||||
import com.printcalculator.service.payment.InvoicePdfRenderingService;
|
||||
import com.printcalculator.service.payment.QrBillService;
|
||||
import com.printcalculator.service.storage.StorageService;
|
||||
import com.printcalculator.service.email.EmailNotificationService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -3,6 +3,8 @@ package com.printcalculator.service;
|
||||
import com.printcalculator.entity.PricingPolicy;
|
||||
import com.printcalculator.entity.QuoteLineItem;
|
||||
import com.printcalculator.entity.QuoteSession;
|
||||
import com.printcalculator.entity.NozzleOption;
|
||||
import com.printcalculator.repository.NozzleOptionRepository;
|
||||
import com.printcalculator.repository.PricingPolicyRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -20,13 +22,15 @@ import static org.mockito.Mockito.when;
|
||||
class QuoteSessionTotalsServiceTest {
|
||||
private PricingPolicyRepository pricingRepo;
|
||||
private QuoteCalculator quoteCalculator;
|
||||
private NozzleOptionRepository nozzleOptionRepo;
|
||||
private QuoteSessionTotalsService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
pricingRepo = mock(PricingPolicyRepository.class);
|
||||
quoteCalculator = mock(QuoteCalculator.class);
|
||||
service = new QuoteSessionTotalsService(pricingRepo, quoteCalculator);
|
||||
nozzleOptionRepo = mock(NozzleOptionRepository.class);
|
||||
service = new QuoteSessionTotalsService(pricingRepo, quoteCalculator, nozzleOptionRepo);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -77,6 +81,51 @@ class QuoteSessionTotalsServiceTest {
|
||||
assertAmountEquals("120.00", totals.grandTotalChf());
|
||||
}
|
||||
|
||||
@Test
|
||||
void compute_WithRepeatedNozzleAcrossItems_ShouldChargeNozzleFeeOnlyOncePerType() {
|
||||
QuoteSession session = new QuoteSession();
|
||||
session.setSetupCostChf(new BigDecimal("2.00"));
|
||||
|
||||
QuoteLineItem itemA = createItem(new BigDecimal("10.00"), 3, 3600, "0.60");
|
||||
QuoteLineItem itemB = createItem(new BigDecimal("4.00"), 2, 1200, "0.60");
|
||||
QuoteLineItem itemC = createItem(new BigDecimal("5.00"), 1, 600, "0.80");
|
||||
|
||||
PricingPolicy policy = new PricingPolicy();
|
||||
when(pricingRepo.findFirstByIsActiveTrueOrderByValidFromDesc()).thenReturn(policy);
|
||||
when(quoteCalculator.calculateSessionMachineCost(eq(policy), any(BigDecimal.class))).thenReturn(BigDecimal.ZERO);
|
||||
when(nozzleOptionRepo.findFirstByNozzleDiameterMmAndIsActiveTrue(new BigDecimal("0.60")))
|
||||
.thenReturn(java.util.Optional.of(nozzleOption("0.60", "1.50")));
|
||||
when(nozzleOptionRepo.findFirstByNozzleDiameterMmAndIsActiveTrue(new BigDecimal("0.80")))
|
||||
.thenReturn(java.util.Optional.of(nozzleOption("0.80", "1.50")));
|
||||
|
||||
QuoteSessionTotalsService.QuoteSessionTotals totals = service.compute(session, List.of(itemA, itemB, itemC));
|
||||
|
||||
assertAmountEquals("43.00", totals.itemsTotalChf());
|
||||
assertAmountEquals("3.00", totals.nozzleChangeCostChf());
|
||||
assertAmountEquals("5.00", totals.setupCostChf());
|
||||
assertAmountEquals("50.00", totals.grandTotalChf());
|
||||
}
|
||||
|
||||
private QuoteLineItem createItem(BigDecimal unitPrice, int quantity, int printSeconds, String nozzleMm) {
|
||||
QuoteLineItem item = new QuoteLineItem();
|
||||
item.setQuantity(quantity);
|
||||
item.setUnitPriceChf(unitPrice);
|
||||
item.setPrintTimeSeconds(printSeconds);
|
||||
item.setNozzleDiameterMm(new BigDecimal(nozzleMm));
|
||||
item.setBoundingBoxXMm(new BigDecimal("10"));
|
||||
item.setBoundingBoxYMm(new BigDecimal("10"));
|
||||
item.setBoundingBoxZMm(new BigDecimal("10"));
|
||||
return item;
|
||||
}
|
||||
|
||||
private NozzleOption nozzleOption(String diameterMm, String feeChf) {
|
||||
NozzleOption option = new NozzleOption();
|
||||
option.setNozzleDiameterMm(new BigDecimal(diameterMm));
|
||||
option.setExtraNozzleChangeFeeChf(new BigDecimal(feeChf));
|
||||
option.setIsActive(true);
|
||||
return option;
|
||||
}
|
||||
|
||||
private void assertAmountEquals(String expected, BigDecimal actual) {
|
||||
assertTrue(new BigDecimal(expected).compareTo(actual) == 0,
|
||||
"Expected " + expected + " but got " + actual);
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
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.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AdminFilamentControllerServiceTest {
|
||||
|
||||
@Mock
|
||||
private FilamentMaterialTypeRepository materialRepo;
|
||||
@Mock
|
||||
private FilamentVariantRepository variantRepo;
|
||||
@Mock
|
||||
private QuoteLineItemRepository quoteLineItemRepo;
|
||||
@Mock
|
||||
private OrderItemRepository orderItemRepo;
|
||||
|
||||
@InjectMocks
|
||||
private AdminFilamentControllerService service;
|
||||
|
||||
@Test
|
||||
void createMaterial_withDuplicateCode_shouldReturnBadRequest() {
|
||||
AdminUpsertFilamentMaterialTypeRequest payload = new AdminUpsertFilamentMaterialTypeRequest();
|
||||
payload.setMaterialCode("pla");
|
||||
|
||||
FilamentMaterialType existing = new FilamentMaterialType();
|
||||
existing.setId(1L);
|
||||
existing.setMaterialCode("PLA");
|
||||
when(materialRepo.findByMaterialCode("PLA")).thenReturn(Optional.of(existing));
|
||||
|
||||
ResponseStatusException ex = assertThrows(
|
||||
ResponseStatusException.class,
|
||||
() -> service.createMaterial(payload)
|
||||
);
|
||||
|
||||
assertEquals(HttpStatus.BAD_REQUEST, ex.getStatusCode());
|
||||
verify(materialRepo, never()).save(any(FilamentMaterialType.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createVariant_withInvalidColorHex_shouldReturnBadRequest() {
|
||||
FilamentMaterialType material = new FilamentMaterialType();
|
||||
material.setId(10L);
|
||||
material.setMaterialCode("PLA");
|
||||
when(materialRepo.findById(10L)).thenReturn(Optional.of(material));
|
||||
when(variantRepo.findByFilamentMaterialTypeAndVariantDisplayName(material, "Sunset Orange"))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
AdminUpsertFilamentVariantRequest payload = baseVariantPayload();
|
||||
payload.setColorHex("#12");
|
||||
|
||||
ResponseStatusException ex = assertThrows(
|
||||
ResponseStatusException.class,
|
||||
() -> service.createVariant(payload)
|
||||
);
|
||||
|
||||
assertEquals(HttpStatus.BAD_REQUEST, ex.getStatusCode());
|
||||
verify(variantRepo, never()).save(any(FilamentVariant.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createVariant_withValidPayload_shouldNormalizeDerivedFields() {
|
||||
FilamentMaterialType material = new FilamentMaterialType();
|
||||
material.setId(10L);
|
||||
material.setMaterialCode("PLA");
|
||||
when(materialRepo.findById(10L)).thenReturn(Optional.of(material));
|
||||
when(variantRepo.findByFilamentMaterialTypeAndVariantDisplayName(material, "Sunset Orange"))
|
||||
.thenReturn(Optional.empty());
|
||||
when(variantRepo.save(any(FilamentVariant.class))).thenAnswer(invocation -> {
|
||||
FilamentVariant variant = invocation.getArgument(0);
|
||||
variant.setId(42L);
|
||||
return variant;
|
||||
});
|
||||
|
||||
AdminUpsertFilamentVariantRequest payload = baseVariantPayload();
|
||||
payload.setFinishType("matte");
|
||||
payload.setIsMatte(false);
|
||||
payload.setBrand(" Prusa ");
|
||||
payload.setIsActive(null);
|
||||
|
||||
AdminFilamentVariantDto dto = service.createVariant(payload);
|
||||
|
||||
ArgumentCaptor<FilamentVariant> captor = ArgumentCaptor.forClass(FilamentVariant.class);
|
||||
verify(variantRepo).save(captor.capture());
|
||||
FilamentVariant saved = captor.getValue();
|
||||
|
||||
assertEquals(42L, dto.getId());
|
||||
assertEquals("MATTE", saved.getFinishType());
|
||||
assertTrue(saved.getIsMatte());
|
||||
assertEquals("Prusa", saved.getBrand());
|
||||
assertTrue(saved.getIsActive());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteVariant_whenInUse_shouldReturnConflict() {
|
||||
Long variantId = 11L;
|
||||
FilamentVariant variant = new FilamentVariant();
|
||||
variant.setId(variantId);
|
||||
|
||||
when(variantRepo.findById(variantId)).thenReturn(Optional.of(variant));
|
||||
when(quoteLineItemRepo.existsByFilamentVariant_Id(variantId)).thenReturn(true);
|
||||
|
||||
ResponseStatusException ex = assertThrows(
|
||||
ResponseStatusException.class,
|
||||
() -> service.deleteVariant(variantId)
|
||||
);
|
||||
|
||||
assertEquals(HttpStatus.CONFLICT, ex.getStatusCode());
|
||||
verify(variantRepo, never()).delete(any(FilamentVariant.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getMaterials_shouldReturnAlphabeticalByCode() {
|
||||
FilamentMaterialType abs = new FilamentMaterialType();
|
||||
abs.setId(2L);
|
||||
abs.setMaterialCode("ABS");
|
||||
|
||||
FilamentMaterialType pla = new FilamentMaterialType();
|
||||
pla.setId(1L);
|
||||
pla.setMaterialCode("PLA");
|
||||
|
||||
when(materialRepo.findAll()).thenReturn(List.of(pla, abs));
|
||||
|
||||
List<AdminFilamentMaterialTypeDto> result = service.getMaterials();
|
||||
|
||||
assertEquals(2, result.size());
|
||||
assertEquals("ABS", result.get(0).getMaterialCode());
|
||||
assertEquals("PLA", result.get(1).getMaterialCode());
|
||||
}
|
||||
|
||||
private AdminUpsertFilamentVariantRequest baseVariantPayload() {
|
||||
AdminUpsertFilamentVariantRequest payload = new AdminUpsertFilamentVariantRequest();
|
||||
payload.setMaterialTypeId(10L);
|
||||
payload.setVariantDisplayName("Sunset Orange");
|
||||
payload.setColorName("Orange");
|
||||
payload.setColorHex("#FF8800");
|
||||
payload.setFinishType("GLOSSY");
|
||||
payload.setIsMatte(false);
|
||||
payload.setIsSpecial(false);
|
||||
payload.setCostChfPerKg(new BigDecimal("29.90"));
|
||||
payload.setStockSpools(new BigDecimal("2.000"));
|
||||
payload.setSpoolNetKg(new BigDecimal("1.000"));
|
||||
payload.setIsActive(true);
|
||||
return payload;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,496 @@
|
||||
package com.printcalculator.service.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.MediaTextTranslationDto;
|
||||
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.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyCollection;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.nullable;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class AdminMediaControllerServiceTest {
|
||||
|
||||
@Mock
|
||||
private MediaAssetRepository mediaAssetRepository;
|
||||
@Mock
|
||||
private MediaVariantRepository mediaVariantRepository;
|
||||
@Mock
|
||||
private MediaUsageRepository mediaUsageRepository;
|
||||
@Mock
|
||||
private MediaImageInspector mediaImageInspector;
|
||||
@Mock
|
||||
private MediaFfmpegService mediaFfmpegService;
|
||||
@Mock
|
||||
private ClamAVService clamAVService;
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
private AdminMediaControllerService service;
|
||||
private Path storageRoot;
|
||||
|
||||
private final Map<UUID, MediaAsset> assets = new LinkedHashMap<>();
|
||||
private final Map<UUID, MediaVariant> variants = new LinkedHashMap<>();
|
||||
private final Map<UUID, MediaUsage> usages = new LinkedHashMap<>();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
storageRoot = tempDir.resolve("storage_media");
|
||||
MediaStorageService mediaStorageService = new MediaStorageService(
|
||||
storageRoot.toString(),
|
||||
"https://cdn.example/media"
|
||||
);
|
||||
|
||||
service = new AdminMediaControllerService(
|
||||
mediaAssetRepository,
|
||||
mediaVariantRepository,
|
||||
mediaUsageRepository,
|
||||
mediaStorageService,
|
||||
mediaImageInspector,
|
||||
mediaFfmpegService,
|
||||
clamAVService,
|
||||
1024 * 1024
|
||||
);
|
||||
|
||||
when(clamAVService.scan(any())).thenReturn(true);
|
||||
when(mediaFfmpegService.canEncode(anyString())).thenReturn(true);
|
||||
|
||||
when(mediaAssetRepository.save(any(MediaAsset.class))).thenAnswer(invocation -> {
|
||||
MediaAsset asset = invocation.getArgument(0);
|
||||
if (asset.getId() == null) {
|
||||
asset.setId(UUID.randomUUID());
|
||||
}
|
||||
assets.put(asset.getId(), asset);
|
||||
return asset;
|
||||
});
|
||||
when(mediaAssetRepository.findById(any(UUID.class))).thenAnswer(invocation ->
|
||||
Optional.ofNullable(assets.get(invocation.getArgument(0)))
|
||||
);
|
||||
when(mediaAssetRepository.findAllByOrderByCreatedAtDesc()).thenAnswer(invocation -> assets.values().stream()
|
||||
.sorted(Comparator.comparing(MediaAsset::getCreatedAt, Comparator.nullsLast(OffsetDateTime::compareTo)).reversed())
|
||||
.toList());
|
||||
|
||||
when(mediaVariantRepository.save(any(MediaVariant.class))).thenAnswer(invocation -> persistVariant(invocation.getArgument(0)));
|
||||
when(mediaVariantRepository.saveAll(any())).thenAnswer(invocation -> {
|
||||
Iterable<MediaVariant> iterable = invocation.getArgument(0);
|
||||
List<MediaVariant> saved = new ArrayList<>();
|
||||
for (MediaVariant variant : iterable) {
|
||||
saved.add(persistVariant(variant));
|
||||
}
|
||||
return saved;
|
||||
});
|
||||
when(mediaVariantRepository.findByMediaAsset_IdIn(anyCollection())).thenAnswer(invocation ->
|
||||
variantsForAssets(invocation.getArgument(0))
|
||||
);
|
||||
when(mediaVariantRepository.findByMediaAsset_IdOrderByCreatedAtAsc(any(UUID.class))).thenAnswer(invocation ->
|
||||
variants.values().stream()
|
||||
.filter(variant -> variant.getMediaAsset().getId().equals(invocation.getArgument(0)))
|
||||
.sorted(Comparator.comparing(MediaVariant::getCreatedAt, Comparator.nullsLast(OffsetDateTime::compareTo)))
|
||||
.toList()
|
||||
);
|
||||
|
||||
when(mediaUsageRepository.save(any(MediaUsage.class))).thenAnswer(invocation -> persistUsage(invocation.getArgument(0)));
|
||||
when(mediaUsageRepository.saveAll(any())).thenAnswer(invocation -> {
|
||||
Iterable<MediaUsage> iterable = invocation.getArgument(0);
|
||||
List<MediaUsage> saved = new ArrayList<>();
|
||||
for (MediaUsage usage : iterable) {
|
||||
saved.add(persistUsage(usage));
|
||||
}
|
||||
return saved;
|
||||
});
|
||||
when(mediaUsageRepository.findByMediaAsset_IdIn(anyCollection())).thenAnswer(invocation ->
|
||||
usagesForAssets(invocation.getArgument(0))
|
||||
);
|
||||
when(mediaUsageRepository.findByUsageScope(anyString(), anyString(), nullable(UUID.class))).thenAnswer(invocation ->
|
||||
usages.values().stream()
|
||||
.filter(usage -> usage.getUsageType().equals(invocation.getArgument(0)))
|
||||
.filter(usage -> usage.getUsageKey().equals(invocation.getArgument(1)))
|
||||
.filter(usage -> {
|
||||
UUID ownerId = invocation.getArgument(2);
|
||||
return ownerId == null ? usage.getOwnerId() == null : ownerId.equals(usage.getOwnerId());
|
||||
})
|
||||
.sorted(Comparator.comparing(MediaUsage::getSortOrder).thenComparing(MediaUsage::getCreatedAt))
|
||||
.toList()
|
||||
);
|
||||
when(mediaUsageRepository.findById(any(UUID.class))).thenAnswer(invocation ->
|
||||
Optional.ofNullable(usages.get(invocation.getArgument(0)))
|
||||
);
|
||||
|
||||
doAnswer(invocation -> {
|
||||
Path outputFile = invocation.getArgument(1);
|
||||
String format = invocation.getArgument(4);
|
||||
Files.createDirectories(outputFile.getParent());
|
||||
Files.writeString(outputFile, "generated-" + format, StandardCharsets.UTF_8);
|
||||
return null;
|
||||
}).when(mediaFfmpegService).generateVariant(any(Path.class), any(Path.class), anyInt(), anyInt(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadAsset_withValidImage_shouldPersistMetadataAndExposePublicUrls() throws Exception {
|
||||
when(mediaImageInspector.inspect(any(Path.class))).thenReturn(
|
||||
new MediaImageInspector.ImageMetadata("image/png", "png", 1600, 900)
|
||||
);
|
||||
|
||||
MockMultipartFile file = new MockMultipartFile(
|
||||
"file",
|
||||
"landing-hero.png",
|
||||
"image/png",
|
||||
"png-image-content".getBytes(StandardCharsets.UTF_8)
|
||||
);
|
||||
|
||||
AdminMediaAssetDto dto = service.uploadAsset(file, " Landing hero ", " Main headline ", null);
|
||||
|
||||
assertEquals("READY", dto.getStatus());
|
||||
assertEquals("PUBLIC", dto.getVisibility());
|
||||
assertEquals("landing-hero.png", dto.getOriginalFilename());
|
||||
assertEquals("Landing hero", dto.getTitle());
|
||||
assertEquals("Main headline", dto.getAltText());
|
||||
assertEquals("image/png", dto.getMimeType());
|
||||
assertEquals(1600, dto.getWidthPx());
|
||||
assertEquals(900, dto.getHeightPx());
|
||||
assertEquals(file.getSize(), dto.getFileSizeBytes());
|
||||
assertEquals(64, dto.getSha256Hex().length());
|
||||
assertEquals(10, dto.getVariants().size());
|
||||
|
||||
long publicVariants = dto.getVariants().stream()
|
||||
.filter(variant -> !"ORIGINAL".equals(variant.getFormat()))
|
||||
.count();
|
||||
assertEquals(9, publicVariants);
|
||||
assertTrue(dto.getVariants().stream()
|
||||
.filter(variant -> "WEBP".equals(variant.getFormat()) && "hero".equals(variant.getVariantName()))
|
||||
.allMatch(variant -> variant.getPublicUrl().startsWith("https://cdn.example/media/")));
|
||||
assertTrue(dto.getVariants().stream()
|
||||
.filter(variant -> "ORIGINAL".equals(variant.getFormat()))
|
||||
.allMatch(variant -> variant.getPublicUrl() == null));
|
||||
|
||||
MediaVariant heroWebp = variants.values().stream()
|
||||
.filter(variant -> "hero".equals(variant.getVariantName()))
|
||||
.filter(variant -> "WEBP".equals(variant.getFormat()))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
assertTrue(Files.exists(storageRoot.resolve("public").resolve(heroWebp.getStorageKey())));
|
||||
|
||||
MediaVariant originalVariant = variants.values().stream()
|
||||
.filter(variant -> "ORIGINAL".equals(variant.getFormat()))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
assertTrue(Files.exists(storageRoot.resolve("original").resolve(originalVariant.getStorageKey())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadAsset_withUnsupportedImageType_shouldReturnBadRequest() throws Exception {
|
||||
when(mediaImageInspector.inspect(any(Path.class))).thenReturn(
|
||||
new MediaImageInspector.ImageMetadata("image/svg+xml", "svg", 400, 400)
|
||||
);
|
||||
|
||||
MockMultipartFile file = new MockMultipartFile(
|
||||
"file",
|
||||
"logo.svg",
|
||||
"image/svg+xml",
|
||||
"<svg/>".getBytes(StandardCharsets.UTF_8)
|
||||
);
|
||||
|
||||
ResponseStatusException ex = assertThrows(
|
||||
ResponseStatusException.class,
|
||||
() -> service.uploadAsset(file, null, null, null)
|
||||
);
|
||||
|
||||
assertEquals(HttpStatus.BAD_REQUEST, ex.getStatusCode());
|
||||
assertTrue(assets.isEmpty());
|
||||
assertTrue(variants.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadAsset_withLimitedEncoders_shouldKeepAssetReadyAndExposeOnlySupportedVariants() throws Exception {
|
||||
when(mediaImageInspector.inspect(any(Path.class))).thenReturn(
|
||||
new MediaImageInspector.ImageMetadata("image/jpeg", "jpg", 1200, 800)
|
||||
);
|
||||
when(mediaFfmpegService.canEncode("JPEG")).thenReturn(true);
|
||||
when(mediaFfmpegService.canEncode("WEBP")).thenReturn(false);
|
||||
when(mediaFfmpegService.canEncode("AVIF")).thenReturn(false);
|
||||
|
||||
MockMultipartFile file = new MockMultipartFile(
|
||||
"file",
|
||||
"capability.jpg",
|
||||
"image/jpeg",
|
||||
"jpeg-image-content".getBytes(StandardCharsets.UTF_8)
|
||||
);
|
||||
|
||||
AdminMediaAssetDto dto = service.uploadAsset(file, "Capability", null, "PUBLIC");
|
||||
|
||||
assertEquals("READY", dto.getStatus());
|
||||
assertEquals(4, dto.getVariants().size());
|
||||
assertEquals(3, dto.getVariants().stream()
|
||||
.filter(variant -> "JPEG".equals(variant.getFormat()))
|
||||
.count());
|
||||
assertTrue(dto.getVariants().stream()
|
||||
.noneMatch(variant -> "WEBP".equals(variant.getFormat()) || "AVIF".equals(variant.getFormat())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadAsset_whenAvifGenerationFails_shouldKeepAssetReadyAndStoreOtherVariants() throws Exception {
|
||||
when(mediaImageInspector.inspect(any(Path.class))).thenReturn(
|
||||
new MediaImageInspector.ImageMetadata("image/png", "png", 1600, 900)
|
||||
);
|
||||
doThrow(new java.io.IOException("FFmpeg failed to generate media variant. Unrecognized option 'still-picture'."))
|
||||
.when(mediaFfmpegService)
|
||||
.generateVariant(any(Path.class), any(Path.class), anyInt(), anyInt(), org.mockito.ArgumentMatchers.eq("AVIF"));
|
||||
|
||||
MockMultipartFile file = new MockMultipartFile(
|
||||
"file",
|
||||
"landing-hero.png",
|
||||
"image/png",
|
||||
"png-image-content".getBytes(StandardCharsets.UTF_8)
|
||||
);
|
||||
|
||||
AdminMediaAssetDto dto = service.uploadAsset(file, " Landing hero ", " Main headline ", null);
|
||||
|
||||
assertEquals("READY", dto.getStatus());
|
||||
assertEquals(7, dto.getVariants().size());
|
||||
assertTrue(dto.getVariants().stream().noneMatch(variant -> "AVIF".equals(variant.getFormat())));
|
||||
assertEquals(3, dto.getVariants().stream().filter(variant -> "JPEG".equals(variant.getFormat())).count());
|
||||
assertEquals(3, dto.getVariants().stream().filter(variant -> "WEBP".equals(variant.getFormat())).count());
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadAsset_withOversizedFile_shouldFailValidationBeforePersistence() {
|
||||
service = new AdminMediaControllerService(
|
||||
mediaAssetRepository,
|
||||
mediaVariantRepository,
|
||||
mediaUsageRepository,
|
||||
new MediaStorageService(storageRoot.toString(), "https://cdn.example/media"),
|
||||
mediaImageInspector,
|
||||
mediaFfmpegService,
|
||||
clamAVService,
|
||||
4
|
||||
);
|
||||
|
||||
MockMultipartFile file = new MockMultipartFile(
|
||||
"file",
|
||||
"big.png",
|
||||
"image/png",
|
||||
"12345".getBytes(StandardCharsets.UTF_8)
|
||||
);
|
||||
|
||||
ResponseStatusException ex = assertThrows(
|
||||
ResponseStatusException.class,
|
||||
() -> service.uploadAsset(file, null, null, null)
|
||||
);
|
||||
|
||||
assertEquals(HttpStatus.BAD_REQUEST, ex.getStatusCode());
|
||||
verifyNoInteractions(mediaAssetRepository, mediaVariantRepository, mediaUsageRepository, mediaImageInspector, mediaFfmpegService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createUsage_withPrimaryFlag_shouldUnsetExistingPrimaryAndMapUsageOnAsset() {
|
||||
MediaAsset asset = persistAsset(seedAsset("PUBLIC"));
|
||||
|
||||
MediaUsage existingPrimary = new MediaUsage();
|
||||
existingPrimary.setId(UUID.randomUUID());
|
||||
existingPrimary.setUsageType("HOME");
|
||||
existingPrimary.setUsageKey("landing");
|
||||
existingPrimary.setOwnerId(null);
|
||||
existingPrimary.setMediaAsset(asset);
|
||||
existingPrimary.setSortOrder(0);
|
||||
existingPrimary.setIsPrimary(true);
|
||||
existingPrimary.setIsActive(true);
|
||||
existingPrimary.setCreatedAt(OffsetDateTime.now().minusDays(1));
|
||||
persistUsage(existingPrimary);
|
||||
|
||||
AdminCreateMediaUsageRequest payload = new AdminCreateMediaUsageRequest();
|
||||
payload.setUsageType("home");
|
||||
payload.setUsageKey("landing");
|
||||
payload.setMediaAssetId(asset.getId());
|
||||
payload.setSortOrder(5);
|
||||
payload.setIsPrimary(true);
|
||||
payload.setTranslations(buildTranslations("Landing hero", "Hero home alt"));
|
||||
|
||||
AdminMediaUsageDto created = service.createUsage(payload);
|
||||
|
||||
assertEquals("HOME", created.getUsageType());
|
||||
assertEquals("landing", created.getUsageKey());
|
||||
assertEquals(asset.getId(), created.getMediaAssetId());
|
||||
assertEquals(5, created.getSortOrder());
|
||||
assertTrue(created.getIsPrimary());
|
||||
assertEquals("Landing hero IT", created.getTranslations().get("it").getTitle());
|
||||
assertEquals("Hero home alt EN", created.getTranslations().get("en").getAltText());
|
||||
assertFalse(usages.get(existingPrimary.getId()).getIsPrimary());
|
||||
|
||||
AdminMediaAssetDto assetDto = service.getAsset(asset.getId());
|
||||
assertEquals(2, assetDto.getUsages().size());
|
||||
assertTrue(assetDto.getUsages().stream().anyMatch(usage -> usage.getId().equals(created.getId()) && usage.getIsPrimary()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createUsage_withoutAllTranslations_shouldFailValidation() {
|
||||
MediaAsset asset = persistAsset(seedAsset("PUBLIC"));
|
||||
|
||||
AdminCreateMediaUsageRequest payload = new AdminCreateMediaUsageRequest();
|
||||
payload.setUsageType("home");
|
||||
payload.setUsageKey("landing");
|
||||
payload.setMediaAssetId(asset.getId());
|
||||
payload.setTranslations(new LinkedHashMap<>(Map.of(
|
||||
"it", translation("Titolo IT", "Alt IT"),
|
||||
"en", translation("Title EN", "Alt EN")
|
||||
)));
|
||||
|
||||
ResponseStatusException ex = assertThrows(
|
||||
ResponseStatusException.class,
|
||||
() -> service.createUsage(payload)
|
||||
);
|
||||
|
||||
assertEquals(HttpStatus.BAD_REQUEST, ex.getStatusCode());
|
||||
assertTrue(ex.getReason().contains("translations must include exactly"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateAsset_withPrivateVisibility_shouldMoveGeneratedFilesAndHidePublicUrls() throws Exception {
|
||||
when(mediaImageInspector.inspect(any(Path.class))).thenReturn(
|
||||
new MediaImageInspector.ImageMetadata("image/jpeg", "jpg", 1200, 800)
|
||||
);
|
||||
|
||||
MockMultipartFile file = new MockMultipartFile(
|
||||
"file",
|
||||
"gallery.jpg",
|
||||
"image/jpeg",
|
||||
"jpeg-image-content".getBytes(StandardCharsets.UTF_8)
|
||||
);
|
||||
|
||||
AdminMediaAssetDto uploaded = service.uploadAsset(file, null, null, "PUBLIC");
|
||||
MediaVariant thumbJpeg = variants.values().stream()
|
||||
.filter(variant -> "thumb".equals(variant.getVariantName()))
|
||||
.filter(variant -> "JPEG".equals(variant.getFormat()))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
|
||||
Path publicFile = storageRoot.resolve("public").resolve(thumbJpeg.getStorageKey());
|
||||
assertTrue(Files.exists(publicFile));
|
||||
|
||||
AdminUpdateMediaAssetRequest payload = new AdminUpdateMediaAssetRequest();
|
||||
payload.setVisibility("PRIVATE");
|
||||
|
||||
AdminMediaAssetDto updated = service.updateAsset(uploaded.getId(), payload);
|
||||
|
||||
assertEquals("PRIVATE", updated.getVisibility());
|
||||
assertFalse(Files.exists(publicFile));
|
||||
assertTrue(Files.exists(storageRoot.resolve("private").resolve(thumbJpeg.getStorageKey())));
|
||||
assertTrue(updated.getVariants().stream()
|
||||
.filter(variant -> !"ORIGINAL".equals(variant.getFormat()))
|
||||
.allMatch(variant -> variant.getPublicUrl() == null));
|
||||
}
|
||||
|
||||
private MediaAsset seedAsset(String visibility) {
|
||||
MediaAsset asset = new MediaAsset();
|
||||
asset.setId(UUID.randomUUID());
|
||||
asset.setOriginalFilename("asset.png");
|
||||
asset.setStorageKey("2026/03/" + UUID.randomUUID() + "/original.png");
|
||||
asset.setMimeType("image/png");
|
||||
asset.setFileSizeBytes(123L);
|
||||
asset.setSha256Hex("a".repeat(64));
|
||||
asset.setWidthPx(1200);
|
||||
asset.setHeightPx(800);
|
||||
asset.setStatus("READY");
|
||||
asset.setVisibility(visibility);
|
||||
asset.setCreatedAt(OffsetDateTime.now());
|
||||
asset.setUpdatedAt(OffsetDateTime.now());
|
||||
return asset;
|
||||
}
|
||||
|
||||
private MediaAsset persistAsset(MediaAsset asset) {
|
||||
assets.put(asset.getId(), asset);
|
||||
return asset;
|
||||
}
|
||||
|
||||
private MediaVariant persistVariant(MediaVariant variant) {
|
||||
if (variant.getId() == null) {
|
||||
variant.setId(UUID.randomUUID());
|
||||
}
|
||||
variants.put(variant.getId(), variant);
|
||||
return variant;
|
||||
}
|
||||
|
||||
private MediaUsage persistUsage(MediaUsage usage) {
|
||||
if (usage.getId() == null) {
|
||||
usage.setId(UUID.randomUUID());
|
||||
}
|
||||
usages.put(usage.getId(), usage);
|
||||
return usage;
|
||||
}
|
||||
|
||||
private Map<String, MediaTextTranslationDto> buildTranslations(String titleBase, String altBase) {
|
||||
LinkedHashMap<String, MediaTextTranslationDto> translations = new LinkedHashMap<>();
|
||||
translations.put("it", translation(titleBase + " IT", altBase + " IT"));
|
||||
translations.put("en", translation(titleBase + " EN", altBase + " EN"));
|
||||
translations.put("de", translation(titleBase + " DE", altBase + " DE"));
|
||||
translations.put("fr", translation(titleBase + " FR", altBase + " FR"));
|
||||
return translations;
|
||||
}
|
||||
|
||||
private MediaTextTranslationDto translation(String title, String altText) {
|
||||
MediaTextTranslationDto dto = new MediaTextTranslationDto();
|
||||
dto.setTitle(title);
|
||||
dto.setAltText(altText);
|
||||
return dto;
|
||||
}
|
||||
|
||||
private List<MediaVariant> variantsForAssets(Collection<UUID> assetIds) {
|
||||
return variants.values().stream()
|
||||
.filter(variant -> assetIds.contains(variant.getMediaAsset().getId()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private List<MediaUsage> usagesForAssets(Collection<UUID> assetIds) {
|
||||
return usages.values().stream()
|
||||
.filter(usage -> assetIds.contains(usage.getMediaAsset().getId()))
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package com.printcalculator.service.admin;
|
||||
|
||||
import com.printcalculator.dto.AdminCadInvoiceCreateRequest;
|
||||
import com.printcalculator.dto.AdminCadInvoiceDto;
|
||||
import com.printcalculator.dto.AdminContactRequestDetailDto;
|
||||
import com.printcalculator.dto.AdminUpdateContactRequestStatusRequest;
|
||||
import com.printcalculator.entity.CustomQuoteRequest;
|
||||
import com.printcalculator.entity.CustomQuoteRequestAttachment;
|
||||
import com.printcalculator.entity.PricingPolicy;
|
||||
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.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AdminOperationsControllerServiceTest {
|
||||
|
||||
@Mock
|
||||
private FilamentVariantStockKgRepository filamentStockRepo;
|
||||
@Mock
|
||||
private FilamentVariantRepository filamentVariantRepo;
|
||||
@Mock
|
||||
private CustomQuoteRequestRepository customQuoteRequestRepo;
|
||||
@Mock
|
||||
private CustomQuoteRequestAttachmentRepository customQuoteRequestAttachmentRepo;
|
||||
@Mock
|
||||
private QuoteSessionRepository quoteSessionRepo;
|
||||
@Mock
|
||||
private QuoteLineItemRepository quoteLineItemRepo;
|
||||
@Mock
|
||||
private OrderRepository orderRepo;
|
||||
@Mock
|
||||
private PricingPolicyRepository pricingRepo;
|
||||
@Mock
|
||||
private QuoteSessionTotalsService quoteSessionTotalsService;
|
||||
|
||||
@InjectMocks
|
||||
private AdminOperationsControllerService service;
|
||||
|
||||
@Test
|
||||
void updateContactRequestStatus_withInvalidStatus_shouldReturnBadRequest() {
|
||||
UUID requestId = UUID.randomUUID();
|
||||
CustomQuoteRequest request = new CustomQuoteRequest();
|
||||
request.setId(requestId);
|
||||
request.setStatus("PENDING");
|
||||
when(customQuoteRequestRepo.findById(requestId)).thenReturn(Optional.of(request));
|
||||
|
||||
AdminUpdateContactRequestStatusRequest payload = new AdminUpdateContactRequestStatusRequest();
|
||||
payload.setStatus("wrong");
|
||||
|
||||
ResponseStatusException ex = assertThrows(
|
||||
ResponseStatusException.class,
|
||||
() -> service.updateContactRequestStatus(requestId, payload)
|
||||
);
|
||||
|
||||
assertEquals(HttpStatus.BAD_REQUEST, ex.getStatusCode());
|
||||
verify(customQuoteRequestRepo, never()).save(any(CustomQuoteRequest.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateContactRequestStatus_withValidStatus_shouldPersistAndReturnDetail() {
|
||||
UUID requestId = UUID.randomUUID();
|
||||
CustomQuoteRequest request = new CustomQuoteRequest();
|
||||
request.setId(requestId);
|
||||
request.setStatus("PENDING");
|
||||
request.setCreatedAt(OffsetDateTime.now());
|
||||
request.setUpdatedAt(OffsetDateTime.now());
|
||||
|
||||
CustomQuoteRequestAttachment attachment = new CustomQuoteRequestAttachment();
|
||||
attachment.setId(UUID.randomUUID());
|
||||
attachment.setOriginalFilename("drawing.stp");
|
||||
attachment.setMimeType("application/step");
|
||||
attachment.setFileSizeBytes(123L);
|
||||
attachment.setCreatedAt(OffsetDateTime.now());
|
||||
|
||||
when(customQuoteRequestRepo.findById(requestId)).thenReturn(Optional.of(request));
|
||||
when(customQuoteRequestRepo.save(any(CustomQuoteRequest.class))).thenAnswer(invocation -> invocation.getArgument(0));
|
||||
when(customQuoteRequestAttachmentRepo.findByRequest_IdOrderByCreatedAtAsc(requestId)).thenReturn(List.of(attachment));
|
||||
|
||||
AdminUpdateContactRequestStatusRequest payload = new AdminUpdateContactRequestStatusRequest();
|
||||
payload.setStatus("done");
|
||||
|
||||
AdminContactRequestDetailDto dto = service.updateContactRequestStatus(requestId, payload);
|
||||
|
||||
assertEquals("DONE", dto.getStatus());
|
||||
assertNotNull(dto.getUpdatedAt());
|
||||
assertEquals(1, dto.getAttachments().size());
|
||||
verify(customQuoteRequestRepo).save(request);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createOrUpdateCadInvoice_withMissingCadHours_shouldReturnBadRequest() {
|
||||
AdminCadInvoiceCreateRequest payload = new AdminCadInvoiceCreateRequest();
|
||||
|
||||
ResponseStatusException ex = assertThrows(
|
||||
ResponseStatusException.class,
|
||||
() -> service.createOrUpdateCadInvoice(payload)
|
||||
);
|
||||
|
||||
assertEquals(HttpStatus.BAD_REQUEST, ex.getStatusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createOrUpdateCadInvoice_withConvertedSession_shouldReturnConflict() {
|
||||
UUID sessionId = UUID.randomUUID();
|
||||
QuoteSession session = new QuoteSession();
|
||||
session.setId(sessionId);
|
||||
session.setStatus("CONVERTED");
|
||||
|
||||
when(quoteSessionRepo.findById(sessionId)).thenReturn(Optional.of(session));
|
||||
|
||||
AdminCadInvoiceCreateRequest payload = new AdminCadInvoiceCreateRequest();
|
||||
payload.setSessionId(sessionId);
|
||||
payload.setCadHours(new BigDecimal("1.0"));
|
||||
|
||||
ResponseStatusException ex = assertThrows(
|
||||
ResponseStatusException.class,
|
||||
() -> service.createOrUpdateCadInvoice(payload)
|
||||
);
|
||||
|
||||
assertEquals(HttpStatus.CONFLICT, ex.getStatusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createOrUpdateCadInvoice_withNewSession_shouldUsePolicyCadRate() {
|
||||
PricingPolicy policy = new PricingPolicy();
|
||||
policy.setCadCostChfPerHour(new BigDecimal("85"));
|
||||
|
||||
when(pricingRepo.findFirstByIsActiveTrueOrderByValidFromDesc()).thenReturn(policy);
|
||||
when(quoteSessionRepo.save(any(QuoteSession.class))).thenAnswer(invocation -> {
|
||||
QuoteSession session = invocation.getArgument(0);
|
||||
if (session.getId() == null) {
|
||||
session.setId(UUID.randomUUID());
|
||||
}
|
||||
return session;
|
||||
});
|
||||
when(quoteLineItemRepo.findByQuoteSessionId(any(UUID.class))).thenReturn(List.of());
|
||||
when(quoteSessionTotalsService.compute(any(QuoteSession.class), anyList()))
|
||||
.thenReturn(new QuoteSessionTotalsService.QuoteSessionTotals(
|
||||
BigDecimal.ZERO,
|
||||
BigDecimal.ZERO,
|
||||
new BigDecimal("212.50"),
|
||||
new BigDecimal("212.50"),
|
||||
BigDecimal.ZERO,
|
||||
BigDecimal.ZERO,
|
||||
BigDecimal.ZERO,
|
||||
BigDecimal.ZERO,
|
||||
new BigDecimal("212.50"),
|
||||
BigDecimal.ZERO
|
||||
));
|
||||
|
||||
AdminCadInvoiceCreateRequest payload = new AdminCadInvoiceCreateRequest();
|
||||
payload.setCadHours(new BigDecimal("2.5"));
|
||||
payload.setCadHourlyRateChf(null);
|
||||
payload.setNotes(" Custom CAD work ");
|
||||
|
||||
AdminCadInvoiceDto dto = service.createOrUpdateCadInvoice(payload);
|
||||
|
||||
assertEquals("CAD_ACTIVE", dto.getSessionStatus());
|
||||
assertEquals(new BigDecimal("2.50"), dto.getCadHours());
|
||||
assertEquals(new BigDecimal("85.00"), dto.getCadHourlyRateChf());
|
||||
assertEquals("Custom CAD work", dto.getNotes());
|
||||
assertEquals(new BigDecimal("212.50"), dto.getCadTotalChf());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteQuoteSession_whenLinkedToOrder_shouldReturnConflict() {
|
||||
UUID sessionId = UUID.randomUUID();
|
||||
QuoteSession session = new QuoteSession();
|
||||
session.setId(sessionId);
|
||||
|
||||
when(quoteSessionRepo.findById(sessionId)).thenReturn(Optional.of(session));
|
||||
when(orderRepo.existsBySourceQuoteSession_Id(sessionId)).thenReturn(true);
|
||||
|
||||
ResponseStatusException ex = assertThrows(
|
||||
ResponseStatusException.class,
|
||||
() -> service.deleteQuoteSession(sessionId)
|
||||
);
|
||||
|
||||
assertEquals(HttpStatus.CONFLICT, ex.getStatusCode());
|
||||
verify(quoteSessionRepo, never()).delete(any(QuoteSession.class));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package com.printcalculator.service.media;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.PosixFilePermission;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class MediaFfmpegServiceTest {
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@Test
|
||||
void sanitizeExecutable_rejectsControlCharacters() {
|
||||
IllegalArgumentException ex = assertThrows(
|
||||
IllegalArgumentException.class,
|
||||
() -> MediaFfmpegService.sanitizeExecutable("ffmpeg\n--help")
|
||||
);
|
||||
|
||||
assertEquals("media.ffmpeg.path contains control characters.", ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveExecutable_shouldFallbackToPathWhenAbsoluteLocationIsMissing() {
|
||||
String resolved = MediaFfmpegService.resolveExecutable("/opt/homebrew/bin/ffmpeg");
|
||||
|
||||
assertEquals("ffmpeg", resolved);
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateVariant_rejectsSourceNamesStartingWithDash() throws Exception {
|
||||
MediaFfmpegService service = new MediaFfmpegService("missing-ffmpeg-binary");
|
||||
Path source = tempDir.resolve("-input.png");
|
||||
Path target = tempDir.resolve("output.jpg");
|
||||
Files.writeString(source, "image");
|
||||
|
||||
IOException ex = assertThrows(
|
||||
IOException.class,
|
||||
() -> service.generateVariant(source, target, 120, 80, "JPEG")
|
||||
);
|
||||
|
||||
assertEquals("Media source file name must not start with '-'.", ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateVariant_rejectsTargetNamesStartingWithDash() throws Exception {
|
||||
MediaFfmpegService service = new MediaFfmpegService("missing-ffmpeg-binary");
|
||||
Path source = tempDir.resolve("input.png");
|
||||
Path target = tempDir.resolve("-output.jpg");
|
||||
Files.writeString(source, "image");
|
||||
|
||||
IOException ex = assertThrows(
|
||||
IOException.class,
|
||||
() -> service.generateVariant(source, target, 120, 80, "JPEG")
|
||||
);
|
||||
|
||||
assertEquals("Media target file name must not start with '-'.", ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateVariant_avifShouldNotUseStillPictureFlag() throws Exception {
|
||||
Path fakeFfmpeg = tempDir.resolve("fake-ffmpeg.sh");
|
||||
Files.writeString(
|
||||
fakeFfmpeg,
|
||||
"""
|
||||
#!/bin/sh
|
||||
if [ "$1" = "-hide_banner" ] && [ "$2" = "-encoders" ]; then
|
||||
cat <<'EOF'
|
||||
V..... mjpeg
|
||||
V..... libwebp
|
||||
V..... libaom-av1
|
||||
EOF
|
||||
exit 0
|
||||
fi
|
||||
|
||||
for arg in "$@"; do
|
||||
if [ "$arg" = "-still-picture" ]; then
|
||||
echo "Unrecognized option 'still-picture'. Error splitting the argument list: Option not found"
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
last_arg=""
|
||||
for arg in "$@"; do
|
||||
last_arg="$arg"
|
||||
done
|
||||
|
||||
mkdir -p "$(dirname "$last_arg")"
|
||||
printf 'ok' > "$last_arg"
|
||||
exit 0
|
||||
"""
|
||||
);
|
||||
Files.setPosixFilePermissions(
|
||||
fakeFfmpeg,
|
||||
Set.of(
|
||||
PosixFilePermission.OWNER_READ,
|
||||
PosixFilePermission.OWNER_WRITE,
|
||||
PosixFilePermission.OWNER_EXECUTE
|
||||
)
|
||||
);
|
||||
|
||||
MediaFfmpegService service = new MediaFfmpegService(fakeFfmpeg.toString());
|
||||
Path source = tempDir.resolve("input.png");
|
||||
Path target = tempDir.resolve("output.avif");
|
||||
Files.writeString(source, "image");
|
||||
|
||||
service.generateVariant(source, target, 120, 80, "AVIF");
|
||||
|
||||
assertTrue(Files.exists(target));
|
||||
assertEquals("ok", Files.readString(target));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package com.printcalculator.service.media;
|
||||
|
||||
import com.printcalculator.dto.PublicMediaUsageDto;
|
||||
import com.printcalculator.dto.MediaTextTranslationDto;
|
||||
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.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class PublicMediaQueryServiceTest {
|
||||
|
||||
@Mock
|
||||
private MediaUsageRepository mediaUsageRepository;
|
||||
@Mock
|
||||
private MediaVariantRepository mediaVariantRepository;
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
private PublicMediaQueryService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MediaStorageService mediaStorageService = new MediaStorageService(
|
||||
tempDir.resolve("storage_media").toString(),
|
||||
"https://cdn.example/media"
|
||||
);
|
||||
service = new PublicMediaQueryService(mediaUsageRepository, mediaVariantRepository, mediaStorageService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getUsageMedia_shouldReturnOnlyActiveReadyPublicUsagesOrderedBySortOrder() {
|
||||
MediaAsset readyPublicAsset = buildAsset("READY", "PUBLIC", "Shop hero fallback", "Shop alt fallback");
|
||||
MediaAsset draftAsset = buildAsset("PROCESSING", "PUBLIC", "Draft", "Draft alt");
|
||||
MediaAsset privateAsset = buildAsset("READY", "PRIVATE", "Private", "Private alt");
|
||||
|
||||
MediaUsage usageSecond = buildUsage(readyPublicAsset, "HOME_SECTION", "shop-gallery", 2, false, true);
|
||||
MediaUsage usageFirst = buildUsage(readyPublicAsset, "HOME_SECTION", "shop-gallery", 1, true, true);
|
||||
applyTranslation(usageSecond, "it", "Shop hero IT", "Shop alt IT");
|
||||
applyTranslation(usageSecond, "en", "Shop hero EN", "Shop alt EN");
|
||||
applyTranslation(usageSecond, "de", "Shop hero DE", "Shop alt DE");
|
||||
applyTranslation(usageSecond, "fr", "Shop hero FR", "Shop alt FR");
|
||||
applyTranslation(usageFirst, "it", "Shop hero IT", "Shop alt IT");
|
||||
applyTranslation(usageFirst, "en", "Shop hero EN", "Shop alt EN");
|
||||
applyTranslation(usageFirst, "de", "Shop hero DE", "Shop alt DE");
|
||||
applyTranslation(usageFirst, "fr", "Shop hero FR", "Shop alt FR");
|
||||
MediaUsage usageDraft = buildUsage(draftAsset, "HOME_SECTION", "shop-gallery", 0, false, true);
|
||||
MediaUsage usagePrivate = buildUsage(privateAsset, "HOME_SECTION", "shop-gallery", 3, false, true);
|
||||
|
||||
when(mediaUsageRepository.findByUsageTypeAndUsageKeyAndIsActiveTrueOrderBySortOrderAscCreatedAtAsc(
|
||||
"HOME_SECTION", "shop-gallery"
|
||||
)).thenReturn(List.of(usageSecond, usageFirst, usageDraft, usagePrivate));
|
||||
when(mediaVariantRepository.findByMediaAsset_IdIn(List.of(readyPublicAsset.getId())))
|
||||
.thenReturn(List.of(
|
||||
buildVariant(readyPublicAsset, "thumb", "JPEG", "asset/thumb.jpg"),
|
||||
buildVariant(readyPublicAsset, "thumb", "WEBP", "asset/thumb.webp"),
|
||||
buildVariant(readyPublicAsset, "hero", "AVIF", "asset/hero.avif"),
|
||||
buildVariant(readyPublicAsset, "hero", "JPEG", "asset/hero.jpg")
|
||||
));
|
||||
|
||||
List<PublicMediaUsageDto> result = service.getUsageMedia("home_section", "shop-gallery", "en");
|
||||
|
||||
assertEquals(2, result.size());
|
||||
assertEquals(1, result.get(0).getSortOrder());
|
||||
assertEquals(Boolean.TRUE, result.get(0).getIsPrimary());
|
||||
assertEquals("Shop hero EN", result.get(0).getTitle());
|
||||
assertEquals("Shop alt EN", result.get(0).getAltText());
|
||||
assertEquals("https://cdn.example/media/asset/thumb.jpg", result.get(0).getThumb().getJpegUrl());
|
||||
assertEquals("https://cdn.example/media/asset/thumb.webp", result.get(0).getThumb().getWebpUrl());
|
||||
assertEquals("https://cdn.example/media/asset/hero.avif", result.get(0).getHero().getAvifUrl());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getUsageMedia_shouldReturnNullForMissingFormatsOrPresetsAndFallbackToAssetMetadata() {
|
||||
MediaAsset asset = buildAsset("READY", "PUBLIC", "Joe portrait", "Joe portrait fallback");
|
||||
MediaUsage usage = buildUsage(asset, "ABOUT_MEMBER", "joe", 0, true, true);
|
||||
|
||||
when(mediaUsageRepository.findByUsageTypeAndUsageKeyAndIsActiveTrueOrderBySortOrderAscCreatedAtAsc(
|
||||
"ABOUT_MEMBER", "joe"
|
||||
)).thenReturn(List.of(usage));
|
||||
when(mediaVariantRepository.findByMediaAsset_IdIn(List.of(asset.getId())))
|
||||
.thenReturn(List.of(buildVariant(asset, "card", "JPEG", "joe/card.jpg")));
|
||||
|
||||
List<PublicMediaUsageDto> result = service.getUsageMedia("ABOUT_MEMBER", "joe", "fr");
|
||||
|
||||
assertEquals(1, result.size());
|
||||
assertEquals("Joe portrait", result.get(0).getTitle());
|
||||
assertEquals("Joe portrait fallback", result.get(0).getAltText());
|
||||
assertNull(result.get(0).getThumb().getJpegUrl());
|
||||
assertNull(result.get(0).getCard().getAvifUrl());
|
||||
assertEquals("https://cdn.example/media/joe/card.jpg", result.get(0).getCard().getJpegUrl());
|
||||
assertNull(result.get(0).getHero().getWebpUrl());
|
||||
assertTrue(result.get(0).getIsPrimary());
|
||||
}
|
||||
|
||||
private MediaAsset buildAsset(String status, String visibility, String title, String altText) {
|
||||
MediaAsset asset = new MediaAsset();
|
||||
asset.setId(UUID.randomUUID());
|
||||
asset.setStatus(status);
|
||||
asset.setVisibility(visibility);
|
||||
asset.setTitle(title);
|
||||
asset.setAltText(altText);
|
||||
asset.setCreatedAt(OffsetDateTime.now());
|
||||
asset.setUpdatedAt(OffsetDateTime.now());
|
||||
return asset;
|
||||
}
|
||||
|
||||
private MediaUsage buildUsage(MediaAsset asset,
|
||||
String usageType,
|
||||
String usageKey,
|
||||
int sortOrder,
|
||||
boolean isPrimary,
|
||||
boolean isActive) {
|
||||
MediaUsage usage = new MediaUsage();
|
||||
usage.setId(UUID.randomUUID());
|
||||
usage.setMediaAsset(asset);
|
||||
usage.setUsageType(usageType);
|
||||
usage.setUsageKey(usageKey);
|
||||
usage.setSortOrder(sortOrder);
|
||||
usage.setIsPrimary(isPrimary);
|
||||
usage.setIsActive(isActive);
|
||||
usage.setCreatedAt(OffsetDateTime.now().plusSeconds(sortOrder));
|
||||
return usage;
|
||||
}
|
||||
|
||||
private MediaVariant buildVariant(MediaAsset asset, String variantName, String format, String storageKey) {
|
||||
MediaVariant variant = new MediaVariant();
|
||||
variant.setId(UUID.randomUUID());
|
||||
variant.setMediaAsset(asset);
|
||||
variant.setVariantName(variantName);
|
||||
variant.setFormat(format);
|
||||
variant.setStorageKey(storageKey);
|
||||
variant.setCreatedAt(OffsetDateTime.now());
|
||||
return variant;
|
||||
}
|
||||
|
||||
private void applyTranslation(MediaUsage usage, String language, String title, String altText) {
|
||||
MediaTextTranslationDto translation = new MediaTextTranslationDto();
|
||||
translation.setTitle(title);
|
||||
translation.setAltText(altText);
|
||||
usage.setTitleForLanguage(language, translation.getTitle());
|
||||
usage.setAltTextForLanguage(language, translation.getAltText());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
package com.printcalculator.service.order;
|
||||
|
||||
import com.printcalculator.dto.AdminOrderStatusUpdateRequest;
|
||||
import com.printcalculator.dto.OrderDto;
|
||||
import com.printcalculator.entity.FilamentVariant;
|
||||
import com.printcalculator.entity.Order;
|
||||
import com.printcalculator.entity.OrderItem;
|
||||
import com.printcalculator.entity.Payment;
|
||||
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.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AdminOrderControllerServiceTest {
|
||||
|
||||
@Mock
|
||||
private OrderRepository orderRepo;
|
||||
@Mock
|
||||
private OrderItemRepository orderItemRepo;
|
||||
@Mock
|
||||
private PaymentRepository paymentRepo;
|
||||
@Mock
|
||||
private QuoteLineItemRepository quoteLineItemRepo;
|
||||
@Mock
|
||||
private PaymentService paymentService;
|
||||
@Mock
|
||||
private StorageService storageService;
|
||||
@Mock
|
||||
private InvoicePdfRenderingService invoiceService;
|
||||
@Mock
|
||||
private QrBillService qrBillService;
|
||||
@Mock
|
||||
private ApplicationEventPublisher eventPublisher;
|
||||
|
||||
@InjectMocks
|
||||
private AdminOrderControllerService service;
|
||||
|
||||
@Test
|
||||
void updatePaymentMethod_withBlankMethod_shouldReturnBadRequest() {
|
||||
UUID orderId = UUID.randomUUID();
|
||||
when(orderRepo.findById(orderId)).thenReturn(Optional.of(buildOrder(orderId, "PENDING_PAYMENT")));
|
||||
|
||||
ResponseStatusException ex = assertThrows(
|
||||
ResponseStatusException.class,
|
||||
() -> service.updatePaymentMethod(orderId, Map.of("method", " "))
|
||||
);
|
||||
|
||||
assertEquals(HttpStatus.BAD_REQUEST, ex.getStatusCode());
|
||||
verify(paymentService, never()).updatePaymentMethod(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updatePaymentMethod_withValidMethod_shouldDelegateAndReturnUpdatedDto() {
|
||||
UUID orderId = UUID.randomUUID();
|
||||
Order order = buildOrder(orderId, "PENDING_PAYMENT");
|
||||
Payment payment = new Payment();
|
||||
payment.setMethod("BANK_TRANSFER");
|
||||
payment.setStatus("PENDING");
|
||||
|
||||
when(orderRepo.findById(orderId)).thenReturn(Optional.of(order));
|
||||
when(orderItemRepo.findByOrder_Id(orderId)).thenReturn(List.of());
|
||||
when(paymentRepo.findByOrder_Id(orderId)).thenReturn(Optional.of(payment));
|
||||
|
||||
OrderDto dto = service.updatePaymentMethod(orderId, Map.of("method", "BANK_TRANSFER"));
|
||||
|
||||
assertEquals("BANK_TRANSFER", dto.getPaymentMethod());
|
||||
assertEquals("PENDING", dto.getPaymentStatus());
|
||||
verify(paymentService).updatePaymentMethod(orderId, "BANK_TRANSFER");
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateOrderStatus_toShipped_shouldPublishOrderShippedEvent() {
|
||||
UUID orderId = UUID.randomUUID();
|
||||
Order order = buildOrder(orderId, "PAID");
|
||||
|
||||
when(orderRepo.findById(orderId)).thenReturn(Optional.of(order));
|
||||
when(orderRepo.save(any(Order.class))).thenAnswer(invocation -> invocation.getArgument(0));
|
||||
when(orderItemRepo.findByOrder_Id(orderId)).thenReturn(List.of());
|
||||
when(paymentRepo.findByOrder_Id(orderId)).thenReturn(Optional.empty());
|
||||
|
||||
AdminOrderStatusUpdateRequest payload = new AdminOrderStatusUpdateRequest();
|
||||
payload.setStatus("shipped");
|
||||
|
||||
OrderDto dto = service.updateOrderStatus(orderId, payload);
|
||||
|
||||
assertEquals("SHIPPED", dto.getStatus());
|
||||
verify(eventPublisher).publishEvent(any(OrderShippedEvent.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateOrderStatus_fromShippedToShipped_shouldNotPublishEvent() {
|
||||
UUID orderId = UUID.randomUUID();
|
||||
Order order = buildOrder(orderId, "SHIPPED");
|
||||
|
||||
when(orderRepo.findById(orderId)).thenReturn(Optional.of(order));
|
||||
when(orderRepo.save(any(Order.class))).thenAnswer(invocation -> invocation.getArgument(0));
|
||||
when(orderItemRepo.findByOrder_Id(orderId)).thenReturn(List.of());
|
||||
when(paymentRepo.findByOrder_Id(orderId)).thenReturn(Optional.empty());
|
||||
|
||||
AdminOrderStatusUpdateRequest payload = new AdminOrderStatusUpdateRequest();
|
||||
payload.setStatus("SHIPPED");
|
||||
|
||||
service.updateOrderStatus(orderId, payload);
|
||||
|
||||
verify(eventPublisher, never()).publishEvent(any(OrderShippedEvent.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void downloadOrderItemFile_withInvalidRelativePath_shouldReturnNotFound() {
|
||||
UUID orderId = UUID.randomUUID();
|
||||
UUID orderItemId = UUID.randomUUID();
|
||||
|
||||
Order order = buildOrder(orderId, "PAID");
|
||||
OrderItem item = new OrderItem();
|
||||
item.setId(orderItemId);
|
||||
item.setOrder(order);
|
||||
item.setStoredRelativePath("../escape/path.stl");
|
||||
|
||||
when(orderItemRepo.findById(orderItemId)).thenReturn(Optional.of(item));
|
||||
|
||||
ResponseStatusException ex = assertThrows(
|
||||
ResponseStatusException.class,
|
||||
() -> service.downloadOrderItemFile(orderId, orderItemId)
|
||||
);
|
||||
|
||||
assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getOrder_shouldIncludePerItemPrintSettingsAndVariantMetadata() {
|
||||
UUID orderId = UUID.randomUUID();
|
||||
Order order = buildOrder(orderId, "PAID");
|
||||
|
||||
FilamentVariant variant = new FilamentVariant();
|
||||
variant.setId(42L);
|
||||
variant.setVariantDisplayName("PLA Arancione Opaco");
|
||||
variant.setColorName("Arancione");
|
||||
variant.setColorHex("#ff7a00");
|
||||
|
||||
OrderItem item = new OrderItem();
|
||||
item.setId(UUID.randomUUID());
|
||||
item.setOrder(order);
|
||||
item.setOriginalFilename("obj_4_Part 1.stl");
|
||||
item.setMaterialCode("PLA");
|
||||
item.setColorCode("Arancione");
|
||||
item.setFilamentVariant(variant);
|
||||
item.setQuality("standard");
|
||||
item.setNozzleDiameterMm(new BigDecimal("0.60"));
|
||||
item.setLayerHeightMm(new BigDecimal("0.24"));
|
||||
item.setInfillPercent(15);
|
||||
item.setInfillPattern("grid");
|
||||
item.setSupportsEnabled(Boolean.FALSE);
|
||||
item.setQuantity(1);
|
||||
item.setPrintTimeSeconds(2340);
|
||||
item.setMaterialGrams(new BigDecimal("22.76"));
|
||||
item.setUnitPriceChf(new BigDecimal("0.99"));
|
||||
item.setLineTotalChf(new BigDecimal("0.99"));
|
||||
|
||||
when(orderRepo.findById(orderId)).thenReturn(Optional.of(order));
|
||||
when(orderItemRepo.findByOrder_Id(orderId)).thenReturn(List.of(item));
|
||||
when(paymentRepo.findByOrder_Id(orderId)).thenReturn(Optional.empty());
|
||||
|
||||
OrderDto dto = service.getOrder(orderId);
|
||||
|
||||
assertEquals(1, dto.getItems().size());
|
||||
var itemDto = dto.getItems().get(0);
|
||||
assertEquals(new BigDecimal("0.60"), itemDto.getNozzleDiameterMm());
|
||||
assertEquals(new BigDecimal("0.24"), itemDto.getLayerHeightMm());
|
||||
assertEquals(15, itemDto.getInfillPercent());
|
||||
assertEquals("grid", itemDto.getInfillPattern());
|
||||
assertEquals(Boolean.FALSE, itemDto.getSupportsEnabled());
|
||||
assertEquals(42L, itemDto.getFilamentVariantId());
|
||||
assertEquals("PLA Arancione Opaco", itemDto.getFilamentVariantDisplayName());
|
||||
assertEquals("Arancione", itemDto.getFilamentColorName());
|
||||
assertEquals("#ff7a00", itemDto.getFilamentColorHex());
|
||||
}
|
||||
|
||||
private Order buildOrder(UUID orderId, String status) {
|
||||
Order order = new Order();
|
||||
order.setId(orderId);
|
||||
order.setStatus(status);
|
||||
order.setCustomerEmail("customer@example.com");
|
||||
order.setCustomerPhone("+41910000000");
|
||||
order.setBillingCustomerType("PRIVATE");
|
||||
order.setBillingFirstName("Mario");
|
||||
order.setBillingLastName("Rossi");
|
||||
order.setBillingAddressLine1("Via Test 1");
|
||||
order.setBillingZip("6900");
|
||||
order.setBillingCity("Lugano");
|
||||
order.setBillingCountryCode("CH");
|
||||
order.setShippingSameAsBilling(true);
|
||||
order.setCurrency("CHF");
|
||||
order.setSetupCostChf(BigDecimal.ZERO);
|
||||
order.setShippingCostChf(BigDecimal.ZERO);
|
||||
order.setDiscountChf(BigDecimal.ZERO);
|
||||
order.setSubtotalChf(BigDecimal.ZERO);
|
||||
order.setCadTotalChf(BigDecimal.ZERO);
|
||||
order.setTotalChf(BigDecimal.ZERO);
|
||||
return order;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package com.printcalculator.service.order;
|
||||
|
||||
import com.printcalculator.dto.OrderDto;
|
||||
import com.printcalculator.entity.Order;
|
||||
import com.printcalculator.entity.OrderItem;
|
||||
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.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class OrderControllerServiceTest {
|
||||
|
||||
@Mock
|
||||
private OrderService orderService;
|
||||
@Mock
|
||||
private OrderRepository orderRepo;
|
||||
@Mock
|
||||
private OrderItemRepository orderItemRepo;
|
||||
@Mock
|
||||
private StorageService storageService;
|
||||
@Mock
|
||||
private InvoicePdfRenderingService invoiceService;
|
||||
@Mock
|
||||
private QrBillService qrBillService;
|
||||
@Mock
|
||||
private TwintPaymentService twintPaymentService;
|
||||
@Mock
|
||||
private PaymentService paymentService;
|
||||
@Mock
|
||||
private PaymentRepository paymentRepo;
|
||||
|
||||
@InjectMocks
|
||||
private OrderControllerService service;
|
||||
|
||||
@Test
|
||||
void uploadOrderItemFile_withOrderMismatch_shouldReturnFalse() throws Exception {
|
||||
UUID expectedOrderId = UUID.randomUUID();
|
||||
UUID wrongOrderId = UUID.randomUUID();
|
||||
UUID orderItemId = UUID.randomUUID();
|
||||
|
||||
Order order = new Order();
|
||||
order.setId(expectedOrderId);
|
||||
|
||||
OrderItem item = new OrderItem();
|
||||
item.setId(orderItemId);
|
||||
item.setOrder(order);
|
||||
item.setStoredRelativePath("PENDING");
|
||||
|
||||
when(orderItemRepo.findById(orderItemId)).thenReturn(Optional.of(item));
|
||||
|
||||
MockMultipartFile file = new MockMultipartFile("file", "part.stl", "model/stl", "solid".getBytes());
|
||||
|
||||
boolean result = service.uploadOrderItemFile(wrongOrderId, orderItemId, file);
|
||||
|
||||
assertFalse(result);
|
||||
verify(storageService, never()).store(any(MockMultipartFile.class), any(Path.class));
|
||||
verify(orderItemRepo, never()).save(any(OrderItem.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadOrderItemFile_withPendingPath_shouldStoreAndPersistMetadata() throws Exception {
|
||||
UUID orderId = UUID.randomUUID();
|
||||
UUID orderItemId = UUID.randomUUID();
|
||||
|
||||
Order order = new Order();
|
||||
order.setId(orderId);
|
||||
|
||||
OrderItem item = new OrderItem();
|
||||
item.setId(orderItemId);
|
||||
item.setOrder(order);
|
||||
item.setStoredRelativePath("PENDING");
|
||||
|
||||
when(orderItemRepo.findById(orderItemId)).thenReturn(Optional.of(item));
|
||||
|
||||
MockMultipartFile file = new MockMultipartFile("file", "model.STL", "model/stl", "mesh".getBytes());
|
||||
|
||||
boolean result = service.uploadOrderItemFile(orderId, orderItemId, file);
|
||||
|
||||
assertTrue(result);
|
||||
|
||||
ArgumentCaptor<Path> pathCaptor = ArgumentCaptor.forClass(Path.class);
|
||||
verify(storageService).store(eq(file), pathCaptor.capture());
|
||||
Path storedPath = pathCaptor.getValue();
|
||||
assertTrue(storedPath.startsWith(Path.of("orders", orderId.toString(), "3d-files", orderItemId.toString())));
|
||||
|
||||
assertTrue(item.getStoredFilename().endsWith(".stl"));
|
||||
assertEquals(file.getSize(), item.getFileSizeBytes());
|
||||
assertEquals("model/stl", item.getMimeType());
|
||||
verify(orderItemRepo).save(item);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getOrder_withShippedStatus_shouldRedactPersonalData() {
|
||||
UUID orderId = UUID.randomUUID();
|
||||
Order order = buildOrder(orderId, "SHIPPED");
|
||||
|
||||
when(orderRepo.findById(orderId)).thenReturn(Optional.of(order));
|
||||
when(orderItemRepo.findByOrder_Id(orderId)).thenReturn(List.of());
|
||||
when(paymentRepo.findByOrder_Id(orderId)).thenReturn(Optional.empty());
|
||||
|
||||
Optional<OrderDto> result = service.getOrder(orderId);
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
OrderDto dto = result.get();
|
||||
assertNull(dto.getCustomerEmail());
|
||||
assertNull(dto.getCustomerPhone());
|
||||
assertNull(dto.getBillingAddress());
|
||||
assertNull(dto.getShippingAddress());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTwintQr_withOversizedInput_shouldClampSizeTo600() {
|
||||
UUID orderId = UUID.randomUUID();
|
||||
Order order = buildOrder(orderId, "PENDING_PAYMENT");
|
||||
|
||||
byte[] png = new byte[]{1, 2, 3};
|
||||
when(orderRepo.findById(orderId)).thenReturn(Optional.of(order));
|
||||
when(twintPaymentService.generateQrPng(order, 600)).thenReturn(png);
|
||||
|
||||
ResponseEntity<byte[]> response = service.getTwintQr(orderId, 5000);
|
||||
|
||||
assertEquals(200, response.getStatusCode().value());
|
||||
assertEquals(MediaType.IMAGE_PNG, response.getHeaders().getContentType());
|
||||
assertArrayEquals(png, response.getBody());
|
||||
verify(twintPaymentService).generateQrPng(order, 600);
|
||||
}
|
||||
|
||||
private Order buildOrder(UUID orderId, String status) {
|
||||
Order order = new Order();
|
||||
order.setId(orderId);
|
||||
order.setStatus(status);
|
||||
order.setCustomerEmail("customer@example.com");
|
||||
order.setCustomerPhone("+41910000000");
|
||||
order.setBillingCustomerType("PRIVATE");
|
||||
order.setBillingFirstName("Mario");
|
||||
order.setBillingLastName("Rossi");
|
||||
order.setBillingAddressLine1("Via Test 1");
|
||||
order.setBillingZip("6900");
|
||||
order.setBillingCity("Lugano");
|
||||
order.setBillingCountryCode("CH");
|
||||
order.setShippingSameAsBilling(true);
|
||||
order.setCurrency("CHF");
|
||||
order.setSetupCostChf(BigDecimal.ZERO);
|
||||
order.setShippingCostChf(BigDecimal.ZERO);
|
||||
order.setDiscountChf(BigDecimal.ZERO);
|
||||
order.setSubtotalChf(BigDecimal.ZERO);
|
||||
order.setCadTotalChf(BigDecimal.ZERO);
|
||||
order.setTotalChf(BigDecimal.ZERO);
|
||||
return order;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.printcalculator.service.request;
|
||||
|
||||
import com.printcalculator.entity.CustomQuoteRequest;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class ContactRequestLocalizationServiceTest {
|
||||
|
||||
private ContactRequestLocalizationService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new ContactRequestLocalizationService();
|
||||
}
|
||||
|
||||
@Test
|
||||
void normalizeLanguage_shouldMapKnownPrefixes() {
|
||||
assertEquals("de", service.normalizeLanguage("de-CH"));
|
||||
assertEquals("en", service.normalizeLanguage("EN"));
|
||||
assertEquals("fr", service.normalizeLanguage("fr_CA"));
|
||||
assertEquals("it", service.normalizeLanguage(""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveRecipientName_shouldUsePriorityAndFallback() {
|
||||
CustomQuoteRequest request = new CustomQuoteRequest();
|
||||
request.setName("Mario Rossi");
|
||||
assertEquals("Mario Rossi", service.resolveRecipientName(request, "it"));
|
||||
|
||||
request.setName(" ");
|
||||
request.setContactPerson("Laura Bianchi");
|
||||
assertEquals("Laura Bianchi", service.resolveRecipientName(request, "it"));
|
||||
|
||||
request.setContactPerson(" ");
|
||||
request.setCompanyName("3D Fab SA");
|
||||
assertEquals("3D Fab SA", service.resolveRecipientName(request, "it"));
|
||||
|
||||
request.setCompanyName(" ");
|
||||
assertEquals("customer", service.resolveRecipientName(request, "en"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void applyCustomerContactRequestTexts_shouldPopulateLocalizedLabels() {
|
||||
Map<String, Object> templateData = new HashMap<>();
|
||||
templateData.put("recipientName", "Mario");
|
||||
UUID requestId = UUID.randomUUID();
|
||||
|
||||
String subject = service.applyCustomerContactRequestTexts(templateData, "fr", requestId);
|
||||
|
||||
assertEquals("Nous avons recu votre demande de contact #" + requestId + " - 3D-Fab", subject);
|
||||
assertEquals("Date", templateData.get("labelDate"));
|
||||
assertEquals("Bonjour Mario,", templateData.get("greetingText"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void localizeRequestType_andCustomerType_shouldReturnExpectedValues() {
|
||||
assertEquals("Custom part request", service.localizeRequestType("print_service", "en"));
|
||||
assertEquals("Azienda", service.localizeCustomerType("business", "it"));
|
||||
assertEquals("-", service.localizeCustomerType(null, "de"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void localeForLanguage_shouldReturnExpectedLocale() {
|
||||
assertEquals(Locale.GERMAN, service.localeForLanguage("de"));
|
||||
assertEquals(Locale.ITALIAN, service.localeForLanguage("unknown"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package com.printcalculator.service.request;
|
||||
|
||||
import com.printcalculator.entity.CustomQuoteRequest;
|
||||
import com.printcalculator.entity.CustomQuoteRequestAttachment;
|
||||
import com.printcalculator.repository.CustomQuoteRequestAttachmentRepository;
|
||||
import com.printcalculator.service.storage.ClamAVService;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class CustomQuoteRequestAttachmentServiceTest {
|
||||
|
||||
@Mock
|
||||
private CustomQuoteRequestAttachmentRepository attachmentRepo;
|
||||
@Mock
|
||||
private ClamAVService clamAVService;
|
||||
|
||||
@InjectMocks
|
||||
private CustomQuoteRequestAttachmentService service;
|
||||
|
||||
private UUID lastRequestIdForCleanup;
|
||||
|
||||
@AfterEach
|
||||
void cleanStorageDirectory() {
|
||||
if (lastRequestIdForCleanup == null) {
|
||||
return;
|
||||
}
|
||||
Path requestDir = Paths.get("storage_requests", "quote-requests", lastRequestIdForCleanup.toString());
|
||||
if (!Files.exists(requestDir)) {
|
||||
return;
|
||||
}
|
||||
try (var walk = Files.walk(requestDir)) {
|
||||
walk.sorted(Comparator.reverseOrder()).forEach(path -> {
|
||||
try {
|
||||
Files.deleteIfExists(path);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
});
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void storeAttachments_withNullFiles_shouldReturnZero() throws Exception {
|
||||
CustomQuoteRequest request = buildRequest();
|
||||
|
||||
int count = service.storeAttachments(request, null);
|
||||
|
||||
assertEquals(0, count);
|
||||
verifyNoInteractions(clamAVService, attachmentRepo);
|
||||
}
|
||||
|
||||
@Test
|
||||
void storeAttachments_withTooManyFiles_shouldThrowIOException() {
|
||||
CustomQuoteRequest request = buildRequest();
|
||||
List<MockMultipartFile> files = new ArrayList<>();
|
||||
for (int i = 0; i < 16; i++) {
|
||||
files.add(new MockMultipartFile("files", "file-" + i + ".stl", "model/stl", "solid".getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
|
||||
IOException ex = assertThrows(
|
||||
IOException.class,
|
||||
() -> service.storeAttachments(request, new ArrayList<>(files))
|
||||
);
|
||||
|
||||
assertTrue(ex.getMessage().contains("Too many files"));
|
||||
verifyNoInteractions(clamAVService, attachmentRepo);
|
||||
}
|
||||
|
||||
@Test
|
||||
void storeAttachments_withCompressedFile_shouldThrowBadRequest() {
|
||||
CustomQuoteRequest request = buildRequest();
|
||||
MockMultipartFile file = new MockMultipartFile(
|
||||
"files",
|
||||
"archive.zip",
|
||||
"application/zip",
|
||||
"dummy".getBytes(StandardCharsets.UTF_8)
|
||||
);
|
||||
|
||||
ResponseStatusException ex = assertThrows(
|
||||
ResponseStatusException.class,
|
||||
() -> service.storeAttachments(request, List.of(file))
|
||||
);
|
||||
|
||||
assertEquals(HttpStatus.BAD_REQUEST, ex.getStatusCode());
|
||||
verifyNoInteractions(clamAVService, attachmentRepo);
|
||||
}
|
||||
|
||||
@Test
|
||||
void storeAttachments_withValidFile_shouldScanPersistAndWriteOnDisk() throws Exception {
|
||||
CustomQuoteRequest request = buildRequest();
|
||||
lastRequestIdForCleanup = request.getId();
|
||||
|
||||
MockMultipartFile file = new MockMultipartFile(
|
||||
"files",
|
||||
"part.stl",
|
||||
"model/stl",
|
||||
"solid model".getBytes(StandardCharsets.UTF_8)
|
||||
);
|
||||
|
||||
when(clamAVService.scan(any())).thenReturn(true);
|
||||
when(attachmentRepo.save(any(CustomQuoteRequestAttachment.class))).thenAnswer(invocation -> {
|
||||
CustomQuoteRequestAttachment attachment = invocation.getArgument(0);
|
||||
if (attachment.getId() == null) {
|
||||
attachment.setId(UUID.randomUUID());
|
||||
}
|
||||
return attachment;
|
||||
});
|
||||
|
||||
int savedCount = service.storeAttachments(request, List.of(file));
|
||||
|
||||
assertEquals(1, savedCount);
|
||||
|
||||
ArgumentCaptor<CustomQuoteRequestAttachment> captor = ArgumentCaptor.forClass(CustomQuoteRequestAttachment.class);
|
||||
verify(attachmentRepo, times(2)).save(captor.capture());
|
||||
verify(clamAVService, times(1)).scan(any());
|
||||
|
||||
CustomQuoteRequestAttachment persisted = captor.getAllValues().get(1);
|
||||
Path absolutePath = Paths.get("storage_requests").toAbsolutePath().normalize()
|
||||
.resolve(persisted.getStoredRelativePath())
|
||||
.normalize();
|
||||
|
||||
assertTrue(Files.exists(absolutePath));
|
||||
assertEquals("solid model", Files.readString(absolutePath, StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private CustomQuoteRequest buildRequest() {
|
||||
CustomQuoteRequest request = new CustomQuoteRequest();
|
||||
request.setId(UUID.randomUUID());
|
||||
return request;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package com.printcalculator.service.request;
|
||||
|
||||
import com.printcalculator.dto.QuoteRequestDto;
|
||||
import com.printcalculator.entity.CustomQuoteRequest;
|
||||
import com.printcalculator.repository.CustomQuoteRequestRepository;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class CustomQuoteRequestControllerServiceTest {
|
||||
|
||||
@Mock
|
||||
private CustomQuoteRequestRepository requestRepo;
|
||||
@Mock
|
||||
private CustomQuoteRequestAttachmentService attachmentService;
|
||||
@Mock
|
||||
private CustomQuoteRequestNotificationService notificationService;
|
||||
|
||||
@InjectMocks
|
||||
private CustomQuoteRequestControllerService service;
|
||||
|
||||
@Test
|
||||
void createCustomQuoteRequest_withMissingConsents_shouldThrowBadRequest() throws Exception {
|
||||
QuoteRequestDto dto = buildRequest(false, true);
|
||||
|
||||
ResponseStatusException ex = assertThrows(
|
||||
ResponseStatusException.class,
|
||||
() -> service.createCustomQuoteRequest(dto, List.of())
|
||||
);
|
||||
|
||||
assertEquals(HttpStatus.BAD_REQUEST, ex.getStatusCode());
|
||||
verifyNoInteractions(requestRepo, attachmentService, notificationService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createCustomQuoteRequest_withValidPayload_shouldPersistAndDelegate() throws Exception {
|
||||
UUID requestId = UUID.randomUUID();
|
||||
QuoteRequestDto dto = buildRequest(true, true);
|
||||
List<MultipartFile> files = List.of();
|
||||
|
||||
when(requestRepo.save(any(CustomQuoteRequest.class))).thenAnswer(invocation -> {
|
||||
CustomQuoteRequest request = invocation.getArgument(0);
|
||||
request.setId(requestId);
|
||||
return request;
|
||||
});
|
||||
when(attachmentService.storeAttachments(any(CustomQuoteRequest.class), eq(files))).thenReturn(2);
|
||||
|
||||
CustomQuoteRequest saved = service.createCustomQuoteRequest(dto, files);
|
||||
|
||||
assertNotNull(saved);
|
||||
assertEquals(requestId, saved.getId());
|
||||
assertEquals("PENDING", saved.getStatus());
|
||||
assertNotNull(saved.getCreatedAt());
|
||||
assertNotNull(saved.getUpdatedAt());
|
||||
|
||||
verify(requestRepo).save(any(CustomQuoteRequest.class));
|
||||
verify(attachmentService).storeAttachments(saved, files);
|
||||
verify(notificationService).sendNotifications(saved, 2, "de-CH");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCustomQuoteRequest_shouldDelegateToRepository() {
|
||||
UUID requestId = UUID.randomUUID();
|
||||
CustomQuoteRequest request = new CustomQuoteRequest();
|
||||
request.setId(requestId);
|
||||
when(requestRepo.findById(requestId)).thenReturn(Optional.of(request));
|
||||
|
||||
Optional<CustomQuoteRequest> result = service.getCustomQuoteRequest(requestId);
|
||||
|
||||
assertEquals(Optional.of(request), result);
|
||||
verify(requestRepo).findById(requestId);
|
||||
}
|
||||
|
||||
private QuoteRequestDto buildRequest(boolean acceptTerms, boolean acceptPrivacy) {
|
||||
QuoteRequestDto dto = new QuoteRequestDto();
|
||||
dto.setRequestType("PRINT_SERVICE");
|
||||
dto.setCustomerType("PRIVATE");
|
||||
dto.setLanguage("de-CH");
|
||||
dto.setEmail("customer@example.com");
|
||||
dto.setPhone("+41910000000");
|
||||
dto.setName("Mario Rossi");
|
||||
dto.setCompanyName("3D Fab SA");
|
||||
dto.setContactPerson("Mario Rossi");
|
||||
dto.setMessage("Vorrei una quotazione.");
|
||||
dto.setAcceptTerms(acceptTerms);
|
||||
dto.setAcceptPrivacy(acceptPrivacy);
|
||||
return dto;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package com.printcalculator.service.request;
|
||||
|
||||
import com.printcalculator.entity.CustomQuoteRequest;
|
||||
import com.printcalculator.service.email.EmailNotificationService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class CustomQuoteRequestNotificationServiceTest {
|
||||
|
||||
@Mock
|
||||
private EmailNotificationService emailNotificationService;
|
||||
|
||||
private ContactRequestLocalizationService localizationService;
|
||||
private CustomQuoteRequestNotificationService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
localizationService = new ContactRequestLocalizationService();
|
||||
service = new CustomQuoteRequestNotificationService(emailNotificationService, localizationService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sendNotifications_withAdminAndCustomerEnabled_shouldSendBothEmails() {
|
||||
ReflectionTestUtils.setField(service, "contactRequestAdminMailEnabled", true);
|
||||
ReflectionTestUtils.setField(service, "contactRequestAdminMailAddress", "admin@3d-fab.ch");
|
||||
ReflectionTestUtils.setField(service, "contactRequestCustomerMailEnabled", true);
|
||||
|
||||
CustomQuoteRequest request = buildRequest();
|
||||
|
||||
service.sendNotifications(request, 3, "en-US");
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<Map<String, Object>> dataCaptor = (ArgumentCaptor<Map<String, Object>>) (ArgumentCaptor<?>) ArgumentCaptor.forClass(Map.class);
|
||||
ArgumentCaptor<String> toCaptor = ArgumentCaptor.forClass(String.class);
|
||||
ArgumentCaptor<String> subjectCaptor = ArgumentCaptor.forClass(String.class);
|
||||
ArgumentCaptor<String> templateCaptor = ArgumentCaptor.forClass(String.class);
|
||||
|
||||
verify(emailNotificationService, times(2)).sendEmail(
|
||||
toCaptor.capture(),
|
||||
subjectCaptor.capture(),
|
||||
templateCaptor.capture(),
|
||||
dataCaptor.capture()
|
||||
);
|
||||
|
||||
List<String> recipients = toCaptor.getAllValues();
|
||||
assertTrue(recipients.contains("admin@3d-fab.ch"));
|
||||
assertTrue(recipients.contains("customer@example.com"));
|
||||
|
||||
int customerIndex = recipients.indexOf("customer@example.com");
|
||||
assertEquals("contact-request-customer", templateCaptor.getAllValues().get(customerIndex));
|
||||
assertEquals("We received your contact request #" + request.getId() + " - 3D-Fab", subjectCaptor.getAllValues().get(customerIndex));
|
||||
assertEquals("Date", dataCaptor.getAllValues().get(customerIndex).get("labelDate"));
|
||||
|
||||
int adminIndex = recipients.indexOf("admin@3d-fab.ch");
|
||||
assertEquals("contact-request-admin", templateCaptor.getAllValues().get(adminIndex));
|
||||
assertEquals(3, dataCaptor.getAllValues().get(adminIndex).get("attachmentsCount"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sendNotifications_withCustomerDisabled_shouldOnlySendAdminEmail() {
|
||||
ReflectionTestUtils.setField(service, "contactRequestAdminMailEnabled", true);
|
||||
ReflectionTestUtils.setField(service, "contactRequestAdminMailAddress", "admin@3d-fab.ch");
|
||||
ReflectionTestUtils.setField(service, "contactRequestCustomerMailEnabled", false);
|
||||
|
||||
service.sendNotifications(buildRequest(), 1, "it");
|
||||
|
||||
verify(emailNotificationService, times(1)).sendEmail(
|
||||
org.mockito.ArgumentMatchers.eq("admin@3d-fab.ch"),
|
||||
org.mockito.ArgumentMatchers.anyString(),
|
||||
org.mockito.ArgumentMatchers.eq("contact-request-admin"),
|
||||
org.mockito.ArgumentMatchers.anyMap()
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sendNotifications_withMissingAdminAddressAndCustomerDisabled_shouldSendNothing() {
|
||||
ReflectionTestUtils.setField(service, "contactRequestAdminMailEnabled", true);
|
||||
ReflectionTestUtils.setField(service, "contactRequestAdminMailAddress", " ");
|
||||
ReflectionTestUtils.setField(service, "contactRequestCustomerMailEnabled", false);
|
||||
|
||||
service.sendNotifications(buildRequest(), 1, "fr");
|
||||
|
||||
verify(emailNotificationService, never()).sendEmail(
|
||||
org.mockito.ArgumentMatchers.anyString(),
|
||||
org.mockito.ArgumentMatchers.anyString(),
|
||||
org.mockito.ArgumentMatchers.anyString(),
|
||||
org.mockito.ArgumentMatchers.anyMap()
|
||||
);
|
||||
}
|
||||
|
||||
private CustomQuoteRequest buildRequest() {
|
||||
CustomQuoteRequest request = new CustomQuoteRequest();
|
||||
request.setId(UUID.randomUUID());
|
||||
request.setRequestType("PRINT_SERVICE");
|
||||
request.setCustomerType("PRIVATE");
|
||||
request.setName("Mario Rossi");
|
||||
request.setCompanyName("3D Fab SA");
|
||||
request.setContactPerson("Mario Rossi");
|
||||
request.setEmail("customer@example.com");
|
||||
request.setPhone("+41910000000");
|
||||
request.setMessage("Vorrei una quotazione.");
|
||||
request.setCreatedAt(OffsetDateTime.parse("2026-03-05T10:15:30+01:00"));
|
||||
return request;
|
||||
}
|
||||
}
|
||||
112
db.sql
112
db.sql
@@ -660,6 +660,12 @@ CREATE TABLE IF NOT EXISTS quote_line_items
|
||||
quantity integer NOT NULL DEFAULT 1 CHECK (quantity >= 1),
|
||||
color_code text, -- es: white/black o codice interno
|
||||
filament_variant_id bigint REFERENCES filament_variant (filament_variant_id),
|
||||
material_code text,
|
||||
nozzle_diameter_mm numeric(5, 2),
|
||||
layer_height_mm numeric(6, 3),
|
||||
infill_pattern text,
|
||||
infill_percent integer CHECK (infill_percent BETWEEN 0 AND 100),
|
||||
supports_enabled boolean,
|
||||
|
||||
-- Output slicing / calcolo
|
||||
bounding_box_x_mm numeric(10, 3),
|
||||
@@ -680,6 +686,24 @@ CREATE TABLE IF NOT EXISTS quote_line_items
|
||||
CREATE INDEX IF NOT EXISTS ix_quote_line_items_session
|
||||
ON quote_line_items (quote_session_id);
|
||||
|
||||
ALTER TABLE quote_line_items
|
||||
ADD COLUMN IF NOT EXISTS material_code text;
|
||||
|
||||
ALTER TABLE quote_line_items
|
||||
ADD COLUMN IF NOT EXISTS nozzle_diameter_mm numeric(5, 2);
|
||||
|
||||
ALTER TABLE quote_line_items
|
||||
ADD COLUMN IF NOT EXISTS layer_height_mm numeric(6, 3);
|
||||
|
||||
ALTER TABLE quote_line_items
|
||||
ADD COLUMN IF NOT EXISTS infill_pattern text;
|
||||
|
||||
ALTER TABLE quote_line_items
|
||||
ADD COLUMN IF NOT EXISTS infill_percent integer;
|
||||
|
||||
ALTER TABLE quote_line_items
|
||||
ADD COLUMN IF NOT EXISTS supports_enabled boolean;
|
||||
|
||||
-- Vista utile per totale quote
|
||||
CREATE OR REPLACE VIEW quote_session_totals AS
|
||||
SELECT qs.quote_session_id,
|
||||
@@ -895,6 +919,94 @@ CREATE TABLE IF NOT EXISTS custom_quote_request_attachments
|
||||
CREATE INDEX IF NOT EXISTS ix_custom_quote_attachments_request
|
||||
ON custom_quote_request_attachments (request_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS media_asset
|
||||
(
|
||||
media_asset_id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
original_filename text NOT NULL,
|
||||
storage_key text NOT NULL UNIQUE,
|
||||
mime_type text NOT NULL,
|
||||
file_size_bytes bigint NOT NULL CHECK (file_size_bytes >= 0),
|
||||
sha256_hex text NOT NULL,
|
||||
width_px integer,
|
||||
height_px integer,
|
||||
status text NOT NULL CHECK (status IN ('UPLOADED', 'PROCESSING', 'READY', 'FAILED', 'ARCHIVED')),
|
||||
visibility text NOT NULL CHECK (visibility IN ('PUBLIC', 'PRIVATE')),
|
||||
title text,
|
||||
alt_text text,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS ix_media_asset_status_visibility_created_at
|
||||
ON media_asset (status, visibility, created_at DESC);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS media_variant
|
||||
(
|
||||
media_variant_id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
media_asset_id uuid NOT NULL REFERENCES media_asset (media_asset_id) ON DELETE CASCADE,
|
||||
variant_name text NOT NULL,
|
||||
format text NOT NULL CHECK (format IN ('ORIGINAL', 'JPEG', 'WEBP', 'AVIF')),
|
||||
storage_key text NOT NULL UNIQUE,
|
||||
mime_type text NOT NULL,
|
||||
width_px integer NOT NULL,
|
||||
height_px integer NOT NULL,
|
||||
file_size_bytes bigint NOT NULL CHECK (file_size_bytes >= 0),
|
||||
is_generated boolean NOT NULL DEFAULT true,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT uq_media_variant_asset_name_format UNIQUE (media_asset_id, variant_name, format)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS ix_media_variant_asset
|
||||
ON media_variant (media_asset_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS media_usage
|
||||
(
|
||||
media_usage_id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
usage_type text NOT NULL,
|
||||
usage_key text NOT NULL,
|
||||
owner_id uuid,
|
||||
media_asset_id uuid NOT NULL REFERENCES media_asset (media_asset_id) ON DELETE CASCADE,
|
||||
sort_order integer NOT NULL DEFAULT 0,
|
||||
is_primary boolean NOT NULL DEFAULT false,
|
||||
is_active boolean NOT NULL DEFAULT true,
|
||||
title_it text,
|
||||
title_en text,
|
||||
title_de text,
|
||||
title_fr text,
|
||||
alt_text_it text,
|
||||
alt_text_en text,
|
||||
alt_text_de text,
|
||||
alt_text_fr text,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS ix_media_usage_scope
|
||||
ON media_usage (usage_type, usage_key, is_active, sort_order);
|
||||
|
||||
ALTER TABLE media_usage
|
||||
ADD COLUMN IF NOT EXISTS title_it text;
|
||||
|
||||
ALTER TABLE media_usage
|
||||
ADD COLUMN IF NOT EXISTS title_en text;
|
||||
|
||||
ALTER TABLE media_usage
|
||||
ADD COLUMN IF NOT EXISTS title_de text;
|
||||
|
||||
ALTER TABLE media_usage
|
||||
ADD COLUMN IF NOT EXISTS title_fr text;
|
||||
|
||||
ALTER TABLE media_usage
|
||||
ADD COLUMN IF NOT EXISTS alt_text_it text;
|
||||
|
||||
ALTER TABLE media_usage
|
||||
ADD COLUMN IF NOT EXISTS alt_text_en text;
|
||||
|
||||
ALTER TABLE media_usage
|
||||
ADD COLUMN IF NOT EXISTS alt_text_de text;
|
||||
|
||||
ALTER TABLE media_usage
|
||||
ADD COLUMN IF NOT EXISTS alt_text_fr text;
|
||||
|
||||
ALTER TABLE quote_sessions
|
||||
DROP CONSTRAINT IF EXISTS fk_quote_sessions_source_request;
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
services:
|
||||
backend:
|
||||
# L'immagine usa il tag specificato nel file .env o passato da riga di comando
|
||||
# Nginx esterno deve servire /media/ con un alias verso
|
||||
# /mnt/cache/appdata/print-calculator/${ENV}/storage_media/public/
|
||||
image: ${REGISTRY_URL}/${REPO_OWNER}/print-calculator-backend:${TAG}
|
||||
container_name: print-calculator-backend-${ENV}
|
||||
ports:
|
||||
@@ -13,6 +15,7 @@ services:
|
||||
- CLAMAV_HOST=${CLAMAV_HOST}
|
||||
- CLAMAV_PORT=${CLAMAV_PORT}
|
||||
- CLAMAV_ENABLED=${CLAMAV_ENABLED}
|
||||
- TWINT_PAYMENT_URL=${TWINT_PAYMENT_URL:-}
|
||||
- MAIL_HOST=${MAIL_HOST:-mail.infomaniak.com}
|
||||
- MAIL_PORT=${MAIL_PORT:-587}
|
||||
- MAIL_USERNAME=${MAIL_USERNAME:-info@3d-fab.ch}
|
||||
@@ -28,6 +31,10 @@ services:
|
||||
- ADMIN_SESSION_TTL_MINUTES=${ADMIN_SESSION_TTL_MINUTES:-480}
|
||||
- TEMP_DIR=/app/temp
|
||||
- PROFILES_DIR=/app/profiles
|
||||
- MEDIA_STORAGE_ROOT=${MEDIA_STORAGE_ROOT:-/app/storage_media}
|
||||
- MEDIA_PUBLIC_BASE_URL=${MEDIA_PUBLIC_BASE_URL:-http://localhost:8080/media}
|
||||
- MEDIA_FFMPEG_PATH=${MEDIA_FFMPEG_PATH:-ffmpeg}
|
||||
- MEDIA_UPLOAD_MAX_FILE_SIZE_BYTES=${MEDIA_UPLOAD_MAX_FILE_SIZE_BYTES:-26214400}
|
||||
restart: always
|
||||
logging:
|
||||
driver: "json-file"
|
||||
@@ -39,6 +46,7 @@ services:
|
||||
- /mnt/cache/appdata/print-calculator/${ENV}/storage_quotes:/app/storage_quotes
|
||||
- /mnt/cache/appdata/print-calculator/${ENV}/storage_orders:/app/storage_orders
|
||||
- /mnt/cache/appdata/print-calculator/${ENV}/storage_requests:/app/storage_requests
|
||||
- /mnt/cache/appdata/print-calculator/${ENV}/storage_media:/app/storage_media
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
|
||||
|
||||
21
frontend/public/robots.txt
Normal file
21
frontend/public/robots.txt
Normal file
@@ -0,0 +1,21 @@
|
||||
User-agent: *
|
||||
Allow: /
|
||||
|
||||
Disallow: /admin
|
||||
Disallow: /admin/
|
||||
Disallow: /*/admin
|
||||
Disallow: /*/admin/
|
||||
Disallow: /order/
|
||||
Disallow: /*/order/
|
||||
Disallow: /co/
|
||||
Disallow: /*/co/
|
||||
Disallow: /checkout
|
||||
Disallow: /checkout/
|
||||
Disallow: /*/checkout
|
||||
Disallow: /*/checkout/
|
||||
Disallow: /shop
|
||||
Disallow: /shop/
|
||||
Disallow: /*/shop
|
||||
Disallow: /*/shop/
|
||||
|
||||
Sitemap: https://3d-fab.ch/sitemap.xml
|
||||
144
frontend/public/sitemap.xml
Normal file
144
frontend/public/sitemap.xml
Normal file
@@ -0,0 +1,144 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<urlset
|
||||
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
|
||||
xmlns:xhtml="http://www.w3.org/1999/xhtml"
|
||||
>
|
||||
<url>
|
||||
<loc>https://3d-fab.ch/it</loc>
|
||||
<xhtml:link rel="alternate" hreflang="it" href="https://3d-fab.ch/it" />
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://3d-fab.ch/en" />
|
||||
<xhtml:link rel="alternate" hreflang="de" href="https://3d-fab.ch/de" />
|
||||
<xhtml:link rel="alternate" hreflang="fr" href="https://3d-fab.ch/fr" />
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://3d-fab.ch/it" />
|
||||
<changefreq>weekly</changefreq>
|
||||
<priority>1.0</priority>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://3d-fab.ch/it/calculator/basic</loc>
|
||||
<xhtml:link
|
||||
rel="alternate"
|
||||
hreflang="it"
|
||||
href="https://3d-fab.ch/it/calculator/basic"
|
||||
/>
|
||||
<xhtml:link
|
||||
rel="alternate"
|
||||
hreflang="en"
|
||||
href="https://3d-fab.ch/en/calculator/basic"
|
||||
/>
|
||||
<xhtml:link
|
||||
rel="alternate"
|
||||
hreflang="de"
|
||||
href="https://3d-fab.ch/de/calculator/basic"
|
||||
/>
|
||||
<xhtml:link
|
||||
rel="alternate"
|
||||
hreflang="fr"
|
||||
href="https://3d-fab.ch/fr/calculator/basic"
|
||||
/>
|
||||
<xhtml:link
|
||||
rel="alternate"
|
||||
hreflang="x-default"
|
||||
href="https://3d-fab.ch/it/calculator/basic"
|
||||
/>
|
||||
<changefreq>weekly</changefreq>
|
||||
<priority>0.9</priority>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://3d-fab.ch/it/calculator/advanced</loc>
|
||||
<xhtml:link
|
||||
rel="alternate"
|
||||
hreflang="it"
|
||||
href="https://3d-fab.ch/it/calculator/advanced"
|
||||
/>
|
||||
<xhtml:link
|
||||
rel="alternate"
|
||||
hreflang="en"
|
||||
href="https://3d-fab.ch/en/calculator/advanced"
|
||||
/>
|
||||
<xhtml:link
|
||||
rel="alternate"
|
||||
hreflang="de"
|
||||
href="https://3d-fab.ch/de/calculator/advanced"
|
||||
/>
|
||||
<xhtml:link
|
||||
rel="alternate"
|
||||
hreflang="fr"
|
||||
href="https://3d-fab.ch/fr/calculator/advanced"
|
||||
/>
|
||||
<xhtml:link
|
||||
rel="alternate"
|
||||
hreflang="x-default"
|
||||
href="https://3d-fab.ch/it/calculator/advanced"
|
||||
/>
|
||||
<changefreq>weekly</changefreq>
|
||||
<priority>0.8</priority>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://3d-fab.ch/it/about</loc>
|
||||
<xhtml:link rel="alternate" hreflang="it" href="https://3d-fab.ch/it/about" />
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://3d-fab.ch/en/about" />
|
||||
<xhtml:link rel="alternate" hreflang="de" href="https://3d-fab.ch/de/about" />
|
||||
<xhtml:link rel="alternate" hreflang="fr" href="https://3d-fab.ch/fr/about" />
|
||||
<xhtml:link
|
||||
rel="alternate"
|
||||
hreflang="x-default"
|
||||
href="https://3d-fab.ch/it/about"
|
||||
/>
|
||||
<changefreq>monthly</changefreq>
|
||||
<priority>0.7</priority>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://3d-fab.ch/it/contact</loc>
|
||||
<xhtml:link
|
||||
rel="alternate"
|
||||
hreflang="it"
|
||||
href="https://3d-fab.ch/it/contact"
|
||||
/>
|
||||
<xhtml:link
|
||||
rel="alternate"
|
||||
hreflang="en"
|
||||
href="https://3d-fab.ch/en/contact"
|
||||
/>
|
||||
<xhtml:link
|
||||
rel="alternate"
|
||||
hreflang="de"
|
||||
href="https://3d-fab.ch/de/contact"
|
||||
/>
|
||||
<xhtml:link
|
||||
rel="alternate"
|
||||
hreflang="fr"
|
||||
href="https://3d-fab.ch/fr/contact"
|
||||
/>
|
||||
<xhtml:link
|
||||
rel="alternate"
|
||||
hreflang="x-default"
|
||||
href="https://3d-fab.ch/it/contact"
|
||||
/>
|
||||
<changefreq>monthly</changefreq>
|
||||
<priority>0.7</priority>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://3d-fab.ch/it/privacy</loc>
|
||||
<xhtml:link rel="alternate" hreflang="it" href="https://3d-fab.ch/it/privacy" />
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://3d-fab.ch/en/privacy" />
|
||||
<xhtml:link rel="alternate" hreflang="de" href="https://3d-fab.ch/de/privacy" />
|
||||
<xhtml:link rel="alternate" hreflang="fr" href="https://3d-fab.ch/fr/privacy" />
|
||||
<xhtml:link
|
||||
rel="alternate"
|
||||
hreflang="x-default"
|
||||
href="https://3d-fab.ch/it/privacy"
|
||||
/>
|
||||
<changefreq>yearly</changefreq>
|
||||
<priority>0.4</priority>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://3d-fab.ch/it/terms</loc>
|
||||
<xhtml:link rel="alternate" hreflang="it" href="https://3d-fab.ch/it/terms" />
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://3d-fab.ch/en/terms" />
|
||||
<xhtml:link rel="alternate" hreflang="de" href="https://3d-fab.ch/de/terms" />
|
||||
<xhtml:link rel="alternate" hreflang="fr" href="https://3d-fab.ch/fr/terms" />
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://3d-fab.ch/it/terms" />
|
||||
<changefreq>yearly</changefreq>
|
||||
<priority>0.4</priority>
|
||||
</url>
|
||||
</urlset>
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Component } from '@angular/core';
|
||||
import { Component, inject } from '@angular/core';
|
||||
import { RouterOutlet } from '@angular/router';
|
||||
import { SeoService } from './core/services/seo.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-root',
|
||||
@@ -8,4 +9,6 @@ import { RouterOutlet } from '@angular/router';
|
||||
templateUrl: './app.component.html',
|
||||
styleUrl: './app.component.scss',
|
||||
})
|
||||
export class AppComponent {}
|
||||
export class AppComponent {
|
||||
private readonly seoService = inject(SeoService);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,11 @@ const appChildRoutes: Routes = [
|
||||
path: '',
|
||||
loadComponent: () =>
|
||||
import('./features/home/home.component').then((m) => m.HomeComponent),
|
||||
data: {
|
||||
seoTitle: '3D fab | Stampa 3D su misura',
|
||||
seoDescription:
|
||||
'Servizio di stampa 3D con preventivo online immediato per prototipi, piccole serie e pezzi personalizzati.',
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'calculator',
|
||||
@@ -12,21 +17,42 @@ const appChildRoutes: Routes = [
|
||||
import('./features/calculator/calculator.routes').then(
|
||||
(m) => m.CALCULATOR_ROUTES,
|
||||
),
|
||||
data: {
|
||||
seoTitle: 'Calcolatore preventivo stampa 3D | 3D fab',
|
||||
seoDescription:
|
||||
'Carica il file 3D e ottieni prezzo e tempi in pochi secondi con slicing reale.',
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'shop',
|
||||
loadChildren: () =>
|
||||
import('./features/shop/shop.routes').then((m) => m.SHOP_ROUTES),
|
||||
data: {
|
||||
seoTitle: 'Shop 3D fab',
|
||||
seoDescription:
|
||||
'Catalogo prodotti stampati in 3D e soluzioni tecniche pronte all uso.',
|
||||
seoRobots: 'noindex, nofollow',
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'about',
|
||||
loadChildren: () =>
|
||||
import('./features/about/about.routes').then((m) => m.ABOUT_ROUTES),
|
||||
data: {
|
||||
seoTitle: 'Chi siamo | 3D fab',
|
||||
seoDescription:
|
||||
'Scopri il team 3D fab e il laboratorio di stampa 3D con sedi in Ticino e Bienne.',
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'contact',
|
||||
loadChildren: () =>
|
||||
import('./features/contact/contact.routes').then((m) => m.CONTACT_ROUTES),
|
||||
data: {
|
||||
seoTitle: 'Contatti | 3D fab',
|
||||
seoDescription:
|
||||
'Contatta 3D fab per preventivi, supporto tecnico e richieste personalizzate di stampa 3D.',
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'checkout/cad',
|
||||
@@ -34,6 +60,10 @@ const appChildRoutes: Routes = [
|
||||
import('./features/checkout/checkout.component').then(
|
||||
(m) => m.CheckoutComponent,
|
||||
),
|
||||
data: {
|
||||
seoTitle: 'Checkout | 3D fab',
|
||||
seoRobots: 'noindex, nofollow',
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'checkout',
|
||||
@@ -41,16 +71,28 @@ const appChildRoutes: Routes = [
|
||||
import('./features/checkout/checkout.component').then(
|
||||
(m) => m.CheckoutComponent,
|
||||
),
|
||||
data: {
|
||||
seoTitle: 'Checkout | 3D fab',
|
||||
seoRobots: 'noindex, nofollow',
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'order/:orderId',
|
||||
loadComponent: () =>
|
||||
import('./features/order/order.component').then((m) => m.OrderComponent),
|
||||
data: {
|
||||
seoTitle: 'Ordine | 3D fab',
|
||||
seoRobots: 'noindex, nofollow',
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'co/:orderId',
|
||||
loadComponent: () =>
|
||||
import('./features/order/order.component').then((m) => m.OrderComponent),
|
||||
data: {
|
||||
seoTitle: 'Ordine | 3D fab',
|
||||
seoRobots: 'noindex, nofollow',
|
||||
},
|
||||
},
|
||||
{
|
||||
path: '',
|
||||
@@ -61,6 +103,10 @@ const appChildRoutes: Routes = [
|
||||
path: 'admin',
|
||||
loadChildren: () =>
|
||||
import('./features/admin/admin.routes').then((m) => m.ADMIN_ROUTES),
|
||||
data: {
|
||||
seoTitle: 'Admin | 3D fab',
|
||||
seoRobots: 'noindex, nofollow',
|
||||
},
|
||||
},
|
||||
{
|
||||
path: '**',
|
||||
|
||||
264
frontend/src/app/core/services/public-media.service.ts
Normal file
264
frontend/src/app/core/services/public-media.service.ts
Normal file
@@ -0,0 +1,264 @@
|
||||
import { inject, Injectable, Injector } from '@angular/core';
|
||||
import { toObservable } from '@angular/core/rxjs-interop';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import {
|
||||
Observable,
|
||||
combineLatest,
|
||||
map,
|
||||
of,
|
||||
catchError,
|
||||
distinctUntilChanged,
|
||||
switchMap,
|
||||
} from 'rxjs';
|
||||
import { environment } from '../../../environments/environment';
|
||||
import { LanguageService } from './language.service';
|
||||
|
||||
export type PublicMediaUsageType = string;
|
||||
export type PublicMediaPreset = 'thumb' | 'card' | 'hero';
|
||||
|
||||
export interface PublicMediaVariantDto {
|
||||
avifUrl: string | null;
|
||||
webpUrl: string | null;
|
||||
jpegUrl: string | null;
|
||||
}
|
||||
|
||||
export interface PublicMediaUsageDto {
|
||||
mediaAssetId: string;
|
||||
title: string | null;
|
||||
altText: string | null;
|
||||
usageType: string;
|
||||
usageKey: string;
|
||||
sortOrder: number;
|
||||
isPrimary: boolean;
|
||||
thumb: PublicMediaVariantDto | null;
|
||||
card: PublicMediaVariantDto | null;
|
||||
hero: PublicMediaVariantDto | null;
|
||||
}
|
||||
|
||||
export interface PublicMediaSourceSet {
|
||||
preset: PublicMediaPreset;
|
||||
avifUrl: string | null;
|
||||
webpUrl: string | null;
|
||||
jpegUrl: string | null;
|
||||
fallbackUrl: string | null;
|
||||
}
|
||||
|
||||
export interface PublicMediaResolvedSourceSet
|
||||
extends Omit<PublicMediaSourceSet, 'fallbackUrl'> {
|
||||
fallbackUrl: string;
|
||||
}
|
||||
|
||||
export interface PublicMediaImage {
|
||||
mediaAssetId: string;
|
||||
title: string | null;
|
||||
altText: string | null;
|
||||
usageType: string;
|
||||
usageKey: string;
|
||||
sortOrder: number;
|
||||
isPrimary: boolean;
|
||||
thumb: PublicMediaSourceSet;
|
||||
card: PublicMediaSourceSet;
|
||||
hero: PublicMediaSourceSet;
|
||||
}
|
||||
|
||||
export interface PublicMediaDisplayImage
|
||||
extends Omit<PublicMediaImage, 'thumb' | 'card' | 'hero'> {
|
||||
source: PublicMediaResolvedSourceSet;
|
||||
}
|
||||
|
||||
export interface PublicMediaUsageRequest {
|
||||
usageType: PublicMediaUsageType;
|
||||
usageKey: string;
|
||||
}
|
||||
|
||||
export type PublicMediaUsageCollectionMap = Record<
|
||||
string,
|
||||
readonly PublicMediaImage[]
|
||||
>;
|
||||
|
||||
export function buildPublicMediaUsageScopeKey(
|
||||
usageType: string,
|
||||
usageKey: string,
|
||||
): string {
|
||||
return `${usageType}::${usageKey}`;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class PublicMediaService {
|
||||
private readonly http = inject(HttpClient);
|
||||
private readonly injector = inject(Injector);
|
||||
private readonly languageService = inject(LanguageService);
|
||||
private readonly baseUrl = `${environment.apiUrl}/api/public/media`;
|
||||
private readonly selectedLang$ = toObservable(
|
||||
this.languageService.currentLang,
|
||||
{
|
||||
injector: this.injector,
|
||||
},
|
||||
).pipe(distinctUntilChanged());
|
||||
|
||||
getUsageMedia(
|
||||
usageType: PublicMediaUsageType,
|
||||
usageKey: string,
|
||||
): Observable<readonly PublicMediaImage[]> {
|
||||
return this.selectedLang$.pipe(
|
||||
switchMap((lang) => {
|
||||
const params = new HttpParams()
|
||||
.set('usageType', usageType)
|
||||
.set('usageKey', usageKey)
|
||||
.set('lang', lang);
|
||||
|
||||
return this.http
|
||||
.get<PublicMediaUsageDto[]>(`${this.baseUrl}/usages`, { params })
|
||||
.pipe(
|
||||
map((items) =>
|
||||
items
|
||||
.map((item) => this.mapUsageDto(item))
|
||||
.filter((item) => this.hasAnyFallback(item)),
|
||||
),
|
||||
catchError(() => of([])),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
getUsageCollections(
|
||||
requests: readonly PublicMediaUsageRequest[],
|
||||
): Observable<PublicMediaUsageCollectionMap> {
|
||||
if (requests.length === 0) {
|
||||
return of({});
|
||||
}
|
||||
|
||||
return combineLatest(
|
||||
requests.map((request) =>
|
||||
this.getUsageMedia(request.usageType, request.usageKey).pipe(
|
||||
map(
|
||||
(items) =>
|
||||
[
|
||||
buildPublicMediaUsageScopeKey(
|
||||
request.usageType,
|
||||
request.usageKey,
|
||||
),
|
||||
items,
|
||||
] as const,
|
||||
),
|
||||
),
|
||||
),
|
||||
).pipe(
|
||||
map((entries) =>
|
||||
entries.reduce<PublicMediaUsageCollectionMap>((acc, [key, value]) => {
|
||||
acc[key] = value;
|
||||
return acc;
|
||||
}, {}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
pickPrimaryUsage(
|
||||
items: readonly PublicMediaImage[],
|
||||
): PublicMediaImage | null {
|
||||
if (items.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return items.find((item) => item.isPrimary) ?? items[0] ?? null;
|
||||
}
|
||||
|
||||
toDisplayImage(
|
||||
item: PublicMediaImage,
|
||||
preferredPreset: PublicMediaPreset,
|
||||
): PublicMediaDisplayImage | null {
|
||||
const source = this.pickPresetSource(item, preferredPreset);
|
||||
if (!source) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
mediaAssetId: item.mediaAssetId,
|
||||
title: item.title,
|
||||
altText: item.altText,
|
||||
usageType: item.usageType,
|
||||
usageKey: item.usageKey,
|
||||
sortOrder: item.sortOrder,
|
||||
isPrimary: item.isPrimary,
|
||||
source,
|
||||
};
|
||||
}
|
||||
|
||||
private mapUsageDto(item: PublicMediaUsageDto): PublicMediaImage {
|
||||
return {
|
||||
mediaAssetId: item.mediaAssetId,
|
||||
title: item.title ?? null,
|
||||
altText: item.altText ?? null,
|
||||
usageType: item.usageType,
|
||||
usageKey: item.usageKey,
|
||||
sortOrder: item.sortOrder,
|
||||
isPrimary: item.isPrimary,
|
||||
thumb: this.mapPreset(item.thumb, 'thumb'),
|
||||
card: this.mapPreset(item.card, 'card'),
|
||||
hero: this.mapPreset(item.hero, 'hero'),
|
||||
};
|
||||
}
|
||||
|
||||
private mapPreset(
|
||||
preset: PublicMediaVariantDto | null | undefined,
|
||||
presetName: PublicMediaPreset,
|
||||
): PublicMediaSourceSet {
|
||||
const avifUrl = this.normalizeUrl(preset?.avifUrl);
|
||||
const webpUrl = this.normalizeUrl(preset?.webpUrl);
|
||||
const jpegUrl = this.normalizeUrl(preset?.jpegUrl);
|
||||
|
||||
return {
|
||||
preset: presetName,
|
||||
avifUrl,
|
||||
webpUrl,
|
||||
jpegUrl,
|
||||
fallbackUrl: jpegUrl ?? webpUrl ?? avifUrl,
|
||||
};
|
||||
}
|
||||
|
||||
private pickPresetSource(
|
||||
item: PublicMediaImage,
|
||||
preferredPreset: PublicMediaPreset,
|
||||
): PublicMediaResolvedSourceSet | null {
|
||||
const presetOrder = this.buildPresetFallbackOrder(preferredPreset);
|
||||
const source = presetOrder
|
||||
.map((preset) => item[preset])
|
||||
.find((sourceSet) => sourceSet.fallbackUrl !== null);
|
||||
|
||||
if (!source || source.fallbackUrl === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
preset: source.preset,
|
||||
avifUrl: source.avifUrl,
|
||||
webpUrl: source.webpUrl,
|
||||
jpegUrl: source.jpegUrl,
|
||||
fallbackUrl: source.fallbackUrl,
|
||||
};
|
||||
}
|
||||
|
||||
private buildPresetFallbackOrder(
|
||||
preferredPreset: PublicMediaPreset,
|
||||
): readonly PublicMediaPreset[] {
|
||||
switch (preferredPreset) {
|
||||
case 'thumb':
|
||||
return ['thumb', 'card', 'hero'];
|
||||
case 'card':
|
||||
return ['card', 'thumb', 'hero'];
|
||||
case 'hero':
|
||||
return ['hero', 'card', 'thumb'];
|
||||
}
|
||||
}
|
||||
|
||||
private hasAnyFallback(item: PublicMediaImage): boolean {
|
||||
return [item.thumb, item.card, item.hero].some(
|
||||
(preset) => preset.fallbackUrl !== null,
|
||||
);
|
||||
}
|
||||
|
||||
private normalizeUrl(value: string | null | undefined): string | null {
|
||||
return value && value.trim() ? value : null;
|
||||
}
|
||||
}
|
||||
129
frontend/src/app/core/services/seo.service.ts
Normal file
129
frontend/src/app/core/services/seo.service.ts
Normal file
@@ -0,0 +1,129 @@
|
||||
import { DOCUMENT } from '@angular/common';
|
||||
import { Inject, Injectable } from '@angular/core';
|
||||
import { Title, Meta } from '@angular/platform-browser';
|
||||
import { ActivatedRouteSnapshot, NavigationEnd, Router } from '@angular/router';
|
||||
import { filter } from 'rxjs/operators';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class SeoService {
|
||||
private readonly defaultTitle = '3D fab | Stampa 3D su misura';
|
||||
private readonly defaultDescription =
|
||||
'Stampa 3D su misura con preventivo online immediato. Carica il file, scegli materiale e qualità, ricevi prezzo e tempi in pochi secondi.';
|
||||
private readonly supportedLangs = new Set(['it', 'en', 'de', 'fr']);
|
||||
|
||||
constructor(
|
||||
private router: Router,
|
||||
private titleService: Title,
|
||||
private metaService: Meta,
|
||||
@Inject(DOCUMENT) private document: Document,
|
||||
) {
|
||||
this.applyRouteSeo(this.router.routerState.snapshot.root);
|
||||
this.router.events
|
||||
.pipe(
|
||||
filter(
|
||||
(event): event is NavigationEnd => event instanceof NavigationEnd,
|
||||
),
|
||||
)
|
||||
.subscribe(() => {
|
||||
this.applyRouteSeo(this.router.routerState.snapshot.root);
|
||||
});
|
||||
}
|
||||
|
||||
private applyRouteSeo(rootSnapshot: ActivatedRouteSnapshot): void {
|
||||
const mergedData = this.getMergedRouteData(rootSnapshot);
|
||||
const title = this.asString(mergedData['seoTitle']) ?? this.defaultTitle;
|
||||
const description =
|
||||
this.asString(mergedData['seoDescription']) ?? this.defaultDescription;
|
||||
const robots = this.asString(mergedData['seoRobots']) ?? 'index, follow';
|
||||
|
||||
this.titleService.setTitle(title);
|
||||
this.metaService.updateTag({ name: 'description', content: description });
|
||||
this.metaService.updateTag({ name: 'robots', content: robots });
|
||||
this.metaService.updateTag({ property: 'og:title', content: title });
|
||||
this.metaService.updateTag({
|
||||
property: 'og:description',
|
||||
content: description,
|
||||
});
|
||||
this.metaService.updateTag({ property: 'og:type', content: 'website' });
|
||||
this.metaService.updateTag({ name: 'twitter:card', content: 'summary' });
|
||||
|
||||
const cleanPath = this.getCleanPath(this.router.url);
|
||||
const canonical = `${this.document.location.origin}${cleanPath}`;
|
||||
this.metaService.updateTag({ property: 'og:url', content: canonical });
|
||||
this.updateCanonicalTag(canonical);
|
||||
this.updateLangAndAlternates(cleanPath);
|
||||
}
|
||||
|
||||
private getMergedRouteData(
|
||||
snapshot: ActivatedRouteSnapshot,
|
||||
): Record<string, unknown> {
|
||||
const merged: Record<string, unknown> = {};
|
||||
let cursor: ActivatedRouteSnapshot | null = snapshot;
|
||||
while (cursor) {
|
||||
Object.assign(merged, cursor.data ?? {});
|
||||
cursor = cursor.firstChild;
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
private asString(value: unknown): string | undefined {
|
||||
return typeof value === 'string' ? value : undefined;
|
||||
}
|
||||
|
||||
private getCleanPath(url: string): string {
|
||||
const path = (url || '/').split('?')[0].split('#')[0];
|
||||
return path || '/';
|
||||
}
|
||||
|
||||
private updateCanonicalTag(url: string): void {
|
||||
let link = this.document.head.querySelector(
|
||||
'link[rel="canonical"]',
|
||||
) as HTMLLinkElement | null;
|
||||
if (!link) {
|
||||
link = this.document.createElement('link');
|
||||
link.setAttribute('rel', 'canonical');
|
||||
this.document.head.appendChild(link);
|
||||
}
|
||||
link.setAttribute('href', url);
|
||||
}
|
||||
|
||||
private updateLangAndAlternates(path: string): void {
|
||||
const segments = path.split('/').filter(Boolean);
|
||||
const firstSegment = segments[0]?.toLowerCase();
|
||||
const hasLang = Boolean(
|
||||
firstSegment && this.supportedLangs.has(firstSegment),
|
||||
);
|
||||
const lang = hasLang ? firstSegment : 'it';
|
||||
const suffixSegments = hasLang ? segments.slice(1) : segments;
|
||||
const suffix =
|
||||
suffixSegments.length > 0 ? `/${suffixSegments.join('/')}` : '';
|
||||
|
||||
this.document.documentElement.lang = lang;
|
||||
|
||||
this.document.head
|
||||
.querySelectorAll('link[rel="alternate"][data-seo-managed="true"]')
|
||||
.forEach((node) => node.remove());
|
||||
|
||||
for (const alt of ['it', 'en', 'de', 'fr']) {
|
||||
this.appendAlternateLink(
|
||||
alt,
|
||||
`${this.document.location.origin}/${alt}${suffix}`,
|
||||
);
|
||||
}
|
||||
this.appendAlternateLink(
|
||||
'x-default',
|
||||
`${this.document.location.origin}/it${suffix}`,
|
||||
);
|
||||
}
|
||||
|
||||
private appendAlternateLink(hreflang: string, href: string): void {
|
||||
const link = this.document.createElement('link');
|
||||
link.setAttribute('rel', 'alternate');
|
||||
link.setAttribute('hreflang', hreflang);
|
||||
link.setAttribute('href', href);
|
||||
link.setAttribute('data-seo-managed', 'true');
|
||||
this.document.head.appendChild(link);
|
||||
}
|
||||
}
|
||||
@@ -39,10 +39,22 @@
|
||||
(keydown.space)="toggleSelectedMember('joe'); $event.preventDefault()"
|
||||
>
|
||||
<div class="placeholder-img">
|
||||
<img
|
||||
src="assets/images/joe.jpg"
|
||||
[attr.alt]="'ABOUT.MEMBER_JOE_ALT' | translate"
|
||||
/>
|
||||
@if (joeImage(); as image) {
|
||||
<picture>
|
||||
@if (image.source.avifUrl) {
|
||||
<source [srcset]="image.source.avifUrl" type="image/avif" />
|
||||
}
|
||||
@if (image.source.webpUrl) {
|
||||
<source [srcset]="image.source.webpUrl" type="image/webp" />
|
||||
}
|
||||
<img
|
||||
[src]="image.source.fallbackUrl"
|
||||
[attr.alt]="
|
||||
image.altText || ('ABOUT.MEMBER_JOE_ALT' | translate)
|
||||
"
|
||||
/>
|
||||
</picture>
|
||||
}
|
||||
</div>
|
||||
<div class="member-info">
|
||||
<span class="member-name">{{
|
||||
@@ -71,10 +83,22 @@
|
||||
"
|
||||
>
|
||||
<div class="placeholder-img">
|
||||
<img
|
||||
src="assets/images/matteo.jpg"
|
||||
[attr.alt]="'ABOUT.MEMBER_MATTEO_ALT' | translate"
|
||||
/>
|
||||
@if (matteoImage(); as image) {
|
||||
<picture>
|
||||
@if (image.source.avifUrl) {
|
||||
<source [srcset]="image.source.avifUrl" type="image/avif" />
|
||||
}
|
||||
@if (image.source.webpUrl) {
|
||||
<source [srcset]="image.source.webpUrl" type="image/webp" />
|
||||
}
|
||||
<img
|
||||
[src]="image.source.fallbackUrl"
|
||||
[attr.alt]="
|
||||
image.altText || ('ABOUT.MEMBER_MATTEO_ALT' | translate)
|
||||
"
|
||||
/>
|
||||
</picture>
|
||||
}
|
||||
</div>
|
||||
<div class="member-info">
|
||||
<span class="member-name">{{
|
||||
|
||||
@@ -193,6 +193,12 @@ h1 {
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.placeholder-img picture {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.member-info {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,15 @@
|
||||
import { Component } from '@angular/core';
|
||||
import { Component, computed, inject } from '@angular/core';
|
||||
import { toSignal } from '@angular/core/rxjs-interop';
|
||||
import { TranslateModule } from '@ngx-translate/core';
|
||||
import { AppLocationsComponent } from '../../shared/components/app-locations/app-locations.component';
|
||||
import {
|
||||
buildPublicMediaUsageScopeKey,
|
||||
PublicMediaDisplayImage,
|
||||
PublicMediaService,
|
||||
PublicMediaUsageCollectionMap,
|
||||
} from '../../core/services/public-media.service';
|
||||
|
||||
const EMPTY_MEDIA_COLLECTIONS: PublicMediaUsageCollectionMap = {};
|
||||
|
||||
type MemberId = 'joe' | 'matteo';
|
||||
type PassionId =
|
||||
@@ -32,6 +41,39 @@ interface PassionChip {
|
||||
styleUrl: './about-page.component.scss',
|
||||
})
|
||||
export class AboutPageComponent {
|
||||
private readonly publicMediaService = inject(PublicMediaService);
|
||||
private readonly mediaByUsage = toSignal(
|
||||
this.publicMediaService.getUsageCollections([
|
||||
{
|
||||
usageType: 'ABOUT_MEMBER',
|
||||
usageKey: 'joe',
|
||||
},
|
||||
{
|
||||
usageType: 'ABOUT_MEMBER',
|
||||
usageKey: 'matteo',
|
||||
},
|
||||
]),
|
||||
{ initialValue: EMPTY_MEDIA_COLLECTIONS },
|
||||
);
|
||||
|
||||
readonly joeImage = computed<PublicMediaDisplayImage | null>(() => {
|
||||
const image = this.publicMediaService.pickPrimaryUsage(
|
||||
this.mediaByUsage()[
|
||||
buildPublicMediaUsageScopeKey('ABOUT_MEMBER', 'joe')
|
||||
] ?? [],
|
||||
);
|
||||
return image ? this.publicMediaService.toDisplayImage(image, 'card') : null;
|
||||
});
|
||||
|
||||
readonly matteoImage = computed<PublicMediaDisplayImage | null>(() => {
|
||||
const image = this.publicMediaService.pickPrimaryUsage(
|
||||
this.mediaByUsage()[
|
||||
buildPublicMediaUsageScopeKey('ABOUT_MEMBER', 'matteo')
|
||||
] ?? [],
|
||||
);
|
||||
return image ? this.publicMediaService.toDisplayImage(image, 'card') : null;
|
||||
});
|
||||
|
||||
selectedMember: MemberId | null = null;
|
||||
hoveredMember: MemberId | null = null;
|
||||
|
||||
|
||||
@@ -2,5 +2,13 @@ import { Routes } from '@angular/router';
|
||||
import { AboutPageComponent } from './about-page.component';
|
||||
|
||||
export const ABOUT_ROUTES: Routes = [
|
||||
{ path: '', component: AboutPageComponent },
|
||||
{
|
||||
path: '',
|
||||
component: AboutPageComponent,
|
||||
data: {
|
||||
seoTitle: 'Chi siamo | 3D fab',
|
||||
seoDescription:
|
||||
'Siamo un laboratorio di stampa 3D orientato a prototipi, ricambi e produzioni su misura.',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
@@ -57,6 +57,13 @@ export const ADMIN_ROUTES: Routes = [
|
||||
(m) => m.AdminCadInvoicesComponent,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'home-media',
|
||||
loadComponent: () =>
|
||||
import('./pages/admin-home-media.component').then(
|
||||
(m) => m.AdminHomeMediaComponent,
|
||||
),
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
|
||||
.page-header h1 {
|
||||
margin: 0;
|
||||
font-size: 1.45rem;
|
||||
}
|
||||
|
||||
.page-header p {
|
||||
@@ -43,7 +44,8 @@ button:disabled {
|
||||
}
|
||||
|
||||
.create-box h2 {
|
||||
margin-top: 0;
|
||||
margin: 0 0 var(--space-3);
|
||||
font-size: 1.05rem;
|
||||
}
|
||||
|
||||
.form-grid {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user