53 Commits

Author SHA1 Message Date
379a2161ca Merge remote-tracking branch 'origin/feat/ssr' into feat/ssr
All checks were successful
PR Checks / test-backend (pull_request) Successful in 26s
PR Checks / test-frontend (pull_request) Successful in 59s
PR Checks / prettier-autofix (pull_request) Successful in 8s
PR Checks / security-sast (pull_request) Successful in 30s
2026-03-11 16:57:07 +01:00
c47a7e28c7 feat(front-end): ssr implementation 2026-03-11 16:57:03 +01:00
printcalc-ci
502126c915 style: apply prettier formatting 2026-03-11 15:37:29 +00:00
2ace632022 feat(front-end): ssr implementation
Some checks failed
PR Checks / prettier-autofix (pull_request) Successful in 11s
PR Checks / test-frontend (pull_request) Failing after 57s
PR Checks / security-sast (pull_request) Successful in 30s
PR Checks / test-backend (pull_request) Successful in 27s
2026-03-11 16:37:08 +01:00
b7dfc53bc0 feat(front-end): update header layout
All checks were successful
PR Checks / prettier-autofix (pull_request) Successful in 8s
PR Checks / security-sast (pull_request) Successful in 28s
PR Checks / test-backend (pull_request) Successful in 28s
Build and Deploy / test-backend (push) Successful in 28s
PR Checks / test-frontend (pull_request) Successful in 1m4s
Build and Deploy / test-frontend (push) Successful in 1m2s
Build and Deploy / build-and-push (push) Successful in 48s
Build and Deploy / deploy (push) Successful in 11s
2026-03-11 15:30:21 +01:00
d77c3c7a5c feat(front-end): update header layout
Some checks failed
Build and Deploy / test-frontend (push) Successful in 1m6s
Build and Deploy / test-backend (push) Successful in 27s
PR Checks / prettier-autofix (pull_request) Successful in 8s
PR Checks / security-sast (pull_request) Successful in 36s
Build and Deploy / deploy (push) Has been cancelled
Build and Deploy / build-and-push (push) Has been cancelled
PR Checks / test-backend (pull_request) Successful in 27s
PR Checks / test-frontend (pull_request) Successful in 1m1s
2026-03-11 15:28:40 +01:00
printcalc-ci
faaa59ae01 style: apply prettier formatting 2026-03-11 14:18:47 +00:00
1bde2690b6 Merge branch 'main' into dev
Some checks failed
PR Checks / prettier-autofix (pull_request) Successful in 11s
PR Checks / test-frontend (pull_request) Successful in 1m3s
Build and Deploy / test-frontend (push) Successful in 59s
Build and Deploy / build-and-push (push) Failing after 1m41s
Build and Deploy / deploy (push) Has been skipped
PR Checks / security-sast (pull_request) Successful in 29s
PR Checks / test-backend (pull_request) Successful in 28s
Build and Deploy / test-backend (push) Successful in 28s
2026-03-11 15:17:52 +01:00
92fddd9e4a Merge remote-tracking branch 'origin/dev' into dev
Some checks failed
Build and Deploy / build-and-push (push) Has been cancelled
Build and Deploy / deploy (push) Has been cancelled
Build and Deploy / test-backend (push) Has been cancelled
Build and Deploy / test-frontend (push) Has been cancelled
PR Checks / prettier-autofix (pull_request) Failing after 11s
PR Checks / security-sast (pull_request) Successful in 29s
PR Checks / test-backend (pull_request) Successful in 27s
PR Checks / test-frontend (pull_request) Successful in 1m4s
2026-03-11 15:17:32 +01:00
f9414b2db7 feat(front-end): sitemap update 2026-03-11 15:17:19 +01:00
d1e7e7eaca feat(front-end): sitemap 2026-03-11 15:07:12 +01:00
75929a15f8 Merge pull request 'fix(front-end): fix security' (#39) from dev into main
All checks were successful
Build and Deploy / test-backend (push) Successful in 26s
Build and Deploy / test-frontend (push) Successful in 1m5s
Build and Deploy / build-and-push (push) Successful in 15s
Build and Deploy / deploy (push) Successful in 7s
Reviewed-on: #39
2026-03-11 11:42:50 +01:00
c0585d7107 Merge branch 'main' into dev
All checks were successful
PR Checks / prettier-autofix (pull_request) Successful in 8s
PR Checks / security-sast (pull_request) Successful in 30s
PR Checks / test-backend (pull_request) Successful in 31s
Build and Deploy / test-backend (push) Successful in 26s
PR Checks / test-frontend (pull_request) Successful in 1m1s
Build and Deploy / test-frontend (push) Successful in 1m1s
Build and Deploy / build-and-push (push) Successful in 57s
Build and Deploy / deploy (push) Successful in 12s
2026-03-11 11:39:59 +01:00
aeeed1c138 fix(front-end): fix security
Some checks failed
Build and Deploy / build-and-push (push) Has been cancelled
Build and Deploy / deploy (push) Has been cancelled
Build and Deploy / test-frontend (push) Has been cancelled
Build and Deploy / test-backend (push) Has been cancelled
PR Checks / prettier-autofix (pull_request) Successful in 8s
PR Checks / security-sast (pull_request) Successful in 31s
PR Checks / test-backend (pull_request) Successful in 27s
PR Checks / test-frontend (pull_request) Successful in 1m3s
2026-03-11 11:39:45 +01:00
10f05fabc9 Merge pull request 'dev' (#38) from dev into main
All checks were successful
Build and Deploy / test-frontend (push) Successful in 1m1s
Build and Deploy / deploy (push) Successful in 7s
Build and Deploy / test-backend (push) Successful in 26s
Build and Deploy / build-and-push (push) Successful in 16s
Reviewed-on: #38
2026-03-11 11:05:12 +01:00
78b719d3c2 fix(front-end): fix security
All checks were successful
Build and Deploy / test-backend (push) Successful in 26s
PR Checks / prettier-autofix (pull_request) Successful in 8s
Build and Deploy / test-frontend (push) Successful in 1m5s
PR Checks / security-sast (pull_request) Successful in 36s
PR Checks / test-backend (pull_request) Successful in 27s
Build and Deploy / build-and-push (push) Successful in 23s
PR Checks / test-frontend (pull_request) Successful in 1m1s
Build and Deploy / deploy (push) Successful in 9s
2026-03-11 11:02:47 +01:00
printcalc-ci
052ade3e91 style: apply prettier formatting 2026-03-11 09:59:12 +00:00
035851133e Merge branch 'main' into dev
Some checks failed
Build and Deploy / test-backend (push) Successful in 30s
PR Checks / prettier-autofix (pull_request) Successful in 13s
Build and Deploy / test-frontend (push) Successful in 1m4s
PR Checks / security-sast (pull_request) Failing after 27s
PR Checks / test-backend (pull_request) Successful in 27s
Build and Deploy / build-and-push (push) Successful in 16s
Build and Deploy / deploy (push) Successful in 11s
PR Checks / test-frontend (pull_request) Successful in 1m2s
2026-03-11 10:57:23 +01:00
1ff8883d25 fix(back-end): fix hex color
Some checks failed
Build and Deploy / test-backend (push) Successful in 26s
Build and Deploy / test-frontend (push) Successful in 1m0s
Build and Deploy / build-and-push (push) Successful in 23s
Build and Deploy / deploy (push) Successful in 8s
PR Checks / prettier-autofix (pull_request) Failing after 11s
PR Checks / security-sast (pull_request) Failing after 29s
PR Checks / test-backend (pull_request) Successful in 27s
PR Checks / test-frontend (pull_request) Successful in 1m3s
2026-03-11 10:29:29 +01:00
30ada043ef fix(back-end): fix hex color
All checks were successful
Build and Deploy / test-backend (push) Successful in 26s
Build and Deploy / test-frontend (push) Successful in 1m1s
Build and Deploy / build-and-push (push) Successful in 34s
Build and Deploy / deploy (push) Successful in 9s
2026-03-11 10:21:15 +01:00
e0aaa7c92e fix(back-end): fix hex color
All checks were successful
Build and Deploy / test-backend (push) Successful in 35s
Build and Deploy / test-frontend (push) Successful in 1m1s
Build and Deploy / build-and-push (push) Successful in 1m43s
Build and Deploy / deploy (push) Successful in 10s
2026-03-11 10:14:30 +01:00
edae13541f feat(back-end): rich text improvements
All checks were successful
Build and Deploy / test-backend (push) Successful in 28s
Build and Deploy / test-frontend (push) Successful in 1m3s
Build and Deploy / build-and-push (push) Successful in 27s
Build and Deploy / deploy (push) Successful in 8s
2026-03-10 19:01:17 +01:00
d150c19f9f feat(back-end): rich text
All checks were successful
Build and Deploy / test-backend (push) Successful in 53s
Build and Deploy / test-frontend (push) Successful in 1m3s
Build and Deploy / build-and-push (push) Successful in 57s
Build and Deploy / deploy (push) Successful in 8s
2026-03-10 18:51:15 +01:00
71890e4cc2 feat(front-end): rich text
All checks were successful
Build and Deploy / test-backend (push) Successful in 30s
Build and Deploy / test-frontend (push) Successful in 1m3s
Build and Deploy / build-and-push (push) Successful in 25s
Build and Deploy / deploy (push) Successful in 9s
2026-03-10 18:48:27 +01:00
95494efcae Merge pull request 'dev' (#37) from dev into main
All checks were successful
Build and Deploy / test-backend (push) Successful in 31s
Build and Deploy / test-frontend (push) Successful in 1m5s
Build and Deploy / build-and-push (push) Successful in 18s
Build and Deploy / deploy (push) Successful in 9s
Reviewed-on: #37
2026-03-10 17:43:45 +01:00
8893a80c12 feat(front-end): update media ffmpeg
All checks were successful
Build and Deploy / test-backend (push) Successful in 29s
PR Checks / prettier-autofix (pull_request) Successful in 9s
PR Checks / security-sast (pull_request) Successful in 33s
Build and Deploy / test-frontend (push) Successful in 1m6s
PR Checks / test-frontend (pull_request) Successful in 1m3s
PR Checks / test-backend (pull_request) Successful in 28s
Build and Deploy / build-and-push (push) Successful in 1m40s
Build and Deploy / deploy (push) Successful in 11s
2026-03-10 17:29:38 +01:00
a4facf74d7 feat(front-end): update media ffmpeg
Some checks failed
Build and Deploy / test-backend (push) Successful in 29s
PR Checks / prettier-autofix (pull_request) Successful in 13s
Build and Deploy / test-frontend (push) Successful in 1m3s
PR Checks / security-sast (pull_request) Successful in 32s
PR Checks / test-backend (pull_request) Successful in 29s
PR Checks / test-frontend (pull_request) Successful in 1m6s
Build and Deploy / build-and-push (push) Failing after 1m0s
Build and Deploy / deploy (push) Has been skipped
2026-03-10 17:20:45 +01:00
ed8fd89217 Merge remote-tracking branch 'origin/dev' into dev
All checks were successful
Build and Deploy / test-backend (push) Successful in 26s
PR Checks / security-sast (pull_request) Successful in 31s
Build and Deploy / test-frontend (push) Successful in 1m2s
PR Checks / prettier-autofix (pull_request) Successful in 8s
PR Checks / test-backend (pull_request) Successful in 30s
Build and Deploy / build-and-push (push) Successful in 28s
PR Checks / test-frontend (pull_request) Successful in 1m3s
Build and Deploy / deploy (push) Successful in 9s
2026-03-10 15:32:59 +01:00
58869be9f7 feat(front-end): css allert fix 2026-03-10 15:32:53 +01:00
fda0174a77 Merge branch 'main' into dev
All checks were successful
Build and Deploy / test-backend (push) Successful in 26s
PR Checks / prettier-autofix (pull_request) Successful in 8s
Build and Deploy / test-frontend (push) Successful in 1m5s
PR Checks / security-sast (pull_request) Successful in 36s
PR Checks / test-backend (pull_request) Successful in 29s
Build and Deploy / build-and-push (push) Successful in 25s
PR Checks / test-frontend (pull_request) Successful in 1m3s
Build and Deploy / deploy (push) Successful in 12s
2026-03-10 15:25:51 +01:00
printcalc-ci
52c6239f6d style: apply prettier formatting 2026-03-10 14:23:52 +00:00
c007cee093 feat(front-end): shop category ui
All checks were successful
Build and Deploy / test-backend (push) Successful in 27s
Build and Deploy / test-frontend (push) Successful in 1m3s
PR Checks / test-backend (pull_request) Successful in 27s
PR Checks / prettier-autofix (pull_request) Successful in 12s
PR Checks / security-sast (pull_request) Successful in 31s
Build and Deploy / build-and-push (push) Successful in 26s
PR Checks / test-frontend (pull_request) Successful in 1m3s
Build and Deploy / deploy (push) Successful in 13s
2026-03-10 15:23:08 +01:00
d011268d20 feat(front-end): shop category ui
Some checks failed
Build and Deploy / test-backend (push) Successful in 28s
Build and Deploy / test-frontend (push) Successful in 1m4s
Build and Deploy / build-and-push (push) Failing after 44s
Build and Deploy / deploy (push) Has been skipped
2026-03-10 15:14:10 +01:00
126d3ef4c4 feat(back-end front-end): shop route 2026-03-10 15:04:56 +01:00
3f228ef6e2 feat(back-end front-end): shop feature 2026-03-10 15:04:49 +01:00
8733184dc5 Merge branch 'feat/shop' into dev
All checks were successful
Build and Deploy / test-backend (push) Successful in 31s
Build and Deploy / test-frontend (push) Successful in 1m4s
Build and Deploy / build-and-push (push) Successful in 38s
Build and Deploy / deploy (push) Successful in 10s
2026-03-10 12:42:42 +01:00
5f815d8a54 fix(back-end) url construction for media 2026-03-10 12:42:26 +01:00
6d491eb694 Merge pull request 'feat/shop' (#36) from feat/shop into dev
All checks were successful
Build and Deploy / test-backend (push) Successful in 27s
Build and Deploy / test-frontend (push) Successful in 1m3s
Build and Deploy / build-and-push (push) Successful in 50s
Build and Deploy / deploy (push) Successful in 11s
Reviewed-on: #36
2026-03-10 11:16:22 +01:00
printcalc-ci
42e0e75d70 style: apply prettier formatting 2026-03-10 10:15:56 +00:00
c24e27a9db Merge remote-tracking branch 'origin/feat/shop' into feat/shop
All checks were successful
PR Checks / prettier-autofix (pull_request) Successful in 11s
PR Checks / test-frontend (pull_request) Successful in 1m4s
PR Checks / security-sast (pull_request) Successful in 29s
PR Checks / test-backend (pull_request) Successful in 26s
# Conflicts:
#	frontend/src/app/features/shop/shop-page.component.scss
2026-03-10 11:15:32 +01:00
3d12ae4da4 feat(front-end): ui improvements and alligment 2026-03-10 11:15:25 +01:00
printcalc-ci
b9e6916dfe style: apply prettier formatting 2026-03-10 09:54:16 +00:00
7cd9ef53b5 Merge remote-tracking branch 'origin/feat/shop' into feat/shop
All checks were successful
PR Checks / prettier-autofix (pull_request) Successful in 11s
PR Checks / security-sast (pull_request) Successful in 30s
PR Checks / test-backend (pull_request) Successful in 26s
PR Checks / test-frontend (pull_request) Successful in 1m1s
# Conflicts:
#	frontend/src/app/features/shop/components/product-card/product-card.component.scss
#	frontend/src/app/features/shop/product-detail.component.scss
#	frontend/src/app/features/shop/shop-page.component.html
#	frontend/src/app/features/shop/shop-page.component.scss
#	frontend/src/app/features/shop/shop-page.component.ts
2026-03-10 10:53:42 +01:00
e747a9820e feat(front-end): back-office desing improvements 2026-03-10 10:53:30 +01:00
ba6940e64b Merge branch 'dev' into feat/shop
All checks were successful
PR Checks / prettier-autofix (pull_request) Successful in 8s
PR Checks / security-sast (pull_request) Successful in 29s
PR Checks / test-backend (pull_request) Successful in 27s
PR Checks / test-frontend (pull_request) Successful in 58s
2026-03-10 09:21:28 +01:00
printcalc-ci
4342e9b1b1 style: apply prettier formatting 2026-03-10 07:32:17 +00:00
a212a1d8cc feat(back-end): shop ui implementation
All checks were successful
PR Checks / prettier-autofix (pull_request) Successful in 19s
PR Checks / security-sast (pull_request) Successful in 34s
PR Checks / test-backend (pull_request) Successful in 29s
PR Checks / test-frontend (pull_request) Successful in 59s
2026-03-10 08:31:29 +01:00
cd0c13203f feat(back-end): category and shop implementation 2026-03-09 20:32:13 +01:00
77d7bdb265 fix(back-end): img convert
All checks were successful
Build and Deploy / test-backend (push) Successful in 26s
Build and Deploy / test-frontend (push) Successful in 1m1s
Build and Deploy / build-and-push (push) Successful in 39s
Build and Deploy / deploy (push) Successful in 8s
2026-03-09 20:04:21 +01:00
fb5e753769 feat(back-end) shop logic 2026-03-09 19:58:53 +01:00
c953232f3c feat(back-end) entities for shop 2026-03-09 19:50:00 +01:00
cd2666d8e2 Merge pull request 'feat/shop' (#35) from feat/shop into dev
All checks were successful
Build and Deploy / test-backend (push) Successful in 25s
Build and Deploy / test-frontend (push) Successful in 59s
Build and Deploy / build-and-push (push) Successful in 28s
Build and Deploy / deploy (push) Successful in 10s
Reviewed-on: #35
2026-03-09 19:31:12 +01:00
3ab518a9b6 Merge pull request 'dev' (#29) from dev into main
All checks were successful
Build and Deploy / test-backend (push) Successful in 26s
Build and Deploy / test-frontend (push) Successful in 1m2s
Build and Deploy / build-and-push (push) Successful in 18s
Build and Deploy / deploy (push) Successful in 9s
Reviewed-on: #29
2026-03-09 09:58:45 +01:00
158 changed files with 19477 additions and 1186 deletions

View File

@@ -125,6 +125,18 @@ jobs:
docker build -t "$FRONTEND_IMAGE" ./frontend docker build -t "$FRONTEND_IMAGE" ./frontend
docker push "$FRONTEND_IMAGE" docker push "$FRONTEND_IMAGE"
- name: Cleanup Docker on runner (prevent vdisk growth)
if: always()
shell: bash
run: |
set +e
# Keep recent artifacts, drop old local residue from CI builds.
docker container prune -f --filter "until=168h" || true
docker image prune -a -f --filter "until=168h" || true
docker builder prune -a -f --filter "until=168h" || true
docker network prune -f --filter "until=168h" || true
deploy: deploy:
needs: build-and-push needs: build-and-push
runs-on: ubuntu-latest runs-on: ubuntu-latest

2
.gitignore vendored
View File

@@ -46,10 +46,12 @@ build/
./storage_quotes ./storage_quotes
./storage_requests ./storage_requests
./storage_media ./storage_media
./storage_shop
storage_orders storage_orders
storage_quotes storage_quotes
storage_requests storage_requests
storage_media storage_media
storage_shop
# Qodana local reports/artifacts # Qodana local reports/artifacts
backend/.qodana/ backend/.qodana/

View File

@@ -32,8 +32,8 @@ Crea un database PostgreSQL chiamato `printcalc`. Lo schema viene gestito dal pr
Configura il percorso di OrcaSlicer in `backend/src/main/resources/application.properties` o tramite la variabile d'ambiente `SLICER_PATH`. Per il media service pubblico puoi configurare anche: Configura il percorso di OrcaSlicer in `backend/src/main/resources/application.properties` o tramite la variabile d'ambiente `SLICER_PATH`. Per il media service pubblico puoi configurare anche:
- `MEDIA_STORAGE_ROOT` per la root `storage_media` usata dal backend (`original/`, `public/`, `private/`) - `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` - `SHOP_STORAGE_ROOT` per la root `storage_shop` usata dal backend per i modelli dei prodotti shop
- `MEDIA_FFMPEG_PATH` per il binario `ffmpeg` - `MEDIA_FFMPEG_PATH` per il binario `ffmpeg` (nel deploy Docker default: `/usr/local/bin/ffmpeg-media`)
- `MEDIA_UPLOAD_MAX_FILE_SIZE_BYTES` per il limite per asset immagine - `MEDIA_UPLOAD_MAX_FILE_SIZE_BYTES` per il limite per asset immagine
```bash ```bash
@@ -64,12 +64,13 @@ I prezzi non sono più gestiti tramite variabili d'ambiente fisse ma tramite tab
* `/frontend`: Applicazione Angular. * `/frontend`: Applicazione Angular.
* `/backend/profiles`: Contiene i file di configurazione per OrcaSlicer. * `/backend/profiles`: Contiene i file di configurazione per OrcaSlicer.
* `/storage_media`: Originali e varianti media pubbliche/private su filesystem. * `/storage_media`: Originali e varianti media pubbliche/private su filesystem.
* `/storage_shop`: Modelli e file prodotti dello shop.
## Media pubblici ## 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. 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`. Nel deploy Docker i volumi attesi sono `/mnt/cache/appdata/print-calculator/${ENV}/storage_media:/app/storage_media` e `/mnt/cache/appdata/print-calculator/${ENV}/storage_shop:/app/storage_shop`.
Nginx non deve passare dal backend per i file pubblici. Configurazione attesa: Nginx non deve passare dal backend per i file pubblici. Configurazione attesa:
@@ -106,7 +107,7 @@ Operativamente:
Assicurati che `slicer.path` punti al binario corretto. Su macOS è solitamente `/Applications/OrcaSlicer.app/Contents/MacOS/OrcaSlicer`. Su Linux è il percorso all'AppImage (estratta o meno). Assicurati che `slicer.path` punti al binario corretto. Su macOS è solitamente `/Applications/OrcaSlicer.app/Contents/MacOS/OrcaSlicer`. Su Linux è il percorso all'AppImage (estratta o meno).
### FFmpeg e media pubblici ### 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. Verifica che `MEDIA_FFMPEG_PATH` punti a un `ffmpeg` con supporto JPEG, WebP e AVIF (encoder + muxer AVIF). Nel container backend il default è `/usr/local/bin/ffmpeg-media`: usa `/usr/bin/ffmpeg` se già compatibile, altrimenti installa un fallback statico con supporto AVIF. Se gli URL media restituiti dalle API admin non sono raggiungibili, controlla che `APP_FRONTEND_BASE_URL` punti al dominio corretto, che `location /media/` sia esposto da Nginx e che il volume `storage_media` sia montato correttamente.
### Database connection ### Database connection
Verifica le credenziali in `application.properties`. Se usi Docker, puoi passare `DB_URL`, `DB_USERNAME` e `DB_PASSWORD` come variabili d'ambiente. Verifica le credenziali in `application.properties`. Se usi Docker, puoi passare `DB_URL`, `DB_USERNAME` e `DB_PASSWORD` come variabili d'ambiente.

View File

@@ -12,25 +12,48 @@ RUN ./gradlew bootJar -x test --no-daemon
FROM eclipse-temurin:21-jre-jammy FROM eclipse-temurin:21-jre-jammy
ARG ORCA_VERSION=2.3.1 ARG ORCA_VERSION=2.3.1
ARG ORCA_DOWNLOAD_URL ARG ORCA_DOWNLOAD_URL
ARG FFMPEG_STATIC_URL=https://johnvansickle.com/ffmpeg/releases/ffmpeg-release-amd64-static.tar.xz
# Install system dependencies for OrcaSlicer and media processing. # Install system dependencies for OrcaSlicer and media processing.
# The build fails fast if the packaged ffmpeg lacks JPEG/WebP/AVIF encoders. # Prefer system ffmpeg; if AVIF support is incomplete, install a static ffmpeg fallback.
RUN set -eux; \ RUN set -eux; \
apt-get update; \ apt-get update; \
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
ffmpeg \ ffmpeg \
wget \ wget \
xz-utils \
ca-certificates \
assimp-utils \ assimp-utils \
libgl1 \ libgl1 \
libglib2.0-0 \ libglib2.0-0 \
libgtk-3-0 \ libgtk-3-0 \
libdbus-1-3 \ libdbus-1-3 \
libwebkit2gtk-4.0-37; \ libwebkit2gtk-4.0-37; \
ffmpeg -hide_banner -encoders > /tmp/ffmpeg-encoders.txt; \ check_ffmpeg_support() { \
grep -Eq '[[:space:]]mjpeg[[:space:]]' /tmp/ffmpeg-encoders.txt; \ ffmpeg_bin="$1"; \
grep -Eq '[[:space:]](libwebp|webp)[[:space:]]' /tmp/ffmpeg-encoders.txt; \ "$ffmpeg_bin" -hide_banner -encoders > /tmp/ffmpeg-encoders.txt 2>&1 || return 1; \
grep -Eq '[[:space:]](libaom-av1|librav1e|libsvtav1)[[:space:]]' /tmp/ffmpeg-encoders.txt; \ "$ffmpeg_bin" -hide_banner -muxers > /tmp/ffmpeg-muxers.txt 2>&1 || return 1; \
grep -Eq '[[:space:]]mjpeg[[:space:]]' /tmp/ffmpeg-encoders.txt || return 1; \
grep -Eq '[[:space:]](libwebp|webp)[[:space:]]' /tmp/ffmpeg-encoders.txt || return 1; \
grep -Eq '[[:space:]](libaom-av1|librav1e|libsvtav1)[[:space:]]' /tmp/ffmpeg-encoders.txt || return 1; \
grep -Eq '[[:space:]]avif([[:space:]]|,|$)' /tmp/ffmpeg-muxers.txt || return 1; \
return 0; \
}; \
if check_ffmpeg_support /usr/bin/ffmpeg; then \
ln -sf /usr/bin/ffmpeg /usr/local/bin/ffmpeg-media; \
else \
echo "System ffmpeg lacks AVIF support, installing static fallback from ${FFMPEG_STATIC_URL}"; \
wget -q "${FFMPEG_STATIC_URL}" -O /tmp/ffmpeg-static.tar.xz; \
tar -xJf /tmp/ffmpeg-static.tar.xz -C /tmp; \
FFMPEG_STATIC_BIN="$(find /tmp -maxdepth 2 -type f -name ffmpeg | head -n 1)"; \
test -n "${FFMPEG_STATIC_BIN}"; \
install -m 0755 "${FFMPEG_STATIC_BIN}" /usr/local/bin/ffmpeg-media; \
check_ffmpeg_support /usr/local/bin/ffmpeg-media; \
fi; \
rm -f /tmp/ffmpeg-muxers.txt; \
rm -f /tmp/ffmpeg-encoders.txt; \ rm -f /tmp/ffmpeg-encoders.txt; \
rm -f /tmp/ffmpeg-static.tar.xz; \
rm -rf /tmp/ffmpeg-*-amd64-static; \
rm -rf /var/lib/apt/lists/* rm -rf /var/lib/apt/lists/*
# Install OrcaSlicer # Install OrcaSlicer
@@ -71,6 +94,8 @@ ENV PATH="/opt/orcaslicer/usr/bin:${PATH}"
# Set Slicer Path env variable for Java app # Set Slicer Path env variable for Java app
ENV SLICER_PATH="/opt/orcaslicer/AppRun" ENV SLICER_PATH="/opt/orcaslicer/AppRun"
ENV ASSIMP_PATH="assimp" ENV ASSIMP_PATH="assimp"
# Use ffmpeg selected at image build time (system or static fallback) for media generation.
ENV MEDIA_FFMPEG_PATH="/usr/local/bin/ffmpeg-media"
WORKDIR /app WORKDIR /app
# Copy JAR from build stage # Copy JAR from build stage

View File

@@ -42,6 +42,7 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'net.codecrete.qrbill:qrbill-generator:3.4.0' implementation 'net.codecrete.qrbill:qrbill-generator:3.4.0'
implementation 'org.springframework.boot:spring-boot-starter-mail' implementation 'org.springframework.boot:spring-boot-starter-mail'
implementation 'org.jsoup:jsoup:1.18.3'
implementation platform('org.lwjgl:lwjgl-bom:3.3.4') implementation platform('org.lwjgl:lwjgl-bom:3.3.4')
implementation 'org.lwjgl:lwjgl' implementation 'org.lwjgl:lwjgl'
implementation 'org.lwjgl:lwjgl-assimp' implementation 'org.lwjgl:lwjgl-assimp'

View File

@@ -1,10 +1,61 @@
#!/bin/sh #!/bin/sh
set -e
# In container default to the ffmpeg selected during image build.
if [ -z "${MEDIA_FFMPEG_PATH:-}" ]; then
MEDIA_FFMPEG_PATH="/usr/local/bin/ffmpeg-media"
fi
export MEDIA_FFMPEG_PATH
validate_ffmpeg_support() {
ffmpeg_bin="$1"
if ! command -v "$ffmpeg_bin" >/dev/null 2>&1; then
echo "ERROR: FFmpeg executable not found: ${ffmpeg_bin}" >&2
exit 11
fi
encoders="$(mktemp)"
muxers="$(mktemp)"
trap 'rm -f "$encoders" "$muxers"' EXIT
"$ffmpeg_bin" -hide_banner -encoders > "$encoders" 2>&1 || {
echo "ERROR: Unable to inspect FFmpeg encoders from ${ffmpeg_bin}" >&2
cat "$encoders" >&2
exit 12
}
"$ffmpeg_bin" -hide_banner -muxers > "$muxers" 2>&1 || {
echo "ERROR: Unable to inspect FFmpeg muxers from ${ffmpeg_bin}" >&2
cat "$muxers" >&2
exit 13
}
grep -Eq '[[:space:]]mjpeg[[:space:]]' "$encoders" || {
echo "ERROR: FFmpeg '${ffmpeg_bin}' missing JPEG encoder (mjpeg)." >&2
exit 14
}
grep -Eq '[[:space:]](libwebp|webp)[[:space:]]' "$encoders" || {
echo "ERROR: FFmpeg '${ffmpeg_bin}' missing WebP encoder." >&2
exit 15
}
grep -Eq '[[:space:]](libaom-av1|librav1e|libsvtav1)[[:space:]]' "$encoders" || {
echo "ERROR: FFmpeg '${ffmpeg_bin}' missing AVIF-capable encoder." >&2
exit 16
}
grep -Eq '[[:space:]]avif([[:space:]]|,|$)' "$muxers" || {
echo "ERROR: FFmpeg '${ffmpeg_bin}' missing AVIF muxer." >&2
exit 17
}
}
validate_ffmpeg_support "$MEDIA_FFMPEG_PATH"
echo "----------------------------------------------------------------" echo "----------------------------------------------------------------"
echo "Starting Backend Application" echo "Starting Backend Application"
echo "DB_URL: $DB_URL" echo "DB_URL: $DB_URL"
echo "DB_USERNAME: $DB_USERNAME" echo "DB_USERNAME: $DB_USERNAME"
echo "SPRING_DATASOURCE_URL: $SPRING_DATASOURCE_URL" echo "SPRING_DATASOURCE_URL: $SPRING_DATASOURCE_URL"
echo "SLICER_PATH: $SLICER_PATH" echo "SLICER_PATH: $SLICER_PATH"
echo "MEDIA_FFMPEG_PATH: $MEDIA_FFMPEG_PATH"
echo "----------------------------------------------------------------" echo "----------------------------------------------------------------"
# Determine which environment variables to use for database connection # Determine which environment variables to use for database connection

View File

@@ -0,0 +1,77 @@
package com.printcalculator.controller;
import com.printcalculator.dto.ShopCategoryDetailDto;
import com.printcalculator.dto.ShopCategoryTreeDto;
import com.printcalculator.dto.ShopProductCatalogResponseDto;
import com.printcalculator.dto.ShopProductDetailDto;
import com.printcalculator.service.shop.PublicShopCatalogService;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.List;
@RestController
@RequestMapping("/api/shop")
@Transactional(readOnly = true)
public class PublicShopController {
private final PublicShopCatalogService publicShopCatalogService;
public PublicShopController(PublicShopCatalogService publicShopCatalogService) {
this.publicShopCatalogService = publicShopCatalogService;
}
@GetMapping("/categories")
public ResponseEntity<List<ShopCategoryTreeDto>> getCategories(@RequestParam(required = false) String lang) {
return ResponseEntity.ok(publicShopCatalogService.getCategories(lang));
}
@GetMapping("/categories/{slug}")
public ResponseEntity<ShopCategoryDetailDto> getCategory(@PathVariable String slug,
@RequestParam(required = false) String lang) {
return ResponseEntity.ok(publicShopCatalogService.getCategory(slug, lang));
}
@GetMapping("/products")
public ResponseEntity<ShopProductCatalogResponseDto> getProducts(
@RequestParam(required = false) String categorySlug,
@RequestParam(required = false) Boolean featured,
@RequestParam(required = false) String lang
) {
return ResponseEntity.ok(publicShopCatalogService.getProductCatalog(categorySlug, featured, lang));
}
@GetMapping("/products/{slug}")
public ResponseEntity<ShopProductDetailDto> getProduct(@PathVariable String slug,
@RequestParam(required = false) String lang) {
return ResponseEntity.ok(publicShopCatalogService.getProduct(slug, lang));
}
@GetMapping("/products/{slug}/model")
public ResponseEntity<Resource> getProductModel(@PathVariable String slug) throws IOException {
PublicShopCatalogService.ProductModelDownload model = publicShopCatalogService.getProductModelDownload(slug);
Resource resource = new UrlResource(model.path().toUri());
MediaType contentType = MediaType.APPLICATION_OCTET_STREAM;
if (model.mimeType() != null && !model.mimeType().isBlank()) {
try {
contentType = MediaType.parseMediaType(model.mimeType());
} catch (IllegalArgumentException ignored) {
contentType = MediaType.APPLICATION_OCTET_STREAM;
}
}
return ResponseEntity.ok()
.contentType(contentType)
.header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + model.filename() + "\"")
.body(resource);
}
}

View File

@@ -62,6 +62,7 @@ public class QuoteSessionController {
public ResponseEntity<QuoteSession> createSession() { public ResponseEntity<QuoteSession> createSession() {
QuoteSession session = new QuoteSession(); QuoteSession session = new QuoteSession();
session.setStatus("ACTIVE"); session.setStatus("ACTIVE");
session.setSessionType("PRINT_QUOTE");
session.setPricingVersion("v1"); session.setPricingVersion("v1");
session.setMaterialCode("PLA"); session.setMaterialCode("PLA");
session.setSupportsEnabled(false); session.setSupportsEnabled(false);

View File

@@ -0,0 +1,85 @@
package com.printcalculator.controller;
import com.printcalculator.dto.ShopCartAddItemRequest;
import com.printcalculator.dto.ShopCartUpdateItemRequest;
import com.printcalculator.service.shop.ShopCartCookieService;
import com.printcalculator.service.shop.ShopCartService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.UUID;
@RestController
@RequestMapping("/api/shop/cart")
public class ShopCartController {
private final ShopCartService shopCartService;
private final ShopCartCookieService shopCartCookieService;
public ShopCartController(ShopCartService shopCartService, ShopCartCookieService shopCartCookieService) {
this.shopCartService = shopCartService;
this.shopCartCookieService = shopCartCookieService;
}
@GetMapping
public ResponseEntity<?> getCart(HttpServletRequest request, HttpServletResponse response) {
ShopCartService.CartResult result = shopCartService.loadCart(request);
applyCookie(response, result);
return ResponseEntity.ok(result.response());
}
@PostMapping("/items")
public ResponseEntity<?> addItem(HttpServletRequest request,
HttpServletResponse response,
@Valid @RequestBody ShopCartAddItemRequest payload) {
ShopCartService.CartResult result = shopCartService.addItem(request, payload);
applyCookie(response, result);
return ResponseEntity.ok(result.response());
}
@PatchMapping("/items/{lineItemId}")
public ResponseEntity<?> updateItem(HttpServletRequest request,
HttpServletResponse response,
@PathVariable UUID lineItemId,
@Valid @RequestBody ShopCartUpdateItemRequest payload) {
ShopCartService.CartResult result = shopCartService.updateItem(request, lineItemId, payload);
applyCookie(response, result);
return ResponseEntity.ok(result.response());
}
@DeleteMapping("/items/{lineItemId}")
public ResponseEntity<?> removeItem(HttpServletRequest request,
HttpServletResponse response,
@PathVariable UUID lineItemId) {
ShopCartService.CartResult result = shopCartService.removeItem(request, lineItemId);
applyCookie(response, result);
return ResponseEntity.ok(result.response());
}
@DeleteMapping
public ResponseEntity<?> clearCart(HttpServletRequest request, HttpServletResponse response) {
ShopCartService.CartResult result = shopCartService.clearCart(request);
applyCookie(response, result);
return ResponseEntity.ok(result.response());
}
private void applyCookie(HttpServletResponse response, ShopCartService.CartResult result) {
if (result.clearCookie()) {
response.addHeader(HttpHeaders.SET_COOKIE, shopCartCookieService.buildClearCookie().toString());
return;
}
if (result.sessionId() != null) {
response.addHeader(HttpHeaders.SET_COOKIE, shopCartCookieService.buildSessionCookie(result.sessionId()).toString());
}
}
}

View File

@@ -0,0 +1,37 @@
package com.printcalculator.controller;
import com.printcalculator.service.shop.ShopSitemapService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.CacheControl;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.Duration;
@RestController
public class SitemapController {
private final ShopSitemapService shopSitemapService;
private final long cacheSeconds;
public SitemapController(
ShopSitemapService shopSitemapService,
@Value("${app.sitemap.shop.cache-seconds:3600}") long cacheSeconds
) {
this.shopSitemapService = shopSitemapService;
this.cacheSeconds = Math.max(cacheSeconds, 0L);
}
@GetMapping(value = "/api/sitemap-shop.xml", produces = MediaType.APPLICATION_XML_VALUE)
public ResponseEntity<String> getShopSitemap() {
CacheControl cacheControl = cacheSeconds > 0
? CacheControl.maxAge(Duration.ofSeconds(cacheSeconds)).cachePublic()
: CacheControl.noCache();
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType("application/xml;charset=UTF-8"))
.cacheControl(cacheControl)
.body(shopSitemapService.getShopSitemapXml());
}
}

View File

@@ -53,6 +53,13 @@ public class AdminMediaController {
return ResponseEntity.ok(adminMediaControllerService.getAsset(mediaAssetId)); return ResponseEntity.ok(adminMediaControllerService.getAsset(mediaAssetId));
} }
@GetMapping("/usages")
public ResponseEntity<List<AdminMediaUsageDto>> getUsages(@RequestParam String usageType,
@RequestParam String usageKey,
@RequestParam(required = false) UUID ownerId) {
return ResponseEntity.ok(adminMediaControllerService.getUsages(usageType, usageKey, ownerId));
}
@PatchMapping("/assets/{mediaAssetId}") @PatchMapping("/assets/{mediaAssetId}")
@Transactional @Transactional
public ResponseEntity<AdminMediaAssetDto> updateAsset(@PathVariable UUID mediaAssetId, public ResponseEntity<AdminMediaAssetDto> updateAsset(@PathVariable UUID mediaAssetId,

View File

@@ -0,0 +1,64 @@
package com.printcalculator.controller.admin;
import com.printcalculator.dto.AdminShopCategoryDto;
import com.printcalculator.dto.AdminUpsertShopCategoryRequest;
import com.printcalculator.service.admin.AdminShopCategoryControllerService;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.UUID;
@RestController
@RequestMapping("/api/admin/shop/categories")
@Transactional(readOnly = true)
public class AdminShopCategoryController {
private final AdminShopCategoryControllerService adminShopCategoryControllerService;
public AdminShopCategoryController(AdminShopCategoryControllerService adminShopCategoryControllerService) {
this.adminShopCategoryControllerService = adminShopCategoryControllerService;
}
@GetMapping
public ResponseEntity<List<AdminShopCategoryDto>> getCategories() {
return ResponseEntity.ok(adminShopCategoryControllerService.getCategories());
}
@GetMapping("/tree")
public ResponseEntity<List<AdminShopCategoryDto>> getCategoryTree() {
return ResponseEntity.ok(adminShopCategoryControllerService.getCategoryTree());
}
@GetMapping("/{categoryId}")
public ResponseEntity<AdminShopCategoryDto> getCategory(@PathVariable UUID categoryId) {
return ResponseEntity.ok(adminShopCategoryControllerService.getCategory(categoryId));
}
@PostMapping
@Transactional
public ResponseEntity<AdminShopCategoryDto> createCategory(@RequestBody AdminUpsertShopCategoryRequest payload) {
return ResponseEntity.ok(adminShopCategoryControllerService.createCategory(payload));
}
@PutMapping("/{categoryId}")
@Transactional
public ResponseEntity<AdminShopCategoryDto> updateCategory(@PathVariable UUID categoryId,
@RequestBody AdminUpsertShopCategoryRequest payload) {
return ResponseEntity.ok(adminShopCategoryControllerService.updateCategory(categoryId, payload));
}
@DeleteMapping("/{categoryId}")
@Transactional
public ResponseEntity<Void> deleteCategory(@PathVariable UUID categoryId) {
adminShopCategoryControllerService.deleteCategory(categoryId);
return ResponseEntity.noContent().build();
}
}

View File

@@ -0,0 +1,99 @@
package com.printcalculator.controller.admin;
import com.printcalculator.dto.AdminShopProductDto;
import com.printcalculator.dto.AdminUpsertShopProductRequest;
import com.printcalculator.service.admin.AdminShopProductControllerService;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
@RestController
@RequestMapping("/api/admin/shop/products")
@Transactional(readOnly = true)
public class AdminShopProductController {
private final AdminShopProductControllerService adminShopProductControllerService;
public AdminShopProductController(AdminShopProductControllerService adminShopProductControllerService) {
this.adminShopProductControllerService = adminShopProductControllerService;
}
@GetMapping
public ResponseEntity<List<AdminShopProductDto>> getProducts() {
return ResponseEntity.ok(adminShopProductControllerService.getProducts());
}
@GetMapping("/{productId}")
public ResponseEntity<AdminShopProductDto> getProduct(@PathVariable UUID productId) {
return ResponseEntity.ok(adminShopProductControllerService.getProduct(productId));
}
@PostMapping
@Transactional
public ResponseEntity<AdminShopProductDto> createProduct(@RequestBody AdminUpsertShopProductRequest payload) {
return ResponseEntity.ok(adminShopProductControllerService.createProduct(payload));
}
@PutMapping("/{productId}")
@Transactional
public ResponseEntity<AdminShopProductDto> updateProduct(@PathVariable UUID productId,
@RequestBody AdminUpsertShopProductRequest payload) {
return ResponseEntity.ok(adminShopProductControllerService.updateProduct(productId, payload));
}
@DeleteMapping("/{productId}")
@Transactional
public ResponseEntity<Void> deleteProduct(@PathVariable UUID productId) {
adminShopProductControllerService.deleteProduct(productId);
return ResponseEntity.noContent().build();
}
@PostMapping("/{productId}/model")
@Transactional
public ResponseEntity<AdminShopProductDto> uploadProductModel(@PathVariable UUID productId,
@RequestParam("file") MultipartFile file) throws IOException {
return ResponseEntity.ok(adminShopProductControllerService.uploadProductModel(productId, file));
}
@DeleteMapping("/{productId}/model")
@Transactional
public ResponseEntity<Void> deleteProductModel(@PathVariable UUID productId) {
adminShopProductControllerService.deleteProductModel(productId);
return ResponseEntity.noContent().build();
}
@GetMapping("/{productId}/model")
public ResponseEntity<Resource> getProductModel(@PathVariable UUID productId) throws IOException {
AdminShopProductControllerService.ProductModelDownload model = adminShopProductControllerService.getProductModel(productId);
Resource resource = new UrlResource(model.path().toUri());
MediaType contentType = MediaType.APPLICATION_OCTET_STREAM;
if (model.mimeType() != null && !model.mimeType().isBlank()) {
try {
contentType = MediaType.parseMediaType(model.mimeType());
} catch (IllegalArgumentException ignored) {
contentType = MediaType.APPLICATION_OCTET_STREAM;
}
}
return ResponseEntity.ok()
.contentType(contentType)
.header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + model.filename() + "\"")
.body(resource);
}
}

View File

@@ -7,6 +7,7 @@ import java.util.UUID;
public class AdminQuoteSessionDto { public class AdminQuoteSessionDto {
private UUID id; private UUID id;
private String status; private String status;
private String sessionType;
private String materialCode; private String materialCode;
private OffsetDateTime createdAt; private OffsetDateTime createdAt;
private OffsetDateTime expiresAt; private OffsetDateTime expiresAt;
@@ -32,6 +33,14 @@ public class AdminQuoteSessionDto {
this.status = status; this.status = status;
} }
public String getSessionType() {
return sessionType;
}
public void setSessionType(String sessionType) {
this.sessionType = sessionType;
}
public String getMaterialCode() { public String getMaterialCode() {
return materialCode; return materialCode;
} }

View File

@@ -0,0 +1,215 @@
package com.printcalculator.dto;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.UUID;
public class AdminShopCategoryDto {
private UUID id;
private UUID parentCategoryId;
private String parentCategoryName;
private String slug;
private String name;
private String description;
private String seoTitle;
private String seoDescription;
private String ogTitle;
private String ogDescription;
private Boolean indexable;
private Boolean isActive;
private Integer sortOrder;
private Integer depth;
private Integer childCount;
private Integer directProductCount;
private Integer descendantProductCount;
private String mediaUsageType;
private String mediaUsageKey;
private List<AdminShopCategoryRefDto> breadcrumbs;
private List<AdminShopCategoryDto> children;
private OffsetDateTime createdAt;
private OffsetDateTime updatedAt;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public UUID getParentCategoryId() {
return parentCategoryId;
}
public void setParentCategoryId(UUID parentCategoryId) {
this.parentCategoryId = parentCategoryId;
}
public String getParentCategoryName() {
return parentCategoryName;
}
public void setParentCategoryName(String parentCategoryName) {
this.parentCategoryName = parentCategoryName;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getSeoTitle() {
return seoTitle;
}
public void setSeoTitle(String seoTitle) {
this.seoTitle = seoTitle;
}
public String getSeoDescription() {
return seoDescription;
}
public void setSeoDescription(String seoDescription) {
this.seoDescription = seoDescription;
}
public String getOgTitle() {
return ogTitle;
}
public void setOgTitle(String ogTitle) {
this.ogTitle = ogTitle;
}
public String getOgDescription() {
return ogDescription;
}
public void setOgDescription(String ogDescription) {
this.ogDescription = ogDescription;
}
public Boolean getIndexable() {
return indexable;
}
public void setIndexable(Boolean indexable) {
this.indexable = indexable;
}
public Boolean getIsActive() {
return isActive;
}
public void setIsActive(Boolean active) {
isActive = active;
}
public Integer getSortOrder() {
return sortOrder;
}
public void setSortOrder(Integer sortOrder) {
this.sortOrder = sortOrder;
}
public Integer getDepth() {
return depth;
}
public void setDepth(Integer depth) {
this.depth = depth;
}
public Integer getChildCount() {
return childCount;
}
public void setChildCount(Integer childCount) {
this.childCount = childCount;
}
public Integer getDirectProductCount() {
return directProductCount;
}
public void setDirectProductCount(Integer directProductCount) {
this.directProductCount = directProductCount;
}
public Integer getDescendantProductCount() {
return descendantProductCount;
}
public void setDescendantProductCount(Integer descendantProductCount) {
this.descendantProductCount = descendantProductCount;
}
public String getMediaUsageType() {
return mediaUsageType;
}
public void setMediaUsageType(String mediaUsageType) {
this.mediaUsageType = mediaUsageType;
}
public String getMediaUsageKey() {
return mediaUsageKey;
}
public void setMediaUsageKey(String mediaUsageKey) {
this.mediaUsageKey = mediaUsageKey;
}
public List<AdminShopCategoryRefDto> getBreadcrumbs() {
return breadcrumbs;
}
public void setBreadcrumbs(List<AdminShopCategoryRefDto> breadcrumbs) {
this.breadcrumbs = breadcrumbs;
}
public List<AdminShopCategoryDto> getChildren() {
return children;
}
public void setChildren(List<AdminShopCategoryDto> children) {
this.children = children;
}
public OffsetDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(OffsetDateTime createdAt) {
this.createdAt = createdAt;
}
public OffsetDateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(OffsetDateTime updatedAt) {
this.updatedAt = updatedAt;
}
}

View File

@@ -0,0 +1,33 @@
package com.printcalculator.dto;
import java.util.UUID;
public class AdminShopCategoryRefDto {
private UUID id;
private String slug;
private String name;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@@ -0,0 +1,441 @@
package com.printcalculator.dto;
import java.math.BigDecimal;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.UUID;
public class AdminShopProductDto {
private UUID id;
private UUID categoryId;
private String categoryName;
private String categorySlug;
private String slug;
private String name;
private String nameIt;
private String nameEn;
private String nameDe;
private String nameFr;
private String excerpt;
private String excerptIt;
private String excerptEn;
private String excerptDe;
private String excerptFr;
private String description;
private String descriptionIt;
private String descriptionEn;
private String descriptionDe;
private String descriptionFr;
private String seoTitle;
private String seoTitleIt;
private String seoTitleEn;
private String seoTitleDe;
private String seoTitleFr;
private String seoDescription;
private String seoDescriptionIt;
private String seoDescriptionEn;
private String seoDescriptionDe;
private String seoDescriptionFr;
private String ogTitle;
private String ogDescription;
private Boolean indexable;
private Boolean isFeatured;
private Boolean isActive;
private Integer sortOrder;
private Integer variantCount;
private Integer activeVariantCount;
private BigDecimal priceFromChf;
private BigDecimal priceToChf;
private String mediaUsageType;
private String mediaUsageKey;
private List<AdminMediaUsageDto> mediaUsages;
private List<PublicMediaUsageDto> images;
private ShopProductModelDto model3d;
private List<AdminShopProductVariantDto> variants;
private OffsetDateTime createdAt;
private OffsetDateTime updatedAt;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public UUID getCategoryId() {
return categoryId;
}
public void setCategoryId(UUID categoryId) {
this.categoryId = categoryId;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public String getCategorySlug() {
return categorySlug;
}
public void setCategorySlug(String categorySlug) {
this.categorySlug = categorySlug;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNameIt() {
return nameIt;
}
public void setNameIt(String nameIt) {
this.nameIt = nameIt;
}
public String getNameEn() {
return nameEn;
}
public void setNameEn(String nameEn) {
this.nameEn = nameEn;
}
public String getNameDe() {
return nameDe;
}
public void setNameDe(String nameDe) {
this.nameDe = nameDe;
}
public String getNameFr() {
return nameFr;
}
public void setNameFr(String nameFr) {
this.nameFr = nameFr;
}
public String getExcerpt() {
return excerpt;
}
public void setExcerpt(String excerpt) {
this.excerpt = excerpt;
}
public String getExcerptIt() {
return excerptIt;
}
public void setExcerptIt(String excerptIt) {
this.excerptIt = excerptIt;
}
public String getExcerptEn() {
return excerptEn;
}
public void setExcerptEn(String excerptEn) {
this.excerptEn = excerptEn;
}
public String getExcerptDe() {
return excerptDe;
}
public void setExcerptDe(String excerptDe) {
this.excerptDe = excerptDe;
}
public String getExcerptFr() {
return excerptFr;
}
public void setExcerptFr(String excerptFr) {
this.excerptFr = excerptFr;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescriptionIt() {
return descriptionIt;
}
public void setDescriptionIt(String descriptionIt) {
this.descriptionIt = descriptionIt;
}
public String getDescriptionEn() {
return descriptionEn;
}
public void setDescriptionEn(String descriptionEn) {
this.descriptionEn = descriptionEn;
}
public String getDescriptionDe() {
return descriptionDe;
}
public void setDescriptionDe(String descriptionDe) {
this.descriptionDe = descriptionDe;
}
public String getDescriptionFr() {
return descriptionFr;
}
public void setDescriptionFr(String descriptionFr) {
this.descriptionFr = descriptionFr;
}
public String getSeoTitle() {
return seoTitle;
}
public void setSeoTitle(String seoTitle) {
this.seoTitle = seoTitle;
}
public String getSeoTitleIt() {
return seoTitleIt;
}
public void setSeoTitleIt(String seoTitleIt) {
this.seoTitleIt = seoTitleIt;
}
public String getSeoTitleEn() {
return seoTitleEn;
}
public void setSeoTitleEn(String seoTitleEn) {
this.seoTitleEn = seoTitleEn;
}
public String getSeoTitleDe() {
return seoTitleDe;
}
public void setSeoTitleDe(String seoTitleDe) {
this.seoTitleDe = seoTitleDe;
}
public String getSeoTitleFr() {
return seoTitleFr;
}
public void setSeoTitleFr(String seoTitleFr) {
this.seoTitleFr = seoTitleFr;
}
public String getSeoDescription() {
return seoDescription;
}
public void setSeoDescription(String seoDescription) {
this.seoDescription = seoDescription;
}
public String getSeoDescriptionIt() {
return seoDescriptionIt;
}
public void setSeoDescriptionIt(String seoDescriptionIt) {
this.seoDescriptionIt = seoDescriptionIt;
}
public String getSeoDescriptionEn() {
return seoDescriptionEn;
}
public void setSeoDescriptionEn(String seoDescriptionEn) {
this.seoDescriptionEn = seoDescriptionEn;
}
public String getSeoDescriptionDe() {
return seoDescriptionDe;
}
public void setSeoDescriptionDe(String seoDescriptionDe) {
this.seoDescriptionDe = seoDescriptionDe;
}
public String getSeoDescriptionFr() {
return seoDescriptionFr;
}
public void setSeoDescriptionFr(String seoDescriptionFr) {
this.seoDescriptionFr = seoDescriptionFr;
}
public String getOgTitle() {
return ogTitle;
}
public void setOgTitle(String ogTitle) {
this.ogTitle = ogTitle;
}
public String getOgDescription() {
return ogDescription;
}
public void setOgDescription(String ogDescription) {
this.ogDescription = ogDescription;
}
public Boolean getIndexable() {
return indexable;
}
public void setIndexable(Boolean indexable) {
this.indexable = indexable;
}
public Boolean getIsFeatured() {
return isFeatured;
}
public void setIsFeatured(Boolean featured) {
isFeatured = featured;
}
public Boolean getIsActive() {
return isActive;
}
public void setIsActive(Boolean active) {
isActive = active;
}
public Integer getSortOrder() {
return sortOrder;
}
public void setSortOrder(Integer sortOrder) {
this.sortOrder = sortOrder;
}
public Integer getVariantCount() {
return variantCount;
}
public void setVariantCount(Integer variantCount) {
this.variantCount = variantCount;
}
public Integer getActiveVariantCount() {
return activeVariantCount;
}
public void setActiveVariantCount(Integer activeVariantCount) {
this.activeVariantCount = activeVariantCount;
}
public BigDecimal getPriceFromChf() {
return priceFromChf;
}
public void setPriceFromChf(BigDecimal priceFromChf) {
this.priceFromChf = priceFromChf;
}
public BigDecimal getPriceToChf() {
return priceToChf;
}
public void setPriceToChf(BigDecimal priceToChf) {
this.priceToChf = priceToChf;
}
public String getMediaUsageType() {
return mediaUsageType;
}
public void setMediaUsageType(String mediaUsageType) {
this.mediaUsageType = mediaUsageType;
}
public String getMediaUsageKey() {
return mediaUsageKey;
}
public void setMediaUsageKey(String mediaUsageKey) {
this.mediaUsageKey = mediaUsageKey;
}
public List<AdminMediaUsageDto> getMediaUsages() {
return mediaUsages;
}
public void setMediaUsages(List<AdminMediaUsageDto> mediaUsages) {
this.mediaUsages = mediaUsages;
}
public List<PublicMediaUsageDto> getImages() {
return images;
}
public void setImages(List<PublicMediaUsageDto> images) {
this.images = images;
}
public ShopProductModelDto getModel3d() {
return model3d;
}
public void setModel3d(ShopProductModelDto model3d) {
this.model3d = model3d;
}
public List<AdminShopProductVariantDto> getVariants() {
return variants;
}
public void setVariants(List<AdminShopProductVariantDto> variants) {
this.variants = variants;
}
public OffsetDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(OffsetDateTime createdAt) {
this.createdAt = createdAt;
}
public OffsetDateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(OffsetDateTime updatedAt) {
this.updatedAt = updatedAt;
}
}

View File

@@ -0,0 +1,116 @@
package com.printcalculator.dto;
import java.math.BigDecimal;
import java.time.OffsetDateTime;
import java.util.UUID;
public class AdminShopProductVariantDto {
private UUID id;
private String sku;
private String variantLabel;
private String colorName;
private String colorHex;
private String internalMaterialCode;
private BigDecimal priceChf;
private Boolean isDefault;
private Boolean isActive;
private Integer sortOrder;
private OffsetDateTime createdAt;
private OffsetDateTime updatedAt;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getSku() {
return sku;
}
public void setSku(String sku) {
this.sku = sku;
}
public String getVariantLabel() {
return variantLabel;
}
public void setVariantLabel(String variantLabel) {
this.variantLabel = variantLabel;
}
public String getColorName() {
return colorName;
}
public void setColorName(String colorName) {
this.colorName = colorName;
}
public String getColorHex() {
return colorHex;
}
public void setColorHex(String colorHex) {
this.colorHex = colorHex;
}
public String getInternalMaterialCode() {
return internalMaterialCode;
}
public void setInternalMaterialCode(String internalMaterialCode) {
this.internalMaterialCode = internalMaterialCode;
}
public BigDecimal getPriceChf() {
return priceChf;
}
public void setPriceChf(BigDecimal priceChf) {
this.priceChf = priceChf;
}
public Boolean getIsDefault() {
return isDefault;
}
public void setIsDefault(Boolean aDefault) {
isDefault = aDefault;
}
public Boolean getIsActive() {
return isActive;
}
public void setIsActive(Boolean active) {
isActive = active;
}
public Integer getSortOrder() {
return sortOrder;
}
public void setSortOrder(Integer sortOrder) {
this.sortOrder = sortOrder;
}
public OffsetDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(OffsetDateTime createdAt) {
this.createdAt = createdAt;
}
public OffsetDateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(OffsetDateTime updatedAt) {
this.updatedAt = updatedAt;
}
}

View File

@@ -0,0 +1,105 @@
package com.printcalculator.dto;
import java.util.UUID;
public class AdminUpsertShopCategoryRequest {
private UUID parentCategoryId;
private String slug;
private String name;
private String description;
private String seoTitle;
private String seoDescription;
private String ogTitle;
private String ogDescription;
private Boolean indexable;
private Boolean isActive;
private Integer sortOrder;
public UUID getParentCategoryId() {
return parentCategoryId;
}
public void setParentCategoryId(UUID parentCategoryId) {
this.parentCategoryId = parentCategoryId;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getSeoTitle() {
return seoTitle;
}
public void setSeoTitle(String seoTitle) {
this.seoTitle = seoTitle;
}
public String getSeoDescription() {
return seoDescription;
}
public void setSeoDescription(String seoDescription) {
this.seoDescription = seoDescription;
}
public String getOgTitle() {
return ogTitle;
}
public void setOgTitle(String ogTitle) {
this.ogTitle = ogTitle;
}
public String getOgDescription() {
return ogDescription;
}
public void setOgDescription(String ogDescription) {
this.ogDescription = ogDescription;
}
public Boolean getIndexable() {
return indexable;
}
public void setIndexable(Boolean indexable) {
this.indexable = indexable;
}
public Boolean getIsActive() {
return isActive;
}
public void setIsActive(Boolean active) {
isActive = active;
}
public Integer getSortOrder() {
return sortOrder;
}
public void setSortOrder(Integer sortOrder) {
this.sortOrder = sortOrder;
}
}

View File

@@ -0,0 +1,313 @@
package com.printcalculator.dto;
import java.util.List;
import java.util.UUID;
public class AdminUpsertShopProductRequest {
private UUID categoryId;
private String slug;
private String name;
private String nameIt;
private String nameEn;
private String nameDe;
private String nameFr;
private String excerpt;
private String excerptIt;
private String excerptEn;
private String excerptDe;
private String excerptFr;
private String description;
private String descriptionIt;
private String descriptionEn;
private String descriptionDe;
private String descriptionFr;
private String seoTitle;
private String seoTitleIt;
private String seoTitleEn;
private String seoTitleDe;
private String seoTitleFr;
private String seoDescription;
private String seoDescriptionIt;
private String seoDescriptionEn;
private String seoDescriptionDe;
private String seoDescriptionFr;
private String ogTitle;
private String ogDescription;
private Boolean indexable;
private Boolean isFeatured;
private Boolean isActive;
private Integer sortOrder;
private List<AdminUpsertShopProductVariantRequest> variants;
public UUID getCategoryId() {
return categoryId;
}
public void setCategoryId(UUID categoryId) {
this.categoryId = categoryId;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNameIt() {
return nameIt;
}
public void setNameIt(String nameIt) {
this.nameIt = nameIt;
}
public String getNameEn() {
return nameEn;
}
public void setNameEn(String nameEn) {
this.nameEn = nameEn;
}
public String getNameDe() {
return nameDe;
}
public void setNameDe(String nameDe) {
this.nameDe = nameDe;
}
public String getNameFr() {
return nameFr;
}
public void setNameFr(String nameFr) {
this.nameFr = nameFr;
}
public String getExcerpt() {
return excerpt;
}
public void setExcerpt(String excerpt) {
this.excerpt = excerpt;
}
public String getExcerptIt() {
return excerptIt;
}
public void setExcerptIt(String excerptIt) {
this.excerptIt = excerptIt;
}
public String getExcerptEn() {
return excerptEn;
}
public void setExcerptEn(String excerptEn) {
this.excerptEn = excerptEn;
}
public String getExcerptDe() {
return excerptDe;
}
public void setExcerptDe(String excerptDe) {
this.excerptDe = excerptDe;
}
public String getExcerptFr() {
return excerptFr;
}
public void setExcerptFr(String excerptFr) {
this.excerptFr = excerptFr;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescriptionIt() {
return descriptionIt;
}
public void setDescriptionIt(String descriptionIt) {
this.descriptionIt = descriptionIt;
}
public String getDescriptionEn() {
return descriptionEn;
}
public void setDescriptionEn(String descriptionEn) {
this.descriptionEn = descriptionEn;
}
public String getDescriptionDe() {
return descriptionDe;
}
public void setDescriptionDe(String descriptionDe) {
this.descriptionDe = descriptionDe;
}
public String getDescriptionFr() {
return descriptionFr;
}
public void setDescriptionFr(String descriptionFr) {
this.descriptionFr = descriptionFr;
}
public String getSeoTitle() {
return seoTitle;
}
public void setSeoTitle(String seoTitle) {
this.seoTitle = seoTitle;
}
public String getSeoTitleIt() {
return seoTitleIt;
}
public void setSeoTitleIt(String seoTitleIt) {
this.seoTitleIt = seoTitleIt;
}
public String getSeoTitleEn() {
return seoTitleEn;
}
public void setSeoTitleEn(String seoTitleEn) {
this.seoTitleEn = seoTitleEn;
}
public String getSeoTitleDe() {
return seoTitleDe;
}
public void setSeoTitleDe(String seoTitleDe) {
this.seoTitleDe = seoTitleDe;
}
public String getSeoTitleFr() {
return seoTitleFr;
}
public void setSeoTitleFr(String seoTitleFr) {
this.seoTitleFr = seoTitleFr;
}
public String getSeoDescription() {
return seoDescription;
}
public void setSeoDescription(String seoDescription) {
this.seoDescription = seoDescription;
}
public String getSeoDescriptionIt() {
return seoDescriptionIt;
}
public void setSeoDescriptionIt(String seoDescriptionIt) {
this.seoDescriptionIt = seoDescriptionIt;
}
public String getSeoDescriptionEn() {
return seoDescriptionEn;
}
public void setSeoDescriptionEn(String seoDescriptionEn) {
this.seoDescriptionEn = seoDescriptionEn;
}
public String getSeoDescriptionDe() {
return seoDescriptionDe;
}
public void setSeoDescriptionDe(String seoDescriptionDe) {
this.seoDescriptionDe = seoDescriptionDe;
}
public String getSeoDescriptionFr() {
return seoDescriptionFr;
}
public void setSeoDescriptionFr(String seoDescriptionFr) {
this.seoDescriptionFr = seoDescriptionFr;
}
public String getOgTitle() {
return ogTitle;
}
public void setOgTitle(String ogTitle) {
this.ogTitle = ogTitle;
}
public String getOgDescription() {
return ogDescription;
}
public void setOgDescription(String ogDescription) {
this.ogDescription = ogDescription;
}
public Boolean getIndexable() {
return indexable;
}
public void setIndexable(Boolean indexable) {
this.indexable = indexable;
}
public Boolean getIsFeatured() {
return isFeatured;
}
public void setIsFeatured(Boolean featured) {
isFeatured = featured;
}
public Boolean getIsActive() {
return isActive;
}
public void setIsActive(Boolean active) {
isActive = active;
}
public Integer getSortOrder() {
return sortOrder;
}
public void setSortOrder(Integer sortOrder) {
this.sortOrder = sortOrder;
}
public List<AdminUpsertShopProductVariantRequest> getVariants() {
return variants;
}
public void setVariants(List<AdminUpsertShopProductVariantRequest> variants) {
this.variants = variants;
}
}

View File

@@ -0,0 +1,97 @@
package com.printcalculator.dto;
import java.math.BigDecimal;
import java.util.UUID;
public class AdminUpsertShopProductVariantRequest {
private UUID id;
private String sku;
private String variantLabel;
private String colorName;
private String colorHex;
private String internalMaterialCode;
private BigDecimal priceChf;
private Boolean isDefault;
private Boolean isActive;
private Integer sortOrder;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getSku() {
return sku;
}
public void setSku(String sku) {
this.sku = sku;
}
public String getVariantLabel() {
return variantLabel;
}
public void setVariantLabel(String variantLabel) {
this.variantLabel = variantLabel;
}
public String getColorName() {
return colorName;
}
public void setColorName(String colorName) {
this.colorName = colorName;
}
public String getColorHex() {
return colorHex;
}
public void setColorHex(String colorHex) {
this.colorHex = colorHex;
}
public String getInternalMaterialCode() {
return internalMaterialCode;
}
public void setInternalMaterialCode(String internalMaterialCode) {
this.internalMaterialCode = internalMaterialCode;
}
public BigDecimal getPriceChf() {
return priceChf;
}
public void setPriceChf(BigDecimal priceChf) {
this.priceChf = priceChf;
}
public Boolean getIsDefault() {
return isDefault;
}
public void setIsDefault(Boolean aDefault) {
isDefault = aDefault;
}
public Boolean getIsActive() {
return isActive;
}
public void setIsActive(Boolean active) {
isActive = active;
}
public Integer getSortOrder() {
return sortOrder;
}
public void setSortOrder(Integer sortOrder) {
this.sortOrder = sortOrder;
}
}

View File

@@ -8,6 +8,7 @@ import java.util.UUID;
public class OrderDto { public class OrderDto {
private UUID id; private UUID id;
private String orderNumber; private String orderNumber;
private String sourceType;
private String status; private String status;
private String paymentStatus; private String paymentStatus;
private String paymentMethod; private String paymentMethod;
@@ -45,6 +46,9 @@ public class OrderDto {
public String getOrderNumber() { return orderNumber; } public String getOrderNumber() { return orderNumber; }
public void setOrderNumber(String orderNumber) { this.orderNumber = orderNumber; } public void setOrderNumber(String orderNumber) { this.orderNumber = orderNumber; }
public String getSourceType() { return sourceType; }
public void setSourceType(String sourceType) { this.sourceType = sourceType; }
public String getStatus() { return status; } public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; } public void setStatus(String status) { this.status = status; }

View File

@@ -5,10 +5,19 @@ import java.util.UUID;
public class OrderItemDto { public class OrderItemDto {
private UUID id; private UUID id;
private String itemType;
private String originalFilename; private String originalFilename;
private String displayName;
private String materialCode; private String materialCode;
private String colorCode; private String colorCode;
private Long filamentVariantId; private Long filamentVariantId;
private UUID shopProductId;
private UUID shopProductVariantId;
private String shopProductSlug;
private String shopProductName;
private String shopVariantLabel;
private String shopVariantColorName;
private String shopVariantColorHex;
private String filamentVariantDisplayName; private String filamentVariantDisplayName;
private String filamentColorName; private String filamentColorName;
private String filamentColorHex; private String filamentColorHex;
@@ -28,9 +37,15 @@ public class OrderItemDto {
public UUID getId() { return id; } public UUID getId() { return id; }
public void setId(UUID id) { this.id = id; } public void setId(UUID id) { this.id = id; }
public String getItemType() { return itemType; }
public void setItemType(String itemType) { this.itemType = itemType; }
public String getOriginalFilename() { return originalFilename; } public String getOriginalFilename() { return originalFilename; }
public void setOriginalFilename(String originalFilename) { this.originalFilename = originalFilename; } public void setOriginalFilename(String originalFilename) { this.originalFilename = originalFilename; }
public String getDisplayName() { return displayName; }
public void setDisplayName(String displayName) { this.displayName = displayName; }
public String getMaterialCode() { return materialCode; } public String getMaterialCode() { return materialCode; }
public void setMaterialCode(String materialCode) { this.materialCode = materialCode; } public void setMaterialCode(String materialCode) { this.materialCode = materialCode; }
@@ -40,6 +55,27 @@ public class OrderItemDto {
public Long getFilamentVariantId() { return filamentVariantId; } public Long getFilamentVariantId() { return filamentVariantId; }
public void setFilamentVariantId(Long filamentVariantId) { this.filamentVariantId = filamentVariantId; } public void setFilamentVariantId(Long filamentVariantId) { this.filamentVariantId = filamentVariantId; }
public UUID getShopProductId() { return shopProductId; }
public void setShopProductId(UUID shopProductId) { this.shopProductId = shopProductId; }
public UUID getShopProductVariantId() { return shopProductVariantId; }
public void setShopProductVariantId(UUID shopProductVariantId) { this.shopProductVariantId = shopProductVariantId; }
public String getShopProductSlug() { return shopProductSlug; }
public void setShopProductSlug(String shopProductSlug) { this.shopProductSlug = shopProductSlug; }
public String getShopProductName() { return shopProductName; }
public void setShopProductName(String shopProductName) { this.shopProductName = shopProductName; }
public String getShopVariantLabel() { return shopVariantLabel; }
public void setShopVariantLabel(String shopVariantLabel) { this.shopVariantLabel = shopVariantLabel; }
public String getShopVariantColorName() { return shopVariantColorName; }
public void setShopVariantColorName(String shopVariantColorName) { this.shopVariantColorName = shopVariantColorName; }
public String getShopVariantColorHex() { return shopVariantColorHex; }
public void setShopVariantColorHex(String shopVariantColorHex) { this.shopVariantColorHex = shopVariantColorHex; }
public String getFilamentVariantDisplayName() { return filamentVariantDisplayName; } public String getFilamentVariantDisplayName() { return filamentVariantDisplayName; }
public void setFilamentVariantDisplayName(String filamentVariantDisplayName) { this.filamentVariantDisplayName = filamentVariantDisplayName; } public void setFilamentVariantDisplayName(String filamentVariantDisplayName) { this.filamentVariantDisplayName = filamentVariantDisplayName; }

View File

@@ -0,0 +1,30 @@
package com.printcalculator.dto;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import java.util.UUID;
public class ShopCartAddItemRequest {
@NotNull
private UUID shopProductVariantId;
@Min(1)
private Integer quantity = 1;
public UUID getShopProductVariantId() {
return shopProductVariantId;
}
public void setShopProductVariantId(UUID shopProductVariantId) {
this.shopProductVariantId = shopProductVariantId;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
}

View File

@@ -0,0 +1,18 @@
package com.printcalculator.dto;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
public class ShopCartUpdateItemRequest {
@NotNull
@Min(1)
private Integer quantity;
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
}

View File

@@ -0,0 +1,23 @@
package com.printcalculator.dto;
import java.util.List;
import java.util.UUID;
public record ShopCategoryDetailDto(
UUID id,
String slug,
String name,
String description,
String seoTitle,
String seoDescription,
String ogTitle,
String ogDescription,
Boolean indexable,
Integer sortOrder,
Integer productCount,
List<ShopCategoryRefDto> breadcrumbs,
PublicMediaUsageDto primaryImage,
List<PublicMediaUsageDto> images,
List<ShopCategoryTreeDto> children
) {
}

View File

@@ -0,0 +1,10 @@
package com.printcalculator.dto;
import java.util.UUID;
public record ShopCategoryRefDto(
UUID id,
String slug,
String name
) {
}

View File

@@ -0,0 +1,22 @@
package com.printcalculator.dto;
import java.util.List;
import java.util.UUID;
public record ShopCategoryTreeDto(
UUID id,
UUID parentCategoryId,
String slug,
String name,
String description,
String seoTitle,
String seoDescription,
String ogTitle,
String ogDescription,
Boolean indexable,
Integer sortOrder,
Integer productCount,
PublicMediaUsageDto primaryImage,
List<ShopCategoryTreeDto> children
) {
}

View File

@@ -0,0 +1,11 @@
package com.printcalculator.dto;
import java.util.List;
public record ShopProductCatalogResponseDto(
String categorySlug,
Boolean featuredOnly,
ShopCategoryDetailDto category,
List<ShopProductSummaryDto> products
) {
}

View File

@@ -0,0 +1,30 @@
package com.printcalculator.dto;
import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;
public record ShopProductDetailDto(
UUID id,
String slug,
String name,
String excerpt,
String description,
String seoTitle,
String seoDescription,
String ogTitle,
String ogDescription,
Boolean indexable,
Boolean isFeatured,
Integer sortOrder,
ShopCategoryRefDto category,
List<ShopCategoryRefDto> breadcrumbs,
BigDecimal priceFromChf,
BigDecimal priceToChf,
ShopProductVariantOptionDto defaultVariant,
List<ShopProductVariantOptionDto> variants,
PublicMediaUsageDto primaryImage,
List<PublicMediaUsageDto> images,
ShopProductModelDto model3d
) {
}

View File

@@ -0,0 +1,14 @@
package com.printcalculator.dto;
import java.math.BigDecimal;
public record ShopProductModelDto(
String url,
String originalFilename,
String mimeType,
Long fileSizeBytes,
BigDecimal boundingBoxXMm,
BigDecimal boundingBoxYMm,
BigDecimal boundingBoxZMm
) {
}

View File

@@ -0,0 +1,20 @@
package com.printcalculator.dto;
import java.math.BigDecimal;
import java.util.UUID;
public record ShopProductSummaryDto(
UUID id,
String slug,
String name,
String excerpt,
Boolean isFeatured,
Integer sortOrder,
ShopCategoryRefDto category,
BigDecimal priceFromChf,
BigDecimal priceToChf,
ShopProductVariantOptionDto defaultVariant,
PublicMediaUsageDto primaryImage,
ShopProductModelDto model3d
) {
}

View File

@@ -0,0 +1,15 @@
package com.printcalculator.dto;
import java.math.BigDecimal;
import java.util.UUID;
public record ShopProductVariantOptionDto(
UUID id,
String sku,
String variantLabel,
String colorName,
String colorHex,
BigDecimal priceChf,
Boolean isDefault
) {
}

View File

@@ -20,6 +20,10 @@ public class Order {
@JoinColumn(name = "source_quote_session_id") @JoinColumn(name = "source_quote_session_id")
private QuoteSession sourceQuoteSession; private QuoteSession sourceQuoteSession;
@ColumnDefault("'CALCULATOR'")
@Column(name = "source_type", nullable = false, length = Integer.MAX_VALUE)
private String sourceType;
@Column(name = "status", nullable = false, length = Integer.MAX_VALUE) @Column(name = "status", nullable = false, length = Integer.MAX_VALUE)
private String status; private String status;
@@ -151,6 +155,34 @@ public class Order {
@Column(name = "paid_at") @Column(name = "paid_at")
private OffsetDateTime paidAt; private OffsetDateTime paidAt;
@PrePersist
private void onCreate() {
OffsetDateTime now = OffsetDateTime.now();
if (createdAt == null) {
createdAt = now;
}
if (updatedAt == null) {
updatedAt = now;
}
if (shippingSameAsBilling == null) {
shippingSameAsBilling = true;
}
if (sourceType == null || sourceType.isBlank()) {
sourceType = "CALCULATOR";
}
}
@PreUpdate
private void onUpdate() {
updatedAt = OffsetDateTime.now();
if (shippingSameAsBilling == null) {
shippingSameAsBilling = true;
}
if (sourceType == null || sourceType.isBlank()) {
sourceType = "CALCULATOR";
}
}
public UUID getId() { public UUID getId() {
return id; return id;
} }
@@ -177,6 +209,14 @@ public class Order {
this.sourceQuoteSession = sourceQuoteSession; this.sourceQuoteSession = sourceQuoteSession;
} }
public String getSourceType() {
return sourceType;
}
public void setSourceType(String sourceType) {
this.sourceType = sourceType;
}
public String getStatus() { public String getStatus() {
return status; return status;
} }

View File

@@ -23,9 +23,16 @@ public class OrderItem {
@JoinColumn(name = "order_id", nullable = false) @JoinColumn(name = "order_id", nullable = false)
private Order order; private Order order;
@ColumnDefault("'PRINT_FILE'")
@Column(name = "item_type", nullable = false, length = Integer.MAX_VALUE)
private String itemType;
@Column(name = "original_filename", nullable = false, length = Integer.MAX_VALUE) @Column(name = "original_filename", nullable = false, length = Integer.MAX_VALUE)
private String originalFilename; private String originalFilename;
@Column(name = "display_name", length = Integer.MAX_VALUE)
private String displayName;
@Column(name = "stored_relative_path", nullable = false, length = Integer.MAX_VALUE) @Column(name = "stored_relative_path", nullable = false, length = Integer.MAX_VALUE)
private String storedRelativePath; private String storedRelativePath;
@@ -66,6 +73,29 @@ public class OrderItem {
@JoinColumn(name = "filament_variant_id") @JoinColumn(name = "filament_variant_id")
private FilamentVariant filamentVariant; private FilamentVariant filamentVariant;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "shop_product_id")
private ShopProduct shopProduct;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "shop_product_variant_id")
private ShopProductVariant shopProductVariant;
@Column(name = "shop_product_slug", length = Integer.MAX_VALUE)
private String shopProductSlug;
@Column(name = "shop_product_name", length = Integer.MAX_VALUE)
private String shopProductName;
@Column(name = "shop_variant_label", length = Integer.MAX_VALUE)
private String shopVariantLabel;
@Column(name = "shop_variant_color_name", length = Integer.MAX_VALUE)
private String shopVariantColorName;
@Column(name = "shop_variant_color_hex", length = Integer.MAX_VALUE)
private String shopVariantColorHex;
@Column(name = "color_code", length = Integer.MAX_VALUE) @Column(name = "color_code", length = Integer.MAX_VALUE)
private String colorCode; private String colorCode;
@@ -106,6 +136,14 @@ public class OrderItem {
if (quantity == null) { if (quantity == null) {
quantity = 1; quantity = 1;
} }
if (itemType == null || itemType.isBlank()) {
itemType = "PRINT_FILE";
}
if ((displayName == null || displayName.isBlank()) && originalFilename != null && !originalFilename.isBlank()) {
displayName = originalFilename;
} else if ((displayName == null || displayName.isBlank()) && shopProductName != null && !shopProductName.isBlank()) {
displayName = shopProductName;
}
} }
public UUID getId() { public UUID getId() {
@@ -124,6 +162,14 @@ public class OrderItem {
this.order = order; this.order = order;
} }
public String getItemType() {
return itemType;
}
public void setItemType(String itemType) {
this.itemType = itemType;
}
public String getOriginalFilename() { public String getOriginalFilename() {
return originalFilename; return originalFilename;
} }
@@ -132,6 +178,14 @@ public class OrderItem {
this.originalFilename = originalFilename; this.originalFilename = originalFilename;
} }
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getStoredRelativePath() { public String getStoredRelativePath() {
return storedRelativePath; return storedRelativePath;
} }
@@ -236,6 +290,62 @@ public class OrderItem {
this.filamentVariant = filamentVariant; this.filamentVariant = filamentVariant;
} }
public ShopProduct getShopProduct() {
return shopProduct;
}
public void setShopProduct(ShopProduct shopProduct) {
this.shopProduct = shopProduct;
}
public ShopProductVariant getShopProductVariant() {
return shopProductVariant;
}
public void setShopProductVariant(ShopProductVariant shopProductVariant) {
this.shopProductVariant = shopProductVariant;
}
public String getShopProductSlug() {
return shopProductSlug;
}
public void setShopProductSlug(String shopProductSlug) {
this.shopProductSlug = shopProductSlug;
}
public String getShopProductName() {
return shopProductName;
}
public void setShopProductName(String shopProductName) {
this.shopProductName = shopProductName;
}
public String getShopVariantLabel() {
return shopVariantLabel;
}
public void setShopVariantLabel(String shopVariantLabel) {
this.shopVariantLabel = shopVariantLabel;
}
public String getShopVariantColorName() {
return shopVariantColorName;
}
public void setShopVariantColorName(String shopVariantColorName) {
this.shopVariantColorName = shopVariantColorName;
}
public String getShopVariantColorHex() {
return shopVariantColorHex;
}
public void setShopVariantColorHex(String shopVariantColorHex) {
this.shopVariantColorHex = shopVariantColorHex;
}
public String getColorCode() { public String getColorCode() {
return colorCode; return colorCode;
} }

View File

@@ -30,9 +30,16 @@ public class QuoteLineItem {
@Column(name = "status", nullable = false, length = Integer.MAX_VALUE) @Column(name = "status", nullable = false, length = Integer.MAX_VALUE)
private String status; private String status;
@ColumnDefault("'PRINT_FILE'")
@Column(name = "line_item_type", nullable = false, length = Integer.MAX_VALUE)
private String lineItemType;
@Column(name = "original_filename", nullable = false, length = Integer.MAX_VALUE) @Column(name = "original_filename", nullable = false, length = Integer.MAX_VALUE)
private String originalFilename; private String originalFilename;
@Column(name = "display_name", length = Integer.MAX_VALUE)
private String displayName;
@ColumnDefault("1") @ColumnDefault("1")
@Column(name = "quantity", nullable = false) @Column(name = "quantity", nullable = false)
private Integer quantity; private Integer quantity;
@@ -45,6 +52,31 @@ public class QuoteLineItem {
@com.fasterxml.jackson.annotation.JsonIgnore @com.fasterxml.jackson.annotation.JsonIgnore
private FilamentVariant filamentVariant; private FilamentVariant filamentVariant;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "shop_product_id")
@com.fasterxml.jackson.annotation.JsonIgnore
private ShopProduct shopProduct;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "shop_product_variant_id")
@com.fasterxml.jackson.annotation.JsonIgnore
private ShopProductVariant shopProductVariant;
@Column(name = "shop_product_slug", length = Integer.MAX_VALUE)
private String shopProductSlug;
@Column(name = "shop_product_name", length = Integer.MAX_VALUE)
private String shopProductName;
@Column(name = "shop_variant_label", length = Integer.MAX_VALUE)
private String shopVariantLabel;
@Column(name = "shop_variant_color_name", length = Integer.MAX_VALUE)
private String shopVariantColorName;
@Column(name = "shop_variant_color_hex", length = Integer.MAX_VALUE)
private String shopVariantColorHex;
@Column(name = "material_code", length = Integer.MAX_VALUE) @Column(name = "material_code", length = Integer.MAX_VALUE)
private String materialCode; private String materialCode;
@@ -102,6 +134,41 @@ public class QuoteLineItem {
@Column(name = "updated_at", nullable = false) @Column(name = "updated_at", nullable = false)
private OffsetDateTime updatedAt; private OffsetDateTime updatedAt;
@PrePersist
private void onCreate() {
OffsetDateTime now = OffsetDateTime.now();
if (createdAt == null) {
createdAt = now;
}
if (updatedAt == null) {
updatedAt = now;
}
if (quantity == null) {
quantity = 1;
}
if (lineItemType == null || lineItemType.isBlank()) {
lineItemType = "PRINT_FILE";
}
if ((displayName == null || displayName.isBlank()) && originalFilename != null && !originalFilename.isBlank()) {
displayName = originalFilename;
} else if ((displayName == null || displayName.isBlank()) && shopProductName != null && !shopProductName.isBlank()) {
displayName = shopProductName;
}
}
@PreUpdate
private void onUpdate() {
updatedAt = OffsetDateTime.now();
if (lineItemType == null || lineItemType.isBlank()) {
lineItemType = "PRINT_FILE";
}
if ((displayName == null || displayName.isBlank()) && originalFilename != null && !originalFilename.isBlank()) {
displayName = originalFilename;
} else if ((displayName == null || displayName.isBlank()) && shopProductName != null && !shopProductName.isBlank()) {
displayName = shopProductName;
}
}
public UUID getId() { public UUID getId() {
return id; return id;
} }
@@ -126,6 +193,14 @@ public class QuoteLineItem {
this.status = status; this.status = status;
} }
public String getLineItemType() {
return lineItemType;
}
public void setLineItemType(String lineItemType) {
this.lineItemType = lineItemType;
}
public String getOriginalFilename() { public String getOriginalFilename() {
return originalFilename; return originalFilename;
} }
@@ -134,6 +209,14 @@ public class QuoteLineItem {
this.originalFilename = originalFilename; this.originalFilename = originalFilename;
} }
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public Integer getQuantity() { public Integer getQuantity() {
return quantity; return quantity;
} }
@@ -158,6 +241,62 @@ public class QuoteLineItem {
this.filamentVariant = filamentVariant; this.filamentVariant = filamentVariant;
} }
public ShopProduct getShopProduct() {
return shopProduct;
}
public void setShopProduct(ShopProduct shopProduct) {
this.shopProduct = shopProduct;
}
public ShopProductVariant getShopProductVariant() {
return shopProductVariant;
}
public void setShopProductVariant(ShopProductVariant shopProductVariant) {
this.shopProductVariant = shopProductVariant;
}
public String getShopProductSlug() {
return shopProductSlug;
}
public void setShopProductSlug(String shopProductSlug) {
this.shopProductSlug = shopProductSlug;
}
public String getShopProductName() {
return shopProductName;
}
public void setShopProductName(String shopProductName) {
this.shopProductName = shopProductName;
}
public String getShopVariantLabel() {
return shopVariantLabel;
}
public void setShopVariantLabel(String shopVariantLabel) {
this.shopVariantLabel = shopVariantLabel;
}
public String getShopVariantColorName() {
return shopVariantColorName;
}
public void setShopVariantColorName(String shopVariantColorName) {
this.shopVariantColorName = shopVariantColorName;
}
public String getShopVariantColorHex() {
return shopVariantColorHex;
}
public void setShopVariantColorHex(String shopVariantColorHex) {
this.shopVariantColorHex = shopVariantColorHex;
}
public String getMaterialCode() { public String getMaterialCode() {
return materialCode; return materialCode;
} }

View File

@@ -22,6 +22,10 @@ public class QuoteSession {
@Column(name = "status", nullable = false, length = Integer.MAX_VALUE) @Column(name = "status", nullable = false, length = Integer.MAX_VALUE)
private String status; private String status;
@ColumnDefault("'PRINT_QUOTE'")
@Column(name = "session_type", nullable = false, length = Integer.MAX_VALUE)
private String sessionType;
@Column(name = "pricing_version", nullable = false, length = Integer.MAX_VALUE) @Column(name = "pricing_version", nullable = false, length = Integer.MAX_VALUE)
private String pricingVersion; private String pricingVersion;
@@ -70,6 +74,19 @@ public class QuoteSession {
@Column(name = "cad_hourly_rate_chf", precision = 10, scale = 2) @Column(name = "cad_hourly_rate_chf", precision = 10, scale = 2)
private BigDecimal cadHourlyRateChf; private BigDecimal cadHourlyRateChf;
@PrePersist
private void onCreate() {
if (sessionType == null || sessionType.isBlank()) {
sessionType = "PRINT_QUOTE";
}
if (supportsEnabled == null) {
supportsEnabled = false;
}
if (createdAt == null) {
createdAt = OffsetDateTime.now();
}
}
public UUID getId() { public UUID getId() {
return id; return id;
} }
@@ -86,6 +103,14 @@ public class QuoteSession {
this.status = status; this.status = status;
} }
public String getSessionType() {
return sessionType;
}
public void setSessionType(String sessionType) {
this.sessionType = sessionType;
}
public String getPricingVersion() { public String getPricingVersion() {
return pricingVersion; return pricingVersion;
} }

View File

@@ -0,0 +1,221 @@
package com.printcalculator.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Index;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.PrePersist;
import jakarta.persistence.PreUpdate;
import jakarta.persistence.Table;
import org.hibernate.annotations.ColumnDefault;
import java.time.OffsetDateTime;
import java.util.UUID;
@Entity
@Table(name = "shop_category", indexes = {
@Index(name = "ix_shop_category_parent_sort", columnList = "parent_category_id, sort_order"),
@Index(name = "ix_shop_category_active_sort", columnList = "is_active, sort_order")
})
public class ShopCategory {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "shop_category_id", nullable = false)
private UUID id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_category_id")
private ShopCategory parentCategory;
@Column(name = "slug", nullable = false, unique = true, length = Integer.MAX_VALUE)
private String slug;
@Column(name = "name", nullable = false, length = Integer.MAX_VALUE)
private String name;
@Column(name = "description", length = Integer.MAX_VALUE)
private String description;
@Column(name = "seo_title", length = Integer.MAX_VALUE)
private String seoTitle;
@Column(name = "seo_description", length = Integer.MAX_VALUE)
private String seoDescription;
@Column(name = "og_title", length = Integer.MAX_VALUE)
private String ogTitle;
@Column(name = "og_description", length = Integer.MAX_VALUE)
private String ogDescription;
@ColumnDefault("true")
@Column(name = "indexable", nullable = false)
private Boolean indexable;
@ColumnDefault("true")
@Column(name = "is_active", nullable = false)
private Boolean isActive;
@ColumnDefault("0")
@Column(name = "sort_order", nullable = false)
private Integer sortOrder;
@ColumnDefault("now()")
@Column(name = "created_at", nullable = false)
private OffsetDateTime createdAt;
@ColumnDefault("now()")
@Column(name = "updated_at", nullable = false)
private OffsetDateTime updatedAt;
@PrePersist
private void onCreate() {
OffsetDateTime now = OffsetDateTime.now();
if (createdAt == null) {
createdAt = now;
}
if (updatedAt == null) {
updatedAt = now;
}
if (indexable == null) {
indexable = true;
}
if (isActive == null) {
isActive = true;
}
if (sortOrder == null) {
sortOrder = 0;
}
}
@PreUpdate
private void onUpdate() {
updatedAt = OffsetDateTime.now();
if (indexable == null) {
indexable = true;
}
if (isActive == null) {
isActive = true;
}
if (sortOrder == null) {
sortOrder = 0;
}
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public ShopCategory getParentCategory() {
return parentCategory;
}
public void setParentCategory(ShopCategory parentCategory) {
this.parentCategory = parentCategory;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getSeoTitle() {
return seoTitle;
}
public void setSeoTitle(String seoTitle) {
this.seoTitle = seoTitle;
}
public String getSeoDescription() {
return seoDescription;
}
public void setSeoDescription(String seoDescription) {
this.seoDescription = seoDescription;
}
public String getOgTitle() {
return ogTitle;
}
public void setOgTitle(String ogTitle) {
this.ogTitle = ogTitle;
}
public String getOgDescription() {
return ogDescription;
}
public void setOgDescription(String ogDescription) {
this.ogDescription = ogDescription;
}
public Boolean getIndexable() {
return indexable;
}
public void setIndexable(Boolean indexable) {
this.indexable = indexable;
}
public Boolean getIsActive() {
return isActive;
}
public void setIsActive(Boolean active) {
isActive = active;
}
public Integer getSortOrder() {
return sortOrder;
}
public void setSortOrder(Integer sortOrder) {
this.sortOrder = sortOrder;
}
public OffsetDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(OffsetDateTime createdAt) {
this.createdAt = createdAt;
}
public OffsetDateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(OffsetDateTime updatedAt) {
this.updatedAt = updatedAt;
}
}

View File

@@ -0,0 +1,593 @@
package com.printcalculator.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Index;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.PrePersist;
import jakarta.persistence.PreUpdate;
import jakarta.persistence.Table;
import org.hibernate.annotations.ColumnDefault;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.UUID;
@Entity
@Table(name = "shop_product", indexes = {
@Index(name = "ix_shop_product_category_active_sort", columnList = "shop_category_id, is_active, sort_order"),
@Index(name = "ix_shop_product_featured_sort", columnList = "is_featured, is_active, sort_order")
})
public class ShopProduct {
public static final List<String> SUPPORTED_LANGUAGES = List.of("it", "en", "de", "fr");
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "shop_product_id", nullable = false)
private UUID id;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "shop_category_id", nullable = false)
private ShopCategory category;
@Column(name = "slug", nullable = false, unique = true, length = Integer.MAX_VALUE)
private String slug;
@Column(name = "name", nullable = false, length = Integer.MAX_VALUE)
private String name;
@Column(name = "name_it", length = Integer.MAX_VALUE)
private String nameIt;
@Column(name = "name_en", length = Integer.MAX_VALUE)
private String nameEn;
@Column(name = "name_de", length = Integer.MAX_VALUE)
private String nameDe;
@Column(name = "name_fr", length = Integer.MAX_VALUE)
private String nameFr;
@Column(name = "excerpt", length = Integer.MAX_VALUE)
private String excerpt;
@Column(name = "excerpt_it", length = Integer.MAX_VALUE)
private String excerptIt;
@Column(name = "excerpt_en", length = Integer.MAX_VALUE)
private String excerptEn;
@Column(name = "excerpt_de", length = Integer.MAX_VALUE)
private String excerptDe;
@Column(name = "excerpt_fr", length = Integer.MAX_VALUE)
private String excerptFr;
@Column(name = "description", length = Integer.MAX_VALUE)
private String description;
@Column(name = "description_it", length = Integer.MAX_VALUE)
private String descriptionIt;
@Column(name = "description_en", length = Integer.MAX_VALUE)
private String descriptionEn;
@Column(name = "description_de", length = Integer.MAX_VALUE)
private String descriptionDe;
@Column(name = "description_fr", length = Integer.MAX_VALUE)
private String descriptionFr;
@Column(name = "seo_title", length = Integer.MAX_VALUE)
private String seoTitle;
@Column(name = "seo_title_it", length = Integer.MAX_VALUE)
private String seoTitleIt;
@Column(name = "seo_title_en", length = Integer.MAX_VALUE)
private String seoTitleEn;
@Column(name = "seo_title_de", length = Integer.MAX_VALUE)
private String seoTitleDe;
@Column(name = "seo_title_fr", length = Integer.MAX_VALUE)
private String seoTitleFr;
@Column(name = "seo_description", length = Integer.MAX_VALUE)
private String seoDescription;
@Column(name = "seo_description_it", length = Integer.MAX_VALUE)
private String seoDescriptionIt;
@Column(name = "seo_description_en", length = Integer.MAX_VALUE)
private String seoDescriptionEn;
@Column(name = "seo_description_de", length = Integer.MAX_VALUE)
private String seoDescriptionDe;
@Column(name = "seo_description_fr", length = Integer.MAX_VALUE)
private String seoDescriptionFr;
@Column(name = "og_title", length = Integer.MAX_VALUE)
private String ogTitle;
@Column(name = "og_description", length = Integer.MAX_VALUE)
private String ogDescription;
@ColumnDefault("true")
@Column(name = "indexable", nullable = false)
private Boolean indexable;
@ColumnDefault("false")
@Column(name = "is_featured", nullable = false)
private Boolean isFeatured;
@ColumnDefault("true")
@Column(name = "is_active", nullable = false)
private Boolean isActive;
@ColumnDefault("0")
@Column(name = "sort_order", nullable = false)
private Integer sortOrder;
@ColumnDefault("now()")
@Column(name = "created_at", nullable = false)
private OffsetDateTime createdAt;
@ColumnDefault("now()")
@Column(name = "updated_at", nullable = false)
private OffsetDateTime updatedAt;
@PrePersist
private void onCreate() {
OffsetDateTime now = OffsetDateTime.now();
if (createdAt == null) {
createdAt = now;
}
if (updatedAt == null) {
updatedAt = now;
}
if (indexable == null) {
indexable = true;
}
if (isFeatured == null) {
isFeatured = false;
}
if (isActive == null) {
isActive = true;
}
if (sortOrder == null) {
sortOrder = 0;
}
}
@PreUpdate
private void onUpdate() {
updatedAt = OffsetDateTime.now();
if (indexable == null) {
indexable = true;
}
if (isFeatured == null) {
isFeatured = false;
}
if (isActive == null) {
isActive = true;
}
if (sortOrder == null) {
sortOrder = 0;
}
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public ShopCategory getCategory() {
return category;
}
public void setCategory(ShopCategory category) {
this.category = category;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNameIt() {
return nameIt;
}
public void setNameIt(String nameIt) {
this.nameIt = nameIt;
}
public String getNameEn() {
return nameEn;
}
public void setNameEn(String nameEn) {
this.nameEn = nameEn;
}
public String getNameDe() {
return nameDe;
}
public void setNameDe(String nameDe) {
this.nameDe = nameDe;
}
public String getNameFr() {
return nameFr;
}
public void setNameFr(String nameFr) {
this.nameFr = nameFr;
}
public String getExcerpt() {
return excerpt;
}
public void setExcerpt(String excerpt) {
this.excerpt = excerpt;
}
public String getExcerptIt() {
return excerptIt;
}
public void setExcerptIt(String excerptIt) {
this.excerptIt = excerptIt;
}
public String getExcerptEn() {
return excerptEn;
}
public void setExcerptEn(String excerptEn) {
this.excerptEn = excerptEn;
}
public String getExcerptDe() {
return excerptDe;
}
public void setExcerptDe(String excerptDe) {
this.excerptDe = excerptDe;
}
public String getExcerptFr() {
return excerptFr;
}
public void setExcerptFr(String excerptFr) {
this.excerptFr = excerptFr;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescriptionIt() {
return descriptionIt;
}
public void setDescriptionIt(String descriptionIt) {
this.descriptionIt = descriptionIt;
}
public String getDescriptionEn() {
return descriptionEn;
}
public void setDescriptionEn(String descriptionEn) {
this.descriptionEn = descriptionEn;
}
public String getDescriptionDe() {
return descriptionDe;
}
public void setDescriptionDe(String descriptionDe) {
this.descriptionDe = descriptionDe;
}
public String getDescriptionFr() {
return descriptionFr;
}
public void setDescriptionFr(String descriptionFr) {
this.descriptionFr = descriptionFr;
}
public String getSeoTitle() {
return seoTitle;
}
public void setSeoTitle(String seoTitle) {
this.seoTitle = seoTitle;
}
public String getSeoDescription() {
return seoDescription;
}
public void setSeoDescription(String seoDescription) {
this.seoDescription = seoDescription;
}
public String getSeoTitleIt() {
return seoTitleIt;
}
public void setSeoTitleIt(String seoTitleIt) {
this.seoTitleIt = seoTitleIt;
}
public String getSeoTitleEn() {
return seoTitleEn;
}
public void setSeoTitleEn(String seoTitleEn) {
this.seoTitleEn = seoTitleEn;
}
public String getSeoTitleDe() {
return seoTitleDe;
}
public void setSeoTitleDe(String seoTitleDe) {
this.seoTitleDe = seoTitleDe;
}
public String getSeoTitleFr() {
return seoTitleFr;
}
public void setSeoTitleFr(String seoTitleFr) {
this.seoTitleFr = seoTitleFr;
}
public String getSeoDescriptionIt() {
return seoDescriptionIt;
}
public void setSeoDescriptionIt(String seoDescriptionIt) {
this.seoDescriptionIt = seoDescriptionIt;
}
public String getSeoDescriptionEn() {
return seoDescriptionEn;
}
public void setSeoDescriptionEn(String seoDescriptionEn) {
this.seoDescriptionEn = seoDescriptionEn;
}
public String getSeoDescriptionDe() {
return seoDescriptionDe;
}
public void setSeoDescriptionDe(String seoDescriptionDe) {
this.seoDescriptionDe = seoDescriptionDe;
}
public String getSeoDescriptionFr() {
return seoDescriptionFr;
}
public void setSeoDescriptionFr(String seoDescriptionFr) {
this.seoDescriptionFr = seoDescriptionFr;
}
public String getOgTitle() {
return ogTitle;
}
public void setOgTitle(String ogTitle) {
this.ogTitle = ogTitle;
}
public String getOgDescription() {
return ogDescription;
}
public void setOgDescription(String ogDescription) {
this.ogDescription = ogDescription;
}
public Boolean getIndexable() {
return indexable;
}
public void setIndexable(Boolean indexable) {
this.indexable = indexable;
}
public Boolean getIsFeatured() {
return isFeatured;
}
public void setIsFeatured(Boolean featured) {
isFeatured = featured;
}
public Boolean getIsActive() {
return isActive;
}
public void setIsActive(Boolean active) {
isActive = active;
}
public Integer getSortOrder() {
return sortOrder;
}
public void setSortOrder(Integer sortOrder) {
this.sortOrder = sortOrder;
}
public OffsetDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(OffsetDateTime createdAt) {
this.createdAt = createdAt;
}
public OffsetDateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(OffsetDateTime updatedAt) {
this.updatedAt = updatedAt;
}
public String getNameForLanguage(String language) {
return resolveLocalizedValue(language, name, nameIt, nameEn, nameDe, nameFr);
}
public void setNameForLanguage(String language, String value) {
switch (normalizeLanguage(language)) {
case "it" -> nameIt = value;
case "en" -> nameEn = value;
case "de" -> nameDe = value;
case "fr" -> nameFr = value;
default -> {
}
}
}
public String getExcerptForLanguage(String language) {
return resolveLocalizedValue(language, excerpt, excerptIt, excerptEn, excerptDe, excerptFr);
}
public void setExcerptForLanguage(String language, String value) {
switch (normalizeLanguage(language)) {
case "it" -> excerptIt = value;
case "en" -> excerptEn = value;
case "de" -> excerptDe = value;
case "fr" -> excerptFr = value;
default -> {
}
}
}
public String getDescriptionForLanguage(String language) {
return resolveLocalizedValue(language, description, descriptionIt, descriptionEn, descriptionDe, descriptionFr);
}
public void setDescriptionForLanguage(String language, String value) {
switch (normalizeLanguage(language)) {
case "it" -> descriptionIt = value;
case "en" -> descriptionEn = value;
case "de" -> descriptionDe = value;
case "fr" -> descriptionFr = value;
default -> {
}
}
}
public String getSeoTitleForLanguage(String language) {
return resolveLocalizedValue(language, seoTitle, seoTitleIt, seoTitleEn, seoTitleDe, seoTitleFr);
}
public void setSeoTitleForLanguage(String language, String value) {
switch (normalizeLanguage(language)) {
case "it" -> seoTitleIt = value;
case "en" -> seoTitleEn = value;
case "de" -> seoTitleDe = value;
case "fr" -> seoTitleFr = value;
default -> {
}
}
}
public String getSeoDescriptionForLanguage(String language) {
return resolveLocalizedValue(language, seoDescription, seoDescriptionIt, seoDescriptionEn, seoDescriptionDe, seoDescriptionFr);
}
public void setSeoDescriptionForLanguage(String language, String value) {
switch (normalizeLanguage(language)) {
case "it" -> seoDescriptionIt = value;
case "en" -> seoDescriptionEn = value;
case "de" -> seoDescriptionDe = value;
case "fr" -> seoDescriptionFr = value;
default -> {
}
}
}
private String resolveLocalizedValue(String language,
String fallback,
String valueIt,
String valueEn,
String valueDe,
String valueFr) {
String normalizedLanguage = normalizeLanguage(language);
String preferred = switch (normalizedLanguage) {
case "it" -> valueIt;
case "en" -> valueEn;
case "de" -> valueDe;
case "fr" -> valueFr;
default -> null;
};
String resolved = firstNonBlank(preferred, fallback);
if (resolved != null) {
return resolved;
}
return firstNonBlank(valueIt, valueEn, valueDe, valueFr);
}
private String normalizeLanguage(String language) {
if (language == null) {
return "";
}
String normalized = language.trim().toLowerCase();
int separatorIndex = normalized.indexOf('-');
if (separatorIndex > 0) {
normalized = normalized.substring(0, separatorIndex);
}
return normalized;
}
private String firstNonBlank(String... values) {
if (values == null) {
return null;
}
for (String value : values) {
if (value != null && !value.isBlank()) {
return value;
}
}
return null;
}
}

View File

@@ -0,0 +1,189 @@
package com.printcalculator.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Index;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.OneToOne;
import jakarta.persistence.PrePersist;
import jakarta.persistence.PreUpdate;
import jakarta.persistence.Table;
import org.hibernate.annotations.ColumnDefault;
import java.math.BigDecimal;
import java.time.OffsetDateTime;
import java.util.UUID;
@Entity
@Table(name = "shop_product_model_asset", indexes = {
@Index(name = "ix_shop_product_model_asset_product", columnList = "shop_product_id")
})
public class ShopProductModelAsset {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "shop_product_model_asset_id", nullable = false)
private UUID id;
@OneToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "shop_product_id", nullable = false, unique = true)
private ShopProduct product;
@Column(name = "original_filename", nullable = false, length = Integer.MAX_VALUE)
private String originalFilename;
@Column(name = "stored_relative_path", nullable = false, length = Integer.MAX_VALUE)
private String storedRelativePath;
@Column(name = "stored_filename", nullable = false, length = Integer.MAX_VALUE)
private String storedFilename;
@Column(name = "file_size_bytes")
private Long fileSizeBytes;
@Column(name = "mime_type", length = Integer.MAX_VALUE)
private String mimeType;
@Column(name = "sha256_hex", length = Integer.MAX_VALUE)
private String sha256Hex;
@Column(name = "bounding_box_x_mm", precision = 10, scale = 3)
private BigDecimal boundingBoxXMm;
@Column(name = "bounding_box_y_mm", precision = 10, scale = 3)
private BigDecimal boundingBoxYMm;
@Column(name = "bounding_box_z_mm", precision = 10, scale = 3)
private BigDecimal boundingBoxZMm;
@ColumnDefault("now()")
@Column(name = "created_at", nullable = false)
private OffsetDateTime createdAt;
@ColumnDefault("now()")
@Column(name = "updated_at", nullable = false)
private OffsetDateTime updatedAt;
@PrePersist
private void onCreate() {
OffsetDateTime now = OffsetDateTime.now();
if (createdAt == null) {
createdAt = now;
}
if (updatedAt == null) {
updatedAt = now;
}
}
@PreUpdate
private void onUpdate() {
updatedAt = OffsetDateTime.now();
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public ShopProduct getProduct() {
return product;
}
public void setProduct(ShopProduct product) {
this.product = product;
}
public String getOriginalFilename() {
return originalFilename;
}
public void setOriginalFilename(String originalFilename) {
this.originalFilename = originalFilename;
}
public String getStoredRelativePath() {
return storedRelativePath;
}
public void setStoredRelativePath(String storedRelativePath) {
this.storedRelativePath = storedRelativePath;
}
public String getStoredFilename() {
return storedFilename;
}
public void setStoredFilename(String storedFilename) {
this.storedFilename = storedFilename;
}
public Long getFileSizeBytes() {
return fileSizeBytes;
}
public void setFileSizeBytes(Long fileSizeBytes) {
this.fileSizeBytes = fileSizeBytes;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public String getSha256Hex() {
return sha256Hex;
}
public void setSha256Hex(String sha256Hex) {
this.sha256Hex = sha256Hex;
}
public BigDecimal getBoundingBoxXMm() {
return boundingBoxXMm;
}
public void setBoundingBoxXMm(BigDecimal boundingBoxXMm) {
this.boundingBoxXMm = boundingBoxXMm;
}
public BigDecimal getBoundingBoxYMm() {
return boundingBoxYMm;
}
public void setBoundingBoxYMm(BigDecimal boundingBoxYMm) {
this.boundingBoxYMm = boundingBoxYMm;
}
public BigDecimal getBoundingBoxZMm() {
return boundingBoxZMm;
}
public void setBoundingBoxZMm(BigDecimal boundingBoxZMm) {
this.boundingBoxZMm = boundingBoxZMm;
}
public OffsetDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(OffsetDateTime createdAt) {
this.createdAt = createdAt;
}
public OffsetDateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(OffsetDateTime updatedAt) {
this.updatedAt = updatedAt;
}
}

View File

@@ -0,0 +1,218 @@
package com.printcalculator.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Index;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.PrePersist;
import jakarta.persistence.PreUpdate;
import jakarta.persistence.Table;
import org.hibernate.annotations.ColumnDefault;
import java.math.BigDecimal;
import java.time.OffsetDateTime;
import java.util.UUID;
@Entity
@Table(name = "shop_product_variant", indexes = {
@Index(name = "ix_shop_product_variant_product_active_sort", columnList = "shop_product_id, is_active, sort_order"),
@Index(name = "ix_shop_product_variant_sku", columnList = "sku")
})
public class ShopProductVariant {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "shop_product_variant_id", nullable = false)
private UUID id;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "shop_product_id", nullable = false)
private ShopProduct product;
@Column(name = "sku", unique = true, length = Integer.MAX_VALUE)
private String sku;
@Column(name = "variant_label", nullable = false, length = Integer.MAX_VALUE)
private String variantLabel;
@Column(name = "color_name", nullable = false, length = Integer.MAX_VALUE)
private String colorName;
@Column(name = "color_hex", length = Integer.MAX_VALUE)
private String colorHex;
@Column(name = "internal_material_code", nullable = false, length = Integer.MAX_VALUE)
private String internalMaterialCode;
@ColumnDefault("0.00")
@Column(name = "price_chf", nullable = false, precision = 12, scale = 2)
private BigDecimal priceChf;
@ColumnDefault("false")
@Column(name = "is_default", nullable = false)
private Boolean isDefault;
@ColumnDefault("true")
@Column(name = "is_active", nullable = false)
private Boolean isActive;
@ColumnDefault("0")
@Column(name = "sort_order", nullable = false)
private Integer sortOrder;
@ColumnDefault("now()")
@Column(name = "created_at", nullable = false)
private OffsetDateTime createdAt;
@ColumnDefault("now()")
@Column(name = "updated_at", nullable = false)
private OffsetDateTime updatedAt;
@PrePersist
private void onCreate() {
OffsetDateTime now = OffsetDateTime.now();
if (createdAt == null) {
createdAt = now;
}
if (updatedAt == null) {
updatedAt = now;
}
if (priceChf == null) {
priceChf = BigDecimal.ZERO;
}
if (isDefault == null) {
isDefault = false;
}
if (isActive == null) {
isActive = true;
}
if (sortOrder == null) {
sortOrder = 0;
}
}
@PreUpdate
private void onUpdate() {
updatedAt = OffsetDateTime.now();
if (priceChf == null) {
priceChf = BigDecimal.ZERO;
}
if (isDefault == null) {
isDefault = false;
}
if (isActive == null) {
isActive = true;
}
if (sortOrder == null) {
sortOrder = 0;
}
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public ShopProduct getProduct() {
return product;
}
public void setProduct(ShopProduct product) {
this.product = product;
}
public String getSku() {
return sku;
}
public void setSku(String sku) {
this.sku = sku;
}
public String getVariantLabel() {
return variantLabel;
}
public void setVariantLabel(String variantLabel) {
this.variantLabel = variantLabel;
}
public String getColorName() {
return colorName;
}
public void setColorName(String colorName) {
this.colorName = colorName;
}
public String getColorHex() {
return colorHex;
}
public void setColorHex(String colorHex) {
this.colorHex = colorHex;
}
public String getInternalMaterialCode() {
return internalMaterialCode;
}
public void setInternalMaterialCode(String internalMaterialCode) {
this.internalMaterialCode = internalMaterialCode;
}
public BigDecimal getPriceChf() {
return priceChf;
}
public void setPriceChf(BigDecimal priceChf) {
this.priceChf = priceChf;
}
public Boolean getIsDefault() {
return isDefault;
}
public void setIsDefault(Boolean aDefault) {
isDefault = aDefault;
}
public Boolean getIsActive() {
return isActive;
}
public void setIsActive(Boolean active) {
isActive = active;
}
public Integer getSortOrder() {
return sortOrder;
}
public void setSortOrder(Integer sortOrder) {
this.sortOrder = sortOrder;
}
public OffsetDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(OffsetDateTime createdAt) {
this.createdAt = createdAt;
}
public OffsetDateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(OffsetDateTime updatedAt) {
this.updatedAt = updatedAt;
}
}

View File

@@ -17,6 +17,19 @@ public interface MediaUsageRepository extends JpaRepository<MediaUsage, UUID> {
List<MediaUsage> findByUsageTypeAndUsageKeyAndIsActiveTrueOrderBySortOrderAscCreatedAtAsc(String usageType, List<MediaUsage> findByUsageTypeAndUsageKeyAndIsActiveTrueOrderBySortOrderAscCreatedAtAsc(String usageType,
String usageKey); String usageKey);
List<MediaUsage> findByUsageTypeAndUsageKeyOrderBySortOrderAscCreatedAtAsc(String usageType,
String usageKey);
@Query("""
select usage from MediaUsage usage
where usage.usageType = :usageType
and usage.usageKey in :usageKeys
and usage.isActive = true
order by usage.usageKey asc, usage.sortOrder asc, usage.createdAt asc
""")
List<MediaUsage> findActiveByUsageTypeAndUsageKeys(@Param("usageType") String usageType,
@Param("usageKeys") Collection<String> usageKeys);
@Query(""" @Query("""
select usage from MediaUsage usage select usage from MediaUsage usage
where usage.usageType = :usageType where usage.usageType = :usageType

View File

@@ -9,4 +9,6 @@ import java.util.UUID;
public interface OrderItemRepository extends JpaRepository<OrderItem, UUID> { public interface OrderItemRepository extends JpaRepository<OrderItem, UUID> {
List<OrderItem> findByOrder_Id(UUID orderId); List<OrderItem> findByOrder_Id(UUID orderId);
boolean existsByFilamentVariant_Id(Long filamentVariantId); boolean existsByFilamentVariant_Id(Long filamentVariantId);
boolean existsByShopProduct_Id(UUID shopProductId);
boolean existsByShopProductVariant_Id(UUID shopProductVariantId);
} }

View File

@@ -4,9 +4,19 @@ import com.printcalculator.entity.QuoteLineItem;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List; import java.util.List;
import java.util.Optional;
import java.util.UUID; import java.util.UUID;
public interface QuoteLineItemRepository extends JpaRepository<QuoteLineItem, UUID> { public interface QuoteLineItemRepository extends JpaRepository<QuoteLineItem, UUID> {
List<QuoteLineItem> findByQuoteSessionId(UUID quoteSessionId); List<QuoteLineItem> findByQuoteSessionId(UUID quoteSessionId);
List<QuoteLineItem> findByQuoteSessionIdOrderByCreatedAtAsc(UUID quoteSessionId);
Optional<QuoteLineItem> findByIdAndQuoteSession_Id(UUID lineItemId, UUID quoteSessionId);
Optional<QuoteLineItem> findFirstByQuoteSession_IdAndLineItemTypeAndShopProductVariant_Id(
UUID quoteSessionId,
String lineItemType,
UUID shopProductVariantId
);
boolean existsByFilamentVariant_Id(Long filamentVariantId); boolean existsByFilamentVariant_Id(Long filamentVariantId);
boolean existsByShopProduct_Id(UUID shopProductId);
boolean existsByShopProductVariant_Id(UUID shopProductVariantId);
} }

View File

@@ -4,10 +4,13 @@ import com.printcalculator.entity.QuoteSession;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List; import java.util.List;
import java.util.Optional;
import java.util.UUID; import java.util.UUID;
public interface QuoteSessionRepository extends JpaRepository<QuoteSession, UUID> { public interface QuoteSessionRepository extends JpaRepository<QuoteSession, UUID> {
List<QuoteSession> findByCreatedAtBefore(java.time.OffsetDateTime cutoff); List<QuoteSession> findByCreatedAtBefore(java.time.OffsetDateTime cutoff);
List<QuoteSession> findByStatusInOrderByCreatedAtDesc(List<String> statuses); List<QuoteSession> findByStatusInOrderByCreatedAtDesc(List<String> statuses);
Optional<QuoteSession> findByIdAndSessionType(UUID id, String sessionType);
} }

View File

@@ -0,0 +1,24 @@
package com.printcalculator.repository;
import com.printcalculator.entity.ShopCategory;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
public interface ShopCategoryRepository extends JpaRepository<ShopCategory, UUID> {
Optional<ShopCategory> findBySlug(String slug);
Optional<ShopCategory> findBySlugIgnoreCase(String slug);
Optional<ShopCategory> findBySlugAndIsActiveTrue(String slug);
boolean existsBySlugIgnoreCase(String slug);
boolean existsByParentCategory_Id(UUID parentCategoryId);
List<ShopCategory> findAllByOrderBySortOrderAscNameAsc();
List<ShopCategory> findAllByIsActiveTrueOrderBySortOrderAscNameAsc();
}

View File

@@ -0,0 +1,17 @@
package com.printcalculator.repository;
import com.printcalculator.entity.ShopProductModelAsset;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
public interface ShopProductModelAssetRepository extends JpaRepository<ShopProductModelAsset, UUID> {
Optional<ShopProductModelAsset> findByProduct_Id(UUID productId);
List<ShopProductModelAsset> findByProduct_IdIn(Collection<UUID> productIds);
void deleteByProduct_Id(UUID productId);
}

View File

@@ -0,0 +1,28 @@
package com.printcalculator.repository;
import com.printcalculator.entity.ShopProduct;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
public interface ShopProductRepository extends JpaRepository<ShopProduct, UUID> {
Optional<ShopProduct> findBySlug(String slug);
Optional<ShopProduct> findBySlugIgnoreCase(String slug);
Optional<ShopProduct> findBySlugAndIsActiveTrue(String slug);
boolean existsBySlugIgnoreCase(String slug);
List<ShopProduct> findAllByOrderBySortOrderAscNameAsc();
List<ShopProduct> findAllByOrderByIsFeaturedDescSortOrderAscNameAsc();
List<ShopProduct> findByCategory_IdOrderBySortOrderAscNameAsc(UUID categoryId);
List<ShopProduct> findAllByIsActiveTrueOrderByIsFeaturedDescSortOrderAscNameAsc();
boolean existsByCategory_Id(UUID categoryId);
}

View File

@@ -0,0 +1,25 @@
package com.printcalculator.repository;
import com.printcalculator.entity.ShopProductVariant;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
public interface ShopProductVariantRepository extends JpaRepository<ShopProductVariant, UUID> {
List<ShopProductVariant> findByProduct_IdOrderBySortOrderAscColorNameAsc(UUID productId);
List<ShopProductVariant> findByProduct_IdInOrderBySortOrderAscColorNameAsc(Collection<UUID> productIds);
List<ShopProductVariant> findByProduct_IdAndIsActiveTrueOrderBySortOrderAscColorNameAsc(UUID productId);
List<ShopProductVariant> findByProduct_IdInAndIsActiveTrueOrderBySortOrderAscColorNameAsc(Collection<UUID> productIds);
Optional<ShopProductVariant> findFirstByProduct_IdAndIsDefaultTrue(UUID productId);
boolean existsBySkuIgnoreCase(String sku);
boolean existsBySkuIgnoreCaseAndIdNot(String sku, UUID variantId);
}

View File

@@ -104,6 +104,7 @@ public class OrderService {
Order order = new Order(); Order order = new Order();
order.setSourceQuoteSession(session); order.setSourceQuoteSession(session);
order.setSourceType(resolveOrderSourceType(session));
order.setCustomer(customer); order.setCustomer(customer);
order.setCustomerEmail(request.getCustomer().getEmail()); order.setCustomerEmail(request.getCustomer().getEmail());
order.setCustomerPhone(request.getCustomer().getPhone()); order.setCustomerPhone(request.getCustomer().getPhone());
@@ -172,12 +173,27 @@ public class OrderService {
for (QuoteLineItem qItem : quoteItems) { for (QuoteLineItem qItem : quoteItems) {
OrderItem oItem = new OrderItem(); OrderItem oItem = new OrderItem();
oItem.setOrder(order); oItem.setOrder(order);
oItem.setItemType(qItem.getLineItemType() != null ? qItem.getLineItemType() : "PRINT_FILE");
oItem.setOriginalFilename(qItem.getOriginalFilename()); oItem.setOriginalFilename(qItem.getOriginalFilename());
oItem.setDisplayName(
qItem.getDisplayName() != null && !qItem.getDisplayName().isBlank()
? qItem.getDisplayName()
: qItem.getOriginalFilename()
);
int quantity = qItem.getQuantity() != null && qItem.getQuantity() > 0 ? qItem.getQuantity() : 1; int quantity = qItem.getQuantity() != null && qItem.getQuantity() > 0 ? qItem.getQuantity() : 1;
oItem.setQuantity(quantity); oItem.setQuantity(quantity);
oItem.setColorCode(qItem.getColorCode()); oItem.setColorCode(qItem.getColorCode());
oItem.setFilamentVariant(qItem.getFilamentVariant()); oItem.setFilamentVariant(qItem.getFilamentVariant());
if (qItem.getFilamentVariant() != null oItem.setShopProduct(qItem.getShopProduct());
oItem.setShopProductVariant(qItem.getShopProductVariant());
oItem.setShopProductSlug(qItem.getShopProductSlug());
oItem.setShopProductName(qItem.getShopProductName());
oItem.setShopVariantLabel(qItem.getShopVariantLabel());
oItem.setShopVariantColorName(qItem.getShopVariantColorName());
oItem.setShopVariantColorHex(qItem.getShopVariantColorHex());
if (qItem.getMaterialCode() != null && !qItem.getMaterialCode().isBlank()) {
oItem.setMaterialCode(qItem.getMaterialCode());
} else if (qItem.getFilamentVariant() != null
&& qItem.getFilamentVariant().getFilamentMaterialType() != null && qItem.getFilamentVariant().getFilamentMaterialType() != null
&& qItem.getFilamentVariant().getFilamentMaterialType().getMaterialCode() != null) { && qItem.getFilamentVariant().getFilamentMaterialType().getMaterialCode() != null) {
oItem.setMaterialCode(qItem.getFilamentVariant().getFilamentMaterialType().getMaterialCode()); oItem.setMaterialCode(qItem.getFilamentVariant().getFilamentMaterialType().getMaterialCode());
@@ -319,6 +335,13 @@ public class OrderService {
} }
} }
private String resolveOrderSourceType(QuoteSession session) {
if (session != null && "SHOP_CART".equalsIgnoreCase(session.getSessionType())) {
return "SHOP";
}
return "CALCULATOR";
}
private String getDisplayOrderNumber(Order order) { private String getDisplayOrderNumber(Order order) {
String orderNumber = order.getOrderNumber(); String orderNumber = order.getOrderNumber();
if (orderNumber != null && !orderNumber.isBlank()) { if (orderNumber != null && !orderNumber.isBlank()) {

View File

@@ -330,6 +330,18 @@ public class AdminMediaControllerService {
mediaUsageRepository.delete(getUsageOrThrow(mediaUsageId)); mediaUsageRepository.delete(getUsageOrThrow(mediaUsageId));
} }
public List<AdminMediaUsageDto> getUsages(String usageType, String usageKey, UUID ownerId) {
String normalizedUsageType = requireUsageType(usageType);
String normalizedUsageKey = requireUsageKey(usageKey);
return mediaUsageRepository.findByUsageScope(normalizedUsageType, normalizedUsageKey, ownerId)
.stream()
.sorted(Comparator
.comparing(MediaUsage::getSortOrder, Comparator.nullsLast(Integer::compareTo))
.thenComparing(MediaUsage::getCreatedAt, Comparator.nullsLast(OffsetDateTime::compareTo)))
.map(this::toUsageDto)
.toList();
}
private List<MediaVariant> generateDerivedVariants(MediaAsset asset, Path sourceFile, Path tempDirectory) throws IOException { private List<MediaVariant> generateDerivedVariants(MediaAsset asset, Path sourceFile, Path tempDirectory) throws IOException {
Path generatedDirectory = Files.createDirectories(tempDirectory.resolve("generated")); Path generatedDirectory = Files.createDirectories(tempDirectory.resolve("generated"));
String storageFolder = extractStorageFolder(asset.getStorageKey()); String storageFolder = extractStorageFolder(asset.getStorageKey());
@@ -350,7 +362,27 @@ public class AdminMediaControllerService {
} }
String extension = GENERATED_FORMAT_EXTENSIONS.get(format); String extension = GENERATED_FORMAT_EXTENSIONS.get(format);
Path outputFile = generatedDirectory.resolve(preset.name() + "." + extension); Path outputFile = generatedDirectory.resolve(preset.name() + "." + extension);
mediaFfmpegService.generateVariant(sourceFile, outputFile, dimensions.widthPx(), dimensions.heightPx(), format); 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(); MediaVariant variant = new MediaVariant();
variant.setMediaAsset(asset); variant.setMediaAsset(asset);
@@ -370,7 +402,7 @@ public class AdminMediaControllerService {
if (!skippedFormats.isEmpty()) { if (!skippedFormats.isEmpty()) {
logger.warn( logger.warn(
"Skipping media formats for asset {} because FFmpeg encoders are unavailable: {}", "Skipping media formats for asset {} because FFmpeg support is unavailable: {}",
asset.getId(), asset.getId(),
String.join(", ", skippedFormats) String.join(", ", skippedFormats)
); );

View File

@@ -301,6 +301,7 @@ public class AdminOperationsControllerService {
} else { } else {
session = new QuoteSession(); session = new QuoteSession();
session.setStatus("CAD_ACTIVE"); session.setStatus("CAD_ACTIVE");
session.setSessionType("PRINT_QUOTE");
session.setPricingVersion("v1"); session.setPricingVersion("v1");
session.setMaterialCode("PLA"); session.setMaterialCode("PLA");
session.setNozzleDiameterMm(BigDecimal.valueOf(0.4)); session.setNozzleDiameterMm(BigDecimal.valueOf(0.4));
@@ -398,6 +399,7 @@ public class AdminOperationsControllerService {
AdminQuoteSessionDto dto = new AdminQuoteSessionDto(); AdminQuoteSessionDto dto = new AdminQuoteSessionDto();
dto.setId(session.getId()); dto.setId(session.getId());
dto.setStatus(session.getStatus()); dto.setStatus(session.getStatus());
dto.setSessionType(session.getSessionType() != null ? session.getSessionType() : "PRINT_QUOTE");
dto.setMaterialCode(session.getMaterialCode()); dto.setMaterialCode(session.getMaterialCode());
dto.setCreatedAt(session.getCreatedAt()); dto.setCreatedAt(session.getCreatedAt());
dto.setExpiresAt(session.getExpiresAt()); dto.setExpiresAt(session.getExpiresAt());

View File

@@ -0,0 +1,334 @@
package com.printcalculator.service.admin;
import com.printcalculator.dto.AdminShopCategoryDto;
import com.printcalculator.dto.AdminShopCategoryRefDto;
import com.printcalculator.dto.AdminUpsertShopCategoryRequest;
import com.printcalculator.entity.ShopCategory;
import com.printcalculator.entity.ShopProduct;
import com.printcalculator.repository.ShopCategoryRepository;
import com.printcalculator.repository.ShopProductRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;
import java.text.Normalizer;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.CONFLICT;
import static org.springframework.http.HttpStatus.NOT_FOUND;
@Service
@Transactional(readOnly = true)
public class AdminShopCategoryControllerService {
private static final String SHOP_CATEGORY_MEDIA_USAGE_TYPE = "SHOP_CATEGORY";
private static final Pattern DIACRITICS_PATTERN = Pattern.compile("\\p{M}+");
private static final Pattern NON_ALPHANUMERIC_PATTERN = Pattern.compile("[^a-z0-9]+");
private static final Pattern EDGE_DASH_PATTERN = Pattern.compile("(^-+|-+$)");
private final ShopCategoryRepository shopCategoryRepository;
private final ShopProductRepository shopProductRepository;
public AdminShopCategoryControllerService(ShopCategoryRepository shopCategoryRepository,
ShopProductRepository shopProductRepository) {
this.shopCategoryRepository = shopCategoryRepository;
this.shopProductRepository = shopProductRepository;
}
public List<AdminShopCategoryDto> getCategories() {
CategoryContext context = buildContext();
List<AdminShopCategoryDto> result = new ArrayList<>();
appendFlatCategories(null, 0, context, result);
return result;
}
public List<AdminShopCategoryDto> getCategoryTree() {
return buildCategoryTree(null, 0, buildContext());
}
public AdminShopCategoryDto getCategory(UUID categoryId) {
CategoryContext context = buildContext();
ShopCategory category = context.categoriesById().get(categoryId);
if (category == null) {
throw new ResponseStatusException(NOT_FOUND, "Shop category not found");
}
return toDto(category, resolveDepth(category), context, true);
}
@Transactional
public AdminShopCategoryDto createCategory(AdminUpsertShopCategoryRequest payload) {
ensurePayload(payload);
String normalizedName = normalizeRequiredName(payload.getName());
String normalizedSlug = normalizeAndValidateSlug(payload.getSlug(), normalizedName);
ensureSlugAvailable(normalizedSlug, null);
ShopCategory category = new ShopCategory();
category.setCreatedAt(OffsetDateTime.now());
applyPayload(category, payload, normalizedName, normalizedSlug, null);
ShopCategory saved = shopCategoryRepository.save(category);
return getCategory(saved.getId());
}
@Transactional
public AdminShopCategoryDto updateCategory(UUID categoryId, AdminUpsertShopCategoryRequest payload) {
ensurePayload(payload);
ShopCategory category = shopCategoryRepository.findById(categoryId)
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "Shop category not found"));
String normalizedName = normalizeRequiredName(payload.getName());
String normalizedSlug = normalizeAndValidateSlug(payload.getSlug(), normalizedName);
ensureSlugAvailable(normalizedSlug, category.getId());
applyPayload(category, payload, normalizedName, normalizedSlug, category.getId());
ShopCategory saved = shopCategoryRepository.save(category);
return getCategory(saved.getId());
}
@Transactional
public void deleteCategory(UUID categoryId) {
ShopCategory category = shopCategoryRepository.findById(categoryId)
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "Shop category not found"));
if (shopCategoryRepository.existsByParentCategory_Id(categoryId)) {
throw new ResponseStatusException(CONFLICT, "Category has child categories and cannot be deleted");
}
if (shopProductRepository.existsByCategory_Id(categoryId)) {
throw new ResponseStatusException(CONFLICT, "Category has products and cannot be deleted");
}
shopCategoryRepository.delete(category);
}
private void applyPayload(ShopCategory category,
AdminUpsertShopCategoryRequest payload,
String normalizedName,
String normalizedSlug,
UUID currentCategoryId) {
ShopCategory parentCategory = resolveParentCategory(payload.getParentCategoryId(), currentCategoryId);
category.setParentCategory(parentCategory);
category.setSlug(normalizedSlug);
category.setName(normalizedName);
category.setDescription(normalizeOptional(payload.getDescription()));
category.setSeoTitle(normalizeOptional(payload.getSeoTitle()));
category.setSeoDescription(normalizeOptional(payload.getSeoDescription()));
category.setOgTitle(normalizeOptional(payload.getOgTitle()));
category.setOgDescription(normalizeOptional(payload.getOgDescription()));
category.setIndexable(payload.getIndexable() == null || payload.getIndexable());
category.setIsActive(payload.getIsActive() == null || payload.getIsActive());
category.setSortOrder(payload.getSortOrder() != null ? payload.getSortOrder() : 0);
category.setUpdatedAt(OffsetDateTime.now());
}
private ShopCategory resolveParentCategory(UUID parentCategoryId, UUID currentCategoryId) {
if (parentCategoryId == null) {
return null;
}
if (currentCategoryId != null && currentCategoryId.equals(parentCategoryId)) {
throw new ResponseStatusException(BAD_REQUEST, "Category cannot be its own parent");
}
ShopCategory parentCategory = shopCategoryRepository.findById(parentCategoryId)
.orElseThrow(() -> new ResponseStatusException(BAD_REQUEST, "Parent category not found"));
if (currentCategoryId != null) {
ShopCategory ancestor = parentCategory;
while (ancestor != null) {
if (currentCategoryId.equals(ancestor.getId())) {
throw new ResponseStatusException(BAD_REQUEST, "Category hierarchy would create a cycle");
}
ancestor = ancestor.getParentCategory();
}
}
return parentCategory;
}
private void ensurePayload(AdminUpsertShopCategoryRequest payload) {
if (payload == null) {
throw new ResponseStatusException(BAD_REQUEST, "Payload is required");
}
}
private String normalizeRequiredName(String name) {
String normalized = normalizeOptional(name);
if (normalized == null) {
throw new ResponseStatusException(BAD_REQUEST, "Category name is required");
}
return normalized;
}
private String normalizeAndValidateSlug(String slug, String fallbackName) {
String source = normalizeOptional(slug);
if (source == null) {
source = fallbackName;
}
String normalized = Normalizer.normalize(source, Normalizer.Form.NFD);
normalized = DIACRITICS_PATTERN.matcher(normalized).replaceAll("");
normalized = normalized.toLowerCase(Locale.ROOT);
normalized = NON_ALPHANUMERIC_PATTERN.matcher(normalized).replaceAll("-");
normalized = EDGE_DASH_PATTERN.matcher(normalized).replaceAll("");
if (normalized.isBlank()) {
throw new ResponseStatusException(BAD_REQUEST, "Slug is invalid");
}
return normalized;
}
private void ensureSlugAvailable(String slug, UUID currentCategoryId) {
shopCategoryRepository.findBySlugIgnoreCase(slug).ifPresent(existing -> {
if (currentCategoryId == null || !existing.getId().equals(currentCategoryId)) {
throw new ResponseStatusException(BAD_REQUEST, "Category slug already exists");
}
});
}
private String normalizeOptional(String value) {
if (value == null) {
return null;
}
String normalized = value.trim();
return normalized.isBlank() ? null : normalized;
}
private CategoryContext buildContext() {
List<ShopCategory> categories = shopCategoryRepository.findAllByOrderBySortOrderAscNameAsc();
List<ShopProduct> products = shopProductRepository.findAll();
Map<UUID, ShopCategory> categoriesById = categories.stream()
.collect(Collectors.toMap(ShopCategory::getId, category -> category, (left, right) -> left, LinkedHashMap::new));
Map<UUID, List<ShopCategory>> childrenByParentId = new LinkedHashMap<>();
for (ShopCategory category : categories) {
UUID parentId = category.getParentCategory() != null ? category.getParentCategory().getId() : null;
childrenByParentId.computeIfAbsent(parentId, ignored -> new ArrayList<>()).add(category);
}
Comparator<ShopCategory> comparator = Comparator
.comparing(ShopCategory::getSortOrder, Comparator.nullsLast(Integer::compareTo))
.thenComparing(ShopCategory::getName, Comparator.nullsLast(String.CASE_INSENSITIVE_ORDER));
childrenByParentId.values().forEach(children -> children.sort(comparator));
Map<UUID, Integer> directProductCounts = new LinkedHashMap<>();
for (ShopProduct product : products) {
if (product.getCategory() == null || product.getCategory().getId() == null) {
continue;
}
directProductCounts.merge(product.getCategory().getId(), 1, Integer::sum);
}
Map<UUID, Integer> descendantProductCounts = new LinkedHashMap<>();
for (ShopCategory category : categories) {
resolveDescendantProductCount(category.getId(), childrenByParentId, directProductCounts, descendantProductCounts);
}
return new CategoryContext(categoriesById, childrenByParentId, directProductCounts, descendantProductCounts);
}
private int resolveDescendantProductCount(UUID categoryId,
Map<UUID, List<ShopCategory>> childrenByParentId,
Map<UUID, Integer> directProductCounts,
Map<UUID, Integer> descendantProductCounts) {
Integer cached = descendantProductCounts.get(categoryId);
if (cached != null) {
return cached;
}
int total = directProductCounts.getOrDefault(categoryId, 0);
for (ShopCategory child : childrenByParentId.getOrDefault(categoryId, List.of())) {
total += resolveDescendantProductCount(child.getId(), childrenByParentId, directProductCounts, descendantProductCounts);
}
descendantProductCounts.put(categoryId, total);
return total;
}
private void appendFlatCategories(UUID parentId,
int depth,
CategoryContext context,
List<AdminShopCategoryDto> result) {
for (ShopCategory category : context.childrenByParentId().getOrDefault(parentId, List.of())) {
result.add(toDto(category, depth, context, false));
appendFlatCategories(category.getId(), depth + 1, context, result);
}
}
private List<AdminShopCategoryDto> buildCategoryTree(UUID parentId, int depth, CategoryContext context) {
return context.childrenByParentId().getOrDefault(parentId, List.of()).stream()
.map(category -> toDto(category, depth, context, true))
.toList();
}
private AdminShopCategoryDto toDto(ShopCategory category,
int depth,
CategoryContext context,
boolean includeChildren) {
AdminShopCategoryDto dto = new AdminShopCategoryDto();
dto.setId(category.getId());
dto.setParentCategoryId(category.getParentCategory() != null ? category.getParentCategory().getId() : null);
dto.setParentCategoryName(category.getParentCategory() != null ? category.getParentCategory().getName() : null);
dto.setSlug(category.getSlug());
dto.setName(category.getName());
dto.setDescription(category.getDescription());
dto.setSeoTitle(category.getSeoTitle());
dto.setSeoDescription(category.getSeoDescription());
dto.setOgTitle(category.getOgTitle());
dto.setOgDescription(category.getOgDescription());
dto.setIndexable(category.getIndexable());
dto.setIsActive(category.getIsActive());
dto.setSortOrder(category.getSortOrder());
dto.setDepth(depth);
dto.setChildCount(context.childrenByParentId().getOrDefault(category.getId(), List.of()).size());
dto.setDirectProductCount(context.directProductCounts().getOrDefault(category.getId(), 0));
dto.setDescendantProductCount(context.descendantProductCounts().getOrDefault(category.getId(), 0));
dto.setMediaUsageType(SHOP_CATEGORY_MEDIA_USAGE_TYPE);
dto.setMediaUsageKey(category.getId().toString());
dto.setBreadcrumbs(buildBreadcrumbs(category));
dto.setChildren(includeChildren ? buildCategoryTree(category.getId(), depth + 1, context) : List.of());
dto.setCreatedAt(category.getCreatedAt());
dto.setUpdatedAt(category.getUpdatedAt());
return dto;
}
private List<AdminShopCategoryRefDto> buildBreadcrumbs(ShopCategory category) {
List<AdminShopCategoryRefDto> breadcrumbs = new ArrayList<>();
ShopCategory current = category;
while (current != null) {
AdminShopCategoryRefDto ref = new AdminShopCategoryRefDto();
ref.setId(current.getId());
ref.setSlug(current.getSlug());
ref.setName(current.getName());
breadcrumbs.add(ref);
current = current.getParentCategory();
}
java.util.Collections.reverse(breadcrumbs);
return breadcrumbs;
}
private int resolveDepth(ShopCategory category) {
int depth = 0;
ShopCategory current = category != null ? category.getParentCategory() : null;
while (current != null) {
depth++;
current = current.getParentCategory();
}
return depth;
}
private record CategoryContext(
Map<UUID, ShopCategory> categoriesById,
Map<UUID, List<ShopCategory>> childrenByParentId,
Map<UUID, Integer> directProductCounts,
Map<UUID, Integer> descendantProductCounts
) {
}
}

View File

@@ -0,0 +1,892 @@
package com.printcalculator.service.admin;
import com.printcalculator.dto.AdminMediaUsageDto;
import com.printcalculator.dto.AdminShopProductDto;
import com.printcalculator.dto.AdminShopProductVariantDto;
import com.printcalculator.dto.AdminUpsertShopProductRequest;
import com.printcalculator.dto.AdminUpsertShopProductVariantRequest;
import com.printcalculator.dto.PublicMediaUsageDto;
import com.printcalculator.dto.ShopProductModelDto;
import com.printcalculator.entity.ShopCategory;
import com.printcalculator.entity.ShopProduct;
import com.printcalculator.entity.ShopProductModelAsset;
import com.printcalculator.entity.ShopProductVariant;
import com.printcalculator.model.ModelDimensions;
import com.printcalculator.repository.OrderItemRepository;
import com.printcalculator.repository.QuoteLineItemRepository;
import com.printcalculator.repository.ShopCategoryRepository;
import com.printcalculator.repository.ShopProductModelAssetRepository;
import com.printcalculator.repository.ShopProductRepository;
import com.printcalculator.repository.ShopProductVariantRepository;
import com.printcalculator.service.SlicerService;
import com.printcalculator.service.media.PublicMediaQueryService;
import com.printcalculator.service.shop.ShopStorageService;
import com.printcalculator.service.storage.ClamAVService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Safelist;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.server.ResponseStatusException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.Normalizer;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@Service
@Transactional(readOnly = true)
public class AdminShopProductControllerService {
private static final String SHOP_PRODUCT_MEDIA_USAGE_TYPE = "SHOP_PRODUCT";
private static final Set<String> SUPPORTED_MODEL_EXTENSIONS = Set.of("stl", "3mf");
private static final Pattern HEX_COLOR_PATTERN = Pattern.compile("^#[0-9A-Fa-f]{6}$");
private static final Pattern DIACRITICS_PATTERN = Pattern.compile("\\p{M}+");
private static final Pattern NON_ALPHANUMERIC_PATTERN = Pattern.compile("[^a-z0-9]+");
private static final Pattern EDGE_DASH_PATTERN = Pattern.compile("(^-+|-+$)");
private static final Safelist PRODUCT_DESCRIPTION_SAFELIST = Safelist.none()
.addTags("p", "div", "br", "strong", "b", "em", "i", "u", "ul", "ol", "li", "a")
.addAttributes("a", "href")
.addProtocols("a", "href", "http", "https", "mailto", "tel");
private final ShopProductRepository shopProductRepository;
private final ShopCategoryRepository shopCategoryRepository;
private final ShopProductVariantRepository shopProductVariantRepository;
private final ShopProductModelAssetRepository shopProductModelAssetRepository;
private final QuoteLineItemRepository quoteLineItemRepository;
private final OrderItemRepository orderItemRepository;
private final PublicMediaQueryService publicMediaQueryService;
private final AdminMediaControllerService adminMediaControllerService;
private final ShopStorageService shopStorageService;
private final SlicerService slicerService;
private final ClamAVService clamAVService;
private final long maxModelFileSizeBytes;
public AdminShopProductControllerService(ShopProductRepository shopProductRepository,
ShopCategoryRepository shopCategoryRepository,
ShopProductVariantRepository shopProductVariantRepository,
ShopProductModelAssetRepository shopProductModelAssetRepository,
QuoteLineItemRepository quoteLineItemRepository,
OrderItemRepository orderItemRepository,
PublicMediaQueryService publicMediaQueryService,
AdminMediaControllerService adminMediaControllerService,
ShopStorageService shopStorageService,
SlicerService slicerService,
ClamAVService clamAVService,
@Value("${shop.model.max-file-size-bytes:104857600}") long maxModelFileSizeBytes) {
this.shopProductRepository = shopProductRepository;
this.shopCategoryRepository = shopCategoryRepository;
this.shopProductVariantRepository = shopProductVariantRepository;
this.shopProductModelAssetRepository = shopProductModelAssetRepository;
this.quoteLineItemRepository = quoteLineItemRepository;
this.orderItemRepository = orderItemRepository;
this.publicMediaQueryService = publicMediaQueryService;
this.adminMediaControllerService = adminMediaControllerService;
this.shopStorageService = shopStorageService;
this.slicerService = slicerService;
this.clamAVService = clamAVService;
this.maxModelFileSizeBytes = maxModelFileSizeBytes;
}
public List<AdminShopProductDto> getProducts() {
return toProductDtos(shopProductRepository.findAllByOrderByIsFeaturedDescSortOrderAscNameAsc());
}
public AdminShopProductDto getProduct(UUID productId) {
ShopProduct product = shopProductRepository.findById(productId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Shop product not found"));
return toProductDtos(List.of(product)).get(0);
}
@Transactional
public AdminShopProductDto createProduct(AdminUpsertShopProductRequest payload) {
ensurePayload(payload);
LocalizedProductContent localizedContent = normalizeLocalizedProductContent(payload);
String normalizedSlug = normalizeAndValidateSlug(payload.getSlug(), localizedContent.defaultName());
ensureSlugAvailable(normalizedSlug, null);
ShopProduct product = new ShopProduct();
product.setCreatedAt(OffsetDateTime.now());
applyProductPayload(product, payload, localizedContent, normalizedSlug, resolveCategory(payload.getCategoryId()));
ShopProduct saved = shopProductRepository.save(product);
syncVariants(saved, payload.getVariants());
return getProduct(saved.getId());
}
@Transactional
public AdminShopProductDto updateProduct(UUID productId, AdminUpsertShopProductRequest payload) {
ensurePayload(payload);
ShopProduct product = shopProductRepository.findById(productId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Shop product not found"));
LocalizedProductContent localizedContent = normalizeLocalizedProductContent(payload);
String normalizedSlug = normalizeAndValidateSlug(payload.getSlug(), localizedContent.defaultName());
ensureSlugAvailable(normalizedSlug, productId);
applyProductPayload(product, payload, localizedContent, normalizedSlug, resolveCategory(payload.getCategoryId()));
ShopProduct saved = shopProductRepository.save(product);
syncVariants(saved, payload.getVariants());
return getProduct(saved.getId());
}
@Transactional
public void deleteProduct(UUID productId) {
ShopProduct product = shopProductRepository.findById(productId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Shop product not found"));
if (quoteLineItemRepository.existsByShopProduct_Id(productId)
|| orderItemRepository.existsByShopProduct_Id(productId)) {
throw new ResponseStatusException(HttpStatus.CONFLICT, "Product is already used in carts or orders and cannot be deleted");
}
List<ShopProductVariant> variants = shopProductVariantRepository.findByProduct_IdOrderBySortOrderAscColorNameAsc(productId);
for (ShopProductVariant variant : variants) {
if (quoteLineItemRepository.existsByShopProductVariant_Id(variant.getId())
|| orderItemRepository.existsByShopProductVariant_Id(variant.getId())) {
throw new ResponseStatusException(HttpStatus.CONFLICT, "One or more variants are already used in carts or orders and cannot be deleted");
}
}
shopProductModelAssetRepository.findByProduct_Id(productId).ifPresent(asset -> {
deleteExistingModelFile(asset, productId);
shopProductModelAssetRepository.delete(asset);
});
if (!variants.isEmpty()) {
shopProductVariantRepository.deleteAll(variants);
}
shopProductRepository.delete(product);
}
@Transactional
public AdminShopProductDto uploadProductModel(UUID productId, MultipartFile file) throws IOException {
ShopProduct product = shopProductRepository.findById(productId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Shop product not found"));
validateModelUpload(file);
Path tempDirectory = Files.createTempDirectory("shop-product-model-");
Path destination = null;
try {
String cleanedFilename = sanitizeOriginalFilename(file.getOriginalFilename());
String extension = resolveExtension(cleanedFilename);
Path uploadPath = tempDirectory.resolve("upload." + extension);
file.transferTo(uploadPath);
try (InputStream inputStream = Files.newInputStream(uploadPath)) {
clamAVService.scan(inputStream);
}
Path storageDir = shopStorageService.productModelStorageDir(productId);
destination = storageDir.resolve(UUID.randomUUID() + ".stl");
if ("3mf".equals(extension)) {
slicerService.convert3mfToPersistentStl(uploadPath.toFile(), destination);
} else {
Files.copy(uploadPath, destination, StandardCopyOption.REPLACE_EXISTING);
}
ModelDimensions dimensions = slicerService.inspectModelDimensions(destination.toFile())
.orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "Unable to extract model dimensions"));
ShopProductModelAsset asset = shopProductModelAssetRepository.findByProduct_Id(productId)
.orElseGet(ShopProductModelAsset::new);
String previousStoredRelativePath = asset.getStoredRelativePath();
asset.setProduct(product);
asset.setOriginalFilename(buildDownloadFilename(cleanedFilename));
asset.setStoredFilename(destination.getFileName().toString());
asset.setStoredRelativePath(shopStorageService.toStoredPath(destination));
asset.setMimeType("model/stl");
asset.setFileSizeBytes(Files.size(destination));
asset.setSha256Hex(computeSha256(destination));
asset.setBoundingBoxXMm(BigDecimal.valueOf(dimensions.xMm()));
asset.setBoundingBoxYMm(BigDecimal.valueOf(dimensions.yMm()));
asset.setBoundingBoxZMm(BigDecimal.valueOf(dimensions.zMm()));
if (asset.getCreatedAt() == null) {
asset.setCreatedAt(OffsetDateTime.now());
}
asset.setUpdatedAt(OffsetDateTime.now());
shopProductModelAssetRepository.save(asset);
deleteStoredRelativePath(previousStoredRelativePath, productId, asset.getStoredRelativePath());
return getProduct(productId);
} catch (IOException | RuntimeException e) {
deletePathQuietly(destination);
throw e;
} finally {
deleteRecursively(tempDirectory);
}
}
@Transactional
public void deleteProductModel(UUID productId) {
shopProductRepository.findById(productId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Shop product not found"));
ShopProductModelAsset asset = shopProductModelAssetRepository.findByProduct_Id(productId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Shop product model not found"));
deleteExistingModelFile(asset, productId);
shopProductModelAssetRepository.delete(asset);
}
public ProductModelDownload getProductModel(UUID productId) {
ShopProduct product = shopProductRepository.findById(productId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Shop product not found"));
ShopProductModelAsset asset = shopProductModelAssetRepository.findByProduct_Id(productId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Shop product model not found"));
Path path = shopStorageService.resolveStoredProductPath(asset.getStoredRelativePath(), product.getId());
if (path == null || !Files.exists(path)) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Shop product model not found");
}
return new ProductModelDownload(path, asset.getOriginalFilename(), asset.getMimeType());
}
private void syncVariants(ShopProduct product, List<AdminUpsertShopProductVariantRequest> variantPayloads) {
List<AdminUpsertShopProductVariantRequest> normalizedPayloads = normalizeVariantPayloads(variantPayloads);
List<ShopProductVariant> existingVariants = shopProductVariantRepository.findByProduct_IdOrderBySortOrderAscColorNameAsc(product.getId());
Map<UUID, ShopProductVariant> existingById = existingVariants.stream()
.collect(Collectors.toMap(ShopProductVariant::getId, variant -> variant, (left, right) -> left, LinkedHashMap::new));
Set<UUID> retainedIds = new LinkedHashSet<>();
List<ShopProductVariant> variantsToSave = new ArrayList<>();
for (AdminUpsertShopProductVariantRequest payload : normalizedPayloads) {
ShopProductVariant variant;
if (payload.getId() != null) {
variant = existingById.get(payload.getId());
if (variant == null) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Variant does not belong to the product");
}
retainedIds.add(variant.getId());
} else {
variant = new ShopProductVariant();
variant.setCreatedAt(OffsetDateTime.now());
}
applyVariantPayload(variant, product, payload);
variantsToSave.add(variant);
}
List<ShopProductVariant> variantsToDelete = existingVariants.stream()
.filter(variant -> !retainedIds.contains(variant.getId()))
.toList();
for (ShopProductVariant variant : variantsToDelete) {
if (quoteLineItemRepository.existsByShopProductVariant_Id(variant.getId())
|| orderItemRepository.existsByShopProductVariant_Id(variant.getId())) {
throw new ResponseStatusException(HttpStatus.CONFLICT, "Variant is already used in carts or orders and cannot be removed");
}
}
if (!variantsToDelete.isEmpty()) {
shopProductVariantRepository.deleteAll(variantsToDelete);
}
shopProductVariantRepository.saveAll(variantsToSave);
}
private void applyProductPayload(ShopProduct product,
AdminUpsertShopProductRequest payload,
LocalizedProductContent localizedContent,
String normalizedSlug,
ShopCategory category) {
product.setCategory(category);
product.setSlug(normalizedSlug);
product.setName(localizedContent.defaultName());
product.setNameIt(localizedContent.names().get("it"));
product.setNameEn(localizedContent.names().get("en"));
product.setNameDe(localizedContent.names().get("de"));
product.setNameFr(localizedContent.names().get("fr"));
product.setExcerpt(localizedContent.defaultExcerpt());
product.setExcerptIt(localizedContent.excerpts().get("it"));
product.setExcerptEn(localizedContent.excerpts().get("en"));
product.setExcerptDe(localizedContent.excerpts().get("de"));
product.setExcerptFr(localizedContent.excerpts().get("fr"));
product.setDescription(localizedContent.defaultDescription());
product.setDescriptionIt(localizedContent.descriptions().get("it"));
product.setDescriptionEn(localizedContent.descriptions().get("en"));
product.setDescriptionDe(localizedContent.descriptions().get("de"));
product.setDescriptionFr(localizedContent.descriptions().get("fr"));
product.setSeoTitle(localizedContent.defaultSeoTitle());
product.setSeoTitleIt(localizedContent.seoTitles().get("it"));
product.setSeoTitleEn(localizedContent.seoTitles().get("en"));
product.setSeoTitleDe(localizedContent.seoTitles().get("de"));
product.setSeoTitleFr(localizedContent.seoTitles().get("fr"));
product.setSeoDescription(localizedContent.defaultSeoDescription());
product.setSeoDescriptionIt(localizedContent.seoDescriptions().get("it"));
product.setSeoDescriptionEn(localizedContent.seoDescriptions().get("en"));
product.setSeoDescriptionDe(localizedContent.seoDescriptions().get("de"));
product.setSeoDescriptionFr(localizedContent.seoDescriptions().get("fr"));
product.setOgTitle(localizedContent.defaultSeoTitle());
product.setOgDescription(localizedContent.defaultSeoDescription());
product.setIndexable(payload.getIndexable() == null || payload.getIndexable());
product.setIsFeatured(Boolean.TRUE.equals(payload.getIsFeatured()));
product.setIsActive(payload.getIsActive() == null || payload.getIsActive());
product.setSortOrder(payload.getSortOrder() != null ? payload.getSortOrder() : 0);
product.setUpdatedAt(OffsetDateTime.now());
}
private void applyVariantPayload(ShopProductVariant variant,
ShopProduct product,
AdminUpsertShopProductVariantRequest payload) {
String normalizedColorName = normalizeRequired(payload.getColorName(), "Variant colorName is required");
String normalizedVariantLabel = normalizeOptional(payload.getVariantLabel());
String normalizedSku = normalizeOptional(payload.getSku());
String normalizedMaterialCode = normalizeRequired(
payload.getInternalMaterialCode(),
"Variant internalMaterialCode is required"
).toUpperCase(Locale.ROOT);
BigDecimal price = payload.getPriceChf();
if (price == null || price.compareTo(BigDecimal.ZERO) < 0) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Variant priceChf must be >= 0");
}
if (price.scale() > 2) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Variant priceChf must have at most 2 decimal places");
}
if (normalizedSku != null) {
if (variant.getId() == null) {
if (shopProductVariantRepository.existsBySkuIgnoreCase(normalizedSku)) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Variant SKU already exists");
}
} else if (shopProductVariantRepository.existsBySkuIgnoreCaseAndIdNot(normalizedSku, variant.getId())) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Variant SKU already exists");
}
}
variant.setProduct(product);
variant.setSku(normalizedSku);
variant.setVariantLabel(normalizedVariantLabel != null ? normalizedVariantLabel : normalizedColorName);
variant.setColorName(normalizedColorName);
variant.setColorHex(normalizeColorHex(payload.getColorHex()));
variant.setInternalMaterialCode(normalizedMaterialCode);
variant.setPriceChf(price);
variant.setIsDefault(Boolean.TRUE.equals(payload.getIsDefault()));
variant.setIsActive(payload.getIsActive() == null || payload.getIsActive());
variant.setSortOrder(payload.getSortOrder() != null ? payload.getSortOrder() : 0);
variant.setUpdatedAt(OffsetDateTime.now());
}
private List<AdminUpsertShopProductVariantRequest> normalizeVariantPayloads(List<AdminUpsertShopProductVariantRequest> payloads) {
if (payloads == null || payloads.isEmpty()) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "At least one variant is required");
}
List<AdminUpsertShopProductVariantRequest> normalized = new ArrayList<>(payloads);
Set<String> variantKeys = new LinkedHashSet<>();
int defaultCount = 0;
for (AdminUpsertShopProductVariantRequest payload : normalized) {
if (payload == null) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Variant payload is required");
}
String colorName = normalizeRequired(payload.getColorName(), "Variant colorName is required");
String materialCode = normalizeRequired(
payload.getInternalMaterialCode(),
"Variant internalMaterialCode is required"
).toUpperCase(Locale.ROOT);
String variantKey = materialCode + "|" + colorName.toLowerCase(Locale.ROOT);
if (!variantKeys.add(variantKey)) {
throw new ResponseStatusException(
HttpStatus.BAD_REQUEST,
"Duplicate variant combination: " + materialCode + " / " + colorName
);
}
if (Boolean.TRUE.equals(payload.getIsDefault())) {
defaultCount++;
}
}
if (defaultCount > 1) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Only one variant can be default");
}
if (defaultCount == 0) {
AdminUpsertShopProductVariantRequest fallbackDefault = normalized.stream()
.filter(payload -> payload.getIsActive() == null || payload.getIsActive())
.findFirst()
.orElse(normalized.get(0));
fallbackDefault.setIsDefault(true);
}
return normalized;
}
private List<AdminShopProductDto> toProductDtos(List<ShopProduct> products) {
if (products == null || products.isEmpty()) {
return List.of();
}
List<UUID> productIds = products.stream().map(ShopProduct::getId).toList();
Map<UUID, List<ShopProductVariant>> variantsByProductId = shopProductVariantRepository
.findByProduct_IdInOrderBySortOrderAscColorNameAsc(productIds)
.stream()
.collect(Collectors.groupingBy(
variant -> variant.getProduct().getId(),
LinkedHashMap::new,
Collectors.toList()
));
Map<UUID, ShopProductModelAsset> modelAssetsByProductId = shopProductModelAssetRepository.findByProduct_IdIn(productIds)
.stream()
.collect(Collectors.toMap(asset -> asset.getProduct().getId(), asset -> asset, (left, right) -> left, LinkedHashMap::new));
Map<String, List<PublicMediaUsageDto>> publicImagesByUsageKey = publicMediaQueryService.getUsageMediaMap(
SHOP_PRODUCT_MEDIA_USAGE_TYPE,
products.stream().map(this::mediaUsageKey).toList(),
null
);
return products.stream()
.map(product -> {
String usageKey = mediaUsageKey(product);
return toProductDto(
product,
variantsByProductId.getOrDefault(product.getId(), List.of()),
modelAssetsByProductId.get(product.getId()),
publicImagesByUsageKey.getOrDefault(usageKey, List.of()),
adminMediaControllerService.getUsages(SHOP_PRODUCT_MEDIA_USAGE_TYPE, usageKey, null)
);
})
.toList();
}
private AdminShopProductDto toProductDto(ShopProduct product,
List<ShopProductVariant> variants,
ShopProductModelAsset modelAsset,
List<PublicMediaUsageDto> images,
List<AdminMediaUsageDto> mediaUsages) {
AdminShopProductDto dto = new AdminShopProductDto();
dto.setId(product.getId());
dto.setCategoryId(product.getCategory() != null ? product.getCategory().getId() : null);
dto.setCategoryName(product.getCategory() != null ? product.getCategory().getName() : null);
dto.setCategorySlug(product.getCategory() != null ? product.getCategory().getSlug() : null);
dto.setSlug(product.getSlug());
dto.setName(product.getName());
dto.setNameIt(product.getNameIt());
dto.setNameEn(product.getNameEn());
dto.setNameDe(product.getNameDe());
dto.setNameFr(product.getNameFr());
dto.setExcerpt(product.getExcerpt());
dto.setExcerptIt(product.getExcerptIt());
dto.setExcerptEn(product.getExcerptEn());
dto.setExcerptDe(product.getExcerptDe());
dto.setExcerptFr(product.getExcerptFr());
dto.setDescription(product.getDescription());
dto.setDescriptionIt(product.getDescriptionIt());
dto.setDescriptionEn(product.getDescriptionEn());
dto.setDescriptionDe(product.getDescriptionDe());
dto.setDescriptionFr(product.getDescriptionFr());
dto.setSeoTitle(product.getSeoTitle());
dto.setSeoTitleIt(product.getSeoTitleIt());
dto.setSeoTitleEn(product.getSeoTitleEn());
dto.setSeoTitleDe(product.getSeoTitleDe());
dto.setSeoTitleFr(product.getSeoTitleFr());
dto.setSeoDescription(product.getSeoDescription());
dto.setSeoDescriptionIt(product.getSeoDescriptionIt());
dto.setSeoDescriptionEn(product.getSeoDescriptionEn());
dto.setSeoDescriptionDe(product.getSeoDescriptionDe());
dto.setSeoDescriptionFr(product.getSeoDescriptionFr());
dto.setOgTitle(product.getOgTitle());
dto.setOgDescription(product.getOgDescription());
dto.setIndexable(product.getIndexable());
dto.setIsFeatured(product.getIsFeatured());
dto.setIsActive(product.getIsActive());
dto.setSortOrder(product.getSortOrder());
dto.setVariantCount(variants.size());
dto.setActiveVariantCount((int) variants.stream().filter(variant -> Boolean.TRUE.equals(variant.getIsActive())).count());
dto.setPriceFromChf(resolvePriceFrom(variants));
dto.setPriceToChf(resolvePriceTo(variants));
dto.setMediaUsageType(SHOP_PRODUCT_MEDIA_USAGE_TYPE);
dto.setMediaUsageKey(mediaUsageKey(product));
dto.setMediaUsages(mediaUsages);
dto.setImages(images);
dto.setModel3d(toModelDto(product, modelAsset));
dto.setVariants(variants.stream().map(this::toVariantDto).toList());
dto.setCreatedAt(product.getCreatedAt());
dto.setUpdatedAt(product.getUpdatedAt());
return dto;
}
private AdminShopProductVariantDto toVariantDto(ShopProductVariant variant) {
AdminShopProductVariantDto dto = new AdminShopProductVariantDto();
dto.setId(variant.getId());
dto.setSku(variant.getSku());
dto.setVariantLabel(variant.getVariantLabel());
dto.setColorName(variant.getColorName());
dto.setColorHex(variant.getColorHex());
dto.setInternalMaterialCode(variant.getInternalMaterialCode());
dto.setPriceChf(variant.getPriceChf());
dto.setIsDefault(variant.getIsDefault());
dto.setIsActive(variant.getIsActive());
dto.setSortOrder(variant.getSortOrder());
dto.setCreatedAt(variant.getCreatedAt());
dto.setUpdatedAt(variant.getUpdatedAt());
return dto;
}
private ShopProductModelDto toModelDto(ShopProduct product, ShopProductModelAsset asset) {
if (asset == null) {
return null;
}
return new ShopProductModelDto(
"/api/admin/shop/products/" + product.getId() + "/model",
asset.getOriginalFilename(),
asset.getMimeType(),
asset.getFileSizeBytes(),
asset.getBoundingBoxXMm(),
asset.getBoundingBoxYMm(),
asset.getBoundingBoxZMm()
);
}
private BigDecimal resolvePriceFrom(List<ShopProductVariant> variants) {
return variants.stream()
.map(ShopProductVariant::getPriceChf)
.filter(Objects::nonNull)
.min(BigDecimal::compareTo)
.orElse(BigDecimal.ZERO);
}
private BigDecimal resolvePriceTo(List<ShopProductVariant> variants) {
return variants.stream()
.map(ShopProductVariant::getPriceChf)
.filter(Objects::nonNull)
.max(BigDecimal::compareTo)
.orElse(BigDecimal.ZERO);
}
private ShopCategory resolveCategory(UUID categoryId) {
if (categoryId == null) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "categoryId is required");
}
return shopCategoryRepository.findById(categoryId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "Category not found"));
}
private void ensurePayload(AdminUpsertShopProductRequest payload) {
if (payload == null) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Payload is required");
}
}
private LocalizedProductContent normalizeLocalizedProductContent(AdminUpsertShopProductRequest payload) {
String legacyName = normalizeOptional(payload.getName());
String fallbackName = firstNonBlank(
legacyName,
normalizeOptional(payload.getNameIt()),
normalizeOptional(payload.getNameEn()),
normalizeOptional(payload.getNameDe()),
normalizeOptional(payload.getNameFr())
);
if (fallbackName == null) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Product name is required");
}
Map<String, String> names = new LinkedHashMap<>();
names.put("it", normalizeRequired(firstNonBlank(normalizeOptional(payload.getNameIt()), fallbackName), "Italian product name is required"));
names.put("en", normalizeRequired(firstNonBlank(normalizeOptional(payload.getNameEn()), fallbackName), "English product name is required"));
names.put("de", normalizeRequired(firstNonBlank(normalizeOptional(payload.getNameDe()), fallbackName), "German product name is required"));
names.put("fr", normalizeRequired(firstNonBlank(normalizeOptional(payload.getNameFr()), fallbackName), "French product name is required"));
String fallbackExcerpt = firstNonBlank(
normalizeOptional(payload.getExcerpt()),
normalizeOptional(payload.getExcerptIt()),
normalizeOptional(payload.getExcerptEn()),
normalizeOptional(payload.getExcerptDe()),
normalizeOptional(payload.getExcerptFr())
);
Map<String, String> excerpts = new LinkedHashMap<>();
excerpts.put("it", firstNonBlank(normalizeOptional(payload.getExcerptIt()), fallbackExcerpt));
excerpts.put("en", firstNonBlank(normalizeOptional(payload.getExcerptEn()), fallbackExcerpt));
excerpts.put("de", firstNonBlank(normalizeOptional(payload.getExcerptDe()), fallbackExcerpt));
excerpts.put("fr", firstNonBlank(normalizeOptional(payload.getExcerptFr()), fallbackExcerpt));
String fallbackDescription = firstNonBlank(
normalizeRichTextOptional(payload.getDescription()),
normalizeRichTextOptional(payload.getDescriptionIt()),
normalizeRichTextOptional(payload.getDescriptionEn()),
normalizeRichTextOptional(payload.getDescriptionDe()),
normalizeRichTextOptional(payload.getDescriptionFr())
);
Map<String, String> descriptions = new LinkedHashMap<>();
descriptions.put("it", firstNonBlank(normalizeRichTextOptional(payload.getDescriptionIt()), fallbackDescription));
descriptions.put("en", firstNonBlank(normalizeRichTextOptional(payload.getDescriptionEn()), fallbackDescription));
descriptions.put("de", firstNonBlank(normalizeRichTextOptional(payload.getDescriptionDe()), fallbackDescription));
descriptions.put("fr", firstNonBlank(normalizeRichTextOptional(payload.getDescriptionFr()), fallbackDescription));
String fallbackSeoTitle = firstNonBlank(
normalizeOptional(payload.getSeoTitle()),
normalizeOptional(payload.getSeoTitleIt()),
normalizeOptional(payload.getSeoTitleEn()),
normalizeOptional(payload.getSeoTitleDe()),
normalizeOptional(payload.getSeoTitleFr())
);
Map<String, String> seoTitles = new LinkedHashMap<>();
seoTitles.put("it", firstNonBlank(normalizeOptional(payload.getSeoTitleIt()), fallbackSeoTitle));
seoTitles.put("en", firstNonBlank(normalizeOptional(payload.getSeoTitleEn()), fallbackSeoTitle));
seoTitles.put("de", firstNonBlank(normalizeOptional(payload.getSeoTitleDe()), fallbackSeoTitle));
seoTitles.put("fr", firstNonBlank(normalizeOptional(payload.getSeoTitleFr()), fallbackSeoTitle));
String fallbackSeoDescription = firstNonBlank(
normalizeOptional(payload.getSeoDescription()),
normalizeOptional(payload.getSeoDescriptionIt()),
normalizeOptional(payload.getSeoDescriptionEn()),
normalizeOptional(payload.getSeoDescriptionDe()),
normalizeOptional(payload.getSeoDescriptionFr())
);
Map<String, String> seoDescriptions = new LinkedHashMap<>();
seoDescriptions.put("it", validateSeoDescriptionLength(firstNonBlank(normalizeOptional(payload.getSeoDescriptionIt()), fallbackSeoDescription), "Italian"));
seoDescriptions.put("en", validateSeoDescriptionLength(firstNonBlank(normalizeOptional(payload.getSeoDescriptionEn()), fallbackSeoDescription), "English"));
seoDescriptions.put("de", validateSeoDescriptionLength(firstNonBlank(normalizeOptional(payload.getSeoDescriptionDe()), fallbackSeoDescription), "German"));
seoDescriptions.put("fr", validateSeoDescriptionLength(firstNonBlank(normalizeOptional(payload.getSeoDescriptionFr()), fallbackSeoDescription), "French"));
return new LocalizedProductContent(
names.get("it"),
firstNonBlank(excerpts.get("it"), fallbackExcerpt),
firstNonBlank(descriptions.get("it"), fallbackDescription),
firstNonBlank(seoTitles.get("it"), fallbackSeoTitle),
firstNonBlank(seoDescriptions.get("it"), fallbackSeoDescription),
names,
excerpts,
descriptions,
seoTitles,
seoDescriptions
);
}
private void ensureSlugAvailable(String slug, UUID currentProductId) {
shopProductRepository.findBySlugIgnoreCase(slug).ifPresent(existing -> {
if (currentProductId == null || !existing.getId().equals(currentProductId)) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Product slug already exists");
}
});
}
private String normalizeRequired(String value, String message) {
String normalized = normalizeOptional(value);
if (normalized == null) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, message);
}
return normalized;
}
private String normalizeOptional(String value) {
if (value == null) {
return null;
}
String normalized = value.trim();
return normalized.isBlank() ? null : normalized;
}
private String normalizeRichTextOptional(String value) {
String normalized = normalizeOptional(value);
if (normalized == null) {
return null;
}
String sanitized = Jsoup.clean(
normalized,
"",
PRODUCT_DESCRIPTION_SAFELIST,
new Document.OutputSettings().prettyPrint(false)
).trim();
if (sanitized.isBlank()) {
return null;
}
String plainText = Jsoup.parse(sanitized).text();
return plainText != null && !plainText.trim().isEmpty() ? sanitized : null;
}
private String firstNonBlank(String... values) {
if (values == null) {
return null;
}
for (String value : values) {
if (value != null && !value.isBlank()) {
return value;
}
}
return null;
}
private String normalizeAndValidateSlug(String slug, String fallbackName) {
String source = normalizeOptional(slug);
if (source == null) {
source = fallbackName;
}
String normalized = Normalizer.normalize(source, Normalizer.Form.NFD);
normalized = DIACRITICS_PATTERN.matcher(normalized).replaceAll("");
normalized = normalized.toLowerCase(Locale.ROOT);
normalized = NON_ALPHANUMERIC_PATTERN.matcher(normalized).replaceAll("-");
normalized = EDGE_DASH_PATTERN.matcher(normalized).replaceAll("");
if (normalized.isBlank()) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Slug is invalid");
}
return normalized;
}
private String normalizeColorHex(String value) {
String normalized = normalizeOptional(value);
if (normalized == null) {
return null;
}
if (!HEX_COLOR_PATTERN.matcher(normalized).matches()) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Variant colorHex must be in format #RRGGBB");
}
return normalized.toUpperCase(Locale.ROOT);
}
private String validateSeoDescriptionLength(String value, String languageLabel) {
if (value != null && value.length() > 160) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, languageLabel + " SEO description must be at most 160 characters");
}
return value;
}
private void validateModelUpload(MultipartFile file) {
if (file == null || file.isEmpty()) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "3D model file is required");
}
if (maxModelFileSizeBytes > 0 && file.getSize() > maxModelFileSizeBytes) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "3D model file exceeds size limit");
}
String extension = resolveExtension(sanitizeOriginalFilename(file.getOriginalFilename()));
if (!SUPPORTED_MODEL_EXTENSIONS.contains(extension)) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Unsupported 3D model type. Allowed: stl, 3mf");
}
}
private String sanitizeOriginalFilename(String originalFilename) {
String cleaned = StringUtils.cleanPath(originalFilename == null ? "" : originalFilename);
int separatorIndex = Math.max(cleaned.lastIndexOf('/'), cleaned.lastIndexOf('\\'));
String basename = separatorIndex >= 0 ? cleaned.substring(separatorIndex + 1) : cleaned;
basename = basename.replace("\r", "_").replace("\n", "_");
return basename.isBlank() ? "model.stl" : basename;
}
private String resolveExtension(String filename) {
int dotIndex = filename.lastIndexOf('.');
if (dotIndex < 0 || dotIndex == filename.length() - 1) {
return "";
}
return filename.substring(dotIndex + 1).toLowerCase(Locale.ROOT);
}
private String buildDownloadFilename(String originalFilename) {
int dotIndex = originalFilename.lastIndexOf('.');
String base = dotIndex > 0 ? originalFilename.substring(0, dotIndex) : originalFilename;
return base + ".stl";
}
private String mediaUsageKey(ShopProduct product) {
return product.getId().toString();
}
private void deleteExistingModelFile(ShopProductModelAsset asset, UUID productId) {
if (asset == null || asset.getStoredRelativePath() == null || asset.getStoredRelativePath().isBlank()) {
return;
}
Path existingPath = shopStorageService.resolveStoredProductPath(asset.getStoredRelativePath(), productId);
if (existingPath == null) {
return;
}
try {
Files.deleteIfExists(existingPath);
} catch (IOException ignored) {
}
}
private void deleteStoredRelativePath(String storedRelativePath, UUID productId, String excludeStoredRelativePath) {
if (storedRelativePath == null || storedRelativePath.isBlank()) {
return;
}
if (Objects.equals(storedRelativePath, excludeStoredRelativePath)) {
return;
}
Path existingPath = shopStorageService.resolveStoredProductPath(storedRelativePath, productId);
deletePathQuietly(existingPath);
}
private String computeSha256(Path file) throws IOException {
MessageDigest digest;
try {
digest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new IOException("SHA-256 digest unavailable", e);
}
try (InputStream inputStream = Files.newInputStream(file)) {
byte[] buffer = new byte[8192];
int read;
while ((read = inputStream.read(buffer)) >= 0) {
if (read > 0) {
digest.update(buffer, 0, read);
}
}
}
return HexFormat.of().formatHex(digest.digest());
}
private void deletePathQuietly(Path path) {
if (path == null) {
return;
}
try {
Files.deleteIfExists(path);
} catch (IOException ignored) {
}
}
private void deleteRecursively(Path path) {
if (path == null || !Files.exists(path)) {
return;
}
try (var walk = Files.walk(path)) {
walk.sorted(Comparator.reverseOrder()).forEach(current -> {
try {
Files.deleteIfExists(current);
} catch (IOException ignored) {
}
});
} catch (IOException ignored) {
}
}
public record ProductModelDownload(Path path, String filename, String mimeType) {
}
private record LocalizedProductContent(
String defaultName,
String defaultExcerpt,
String defaultDescription,
String defaultSeoTitle,
String defaultSeoDescription,
Map<String, String> names,
Map<String, String> excerpts,
Map<String, String> descriptions,
Map<String, String> seoTitles,
Map<String, String> seoDescriptions
) {
}
}

View File

@@ -29,13 +29,18 @@ public class MediaFfmpegService {
"WEBP", List.of("libwebp", "webp"), "WEBP", List.of("libwebp", "webp"),
"AVIF", List.of("libaom-av1", "librav1e", "libsvtav1") "AVIF", List.of("libaom-av1", "librav1e", "libsvtav1")
); );
private static final Map<String, List<String>> REQUIRED_MUXERS = Map.of(
"AVIF", List.of("avif")
);
private final String ffmpegExecutable; private final String ffmpegExecutable;
private final Set<String> availableEncoders; private final Set<String> availableEncoders;
private final Set<String> availableMuxers;
public MediaFfmpegService(@Value("${media.ffmpeg.path:ffmpeg}") String ffmpegPath) { public MediaFfmpegService(@Value("${media.ffmpeg.path:ffmpeg}") String ffmpegPath) {
this.ffmpegExecutable = resolveExecutable(ffmpegPath); this.ffmpegExecutable = resolveExecutable(ffmpegPath);
this.availableEncoders = Collections.unmodifiableSet(loadAvailableEncoders()); this.availableEncoders = Collections.unmodifiableSet(loadAvailableEncoders());
this.availableMuxers = Collections.unmodifiableSet(loadAvailableMuxers());
} }
public void generateVariant(Path source, Path target, int widthPx, int heightPx, String format) throws IOException { public void generateVariant(Path source, Path target, int widthPx, int heightPx, String format) throws IOException {
@@ -47,9 +52,13 @@ public class MediaFfmpegService {
Path targetPath = sanitizeMediaPath(target, "target", false); Path targetPath = sanitizeMediaPath(target, "target", false);
Files.createDirectories(targetPath.getParent()); Files.createDirectories(targetPath.getParent());
String encoder = resolveEncoder(format); String normalizedFormat = normalizeFormat(format);
String encoder = resolveEncoder(normalizedFormat);
if (encoder == null) { if (encoder == null) {
throw new IOException("FFmpeg encoder not available for media format " + format + "."); throw new IOException("FFmpeg encoder not available for media format " + normalizedFormat + ".");
}
if (!hasRequiredMuxer(normalizedFormat)) {
throw new IOException("FFmpeg muxer not available for media format " + normalizedFormat + ".");
} }
List<String> command = new ArrayList<>(); List<String> command = new ArrayList<>();
@@ -66,7 +75,7 @@ public class MediaFfmpegService {
command.add("1"); command.add("1");
command.add("-an"); command.add("-an");
switch (format) { switch (normalizedFormat) {
case "JPEG" -> { case "JPEG" -> {
command.add("-c:v"); command.add("-c:v");
command.add(encoder); command.add(encoder);
@@ -82,14 +91,14 @@ public class MediaFfmpegService {
case "AVIF" -> { case "AVIF" -> {
command.add("-c:v"); command.add("-c:v");
command.add(encoder); command.add(encoder);
command.add("-still-picture");
command.add("1");
command.add("-crf"); command.add("-crf");
command.add("30"); command.add("30");
command.add("-b:v"); command.add("-b:v");
command.add("0"); command.add("0");
command.add("-f");
command.add("avif");
} }
default -> throw new IllegalArgumentException("Unsupported media format: " + format); default -> throw new IllegalArgumentException("Unsupported media format: " + normalizedFormat);
} }
command.add(targetPath.toString()); command.add(targetPath.toString());
@@ -114,14 +123,16 @@ public class MediaFfmpegService {
} }
public boolean canEncode(String format) { public boolean canEncode(String format) {
return resolveEncoder(format) != null; String normalizedFormat = normalizeFormat(format);
return resolveEncoder(normalizedFormat) != null && hasRequiredMuxer(normalizedFormat);
} }
private String resolveEncoder(String format) { private String resolveEncoder(String format) {
if (format == null) { String normalizedFormat = normalizeFormat(format);
if (normalizedFormat == null) {
return null; return null;
} }
List<String> candidates = ENCODER_CANDIDATES.get(format.trim().toUpperCase(Locale.ROOT)); List<String> candidates = ENCODER_CANDIDATES.get(normalizedFormat);
if (candidates == null) { if (candidates == null) {
return null; return null;
} }
@@ -131,6 +142,21 @@ public class MediaFfmpegService {
.orElse(null); .orElse(null);
} }
private boolean hasRequiredMuxer(String format) {
List<String> requiredMuxers = REQUIRED_MUXERS.get(format);
if (requiredMuxers == null || requiredMuxers.isEmpty()) {
return true;
}
return requiredMuxers.stream().anyMatch(availableMuxers::contains);
}
private String normalizeFormat(String format) {
if (format == null) {
return null;
}
return format.trim().toUpperCase(Locale.ROOT);
}
private Set<String> loadAvailableEncoders() { private Set<String> loadAvailableEncoders() {
List<String> command = List.of(ffmpegExecutable, "-hide_banner", "-encoders"); List<String> command = List.of(ffmpegExecutable, "-hide_banner", "-encoders");
try { try {
@@ -156,6 +182,31 @@ public class MediaFfmpegService {
} }
} }
private Set<String> loadAvailableMuxers() {
List<String> command = List.of(ffmpegExecutable, "-hide_banner", "-muxers");
try {
Process process = startValidatedProcess(command);
String output;
try (InputStream processStream = process.getInputStream()) {
output = new String(processStream.readAllBytes(), StandardCharsets.UTF_8);
}
int exitCode = process.waitFor();
if (exitCode != 0) {
logger.warn("Unable to inspect FFmpeg muxers. Falling back to empty muxer list.");
return Set.of();
}
return parseAvailableMuxers(output);
} catch (Exception e) {
logger.warn(
"Unable to inspect FFmpeg muxers for executable '{}'. Falling back to empty muxer list. {}",
ffmpegExecutable,
e.getMessage()
);
return Set.of();
}
}
private Process startValidatedProcess(List<String> command) throws IOException { private Process startValidatedProcess(List<String> command) throws IOException {
// nosemgrep: java.lang.security.audit.command-injection-process-builder.command-injection-process-builder // nosemgrep: java.lang.security.audit.command-injection-process-builder.command-injection-process-builder
return new ProcessBuilder(List.copyOf(command)) return new ProcessBuilder(List.copyOf(command))
@@ -266,6 +317,26 @@ public class MediaFfmpegService {
return encoders; return encoders;
} }
private Set<String> parseAvailableMuxers(String output) {
if (output == null || output.isBlank()) {
return Set.of();
}
Set<String> muxers = new LinkedHashSet<>();
for (String line : output.split("\\R")) {
String trimmed = line.trim();
if (trimmed.isBlank() || trimmed.startsWith("--") || trimmed.startsWith("Muxers:")) {
continue;
}
String[] parts = trimmed.split("\\s+", 3);
if (parts.length < 2) {
continue;
}
muxers.add(parts[1]);
}
return muxers;
}
private String truncate(String output) { private String truncate(String output) {
if (output == null || output.isBlank()) { if (output == null || output.isBlank()) {
return ""; return "";

View File

@@ -18,15 +18,15 @@ public class MediaStorageService {
private final Path originalRootLocation; private final Path originalRootLocation;
private final Path publicRootLocation; private final Path publicRootLocation;
private final Path privateRootLocation; private final Path privateRootLocation;
private final String publicBaseUrl; private final String frontendBaseUrl;
public MediaStorageService(@Value("${media.storage.root:storage_media}") String storageRoot, public MediaStorageService(@Value("${media.storage.root:storage_media}") String storageRoot,
@Value("${media.public.base-url:http://localhost:8080/media}") String publicBaseUrl) { @Value("${app.frontend.base-url:${APP_FRONTEND_BASE_URL:http://localhost:8081}}") String frontendBaseUrl) {
this.normalizedRootLocation = Paths.get(storageRoot).toAbsolutePath().normalize(); this.normalizedRootLocation = Paths.get(storageRoot).toAbsolutePath().normalize();
this.originalRootLocation = normalizedRootLocation.resolve("original").normalize(); this.originalRootLocation = normalizedRootLocation.resolve("original").normalize();
this.publicRootLocation = normalizedRootLocation.resolve("public").normalize(); this.publicRootLocation = normalizedRootLocation.resolve("public").normalize();
this.privateRootLocation = normalizedRootLocation.resolve("private").normalize(); this.privateRootLocation = normalizedRootLocation.resolve("private").normalize();
this.publicBaseUrl = publicBaseUrl; this.frontendBaseUrl = frontendBaseUrl;
init(); init();
} }
@@ -73,11 +73,12 @@ public class MediaStorageService {
if (storageKey == null || storageKey.isBlank()) { if (storageKey == null || storageKey.isBlank()) {
return null; return null;
} }
String mediaBaseUrl = buildMediaBaseUrl();
String normalizedKey = storageKey.startsWith("/") ? storageKey.substring(1) : storageKey; String normalizedKey = storageKey.startsWith("/") ? storageKey.substring(1) : storageKey;
if (publicBaseUrl.endsWith("/")) { if (mediaBaseUrl.endsWith("/")) {
return publicBaseUrl + normalizedKey; return mediaBaseUrl + normalizedKey;
} }
return publicBaseUrl + "/" + normalizedKey; return mediaBaseUrl + "/" + normalizedKey;
} }
private void copy(Path source, Path destination) throws IOException { private void copy(Path source, Path destination) throws IOException {
@@ -127,4 +128,18 @@ public class MediaStorageService {
} }
return visibility.trim().toUpperCase(Locale.ROOT); return visibility.trim().toUpperCase(Locale.ROOT);
} }
private String buildMediaBaseUrl() {
String normalized = frontendBaseUrl != null ? frontendBaseUrl.trim() : "";
if (normalized.contains("localhost")){
return "http://localhost:8081";
}
if (normalized.isBlank()) {
normalized = "http://localhost:8081";
}
if (normalized.endsWith("/")) {
normalized = normalized.substring(0, normalized.length() - 1);
}
return normalized + "/media";
}
} }

View File

@@ -14,6 +14,7 @@ import org.springframework.web.server.ResponseStatusException;
import java.time.OffsetDateTime; import java.time.OffsetDateTime;
import java.util.Comparator; import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
@@ -48,22 +49,40 @@ public class PublicMediaQueryService {
public List<PublicMediaUsageDto> getUsageMedia(String usageType, String usageKey, String language) { public List<PublicMediaUsageDto> getUsageMedia(String usageType, String usageKey, String language) {
String normalizedUsageType = normalizeUsageType(usageType); String normalizedUsageType = normalizeUsageType(usageType);
String normalizedUsageKey = normalizeUsageKey(usageKey); String normalizedUsageKey = normalizeUsageKey(usageKey);
return getUsageMediaMap(normalizedUsageType, List.of(normalizedUsageKey), language)
.getOrDefault(normalizedUsageKey, List.of());
}
public Map<String, List<PublicMediaUsageDto>> getUsageMediaMap(String usageType,
List<String> usageKeys,
String language) {
String normalizedUsageType = normalizeUsageType(usageType);
String normalizedLanguage = normalizeLanguage(language); String normalizedLanguage = normalizeLanguage(language);
List<String> normalizedUsageKeys = (usageKeys == null
? List.<String>of()
: usageKeys)
.stream()
.filter(Objects::nonNull)
.map(this::normalizeUsageKey)
.distinct()
.toList();
if (normalizedUsageKeys.isEmpty()) {
return Map.of();
}
List<MediaUsage> usages = mediaUsageRepository List<MediaUsage> usages = mediaUsageRepository
.findByUsageTypeAndUsageKeyAndIsActiveTrueOrderBySortOrderAscCreatedAtAsc( .findActiveByUsageTypeAndUsageKeys(normalizedUsageType, normalizedUsageKeys)
normalizedUsageType,
normalizedUsageKey
)
.stream() .stream()
.filter(this::isPublicReadyUsage) .filter(this::isPublicReadyUsage)
.sorted(Comparator .sorted(Comparator
.comparing(MediaUsage::getSortOrder, Comparator.nullsLast(Integer::compareTo)) .comparing(MediaUsage::getUsageKey, Comparator.nullsLast(String::compareTo))
.thenComparing(MediaUsage::getSortOrder, Comparator.nullsLast(Integer::compareTo))
.thenComparing(MediaUsage::getCreatedAt, Comparator.nullsLast(OffsetDateTime::compareTo))) .thenComparing(MediaUsage::getCreatedAt, Comparator.nullsLast(OffsetDateTime::compareTo)))
.toList(); .toList();
if (usages.isEmpty()) { if (usages.isEmpty()) {
return List.of(); return Map.of();
} }
List<UUID> assetIds = usages.stream() List<UUID> assetIds = usages.stream()
@@ -79,13 +98,16 @@ public class PublicMediaQueryService {
.filter(variant -> !Objects.equals("ORIGINAL", variant.getFormat())) .filter(variant -> !Objects.equals("ORIGINAL", variant.getFormat()))
.collect(Collectors.groupingBy(variant -> variant.getMediaAsset().getId())); .collect(Collectors.groupingBy(variant -> variant.getMediaAsset().getId()));
return usages.stream() Map<String, List<PublicMediaUsageDto>> result = new LinkedHashMap<>();
.map(usage -> toDto( for (MediaUsage usage : usages) {
result.computeIfAbsent(usage.getUsageKey(), ignored -> new java.util.ArrayList<>())
.add(toDto(
usage, usage,
variantsByAssetId.getOrDefault(usage.getMediaAsset().getId(), List.of()), variantsByAssetId.getOrDefault(usage.getMediaAsset().getId(), List.of()),
normalizedLanguage normalizedLanguage
)) ));
.toList(); }
return result;
} }
private boolean isPublicReadyUsage(MediaUsage usage) { private boolean isPublicReadyUsage(MediaUsage usage) {

View File

@@ -197,6 +197,7 @@ public class AdminOrderControllerService {
OrderDto dto = new OrderDto(); OrderDto dto = new OrderDto();
dto.setId(order.getId()); dto.setId(order.getId());
dto.setOrderNumber(getDisplayOrderNumber(order)); dto.setOrderNumber(getDisplayOrderNumber(order));
dto.setSourceType(order.getSourceType() != null ? order.getSourceType() : "CALCULATOR");
dto.setStatus(order.getStatus()); dto.setStatus(order.getStatus());
paymentRepo.findByOrder_Id(order.getId()).ifPresent(payment -> { paymentRepo.findByOrder_Id(order.getId()).ifPresent(payment -> {
@@ -260,9 +261,26 @@ public class AdminOrderControllerService {
List<OrderItemDto> itemDtos = items.stream().map(item -> { List<OrderItemDto> itemDtos = items.stream().map(item -> {
OrderItemDto itemDto = new OrderItemDto(); OrderItemDto itemDto = new OrderItemDto();
itemDto.setId(item.getId()); itemDto.setId(item.getId());
itemDto.setItemType(item.getItemType() != null ? item.getItemType() : "PRINT_FILE");
itemDto.setOriginalFilename(item.getOriginalFilename()); itemDto.setOriginalFilename(item.getOriginalFilename());
itemDto.setDisplayName(
item.getDisplayName() != null && !item.getDisplayName().isBlank()
? item.getDisplayName()
: item.getOriginalFilename()
);
itemDto.setMaterialCode(item.getMaterialCode()); itemDto.setMaterialCode(item.getMaterialCode());
itemDto.setColorCode(item.getColorCode()); itemDto.setColorCode(item.getColorCode());
if (item.getShopProduct() != null) {
itemDto.setShopProductId(item.getShopProduct().getId());
}
if (item.getShopProductVariant() != null) {
itemDto.setShopProductVariantId(item.getShopProductVariant().getId());
}
itemDto.setShopProductSlug(item.getShopProductSlug());
itemDto.setShopProductName(item.getShopProductName());
itemDto.setShopVariantLabel(item.getShopVariantLabel());
itemDto.setShopVariantColorName(item.getShopVariantColorName());
itemDto.setShopVariantColorHex(item.getShopVariantColorHex());
if (item.getFilamentVariant() != null) { if (item.getFilamentVariant() != null) {
itemDto.setFilamentVariantId(item.getFilamentVariant().getId()); itemDto.setFilamentVariantId(item.getFilamentVariant().getId());
itemDto.setFilamentVariantDisplayName(item.getFilamentVariant().getVariantDisplayName()); itemDto.setFilamentVariantDisplayName(item.getFilamentVariant().getVariantDisplayName());

View File

@@ -255,6 +255,7 @@ public class OrderControllerService {
OrderDto dto = new OrderDto(); OrderDto dto = new OrderDto();
dto.setId(order.getId()); dto.setId(order.getId());
dto.setOrderNumber(getDisplayOrderNumber(order)); dto.setOrderNumber(getDisplayOrderNumber(order));
dto.setSourceType(order.getSourceType() != null ? order.getSourceType() : "CALCULATOR");
dto.setStatus(order.getStatus()); dto.setStatus(order.getStatus());
paymentRepo.findByOrder_Id(order.getId()).ifPresent(payment -> { paymentRepo.findByOrder_Id(order.getId()).ifPresent(payment -> {
@@ -314,9 +315,26 @@ public class OrderControllerService {
List<OrderItemDto> itemDtos = items.stream().map(item -> { List<OrderItemDto> itemDtos = items.stream().map(item -> {
OrderItemDto itemDto = new OrderItemDto(); OrderItemDto itemDto = new OrderItemDto();
itemDto.setId(item.getId()); itemDto.setId(item.getId());
itemDto.setItemType(item.getItemType() != null ? item.getItemType() : "PRINT_FILE");
itemDto.setOriginalFilename(item.getOriginalFilename()); itemDto.setOriginalFilename(item.getOriginalFilename());
itemDto.setDisplayName(
item.getDisplayName() != null && !item.getDisplayName().isBlank()
? item.getDisplayName()
: item.getOriginalFilename()
);
itemDto.setMaterialCode(item.getMaterialCode()); itemDto.setMaterialCode(item.getMaterialCode());
itemDto.setColorCode(item.getColorCode()); itemDto.setColorCode(item.getColorCode());
if (item.getShopProduct() != null) {
itemDto.setShopProductId(item.getShopProduct().getId());
}
if (item.getShopProductVariant() != null) {
itemDto.setShopProductVariantId(item.getShopProductVariant().getId());
}
itemDto.setShopProductSlug(item.getShopProductSlug());
itemDto.setShopProductName(item.getShopProductName());
itemDto.setShopVariantLabel(item.getShopVariantLabel());
itemDto.setShopVariantColorName(item.getShopVariantColorName());
itemDto.setShopVariantColorHex(item.getShopVariantColorHex());
if (item.getFilamentVariant() != null) { if (item.getFilamentVariant() != null) {
itemDto.setFilamentVariantId(item.getFilamentVariant().getId()); itemDto.setFilamentVariantId(item.getFilamentVariant().getId());
itemDto.setFilamentVariantDisplayName(item.getFilamentVariant().getVariantDisplayName()); itemDto.setFilamentVariantDisplayName(item.getFilamentVariant().getVariantDisplayName());

View File

@@ -88,14 +88,9 @@ public class InvoicePdfRenderingService {
vars.put("shippingAddressLine2", order.getShippingZip() + " " + order.getShippingCity() + ", " + order.getShippingCountryCode()); vars.put("shippingAddressLine2", order.getShippingZip() + " " + order.getShippingCity() + ", " + order.getShippingCountryCode());
} }
List<Map<String, Object>> invoiceLineItems = items.stream().map(i -> { List<Map<String, Object>> invoiceLineItems = items.stream()
Map<String, Object> line = new HashMap<>(); .map(this::toInvoiceLineItem)
line.put("description", "Stampa 3D: " + i.getOriginalFilename()); .collect(Collectors.toList());
line.put("quantity", i.getQuantity());
line.put("unitPriceFormatted", String.format("CHF %.2f", i.getUnitPriceChf()));
line.put("lineTotalFormatted", String.format("CHF %.2f", i.getLineTotalChf()));
return line;
}).collect(Collectors.toList());
if (order.getCadTotalChf() != null && order.getCadTotalChf().compareTo(BigDecimal.ZERO) > 0) { if (order.getCadTotalChf() != null && order.getCadTotalChf().compareTo(BigDecimal.ZERO) > 0) {
BigDecimal cadHours = order.getCadHours() != null ? order.getCadHours() : BigDecimal.ZERO; BigDecimal cadHours = order.getCadHours() != null ? order.getCadHours() : BigDecimal.ZERO;
@@ -157,4 +152,45 @@ public class InvoicePdfRenderingService {
private String formatCadHours(BigDecimal hours) { private String formatCadHours(BigDecimal hours) {
return hours.setScale(2, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString(); return hours.setScale(2, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString();
} }
private Map<String, Object> toInvoiceLineItem(OrderItem item) {
Map<String, Object> line = new HashMap<>();
line.put("description", buildLineDescription(item));
line.put("quantity", item.getQuantity());
line.put("unitPriceFormatted", String.format("CHF %.2f", item.getUnitPriceChf()));
line.put("lineTotalFormatted", String.format("CHF %.2f", item.getLineTotalChf()));
return line;
}
private String buildLineDescription(OrderItem item) {
if (item == null) {
return "Articolo";
}
if ("SHOP_PRODUCT".equalsIgnoreCase(item.getItemType())) {
String productName = firstNonBlank(
item.getDisplayName(),
item.getShopProductName(),
item.getOriginalFilename(),
"Prodotto shop"
);
String variantLabel = firstNonBlank(item.getShopVariantLabel(), item.getShopVariantColorName(), null);
return variantLabel != null ? productName + " - " + variantLabel : productName;
}
String fileName = firstNonBlank(item.getDisplayName(), item.getOriginalFilename(), "File 3D");
return "Stampa 3D: " + fileName;
}
private String firstNonBlank(String... values) {
if (values == null || values.length == 0) {
return null;
}
for (String value : values) {
if (value != null && !value.isBlank()) {
return value;
}
}
return null;
}
} }

View File

@@ -237,7 +237,9 @@ public class QuoteSessionItemService {
Path convertedPersistentPath) { Path convertedPersistentPath) {
QuoteLineItem item = new QuoteLineItem(); QuoteLineItem item = new QuoteLineItem();
item.setQuoteSession(session); item.setQuoteSession(session);
item.setLineItemType("PRINT_FILE");
item.setOriginalFilename(originalFilename); item.setOriginalFilename(originalFilename);
item.setDisplayName(originalFilename);
item.setStoredPath(quoteStorageService.toStoredPath(persistentPath)); item.setStoredPath(quoteStorageService.toStoredPath(persistentPath));
item.setQuantity(normalizeQuantity(settings.getQuantity())); item.setQuantity(normalizeQuantity(settings.getQuantity()));
item.setColorCode(selectedVariant.getColorName()); item.setColorCode(selectedVariant.getColorName());

View File

@@ -43,15 +43,45 @@ public class QuoteSessionResponseAssembler {
return response; return response;
} }
public Map<String, Object> emptyCart() {
Map<String, Object> response = new HashMap<>();
response.put("session", null);
response.put("items", List.of());
response.put("printItemsTotalChf", BigDecimal.ZERO);
response.put("cadTotalChf", BigDecimal.ZERO);
response.put("itemsTotalChf", BigDecimal.ZERO);
response.put("baseSetupCostChf", BigDecimal.ZERO);
response.put("nozzleChangeCostChf", BigDecimal.ZERO);
response.put("setupCostChf", BigDecimal.ZERO);
response.put("shippingCostChf", BigDecimal.ZERO);
response.put("globalMachineCostChf", BigDecimal.ZERO);
response.put("grandTotalChf", BigDecimal.ZERO);
return response;
}
private Map<String, Object> toItemDto(QuoteLineItem item, QuoteSessionTotalsService.QuoteSessionTotals totals) { private Map<String, Object> toItemDto(QuoteLineItem item, QuoteSessionTotalsService.QuoteSessionTotals totals) {
Map<String, Object> dto = new HashMap<>(); Map<String, Object> dto = new HashMap<>();
dto.put("id", item.getId()); dto.put("id", item.getId());
dto.put("lineItemType", item.getLineItemType() != null ? item.getLineItemType() : "PRINT_FILE");
dto.put("originalFilename", item.getOriginalFilename()); dto.put("originalFilename", item.getOriginalFilename());
dto.put(
"displayName",
item.getDisplayName() != null && !item.getDisplayName().isBlank()
? item.getDisplayName()
: item.getOriginalFilename()
);
dto.put("quantity", item.getQuantity()); dto.put("quantity", item.getQuantity());
dto.put("printTimeSeconds", item.getPrintTimeSeconds()); dto.put("printTimeSeconds", item.getPrintTimeSeconds());
dto.put("materialGrams", item.getMaterialGrams()); dto.put("materialGrams", item.getMaterialGrams());
dto.put("colorCode", item.getColorCode()); dto.put("colorCode", item.getColorCode());
dto.put("filamentVariantId", item.getFilamentVariant() != null ? item.getFilamentVariant().getId() : null); dto.put("filamentVariantId", item.getFilamentVariant() != null ? item.getFilamentVariant().getId() : null);
dto.put("shopProductId", item.getShopProduct() != null ? item.getShopProduct().getId() : null);
dto.put("shopProductVariantId", item.getShopProductVariant() != null ? item.getShopProductVariant().getId() : null);
dto.put("shopProductSlug", item.getShopProductSlug());
dto.put("shopProductName", item.getShopProductName());
dto.put("shopVariantLabel", item.getShopVariantLabel());
dto.put("shopVariantColorName", item.getShopVariantColorName());
dto.put("shopVariantColorHex", item.getShopVariantColorHex());
dto.put("materialCode", item.getMaterialCode()); dto.put("materialCode", item.getMaterialCode());
dto.put("quality", item.getQuality()); dto.put("quality", item.getQuality());
dto.put("nozzleDiameterMm", item.getNozzleDiameterMm()); dto.put("nozzleDiameterMm", item.getNozzleDiameterMm());

View File

@@ -0,0 +1,588 @@
package com.printcalculator.service.shop;
import com.printcalculator.dto.PublicMediaUsageDto;
import com.printcalculator.dto.ShopCategoryDetailDto;
import com.printcalculator.dto.ShopCategoryRefDto;
import com.printcalculator.dto.ShopCategoryTreeDto;
import com.printcalculator.dto.ShopProductCatalogResponseDto;
import com.printcalculator.dto.ShopProductDetailDto;
import com.printcalculator.dto.ShopProductModelDto;
import com.printcalculator.dto.ShopProductSummaryDto;
import com.printcalculator.dto.ShopProductVariantOptionDto;
import com.printcalculator.entity.FilamentVariant;
import com.printcalculator.entity.ShopCategory;
import com.printcalculator.entity.ShopProduct;
import com.printcalculator.entity.ShopProductModelAsset;
import com.printcalculator.entity.ShopProductVariant;
import com.printcalculator.repository.FilamentVariantRepository;
import com.printcalculator.repository.ShopCategoryRepository;
import com.printcalculator.repository.ShopProductModelAssetRepository;
import com.printcalculator.repository.ShopProductRepository;
import com.printcalculator.repository.ShopProductVariantRepository;
import com.printcalculator.service.media.PublicMediaQueryService;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;
@Service
@Transactional(readOnly = true)
public class PublicShopCatalogService {
private static final String SHOP_CATEGORY_MEDIA_USAGE_TYPE = "SHOP_CATEGORY";
private static final String SHOP_PRODUCT_MEDIA_USAGE_TYPE = "SHOP_PRODUCT";
private final ShopCategoryRepository shopCategoryRepository;
private final ShopProductRepository shopProductRepository;
private final ShopProductVariantRepository shopProductVariantRepository;
private final ShopProductModelAssetRepository shopProductModelAssetRepository;
private final FilamentVariantRepository filamentVariantRepository;
private final PublicMediaQueryService publicMediaQueryService;
private final ShopStorageService shopStorageService;
public PublicShopCatalogService(ShopCategoryRepository shopCategoryRepository,
ShopProductRepository shopProductRepository,
ShopProductVariantRepository shopProductVariantRepository,
ShopProductModelAssetRepository shopProductModelAssetRepository,
FilamentVariantRepository filamentVariantRepository,
PublicMediaQueryService publicMediaQueryService,
ShopStorageService shopStorageService) {
this.shopCategoryRepository = shopCategoryRepository;
this.shopProductRepository = shopProductRepository;
this.shopProductVariantRepository = shopProductVariantRepository;
this.shopProductModelAssetRepository = shopProductModelAssetRepository;
this.filamentVariantRepository = filamentVariantRepository;
this.publicMediaQueryService = publicMediaQueryService;
this.shopStorageService = shopStorageService;
}
public List<ShopCategoryTreeDto> getCategories(String language) {
CategoryContext categoryContext = loadCategoryContext(language);
return buildCategoryTree(null, categoryContext);
}
public ShopCategoryDetailDto getCategory(String slug, String language) {
ShopCategory category = shopCategoryRepository.findBySlugAndIsActiveTrue(slug)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Category not found"));
CategoryContext categoryContext = loadCategoryContext(language);
if (!categoryContext.categoriesById().containsKey(category.getId())) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Category not found");
}
return buildCategoryDetail(category, categoryContext);
}
public ShopProductCatalogResponseDto getProductCatalog(String categorySlug, Boolean featuredOnly, String language) {
CategoryContext categoryContext = loadCategoryContext(language);
PublicProductContext productContext = loadPublicProductContext(categoryContext, language);
ShopCategory selectedCategory = null;
if (categorySlug != null && !categorySlug.isBlank()) {
selectedCategory = categoryContext.categoriesBySlug().get(categorySlug.trim());
if (selectedCategory == null) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Category not found");
}
}
Collection<UUID> allowedCategoryIds = selectedCategory == null
? categoryContext.categoriesById().keySet()
: resolveDescendantCategoryIds(selectedCategory.getId(), categoryContext.childrenByParentId());
List<ShopProductSummaryDto> products = productContext.entries().stream()
.filter(entry -> allowedCategoryIds.contains(entry.product().getCategory().getId()))
.filter(entry -> !Boolean.TRUE.equals(featuredOnly) || Boolean.TRUE.equals(entry.product().getIsFeatured()))
.map(entry -> toProductSummaryDto(
entry,
productContext.productMediaBySlug(),
productContext.variantColorHexByMaterialAndColor(),
language
))
.toList();
ShopCategoryDetailDto selectedCategoryDetail = selectedCategory != null
? buildCategoryDetail(selectedCategory, categoryContext)
: null;
return new ShopProductCatalogResponseDto(
selectedCategory != null ? selectedCategory.getSlug() : null,
Boolean.TRUE.equals(featuredOnly),
selectedCategoryDetail,
products
);
}
public ShopProductDetailDto getProduct(String slug, String language) {
CategoryContext categoryContext = loadCategoryContext(language);
PublicProductContext productContext = loadPublicProductContext(categoryContext, language);
ProductEntry entry = productContext.entriesBySlug().get(slug);
if (entry == null) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Product not found");
}
ShopCategory category = entry.product().getCategory();
if (category == null || !categoryContext.categoriesById().containsKey(category.getId())) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Product not found");
}
return toProductDetailDto(
entry,
productContext.productMediaBySlug(),
productContext.variantColorHexByMaterialAndColor(),
language
);
}
public ProductModelDownload getProductModelDownload(String slug) {
CategoryContext categoryContext = loadCategoryContext(null);
PublicProductContext productContext = loadPublicProductContext(categoryContext, null);
ProductEntry entry = productContext.entriesBySlug().get(slug);
if (entry == null || entry.modelAsset() == null) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Product model not found");
}
Path path = shopStorageService.resolveStoredProductPath(
entry.modelAsset().getStoredRelativePath(),
entry.product().getId()
);
if (path == null || !Files.exists(path)) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Product model not found");
}
return new ProductModelDownload(
path,
entry.modelAsset().getOriginalFilename(),
entry.modelAsset().getMimeType()
);
}
private CategoryContext loadCategoryContext(String language) {
List<ShopCategory> categories = shopCategoryRepository.findAllByIsActiveTrueOrderBySortOrderAscNameAsc();
Map<UUID, ShopCategory> categoriesById = categories.stream()
.collect(Collectors.toMap(ShopCategory::getId, category -> category, (left, right) -> left, LinkedHashMap::new));
Map<String, ShopCategory> categoriesBySlug = categories.stream()
.collect(Collectors.toMap(ShopCategory::getSlug, category -> category, (left, right) -> left, LinkedHashMap::new));
Map<UUID, List<ShopCategory>> childrenByParentId = buildChildrenByParentId(categories);
List<ProductEntry> publicProducts = loadPublicProducts(categoriesById.keySet());
Map<UUID, Integer> descendantProductCounts = resolveDescendantProductCounts(categories, childrenByParentId, publicProducts);
Map<String, List<PublicMediaUsageDto>> categoryMediaBySlug = publicMediaQueryService.getUsageMediaMap(
SHOP_CATEGORY_MEDIA_USAGE_TYPE,
categories.stream().map(this::categoryMediaUsageKey).toList(),
language
);
return new CategoryContext(
categoriesById,
categoriesBySlug,
childrenByParentId,
descendantProductCounts,
categoryMediaBySlug
);
}
private PublicProductContext loadPublicProductContext(CategoryContext categoryContext, String language) {
List<ProductEntry> entries = loadPublicProducts(categoryContext.categoriesById().keySet());
Map<String, List<PublicMediaUsageDto>> productMediaBySlug = publicMediaQueryService.getUsageMediaMap(
SHOP_PRODUCT_MEDIA_USAGE_TYPE,
entries.stream().map(entry -> productMediaUsageKey(entry.product())).toList(),
language
);
Map<String, String> variantColorHexByMaterialAndColor = buildFilamentVariantColorHexMap();
Map<String, ProductEntry> entriesBySlug = entries.stream()
.collect(Collectors.toMap(entry -> entry.product().getSlug(), entry -> entry, (left, right) -> left, LinkedHashMap::new));
return new PublicProductContext(entries, entriesBySlug, productMediaBySlug, variantColorHexByMaterialAndColor);
}
private Map<String, String> buildFilamentVariantColorHexMap() {
Map<String, String> colorsByMaterialAndColor = new LinkedHashMap<>();
for (FilamentVariant variant : filamentVariantRepository.findByIsActiveTrue()) {
String materialCode = variant.getFilamentMaterialType() != null
? variant.getFilamentMaterialType().getMaterialCode()
: null;
String key = toMaterialAndColorKey(materialCode, variant.getColorName());
if (key == null) {
continue;
}
String colorHex = trimToNull(variant.getColorHex());
if (colorHex == null) {
continue;
}
colorsByMaterialAndColor.putIfAbsent(key, colorHex);
}
return colorsByMaterialAndColor;
}
private List<ProductEntry> loadPublicProducts(Collection<UUID> activeCategoryIds) {
List<ShopProduct> products = shopProductRepository.findAllByIsActiveTrueOrderByIsFeaturedDescSortOrderAscNameAsc();
if (products.isEmpty()) {
return List.of();
}
List<UUID> productIds = products.stream().map(ShopProduct::getId).toList();
Map<UUID, List<ShopProductVariant>> variantsByProductId = shopProductVariantRepository
.findByProduct_IdInAndIsActiveTrueOrderBySortOrderAscColorNameAsc(productIds)
.stream()
.collect(Collectors.groupingBy(
variant -> variant.getProduct().getId(),
LinkedHashMap::new,
Collectors.toList()
));
Map<UUID, ShopProductModelAsset> modelAssetByProductId = shopProductModelAssetRepository.findByProduct_IdIn(productIds)
.stream()
.collect(Collectors.toMap(asset -> asset.getProduct().getId(), asset -> asset, (left, right) -> left, LinkedHashMap::new));
return products.stream()
.filter(product -> product.getCategory() != null)
.filter(product -> activeCategoryIds.contains(product.getCategory().getId()))
.map(product -> {
List<ShopProductVariant> activeVariants = variantsByProductId.getOrDefault(product.getId(), List.of());
if (activeVariants.isEmpty()) {
return null;
}
ShopProductVariant defaultVariant = pickDefaultVariant(activeVariants);
return new ProductEntry(
product,
activeVariants,
defaultVariant,
modelAssetByProductId.get(product.getId())
);
})
.filter(Objects::nonNull)
.toList();
}
private Map<UUID, List<ShopCategory>> buildChildrenByParentId(List<ShopCategory> categories) {
Map<UUID, List<ShopCategory>> childrenByParentId = new LinkedHashMap<>();
for (ShopCategory category : categories) {
UUID parentId = category.getParentCategory() != null ? category.getParentCategory().getId() : null;
childrenByParentId.computeIfAbsent(parentId, ignored -> new ArrayList<>()).add(category);
}
Comparator<ShopCategory> comparator = Comparator
.comparing(ShopCategory::getSortOrder, Comparator.nullsLast(Integer::compareTo))
.thenComparing(ShopCategory::getName, Comparator.nullsLast(String.CASE_INSENSITIVE_ORDER));
childrenByParentId.values().forEach(children -> children.sort(comparator));
return childrenByParentId;
}
private Map<UUID, Integer> resolveDescendantProductCounts(List<ShopCategory> categories,
Map<UUID, List<ShopCategory>> childrenByParentId,
List<ProductEntry> publicProducts) {
Map<UUID, Integer> directProductCounts = new LinkedHashMap<>();
for (ProductEntry entry : publicProducts) {
UUID categoryId = entry.product().getCategory().getId();
directProductCounts.merge(categoryId, 1, Integer::sum);
}
Map<UUID, Integer> descendantCounts = new LinkedHashMap<>();
for (ShopCategory category : categories) {
resolveCategoryProductCount(category.getId(), childrenByParentId, directProductCounts, descendantCounts);
}
return descendantCounts;
}
private int resolveCategoryProductCount(UUID categoryId,
Map<UUID, List<ShopCategory>> childrenByParentId,
Map<UUID, Integer> directProductCounts,
Map<UUID, Integer> descendantCounts) {
Integer cached = descendantCounts.get(categoryId);
if (cached != null) {
return cached;
}
int total = directProductCounts.getOrDefault(categoryId, 0);
for (ShopCategory child : childrenByParentId.getOrDefault(categoryId, List.of())) {
total += resolveCategoryProductCount(child.getId(), childrenByParentId, directProductCounts, descendantCounts);
}
descendantCounts.put(categoryId, total);
return total;
}
private List<ShopCategoryTreeDto> buildCategoryTree(UUID parentId, CategoryContext categoryContext) {
return categoryContext.childrenByParentId().getOrDefault(parentId, List.of()).stream()
.map(category -> new ShopCategoryTreeDto(
category.getId(),
category.getParentCategory() != null ? category.getParentCategory().getId() : null,
category.getSlug(),
category.getName(),
category.getDescription(),
category.getSeoTitle(),
category.getSeoDescription(),
category.getOgTitle(),
category.getOgDescription(),
category.getIndexable(),
category.getSortOrder(),
categoryContext.descendantProductCounts().getOrDefault(category.getId(), 0),
selectPrimaryMedia(categoryContext.categoryMediaBySlug().get(categoryMediaUsageKey(category))),
buildCategoryTree(category.getId(), categoryContext)
))
.toList();
}
private ShopCategoryDetailDto buildCategoryDetail(ShopCategory category, CategoryContext categoryContext) {
List<PublicMediaUsageDto> images = categoryContext.categoryMediaBySlug().getOrDefault(categoryMediaUsageKey(category), List.of());
return new ShopCategoryDetailDto(
category.getId(),
category.getSlug(),
category.getName(),
category.getDescription(),
category.getSeoTitle(),
category.getSeoDescription(),
category.getOgTitle(),
category.getOgDescription(),
category.getIndexable(),
category.getSortOrder(),
categoryContext.descendantProductCounts().getOrDefault(category.getId(), 0),
buildCategoryBreadcrumbs(category),
selectPrimaryMedia(images),
images,
buildCategoryTree(category.getId(), categoryContext)
);
}
private List<ShopCategoryRefDto> buildCategoryBreadcrumbs(ShopCategory category) {
List<ShopCategoryRefDto> breadcrumbs = new ArrayList<>();
ShopCategory current = category;
while (current != null) {
breadcrumbs.add(new ShopCategoryRefDto(current.getId(), current.getSlug(), current.getName()));
current = current.getParentCategory();
}
java.util.Collections.reverse(breadcrumbs);
return breadcrumbs;
}
private List<UUID> resolveDescendantCategoryIds(UUID rootId, Map<UUID, List<ShopCategory>> childrenByParentId) {
List<UUID> ids = new ArrayList<>();
collectDescendantCategoryIds(rootId, childrenByParentId, ids);
return ids;
}
private void collectDescendantCategoryIds(UUID categoryId,
Map<UUID, List<ShopCategory>> childrenByParentId,
List<UUID> accumulator) {
accumulator.add(categoryId);
for (ShopCategory child : childrenByParentId.getOrDefault(categoryId, List.of())) {
collectDescendantCategoryIds(child.getId(), childrenByParentId, accumulator);
}
}
private ShopProductSummaryDto toProductSummaryDto(ProductEntry entry,
Map<String, List<PublicMediaUsageDto>> productMediaBySlug,
Map<String, String> variantColorHexByMaterialAndColor,
String language) {
List<PublicMediaUsageDto> images = productMediaBySlug.getOrDefault(productMediaUsageKey(entry.product()), List.of());
return new ShopProductSummaryDto(
entry.product().getId(),
entry.product().getSlug(),
entry.product().getNameForLanguage(language),
entry.product().getExcerptForLanguage(language),
entry.product().getIsFeatured(),
entry.product().getSortOrder(),
new ShopCategoryRefDto(
entry.product().getCategory().getId(),
entry.product().getCategory().getSlug(),
entry.product().getCategory().getName()
),
resolvePriceFrom(entry.variants()),
resolvePriceTo(entry.variants()),
toVariantDto(entry.defaultVariant(), entry.defaultVariant(), variantColorHexByMaterialAndColor),
selectPrimaryMedia(images),
toProductModelDto(entry)
);
}
private ShopProductDetailDto toProductDetailDto(ProductEntry entry,
Map<String, List<PublicMediaUsageDto>> productMediaBySlug,
Map<String, String> variantColorHexByMaterialAndColor,
String language) {
List<PublicMediaUsageDto> images = productMediaBySlug.getOrDefault(productMediaUsageKey(entry.product()), List.of());
String localizedSeoTitle = entry.product().getSeoTitleForLanguage(language);
String localizedSeoDescription = entry.product().getSeoDescriptionForLanguage(language);
return new ShopProductDetailDto(
entry.product().getId(),
entry.product().getSlug(),
entry.product().getNameForLanguage(language),
entry.product().getExcerptForLanguage(language),
entry.product().getDescriptionForLanguage(language),
localizedSeoTitle,
localizedSeoDescription,
localizedSeoTitle,
localizedSeoDescription,
entry.product().getIndexable(),
entry.product().getIsFeatured(),
entry.product().getSortOrder(),
new ShopCategoryRefDto(
entry.product().getCategory().getId(),
entry.product().getCategory().getSlug(),
entry.product().getCategory().getName()
),
buildCategoryBreadcrumbs(entry.product().getCategory()),
resolvePriceFrom(entry.variants()),
resolvePriceTo(entry.variants()),
toVariantDto(entry.defaultVariant(), entry.defaultVariant(), variantColorHexByMaterialAndColor),
entry.variants().stream()
.map(variant -> toVariantDto(variant, entry.defaultVariant(), variantColorHexByMaterialAndColor))
.toList(),
selectPrimaryMedia(images),
images,
toProductModelDto(entry)
);
}
private ShopProductVariantOptionDto toVariantDto(ShopProductVariant variant,
ShopProductVariant defaultVariant,
Map<String, String> variantColorHexByMaterialAndColor) {
if (variant == null) {
return null;
}
String colorHex = trimToNull(variant.getColorHex());
if (colorHex == null) {
String key = toMaterialAndColorKey(variant.getInternalMaterialCode(), variant.getColorName());
colorHex = key != null ? variantColorHexByMaterialAndColor.get(key) : null;
}
return new ShopProductVariantOptionDto(
variant.getId(),
variant.getSku(),
variant.getVariantLabel(),
variant.getColorName(),
colorHex,
variant.getPriceChf(),
defaultVariant != null && Objects.equals(defaultVariant.getId(), variant.getId())
);
}
private String toMaterialAndColorKey(String materialCode, String colorName) {
String normalizedMaterialCode = normalizeMaterialCode(materialCode);
String normalizedColorName = normalizeColorName(colorName);
if (normalizedMaterialCode == null || normalizedColorName == null) {
return null;
}
return normalizedMaterialCode + "|" + normalizedColorName;
}
private String normalizeMaterialCode(String materialCode) {
String raw = trimToNull(materialCode);
if (raw == null) {
return null;
}
return raw.toUpperCase(Locale.ROOT);
}
private String normalizeColorName(String colorName) {
String raw = trimToNull(colorName);
if (raw == null) {
return null;
}
return raw.toLowerCase(Locale.ROOT);
}
private String trimToNull(String value) {
String raw = String.valueOf(value == null ? "" : value).trim();
if (raw.isEmpty()) {
return null;
}
return raw;
}
private ShopProductModelDto toProductModelDto(ProductEntry entry) {
if (entry.modelAsset() == null) {
return null;
}
return new ShopProductModelDto(
"/api/shop/products/" + entry.product().getSlug() + "/model",
entry.modelAsset().getOriginalFilename(),
entry.modelAsset().getMimeType(),
entry.modelAsset().getFileSizeBytes(),
entry.modelAsset().getBoundingBoxXMm(),
entry.modelAsset().getBoundingBoxYMm(),
entry.modelAsset().getBoundingBoxZMm()
);
}
private ShopProductVariant pickDefaultVariant(List<ShopProductVariant> variants) {
return variants.stream()
.filter(variant -> Boolean.TRUE.equals(variant.getIsDefault()))
.findFirst()
.orElseGet(() -> variants.isEmpty() ? null : variants.get(0));
}
private BigDecimal resolvePriceFrom(List<ShopProductVariant> variants) {
return variants.stream()
.map(ShopProductVariant::getPriceChf)
.filter(Objects::nonNull)
.min(BigDecimal::compareTo)
.orElse(BigDecimal.ZERO);
}
private BigDecimal resolvePriceTo(List<ShopProductVariant> variants) {
return variants.stream()
.map(ShopProductVariant::getPriceChf)
.filter(Objects::nonNull)
.max(BigDecimal::compareTo)
.orElse(BigDecimal.ZERO);
}
private PublicMediaUsageDto selectPrimaryMedia(List<PublicMediaUsageDto> images) {
if (images == null || images.isEmpty()) {
return null;
}
return images.stream()
.filter(image -> Boolean.TRUE.equals(image.getIsPrimary()))
.findFirst()
.orElse(images.get(0));
}
private String categoryMediaUsageKey(ShopCategory category) {
return category.getId().toString();
}
private String productMediaUsageKey(ShopProduct product) {
return product.getId().toString();
}
public record ProductModelDownload(Path path, String filename, String mimeType) {
}
private record CategoryContext(
Map<UUID, ShopCategory> categoriesById,
Map<String, ShopCategory> categoriesBySlug,
Map<UUID, List<ShopCategory>> childrenByParentId,
Map<UUID, Integer> descendantProductCounts,
Map<String, List<PublicMediaUsageDto>> categoryMediaBySlug
) {
}
private record PublicProductContext(
List<ProductEntry> entries,
Map<String, ProductEntry> entriesBySlug,
Map<String, List<PublicMediaUsageDto>> productMediaBySlug,
Map<String, String> variantColorHexByMaterialAndColor
) {
}
private record ProductEntry(
ShopProduct product,
List<ShopProductVariant> variants,
ShopProductVariant defaultVariant,
ShopProductModelAsset modelAsset
) {
}
}

View File

@@ -0,0 +1,91 @@
package com.printcalculator.service.shop;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseCookie;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.util.Optional;
import java.util.UUID;
@Service
public class ShopCartCookieService {
public static final String COOKIE_NAME = "shop_cart_session";
private static final String COOKIE_PATH = "/api/shop";
private final long cookieTtlDays;
private final boolean secureCookie;
private final String sameSite;
public ShopCartCookieService(
@Value("${shop.cart.cookie.ttl-days:30}") long cookieTtlDays,
@Value("${shop.cart.cookie.secure:false}") boolean secureCookie,
@Value("${shop.cart.cookie.same-site:Lax}") String sameSite
) {
this.cookieTtlDays = cookieTtlDays;
this.secureCookie = secureCookie;
this.sameSite = sameSite;
}
public Optional<UUID> extractSessionId(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
if (cookies == null || cookies.length == 0) {
return Optional.empty();
}
for (Cookie cookie : cookies) {
if (!COOKIE_NAME.equals(cookie.getName())) {
continue;
}
try {
String value = cookie.getValue();
if (value == null || value.isBlank()) {
return Optional.empty();
}
return Optional.of(UUID.fromString(value.trim()));
} catch (IllegalArgumentException ignored) {
return Optional.empty();
}
}
return Optional.empty();
}
public boolean hasCartCookie(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
if (cookies == null || cookies.length == 0) {
return false;
}
for (Cookie cookie : cookies) {
if (COOKIE_NAME.equals(cookie.getName())) {
return true;
}
}
return false;
}
public ResponseCookie buildSessionCookie(UUID sessionId) {
return ResponseCookie.from(COOKIE_NAME, sessionId.toString())
.path(COOKIE_PATH)
.httpOnly(true)
.secure(secureCookie)
.sameSite(sameSite)
.maxAge(Duration.ofDays(Math.max(cookieTtlDays, 1)))
.build();
}
public ResponseCookie buildClearCookie() {
return ResponseCookie.from(COOKIE_NAME, "")
.path(COOKIE_PATH)
.httpOnly(true)
.secure(secureCookie)
.sameSite(sameSite)
.maxAge(Duration.ZERO)
.build();
}
public long getCookieTtlDays() {
return cookieTtlDays;
}
}

View File

@@ -0,0 +1,362 @@
package com.printcalculator.service.shop;
import com.printcalculator.dto.ShopCartAddItemRequest;
import com.printcalculator.dto.ShopCartUpdateItemRequest;
import com.printcalculator.entity.QuoteLineItem;
import com.printcalculator.entity.QuoteSession;
import com.printcalculator.entity.ShopCategory;
import com.printcalculator.entity.ShopProduct;
import com.printcalculator.entity.ShopProductModelAsset;
import com.printcalculator.entity.ShopProductVariant;
import com.printcalculator.repository.QuoteLineItemRepository;
import com.printcalculator.repository.QuoteSessionRepository;
import com.printcalculator.repository.ShopProductModelAssetRepository;
import com.printcalculator.repository.ShopProductVariantRepository;
import com.printcalculator.service.QuoteSessionTotalsService;
import com.printcalculator.service.quote.QuoteSessionResponseAssembler;
import com.printcalculator.service.quote.QuoteStorageService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.time.OffsetDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
@Service
@Transactional(readOnly = true)
public class ShopCartService {
private static final String SHOP_CART_SESSION_TYPE = "SHOP_CART";
private static final String SHOP_LINE_ITEM_TYPE = "SHOP_PRODUCT";
private static final String ACTIVE_STATUS = "ACTIVE";
private static final String EXPIRED_STATUS = "EXPIRED";
private static final String CONVERTED_STATUS = "CONVERTED";
private final QuoteSessionRepository quoteSessionRepository;
private final QuoteLineItemRepository quoteLineItemRepository;
private final ShopProductVariantRepository shopProductVariantRepository;
private final ShopProductModelAssetRepository shopProductModelAssetRepository;
private final QuoteSessionTotalsService quoteSessionTotalsService;
private final QuoteSessionResponseAssembler quoteSessionResponseAssembler;
private final QuoteStorageService quoteStorageService;
private final ShopStorageService shopStorageService;
private final ShopCartCookieService shopCartCookieService;
public ShopCartService(
QuoteSessionRepository quoteSessionRepository,
QuoteLineItemRepository quoteLineItemRepository,
ShopProductVariantRepository shopProductVariantRepository,
ShopProductModelAssetRepository shopProductModelAssetRepository,
QuoteSessionTotalsService quoteSessionTotalsService,
QuoteSessionResponseAssembler quoteSessionResponseAssembler,
QuoteStorageService quoteStorageService,
ShopStorageService shopStorageService,
ShopCartCookieService shopCartCookieService
) {
this.quoteSessionRepository = quoteSessionRepository;
this.quoteLineItemRepository = quoteLineItemRepository;
this.shopProductVariantRepository = shopProductVariantRepository;
this.shopProductModelAssetRepository = shopProductModelAssetRepository;
this.quoteSessionTotalsService = quoteSessionTotalsService;
this.quoteSessionResponseAssembler = quoteSessionResponseAssembler;
this.quoteStorageService = quoteStorageService;
this.shopStorageService = shopStorageService;
this.shopCartCookieService = shopCartCookieService;
}
public CartResult loadCart(HttpServletRequest request) {
boolean hadCookie = shopCartCookieService.hasCartCookie(request);
Optional<QuoteSession> session = resolveValidCartSession(request);
if (session.isEmpty()) {
return CartResult.empty(quoteSessionResponseAssembler.emptyCart(), hadCookie);
}
QuoteSession validSession = session.get();
touchSession(validSession);
return CartResult.withSession(buildCartResponse(validSession), validSession.getId(), false);
}
@Transactional
public CartResult addItem(HttpServletRequest request, ShopCartAddItemRequest payload) {
int quantityToAdd = normalizeQuantity(payload != null ? payload.getQuantity() : null);
ShopProductVariant variant = getPurchasableVariant(payload != null ? payload.getShopProductVariantId() : null);
QuoteSession session = resolveValidCartSession(request).orElseGet(this::createCartSession);
touchSession(session);
QuoteLineItem lineItem = quoteLineItemRepository
.findFirstByQuoteSession_IdAndLineItemTypeAndShopProductVariant_Id(
session.getId(),
SHOP_LINE_ITEM_TYPE,
variant.getId()
)
.orElseGet(() -> buildShopLineItem(session, variant));
int existingQuantity = lineItem.getQuantity() != null && lineItem.getQuantity() > 0
? lineItem.getQuantity()
: 0;
int newQuantity = existingQuantity + quantityToAdd;
lineItem.setQuantity(newQuantity);
refreshLineItemSnapshot(lineItem, variant);
lineItem.setUpdatedAt(OffsetDateTime.now());
quoteLineItemRepository.save(lineItem);
return CartResult.withSession(buildCartResponse(session), session.getId(), false);
}
@Transactional
public CartResult updateItem(HttpServletRequest request, UUID lineItemId, ShopCartUpdateItemRequest payload) {
QuoteSession session = resolveValidCartSession(request)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Cart session not found"));
QuoteLineItem item = quoteLineItemRepository.findByIdAndQuoteSession_Id(lineItemId, session.getId())
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Cart item not found"));
if (!SHOP_LINE_ITEM_TYPE.equals(item.getLineItemType())) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid cart item type");
}
item.setQuantity(normalizeQuantity(payload != null ? payload.getQuantity() : null));
item.setUpdatedAt(OffsetDateTime.now());
if (item.getShopProductVariant() != null) {
refreshLineItemSnapshot(item, item.getShopProductVariant());
}
quoteLineItemRepository.save(item);
touchSession(session);
return CartResult.withSession(buildCartResponse(session), session.getId(), false);
}
@Transactional
public CartResult removeItem(HttpServletRequest request, UUID lineItemId) {
QuoteSession session = resolveValidCartSession(request)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Cart session not found"));
QuoteLineItem item = quoteLineItemRepository.findByIdAndQuoteSession_Id(lineItemId, session.getId())
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Cart item not found"));
quoteLineItemRepository.delete(item);
touchSession(session);
return CartResult.withSession(buildCartResponse(session), session.getId(), false);
}
@Transactional
public CartResult clearCart(HttpServletRequest request) {
boolean hadCookie = shopCartCookieService.hasCartCookie(request);
Optional<QuoteSession> session = resolveValidCartSession(request);
if (session.isPresent()) {
QuoteSession current = session.get();
quoteSessionRepository.delete(current);
}
return CartResult.empty(quoteSessionResponseAssembler.emptyCart(), hadCookie);
}
private Optional<QuoteSession> resolveValidCartSession(HttpServletRequest request) {
Optional<UUID> sessionId = shopCartCookieService.extractSessionId(request);
if (sessionId.isEmpty()) {
return Optional.empty();
}
Optional<QuoteSession> session = quoteSessionRepository.findByIdAndSessionType(sessionId.get(), SHOP_CART_SESSION_TYPE);
if (session.isEmpty()) {
return Optional.empty();
}
QuoteSession quoteSession = session.get();
if (isSessionUnavailable(quoteSession)) {
if (!EXPIRED_STATUS.equals(quoteSession.getStatus()) && !CONVERTED_STATUS.equals(quoteSession.getStatus())) {
quoteSession.setStatus(EXPIRED_STATUS);
quoteSessionRepository.save(quoteSession);
}
return Optional.empty();
}
return Optional.of(quoteSession);
}
private QuoteSession createCartSession() {
QuoteSession session = new QuoteSession();
session.setStatus(ACTIVE_STATUS);
session.setSessionType(SHOP_CART_SESSION_TYPE);
session.setPricingVersion("v1");
session.setMaterialCode("SHOP");
session.setSupportsEnabled(false);
session.setCreatedAt(OffsetDateTime.now());
session.setExpiresAt(nowPlusCookieTtl());
session.setSetupCostChf(BigDecimal.ZERO);
return quoteSessionRepository.save(session);
}
private Map<String, Object> buildCartResponse(QuoteSession session) {
List<QuoteLineItem> items = quoteLineItemRepository.findByQuoteSessionIdOrderByCreatedAtAsc(session.getId());
QuoteSessionTotalsService.QuoteSessionTotals totals = quoteSessionTotalsService.compute(session, items);
return quoteSessionResponseAssembler.assemble(session, items, totals);
}
private QuoteLineItem buildShopLineItem(QuoteSession session, ShopProductVariant variant) {
ShopProduct product = variant.getProduct();
ShopProductModelAsset modelAsset = product != null ? shopProductModelAssetRepository.findByProduct_Id(product.getId()).orElse(null) : null;
QuoteLineItem item = new QuoteLineItem();
item.setQuoteSession(session);
item.setStatus("READY");
item.setLineItemType(SHOP_LINE_ITEM_TYPE);
item.setQuantity(0);
item.setCreatedAt(OffsetDateTime.now());
item.setUpdatedAt(OffsetDateTime.now());
item.setSupportsEnabled(false);
item.setInfillPercent(0);
item.setPricingBreakdown(new HashMap<>());
refreshLineItemSnapshot(item, variant);
applyModelAssetSnapshot(item, session, modelAsset);
return item;
}
private void refreshLineItemSnapshot(QuoteLineItem item, ShopProductVariant variant) {
ShopProduct product = variant.getProduct();
ShopCategory category = product != null ? product.getCategory() : null;
item.setShopProduct(product);
item.setShopProductVariant(variant);
item.setShopProductSlug(product != null ? product.getSlug() : null);
item.setShopProductName(product != null ? product.getName() : null);
item.setShopVariantLabel(variant.getVariantLabel());
item.setShopVariantColorName(variant.getColorName());
item.setShopVariantColorHex(variant.getColorHex());
item.setDisplayName(product != null ? product.getName() : item.getDisplayName());
item.setColorCode(variant.getColorName());
item.setMaterialCode(variant.getInternalMaterialCode());
item.setQuality(null);
item.setUnitPriceChf(variant.getPriceChf() != null ? variant.getPriceChf() : BigDecimal.ZERO);
Map<String, Object> breakdown = item.getPricingBreakdown() != null
? new HashMap<>(item.getPricingBreakdown())
: new HashMap<>();
breakdown.put("type", SHOP_LINE_ITEM_TYPE);
breakdown.put("unitPriceChf", item.getUnitPriceChf());
item.setPricingBreakdown(breakdown);
}
private void applyModelAssetSnapshot(QuoteLineItem item, QuoteSession session, ShopProductModelAsset modelAsset) {
if (modelAsset == null) {
if (item.getOriginalFilename() == null || item.getOriginalFilename().isBlank()) {
item.setOriginalFilename(item.getShopProductSlug() != null ? item.getShopProductSlug() : "shop-product");
}
item.setBoundingBoxXMm(BigDecimal.ZERO);
item.setBoundingBoxYMm(BigDecimal.ZERO);
item.setBoundingBoxZMm(BigDecimal.ZERO);
item.setStoredPath(null);
return;
}
item.setOriginalFilename(modelAsset.getOriginalFilename());
item.setBoundingBoxXMm(modelAsset.getBoundingBoxXMm() != null ? modelAsset.getBoundingBoxXMm() : BigDecimal.ZERO);
item.setBoundingBoxYMm(modelAsset.getBoundingBoxYMm() != null ? modelAsset.getBoundingBoxYMm() : BigDecimal.ZERO);
item.setBoundingBoxZMm(modelAsset.getBoundingBoxZMm() != null ? modelAsset.getBoundingBoxZMm() : BigDecimal.ZERO);
String copiedStoredPath = copyModelAssetIntoSession(session, modelAsset);
item.setStoredPath(copiedStoredPath);
}
private String copyModelAssetIntoSession(QuoteSession session, ShopProductModelAsset modelAsset) {
if (session == null || modelAsset == null || modelAsset.getProduct() == null) {
return null;
}
Path source = shopStorageService.resolveStoredProductPath(
modelAsset.getStoredRelativePath(),
modelAsset.getProduct().getId()
);
if (source == null || !Files.exists(source)) {
return null;
}
try {
Path sessionDir = quoteStorageService.sessionStorageDir(session.getId());
String extension = quoteStorageService.getSafeExtension(modelAsset.getOriginalFilename(), "stl");
Path destination = quoteStorageService.resolveSessionPath(
sessionDir,
UUID.randomUUID() + "." + extension
);
Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
return quoteStorageService.toStoredPath(destination);
} catch (IOException e) {
return null;
}
}
private ShopProductVariant getPurchasableVariant(UUID variantId) {
if (variantId == null) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "shopProductVariantId is required");
}
ShopProductVariant variant = shopProductVariantRepository.findById(variantId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Variant not found"));
ShopProduct product = variant.getProduct();
ShopCategory category = product != null ? product.getCategory() : null;
if (product == null
|| category == null
|| !Boolean.TRUE.equals(variant.getIsActive())
|| !Boolean.TRUE.equals(product.getIsActive())
|| !Boolean.TRUE.equals(category.getIsActive())) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Variant not available");
}
return variant;
}
private void touchSession(QuoteSession session) {
session.setStatus(ACTIVE_STATUS);
session.setExpiresAt(nowPlusCookieTtl());
quoteSessionRepository.save(session);
}
private OffsetDateTime nowPlusCookieTtl() {
return OffsetDateTime.now().plusDays(Math.max(shopCartCookieService.getCookieTtlDays(), 1));
}
private boolean isSessionUnavailable(QuoteSession session) {
if (session == null) {
return true;
}
if (!SHOP_CART_SESSION_TYPE.equalsIgnoreCase(session.getSessionType())) {
return true;
}
if (!ACTIVE_STATUS.equalsIgnoreCase(session.getStatus())) {
return true;
}
if (CONVERTED_STATUS.equalsIgnoreCase(session.getStatus())) {
return true;
}
OffsetDateTime expiresAt = session.getExpiresAt();
return expiresAt != null && expiresAt.isBefore(OffsetDateTime.now());
}
private int normalizeQuantity(Integer quantity) {
if (quantity == null || quantity < 1) {
return 1;
}
return quantity;
}
public record CartResult(Map<String, Object> response, UUID sessionId, boolean clearCookie) {
public static CartResult withSession(Map<String, Object> response, UUID sessionId, boolean clearCookie) {
return new CartResult(response, sessionId, clearCookie);
}
public static CartResult empty(Map<String, Object> response, boolean clearCookie) {
return new CartResult(response, null, clearCookie);
}
}
}

View File

@@ -0,0 +1,244 @@
package com.printcalculator.service.shop;
import com.printcalculator.entity.ShopCategory;
import com.printcalculator.entity.ShopProduct;
import com.printcalculator.repository.ShopCategoryRepository;
import com.printcalculator.repository.ShopProductRepository;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.Normalizer;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.LinkedHashMap;
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;
@Service
@Transactional(readOnly = true)
public class ShopSitemapService {
private static final List<String> SUPPORTED_LANGUAGES = ShopProduct.SUPPORTED_LANGUAGES;
private static final String DEFAULT_LANGUAGE = "it";
private static final DateTimeFormatter LASTMOD_FORMATTER = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
private final ShopCategoryRepository shopCategoryRepository;
private final ShopProductRepository shopProductRepository;
private final String frontendBaseUrl;
private final Duration cacheTtl;
private final Clock clock;
private volatile CachedSitemap cachedSitemap;
@Autowired
public ShopSitemapService(ShopCategoryRepository shopCategoryRepository,
ShopProductRepository shopProductRepository,
@Value("${app.frontend.base-url:http://localhost:4200}") String frontendBaseUrl,
@Value("${app.sitemap.shop.cache-seconds:3600}") long cacheSeconds) {
this(shopCategoryRepository, shopProductRepository, frontendBaseUrl, cacheSeconds, Clock.systemUTC());
}
ShopSitemapService(ShopCategoryRepository shopCategoryRepository,
ShopProductRepository shopProductRepository,
String frontendBaseUrl,
long cacheSeconds,
Clock clock) {
this.shopCategoryRepository = shopCategoryRepository;
this.shopProductRepository = shopProductRepository;
this.frontendBaseUrl = normalizeBaseUrl(frontendBaseUrl);
this.cacheTtl = cacheSeconds > 0 ? Duration.ofSeconds(cacheSeconds) : Duration.ZERO;
this.clock = clock;
}
public String getShopSitemapXml() {
Instant now = Instant.now(clock);
CachedSitemap current = cachedSitemap;
if (current != null && now.isBefore(current.expiresAt())) {
return current.xml();
}
synchronized (this) {
current = cachedSitemap;
now = Instant.now(clock);
if (current != null && now.isBefore(current.expiresAt())) {
return current.xml();
}
String xml = buildSitemapXml();
Instant expiresAt = cacheTtl.isZero() ? now : now.plus(cacheTtl);
cachedSitemap = new CachedSitemap(xml, expiresAt);
return xml;
}
}
private String buildSitemapXml() {
List<ShopCategory> activeCategories = shopCategoryRepository.findAllByIsActiveTrueOrderBySortOrderAscNameAsc();
Set<UUID> activeCategoryIds = activeCategories.stream()
.map(ShopCategory::getId)
.collect(Collectors.toSet());
List<ShopProduct> activeProducts = shopProductRepository.findAllByIsActiveTrueOrderByIsFeaturedDescSortOrderAscNameAsc();
StringBuilder xml = new StringBuilder(16_384);
xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
xml.append("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" ");
xml.append("xmlns:xhtml=\"http://www.w3.org/1999/xhtml\">\n");
appendCategoryUrls(xml, activeCategories);
appendProductUrls(xml, activeProducts, activeCategoryIds);
xml.append("</urlset>\n");
return xml.toString();
}
private void appendCategoryUrls(StringBuilder xml, List<ShopCategory> categories) {
for (ShopCategory category : categories) {
if (!Boolean.TRUE.equals(category.getIndexable())) {
continue;
}
String encodedSlug = pathEncodeSegment(category.getSlug());
Map<String, String> hrefByLanguage = new LinkedHashMap<>();
for (String language : SUPPORTED_LANGUAGES) {
hrefByLanguage.put(language, frontendBaseUrl + "/" + language + "/shop/" + encodedSlug);
}
appendUrlEntry(xml, hrefByLanguage, category.getUpdatedAt());
}
}
private void appendProductUrls(StringBuilder xml,
List<ShopProduct> products,
Set<UUID> activeCategoryIds) {
for (ShopProduct product : products) {
if (!Boolean.TRUE.equals(product.getIndexable())) {
continue;
}
if (product.getCategory() == null || !activeCategoryIds.contains(product.getCategory().getId())) {
continue;
}
Map<String, String> hrefByLanguage = new LinkedHashMap<>();
for (String language : SUPPORTED_LANGUAGES) {
String publicSegment = localizedProductPathSegment(product, language);
hrefByLanguage.put(language, frontendBaseUrl + "/" + language + "/shop/p/" + pathEncodeSegment(publicSegment));
}
appendUrlEntry(xml, hrefByLanguage, product.getUpdatedAt());
}
}
private void appendUrlEntry(StringBuilder xml,
Map<String, String> hrefByLanguage,
OffsetDateTime lastmod) {
String defaultHref = hrefByLanguage.get(DEFAULT_LANGUAGE);
if (defaultHref == null || defaultHref.isBlank()) {
return;
}
xml.append(" <url>\n");
xml.append(" <loc>").append(xmlEscape(defaultHref)).append("</loc>\n");
for (String language : SUPPORTED_LANGUAGES) {
String href = hrefByLanguage.get(language);
if (href == null || href.isBlank()) {
continue;
}
xml.append(" <xhtml:link rel=\"alternate\" hreflang=\"")
.append(language)
.append("\" href=\"")
.append(xmlEscape(href))
.append("\" />\n");
}
xml.append(" <xhtml:link rel=\"alternate\" hreflang=\"x-default\" href=\"")
.append(xmlEscape(defaultHref))
.append("\" />\n");
if (lastmod != null) {
xml.append(" <lastmod>").append(LASTMOD_FORMATTER.format(lastmod)).append("</lastmod>\n");
}
xml.append(" </url>\n");
}
private String localizedProductPathSegment(ShopProduct product, String language) {
String localizedName = product.getNameForLanguage(language);
String idPrefix = productIdPrefix(product.getId());
String tail = firstNonBlank(slugify(localizedName), slugify(product.getSlug()), "product");
return idPrefix.isBlank() ? tail : idPrefix + "-" + tail;
}
private String productIdPrefix(UUID productId) {
if (productId == null) {
return "";
}
String raw = productId.toString().trim().toLowerCase(Locale.ROOT);
int dashIndex = raw.indexOf('-');
if (dashIndex > 0) {
return raw.substring(0, dashIndex);
}
return raw.length() >= 8 ? raw.substring(0, 8) : raw;
}
static String slugify(String rawValue) {
String safeValue = rawValue == null ? "" : rawValue;
String normalized = Normalizer.normalize(safeValue, Normalizer.Form.NFD)
.replaceAll("\\p{M}+", "")
.toLowerCase(Locale.ROOT)
.replaceAll("[^a-z0-9]+", "-")
.replaceAll("^-+|-+$", "")
.replaceAll("-{2,}", "-");
return normalized;
}
private String firstNonBlank(String... values) {
if (values == null) {
return null;
}
for (String value : values) {
if (value != null && !value.isBlank()) {
return value;
}
}
return null;
}
private String pathEncodeSegment(String rawSegment) {
String safeSegment = rawSegment == null ? "" : rawSegment;
return URLEncoder.encode(safeSegment, StandardCharsets.UTF_8).replace("+", "%20");
}
private String xmlEscape(String value) {
return String.valueOf(value)
.replace("&", "&amp;")
.replace("<", "&lt;")
.replace(">", "&gt;")
.replace("\"", "&quot;")
.replace("'", "&apos;");
}
private String normalizeBaseUrl(String baseUrl) {
String normalized = (baseUrl == null ? "" : baseUrl).trim();
if (normalized.isBlank()) {
return "http://localhost:4200";
}
while (normalized.endsWith("/")) {
normalized = normalized.substring(0, normalized.length() - 1);
}
return normalized;
}
private record CachedSitemap(String xml, Instant expiresAt) {
}
}

View File

@@ -0,0 +1,50 @@
package com.printcalculator.service.shop;
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.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
@Service
public class ShopStorageService {
private final Path storageRoot;
public ShopStorageService(@Value("${shop.storage.root:storage_shop}") String storageRoot) {
this.storageRoot = Paths.get(storageRoot).toAbsolutePath().normalize();
}
public Path productModelStorageDir(UUID productId) throws IOException {
Path dir = storageRoot.resolve(Path.of("products", productId.toString(), "3d-models")).normalize();
if (!dir.startsWith(storageRoot)) {
throw new IOException("Invalid shop product storage path");
}
Files.createDirectories(dir);
return dir;
}
public Path resolveStoredProductPath(String storedRelativePath, UUID expectedProductId) {
if (storedRelativePath == null || storedRelativePath.isBlank()) {
return null;
}
try {
Path raw = Path.of(storedRelativePath).normalize();
Path resolved = raw.isAbsolute() ? raw : storageRoot.resolve(raw).normalize();
Path expectedPrefix = storageRoot.resolve(Path.of("products", expectedProductId.toString())).normalize();
if (!resolved.startsWith(expectedPrefix)) {
return null;
}
return resolved;
} catch (InvalidPathException e) {
return null;
}
}
public String toStoredPath(Path absolutePath) {
return storageRoot.relativize(absolutePath.toAbsolutePath().normalize()).toString();
}
}

View File

@@ -9,5 +9,4 @@ admin.session.ttl-minutes=480
# Local media storage served by a local static server on port 8081. # Local media storage served by a local static server on port 8081.
media.storage.root=/Users/joe/IdeaProjects/print-calculator/storage_media media.storage.root=/Users/joe/IdeaProjects/print-calculator/storage_media
media.public.base-url=http://localhost:8081
media.ffmpeg.path=ffmpeg media.ffmpeg.path=ffmpeg

View File

@@ -28,9 +28,13 @@ clamav.enabled=${CLAMAV_ENABLED:false}
# Media configuration # Media configuration
media.storage.root=${MEDIA_STORAGE_ROOT:storage_media} 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.ffmpeg.path=${MEDIA_FFMPEG_PATH:ffmpeg}
media.upload.max-file-size-bytes=${MEDIA_UPLOAD_MAX_FILE_SIZE_BYTES:26214400} media.upload.max-file-size-bytes=${MEDIA_UPLOAD_MAX_FILE_SIZE_BYTES:26214400}
shop.model.max-file-size-bytes=${SHOP_MODEL_MAX_FILE_SIZE_BYTES:104857600}
shop.storage.root=${SHOP_STORAGE_ROOT:storage_shop}
shop.cart.cookie.ttl-days=${SHOP_CART_COOKIE_TTL_DAYS:30}
shop.cart.cookie.secure=${SHOP_CART_COOKIE_SECURE:false}
shop.cart.cookie.same-site=${SHOP_CART_COOKIE_SAME_SITE:Lax}
# TWINT Configuration # TWINT Configuration
payment.twint.url=${TWINT_PAYMENT_URL:https://go.twint.ch/1/e/tw?tw=acq.gERQQytOTnyIMuQHUqn4hlxgciHE5X7nnqHnNSPAr2OF2K3uBlXJDr2n9JU3sgxa.} payment.twint.url=${TWINT_PAYMENT_URL:https://go.twint.ch/1/e/tw?tw=acq.gERQQytOTnyIMuQHUqn4hlxgciHE5X7nnqHnNSPAr2OF2K3uBlXJDr2n9JU3sgxa.}
@@ -52,6 +56,7 @@ app.mail.contact-request.admin.enabled=${APP_MAIL_CONTACT_REQUEST_ADMIN_ENABLED:
app.mail.contact-request.admin.address=${APP_MAIL_CONTACT_REQUEST_ADMIN_ADDRESS:info@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.mail.contact-request.customer.enabled=${APP_MAIL_CONTACT_REQUEST_CUSTOMER_ENABLED:true}
app.frontend.base-url=${APP_FRONTEND_BASE_URL:http://localhost:4200} app.frontend.base-url=${APP_FRONTEND_BASE_URL:http://localhost:4200}
app.sitemap.shop.cache-seconds=${APP_SITEMAP_SHOP_CACHE_SECONDS:3600}
# Admin back-office authentication # Admin back-office authentication
admin.password=${ADMIN_PASSWORD} admin.password=${ADMIN_PASSWORD}

View File

@@ -0,0 +1,138 @@
package com.printcalculator.controller.admin;
import com.printcalculator.config.SecurityConfig;
import com.printcalculator.service.order.AdminOrderControllerService;
import com.printcalculator.security.AdminLoginThrottleService;
import com.printcalculator.security.AdminSessionAuthenticationFilter;
import com.printcalculator.security.AdminSessionService;
import jakarta.servlet.http.Cookie;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.AbstractPlatformTransactionManager;
import org.springframework.transaction.support.DefaultTransactionStatus;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(controllers = {AdminAuthController.class, AdminOrderController.class})
@Import({
SecurityConfig.class,
AdminSessionAuthenticationFilter.class,
AdminSessionService.class,
AdminLoginThrottleService.class,
AdminOrderControllerSecurityTest.TransactionTestConfig.class
})
@TestPropertySource(properties = {
"admin.password=test-admin-password",
"admin.session.secret=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"admin.session.ttl-minutes=60"
})
class AdminOrderControllerSecurityTest {
@Autowired
private MockMvc mockMvc;
@MockitoBean
private AdminOrderControllerService adminOrderControllerService;
@Test
void confirmationDocument_withoutAdminCookie_shouldReturn401() throws Exception {
UUID orderId = UUID.randomUUID();
mockMvc.perform(get("/api/admin/orders/{orderId}/documents/confirmation", orderId))
.andExpect(status().isUnauthorized());
}
@Test
void confirmationDocument_withAdminCookie_shouldReturnPdf() throws Exception {
UUID orderId = UUID.randomUUID();
when(adminOrderControllerService.downloadOrderConfirmation(orderId))
.thenReturn(ResponseEntity.ok()
.contentType(MediaType.APPLICATION_PDF)
.body("confirmation".getBytes()));
mockMvc.perform(get("/api/admin/orders/{orderId}/documents/confirmation", orderId)
.cookie(loginAndExtractCookie()))
.andExpect(status().isOk())
.andExpect(content().bytes("confirmation".getBytes()));
}
@Test
void invoiceDocument_withAdminCookie_shouldReturnPdf() throws Exception {
UUID orderId = UUID.randomUUID();
when(adminOrderControllerService.downloadOrderInvoice(orderId))
.thenReturn(ResponseEntity.ok()
.contentType(MediaType.APPLICATION_PDF)
.body("invoice".getBytes()));
mockMvc.perform(get("/api/admin/orders/{orderId}/documents/invoice", orderId)
.cookie(loginAndExtractCookie()))
.andExpect(status().isOk())
.andExpect(content().bytes("invoice".getBytes()));
}
private Cookie loginAndExtractCookie() throws Exception {
MvcResult login = mockMvc.perform(post("/api/admin/auth/login")
.with(req -> {
req.setRemoteAddr("10.0.0.44");
return req;
})
.contentType(MediaType.APPLICATION_JSON)
.content("{\"password\":\"test-admin-password\"}"))
.andExpect(status().isOk())
.andReturn();
String setCookie = login.getResponse().getHeader(HttpHeaders.SET_COOKIE);
assertNotNull(setCookie);
String[] parts = setCookie.split(";", 2);
String[] keyValue = parts[0].split("=", 2);
return new Cookie(keyValue[0], keyValue.length > 1 ? keyValue[1] : "");
}
@TestConfiguration
static class TransactionTestConfig {
@Bean
PlatformTransactionManager transactionManager() {
return new AbstractPlatformTransactionManager() {
@Override
protected Object doGetTransaction() {
return new Object();
}
@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
// No-op transaction manager for WebMvc security tests.
}
@Override
protected void doCommit(DefaultTransactionStatus status) {
// No-op transaction manager for WebMvc security tests.
}
@Override
protected void doRollback(DefaultTransactionStatus status) {
// No-op transaction manager for WebMvc security tests.
}
};
}
}
}

View File

@@ -0,0 +1,48 @@
package com.printcalculator.entity;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class ShopProductTest {
@Test
void localizedAccessorsShouldReturnLanguageSpecificValues() {
ShopProduct product = new ShopProduct();
product.setName("Desk Cable Clip");
product.setNameIt("Fermacavo da scrivania");
product.setNameEn("Desk Cable Clip");
product.setNameDe("Schreibtisch-Kabelclip");
product.setNameFr("Clip de cable de bureau");
product.setExcerpt("Legacy excerpt");
product.setExcerptIt("Clip compatta per i cavi sulla scrivania.");
product.setExcerptEn("Compact clip to keep desk cables in place.");
product.setExcerptDe("Kompakter Clip fur ordentliche Kabel auf dem Schreibtisch.");
product.setExcerptFr("Clip compact pour garder les cables du bureau en ordre.");
product.setDescription("Legacy description");
product.setDescriptionIt("Supporto con base stabile e passaggio cavi frontale.");
product.setDescriptionEn("Stable desk clip with front cable routing.");
product.setDescriptionDe("Stabiler Tischclip mit frontaler Kabelfuhrung.");
product.setDescriptionFr("Clip de bureau stable avec passage frontal des cables.");
assertEquals("Fermacavo da scrivania", product.getNameForLanguage("it"));
assertEquals("Desk Cable Clip", product.getNameForLanguage("en"));
assertEquals("Schreibtisch-Kabelclip", product.getNameForLanguage("de"));
assertEquals("Clip de cable de bureau", product.getNameForLanguage("fr"));
assertEquals("Compact clip to keep desk cables in place.", product.getExcerptForLanguage("en"));
assertEquals("Clip compact pour garder les cables du bureau en ordre.", product.getExcerptForLanguage("fr"));
assertEquals("Stabiler Tischclip mit frontaler Kabelfuhrung.", product.getDescriptionForLanguage("de"));
}
@Test
void localizedAccessorsShouldFallbackToLegacyValues() {
ShopProduct product = new ShopProduct();
product.setName("Desk Cable Clip");
product.setExcerpt("Compact desk cable clip.");
product.setDescription("Stable clip with front cable channel.");
assertEquals("Desk Cable Clip", product.getNameForLanguage("it"));
assertEquals("Compact desk cable clip.", product.getExcerptForLanguage("de"));
assertEquals("Stable clip with front cable channel.", product.getDescriptionForLanguage("fr-CH"));
}
}

View File

@@ -0,0 +1,248 @@
package com.printcalculator.service;
import com.printcalculator.dto.AddressDto;
import com.printcalculator.dto.CreateOrderRequest;
import com.printcalculator.dto.CustomerDto;
import com.printcalculator.entity.Customer;
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.entity.ShopCategory;
import com.printcalculator.entity.ShopProduct;
import com.printcalculator.entity.ShopProductVariant;
import com.printcalculator.event.OrderCreatedEvent;
import com.printcalculator.repository.CustomerRepository;
import com.printcalculator.repository.OrderItemRepository;
import com.printcalculator.repository.OrderRepository;
import com.printcalculator.repository.QuoteLineItemRepository;
import com.printcalculator.repository.QuoteSessionRepository;
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.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.context.ApplicationEventPublisher;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
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.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
@Mock
private OrderRepository orderRepo;
@Mock
private OrderItemRepository orderItemRepo;
@Mock
private QuoteSessionRepository quoteSessionRepo;
@Mock
private QuoteLineItemRepository quoteLineItemRepo;
@Mock
private CustomerRepository customerRepo;
@Mock
private StorageService storageService;
@Mock
private InvoicePdfRenderingService invoiceService;
@Mock
private QrBillService qrBillService;
@Mock
private ApplicationEventPublisher eventPublisher;
@Mock
private PaymentService paymentService;
@Mock
private QuoteSessionTotalsService quoteSessionTotalsService;
@InjectMocks
private OrderService service;
@Test
void createOrderFromQuote_withShopCart_shouldPreserveShopSnapshotAndMaterialCode() throws Exception {
UUID sessionId = UUID.randomUUID();
UUID orderId = UUID.randomUUID();
UUID orderItemId = UUID.randomUUID();
QuoteSession session = new QuoteSession();
session.setId(sessionId);
session.setStatus("ACTIVE");
session.setSessionType("SHOP_CART");
session.setMaterialCode("SHOP");
session.setPricingVersion("v1");
session.setSetupCostChf(BigDecimal.ZERO);
session.setExpiresAt(OffsetDateTime.now().plusDays(30));
ShopCategory category = new ShopCategory();
category.setId(UUID.randomUUID());
category.setSlug("cable-management");
category.setName("Cable Management");
ShopProduct product = new ShopProduct();
product.setId(UUID.randomUUID());
product.setCategory(category);
product.setSlug("desk-cable-clip");
product.setName("Desk Cable Clip");
ShopProductVariant variant = new ShopProductVariant();
variant.setId(UUID.randomUUID());
variant.setProduct(product);
variant.setVariantLabel("Coral Red");
variant.setColorName("Coral Red");
variant.setColorHex("#ff6b6b");
variant.setInternalMaterialCode("PLA-MATTE");
variant.setPriceChf(new BigDecimal("14.90"));
Path sourceDir = Path.of("storage_quotes").toAbsolutePath().normalize().resolve(sessionId.toString());
Files.createDirectories(sourceDir);
Path sourceFile = sourceDir.resolve("shop-product.stl");
Files.writeString(sourceFile, "solid product\nendsolid product\n", StandardCharsets.UTF_8);
QuoteLineItem qItem = new QuoteLineItem();
qItem.setId(UUID.randomUUID());
qItem.setQuoteSession(session);
qItem.setStatus("READY");
qItem.setLineItemType("SHOP_PRODUCT");
qItem.setOriginalFilename("shop-product.stl");
qItem.setDisplayName("Desk Cable Clip");
qItem.setQuantity(2);
qItem.setColorCode("Coral Red");
qItem.setMaterialCode("PLA-MATTE");
qItem.setShopProduct(product);
qItem.setShopProductVariant(variant);
qItem.setShopProductSlug(product.getSlug());
qItem.setShopProductName(product.getName());
qItem.setShopVariantLabel("Coral Red");
qItem.setShopVariantColorName("Coral Red");
qItem.setShopVariantColorHex("#ff6b6b");
qItem.setBoundingBoxXMm(new BigDecimal("60.000"));
qItem.setBoundingBoxYMm(new BigDecimal("40.000"));
qItem.setBoundingBoxZMm(new BigDecimal("20.000"));
qItem.setUnitPriceChf(new BigDecimal("14.90"));
qItem.setStoredPath(sourceFile.toString());
Customer customer = new Customer();
customer.setId(UUID.randomUUID());
customer.setEmail("buyer@example.com");
when(quoteSessionRepo.findById(sessionId)).thenReturn(Optional.of(session));
when(customerRepo.findByEmail("buyer@example.com")).thenReturn(Optional.empty());
when(customerRepo.save(any(Customer.class))).thenAnswer(invocation -> {
Customer saved = invocation.getArgument(0);
if (saved.getId() == null) {
saved.setId(customer.getId());
}
return saved;
});
when(quoteLineItemRepo.findByQuoteSessionId(sessionId)).thenReturn(List.of(qItem));
when(quoteSessionTotalsService.compute(eq(session), eq(List.of(qItem)))).thenReturn(
new QuoteSessionTotalsService.QuoteSessionTotals(
new BigDecimal("29.80"),
BigDecimal.ZERO,
BigDecimal.ZERO,
new BigDecimal("29.80"),
BigDecimal.ZERO,
BigDecimal.ZERO,
BigDecimal.ZERO,
new BigDecimal("2.00"),
new BigDecimal("31.80"),
BigDecimal.ZERO
)
);
when(orderRepo.save(any(Order.class))).thenAnswer(invocation -> {
Order saved = invocation.getArgument(0);
if (saved.getId() == null) {
saved.setId(orderId);
}
return saved;
});
when(orderItemRepo.save(any(OrderItem.class))).thenAnswer(invocation -> {
OrderItem saved = invocation.getArgument(0);
if (saved.getId() == null) {
saved.setId(orderItemId);
}
return saved;
});
when(qrBillService.generateQrBillSvg(any(Order.class))).thenReturn("<svg/>".getBytes(StandardCharsets.UTF_8));
when(invoiceService.generateDocumentPdf(any(Order.class), any(List.class), eq(true), eq(qrBillService), isNull()))
.thenReturn("pdf".getBytes(StandardCharsets.UTF_8));
when(paymentService.getOrCreatePaymentForOrder(any(Order.class), eq("OTHER"))).thenReturn(new Payment());
Order order = service.createOrderFromQuote(sessionId, buildRequest());
assertEquals(orderId, order.getId());
assertEquals("SHOP", order.getSourceType());
assertEquals("CONVERTED", session.getStatus());
assertEquals(orderId, session.getConvertedOrderId());
assertAmountEquals("29.80", order.getSubtotalChf());
assertAmountEquals("31.80", order.getTotalChf());
ArgumentCaptor<OrderItem> itemCaptor = ArgumentCaptor.forClass(OrderItem.class);
verify(orderItemRepo, times(2)).save(itemCaptor.capture());
OrderItem savedItem = itemCaptor.getAllValues().getLast();
assertEquals("SHOP_PRODUCT", savedItem.getItemType());
assertEquals("Desk Cable Clip", savedItem.getDisplayName());
assertEquals("PLA-MATTE", savedItem.getMaterialCode());
assertEquals("desk-cable-clip", savedItem.getShopProductSlug());
assertEquals("Desk Cable Clip", savedItem.getShopProductName());
assertEquals("Coral Red", savedItem.getShopVariantLabel());
assertEquals("Coral Red", savedItem.getShopVariantColorName());
assertEquals("#ff6b6b", savedItem.getShopVariantColorHex());
assertAmountEquals("14.90", savedItem.getUnitPriceChf());
assertAmountEquals("29.80", savedItem.getLineTotalChf());
verify(storageService).store(eq(sourceFile), eq(Path.of(
"orders", orderId.toString(), "3d-files", orderItemId.toString(), savedItem.getStoredFilename()
)));
verify(paymentService).getOrCreatePaymentForOrder(order, "OTHER");
verify(eventPublisher).publishEvent(any(OrderCreatedEvent.class));
}
private CreateOrderRequest buildRequest() {
CustomerDto customer = new CustomerDto();
customer.setEmail("buyer@example.com");
customer.setPhone("+41790000000");
customer.setCustomerType("PRIVATE");
AddressDto billing = new AddressDto();
billing.setFirstName("Joe");
billing.setLastName("Buyer");
billing.setAddressLine1("Via Test 1");
billing.setZip("6900");
billing.setCity("Lugano");
billing.setCountryCode("CH");
CreateOrderRequest request = new CreateOrderRequest();
request.setCustomer(customer);
request.setBillingAddress(billing);
request.setShippingSameAsBilling(true);
request.setLanguage("it");
request.setAcceptTerms(true);
request.setAcceptPrivacy(true);
return request;
}
private void assertAmountEquals(String expected, BigDecimal actual) {
assertTrue(new BigDecimal(expected).compareTo(actual) == 0,
"Expected " + expected + " but got " + actual);
}
}

View File

@@ -51,6 +51,7 @@ import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@@ -86,7 +87,7 @@ class AdminMediaControllerServiceTest {
storageRoot = tempDir.resolve("storage_media"); storageRoot = tempDir.resolve("storage_media");
MediaStorageService mediaStorageService = new MediaStorageService( MediaStorageService mediaStorageService = new MediaStorageService(
storageRoot.toString(), storageRoot.toString(),
"https://cdn.example/media" "https://cdn.example"
); );
service = new AdminMediaControllerService( service = new AdminMediaControllerService(
@@ -275,6 +276,31 @@ class AdminMediaControllerServiceTest {
.noneMatch(variant -> "WEBP".equals(variant.getFormat()) || "AVIF".equals(variant.getFormat()))); .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 @Test
void uploadAsset_withOversizedFile_shouldFailValidationBeforePersistence() { void uploadAsset_withOversizedFile_shouldFailValidationBeforePersistence() {
service = new AdminMediaControllerService( service = new AdminMediaControllerService(

View File

@@ -0,0 +1,137 @@
package com.printcalculator.service.admin;
import com.printcalculator.entity.ShopProduct;
import com.printcalculator.entity.ShopProductModelAsset;
import com.printcalculator.entity.ShopProductVariant;
import com.printcalculator.repository.OrderItemRepository;
import com.printcalculator.repository.QuoteLineItemRepository;
import com.printcalculator.repository.ShopCategoryRepository;
import com.printcalculator.repository.ShopProductModelAssetRepository;
import com.printcalculator.repository.ShopProductRepository;
import com.printcalculator.repository.ShopProductVariantRepository;
import com.printcalculator.service.SlicerService;
import com.printcalculator.service.media.PublicMediaQueryService;
import com.printcalculator.service.shop.ShopStorageService;
import com.printcalculator.service.storage.ClamAVService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class AdminShopProductControllerServiceTest {
@Mock
private ShopProductRepository shopProductRepository;
@Mock
private ShopCategoryRepository shopCategoryRepository;
@Mock
private ShopProductVariantRepository shopProductVariantRepository;
@Mock
private ShopProductModelAssetRepository shopProductModelAssetRepository;
@Mock
private QuoteLineItemRepository quoteLineItemRepository;
@Mock
private OrderItemRepository orderItemRepository;
@Mock
private PublicMediaQueryService publicMediaQueryService;
@Mock
private AdminMediaControllerService adminMediaControllerService;
@Mock
private ShopStorageService shopStorageService;
@Mock
private SlicerService slicerService;
@Mock
private ClamAVService clamAVService;
private AdminShopProductControllerService service;
@BeforeEach
void setUp() {
service = new AdminShopProductControllerService(
shopProductRepository,
shopCategoryRepository,
shopProductVariantRepository,
shopProductModelAssetRepository,
quoteLineItemRepository,
orderItemRepository,
publicMediaQueryService,
adminMediaControllerService,
shopStorageService,
slicerService,
clamAVService,
104857600L
);
}
@Test
void deleteProduct_shouldDeleteManagedDependenciesBeforeDeletingProduct() {
UUID productId = UUID.randomUUID();
UUID variantId = UUID.randomUUID();
ShopProduct product = new ShopProduct();
product.setId(productId);
ShopProductVariant variant = new ShopProductVariant();
variant.setId(variantId);
variant.setProduct(product);
ShopProductModelAsset asset = new ShopProductModelAsset();
asset.setId(UUID.randomUUID());
asset.setProduct(product);
asset.setStoredRelativePath("products/" + productId + "/model.stl");
when(shopProductRepository.findById(productId)).thenReturn(Optional.of(product));
when(quoteLineItemRepository.existsByShopProduct_Id(productId)).thenReturn(false);
when(orderItemRepository.existsByShopProduct_Id(productId)).thenReturn(false);
when(shopProductVariantRepository.findByProduct_IdOrderBySortOrderAscColorNameAsc(productId)).thenReturn(List.of(variant));
when(quoteLineItemRepository.existsByShopProductVariant_Id(variantId)).thenReturn(false);
when(orderItemRepository.existsByShopProductVariant_Id(variantId)).thenReturn(false);
when(shopProductModelAssetRepository.findByProduct_Id(productId)).thenReturn(Optional.of(asset));
when(shopStorageService.resolveStoredProductPath(asset.getStoredRelativePath(), productId))
.thenReturn(Path.of("/tmp/shop-model.stl"));
service.deleteProduct(productId);
InOrder inOrder = inOrder(shopProductModelAssetRepository, shopProductVariantRepository, shopProductRepository);
inOrder.verify(shopProductModelAssetRepository).delete(asset);
inOrder.verify(shopProductVariantRepository).deleteAll(List.of(variant));
inOrder.verify(shopProductRepository).delete(product);
verify(shopStorageService).resolveStoredProductPath(asset.getStoredRelativePath(), productId);
}
@Test
void deleteProduct_shouldSkipDependencyDeletesWhenNothingIsAttached() {
UUID productId = UUID.randomUUID();
ShopProduct product = new ShopProduct();
product.setId(productId);
when(shopProductRepository.findById(productId)).thenReturn(Optional.of(product));
when(quoteLineItemRepository.existsByShopProduct_Id(productId)).thenReturn(false);
when(orderItemRepository.existsByShopProduct_Id(productId)).thenReturn(false);
when(shopProductVariantRepository.findByProduct_IdOrderBySortOrderAscColorNameAsc(productId)).thenReturn(List.of());
when(shopProductModelAssetRepository.findByProduct_Id(productId)).thenReturn(Optional.empty());
service.deleteProduct(productId);
verify(shopProductRepository).delete(product);
verify(shopProductVariantRepository, never()).deleteAll(any());
verify(shopProductModelAssetRepository, never()).delete(any());
}
}

View File

@@ -6,8 +6,12 @@ import org.junit.jupiter.api.io.TempDir;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; 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.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
class MediaFfmpegServiceTest { class MediaFfmpegServiceTest {
@@ -61,4 +65,101 @@ class MediaFfmpegServiceTest {
assertEquals("Media target file name must not start with '-'.", ex.getMessage()); 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
if [ "$1" = "-hide_banner" ] && [ "$2" = "-muxers" ]; then
cat <<'EOF'
E avif
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));
}
@Test
void canEncode_avifShouldRequireMuxerAvailability() throws Exception {
Path fakeFfmpeg = tempDir.resolve("fake-ffmpeg-no-avif-muxer.sh");
Files.writeString(
fakeFfmpeg,
"""
#!/bin/sh
if [ "$1" = "-hide_banner" ] && [ "$2" = "-encoders" ]; then
cat <<'EOF'
V..... mjpeg
V..... libaom-av1
EOF
exit 0
fi
if [ "$1" = "-hide_banner" ] && [ "$2" = "-muxers" ]; then
cat <<'EOF'
E mp4
EOF
exit 0
fi
exit 0
"""
);
Files.setPosixFilePermissions(
fakeFfmpeg,
Set.of(
PosixFilePermission.OWNER_READ,
PosixFilePermission.OWNER_WRITE,
PosixFilePermission.OWNER_EXECUTE
)
);
MediaFfmpegService service = new MediaFfmpegService(fakeFfmpeg.toString());
assertTrue(service.canEncode("JPEG"));
assertFalse(service.canEncode("AVIF"));
}
} }

View File

@@ -41,7 +41,7 @@ class PublicMediaQueryServiceTest {
void setUp() { void setUp() {
MediaStorageService mediaStorageService = new MediaStorageService( MediaStorageService mediaStorageService = new MediaStorageService(
tempDir.resolve("storage_media").toString(), tempDir.resolve("storage_media").toString(),
"https://cdn.example/media" "https://cdn.example"
); );
service = new PublicMediaQueryService(mediaUsageRepository, mediaVariantRepository, mediaStorageService); service = new PublicMediaQueryService(mediaUsageRepository, mediaVariantRepository, mediaStorageService);
} }
@@ -65,8 +65,8 @@ class PublicMediaQueryServiceTest {
MediaUsage usageDraft = buildUsage(draftAsset, "HOME_SECTION", "shop-gallery", 0, false, true); MediaUsage usageDraft = buildUsage(draftAsset, "HOME_SECTION", "shop-gallery", 0, false, true);
MediaUsage usagePrivate = buildUsage(privateAsset, "HOME_SECTION", "shop-gallery", 3, false, true); MediaUsage usagePrivate = buildUsage(privateAsset, "HOME_SECTION", "shop-gallery", 3, false, true);
when(mediaUsageRepository.findByUsageTypeAndUsageKeyAndIsActiveTrueOrderBySortOrderAscCreatedAtAsc( when(mediaUsageRepository.findActiveByUsageTypeAndUsageKeys(
"HOME_SECTION", "shop-gallery" "HOME_SECTION", List.of("shop-gallery")
)).thenReturn(List.of(usageSecond, usageFirst, usageDraft, usagePrivate)); )).thenReturn(List.of(usageSecond, usageFirst, usageDraft, usagePrivate));
when(mediaVariantRepository.findByMediaAsset_IdIn(List.of(readyPublicAsset.getId()))) when(mediaVariantRepository.findByMediaAsset_IdIn(List.of(readyPublicAsset.getId())))
.thenReturn(List.of( .thenReturn(List.of(
@@ -93,8 +93,8 @@ class PublicMediaQueryServiceTest {
MediaAsset asset = buildAsset("READY", "PUBLIC", "Joe portrait", "Joe portrait fallback"); MediaAsset asset = buildAsset("READY", "PUBLIC", "Joe portrait", "Joe portrait fallback");
MediaUsage usage = buildUsage(asset, "ABOUT_MEMBER", "joe", 0, true, true); MediaUsage usage = buildUsage(asset, "ABOUT_MEMBER", "joe", 0, true, true);
when(mediaUsageRepository.findByUsageTypeAndUsageKeyAndIsActiveTrueOrderBySortOrderAscCreatedAtAsc( when(mediaUsageRepository.findActiveByUsageTypeAndUsageKeys(
"ABOUT_MEMBER", "joe" "ABOUT_MEMBER", List.of("joe")
)).thenReturn(List.of(usage)); )).thenReturn(List.of(usage));
when(mediaVariantRepository.findByMediaAsset_IdIn(List.of(asset.getId()))) when(mediaVariantRepository.findByMediaAsset_IdIn(List.of(asset.getId())))
.thenReturn(List.of(buildVariant(asset, "card", "JPEG", "joe/card.jpg"))); .thenReturn(List.of(buildVariant(asset, "card", "JPEG", "joe/card.jpg")));

View File

@@ -0,0 +1,85 @@
package com.printcalculator.service.payment;
import com.printcalculator.entity.Order;
import com.printcalculator.entity.OrderItem;
import org.junit.jupiter.api.Test;
import org.thymeleaf.TemplateEngine;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
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.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class InvoicePdfRenderingServiceTest {
@Test
void generateDocumentPdf_shouldDescribeShopItemsWithProductAndVariant() {
CapturingInvoicePdfRenderingService service = new CapturingInvoicePdfRenderingService();
QrBillService qrBillService = mock(QrBillService.class);
when(qrBillService.generateQrBillSvg(org.mockito.ArgumentMatchers.any(Order.class)))
.thenReturn("<svg/>".getBytes(StandardCharsets.UTF_8));
Order order = new Order();
order.setId(UUID.randomUUID());
order.setCreatedAt(OffsetDateTime.parse("2026-03-10T10:15:30+01:00"));
order.setBillingCustomerType("PRIVATE");
order.setBillingFirstName("Joe");
order.setBillingLastName("Buyer");
order.setBillingAddressLine1("Via Test 1");
order.setBillingZip("6900");
order.setBillingCity("Lugano");
order.setBillingCountryCode("CH");
order.setSetupCostChf(BigDecimal.ZERO);
order.setShippingCostChf(new BigDecimal("2.00"));
order.setSubtotalChf(new BigDecimal("36.80"));
order.setTotalChf(new BigDecimal("38.80"));
order.setCadTotalChf(BigDecimal.ZERO);
OrderItem shopItem = new OrderItem();
shopItem.setItemType("SHOP_PRODUCT");
shopItem.setDisplayName("Desk Cable Clip");
shopItem.setOriginalFilename("desk-cable-clip.stl");
shopItem.setShopProductName("Desk Cable Clip");
shopItem.setShopVariantLabel("Coral Red");
shopItem.setQuantity(2);
shopItem.setUnitPriceChf(new BigDecimal("14.90"));
shopItem.setLineTotalChf(new BigDecimal("29.80"));
OrderItem printItem = new OrderItem();
printItem.setItemType("PRINT_FILE");
printItem.setDisplayName("gear-cover.stl");
printItem.setOriginalFilename("gear-cover.stl");
printItem.setQuantity(1);
printItem.setUnitPriceChf(new BigDecimal("7.00"));
printItem.setLineTotalChf(new BigDecimal("7.00"));
byte[] pdf = service.generateDocumentPdf(order, List.of(shopItem, printItem), true, qrBillService, null);
assertNotNull(pdf);
@SuppressWarnings("unchecked")
List<Map<String, Object>> invoiceLineItems = (List<Map<String, Object>>) service.capturedVariables.get("invoiceLineItems");
assertEquals("Desk Cable Clip - Coral Red", invoiceLineItems.getFirst().get("description"));
assertEquals("Stampa 3D: gear-cover.stl", invoiceLineItems.get(1).get("description"));
}
private static class CapturingInvoicePdfRenderingService extends InvoicePdfRenderingService {
private Map<String, Object> capturedVariables;
private CapturingInvoicePdfRenderingService() {
super(mock(TemplateEngine.class));
}
@Override
public byte[] generateInvoicePdfBytesFromTemplate(Map<String, Object> invoiceTemplateVariables, String qrBillSvg) {
this.capturedVariables = invoiceTemplateVariables;
return new byte[]{1, 2, 3};
}
}
}

View File

@@ -0,0 +1,220 @@
package com.printcalculator.service.shop;
import com.printcalculator.dto.ShopCartAddItemRequest;
import com.printcalculator.entity.QuoteLineItem;
import com.printcalculator.entity.QuoteSession;
import com.printcalculator.entity.ShopCategory;
import com.printcalculator.entity.ShopProduct;
import com.printcalculator.entity.ShopProductVariant;
import com.printcalculator.repository.QuoteLineItemRepository;
import com.printcalculator.repository.QuoteSessionRepository;
import com.printcalculator.repository.ShopProductModelAssetRepository;
import com.printcalculator.repository.ShopProductVariantRepository;
import com.printcalculator.service.QuoteSessionTotalsService;
import com.printcalculator.service.quote.QuoteSessionResponseAssembler;
import com.printcalculator.service.quote.QuoteStorageService;
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.mock.web.MockHttpServletRequest;
import java.math.BigDecimal;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.HashMap;
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.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class ShopCartServiceTest {
@Mock
private QuoteSessionRepository quoteSessionRepository;
@Mock
private QuoteLineItemRepository quoteLineItemRepository;
@Mock
private ShopProductVariantRepository shopProductVariantRepository;
@Mock
private ShopProductModelAssetRepository shopProductModelAssetRepository;
@Mock
private QuoteSessionTotalsService quoteSessionTotalsService;
@Mock
private QuoteSessionResponseAssembler quoteSessionResponseAssembler;
@Mock
private ShopStorageService shopStorageService;
@Mock
private ShopCartCookieService shopCartCookieService;
private ShopCartService service;
@BeforeEach
void setUp() {
service = new ShopCartService(
quoteSessionRepository,
quoteLineItemRepository,
shopProductVariantRepository,
shopProductModelAssetRepository,
quoteSessionTotalsService,
quoteSessionResponseAssembler,
new QuoteStorageService(),
shopStorageService,
shopCartCookieService
);
}
@Test
void addItem_shouldCreateServerCartAndPersistVariantPricingSnapshot() {
UUID sessionId = UUID.randomUUID();
UUID lineItemId = UUID.randomUUID();
UUID variantId = UUID.randomUUID();
List<QuoteLineItem> savedItems = new ArrayList<>();
ShopProductVariant variant = buildVariant(variantId);
when(shopCartCookieService.extractSessionId(any())).thenReturn(Optional.empty());
when(shopCartCookieService.getCookieTtlDays()).thenReturn(30L);
when(shopProductVariantRepository.findById(variantId)).thenReturn(Optional.of(variant));
when(shopProductModelAssetRepository.findByProduct_Id(variant.getProduct().getId())).thenReturn(Optional.empty());
when(quoteSessionRepository.save(any(QuoteSession.class))).thenAnswer(invocation -> {
QuoteSession session = invocation.getArgument(0);
if (session.getId() == null) {
session.setId(sessionId);
}
return session;
});
when(quoteLineItemRepository.findFirstByQuoteSession_IdAndLineItemTypeAndShopProductVariant_Id(
eq(sessionId),
eq("SHOP_PRODUCT"),
eq(variantId)
)).thenReturn(Optional.empty());
when(quoteLineItemRepository.save(any(QuoteLineItem.class))).thenAnswer(invocation -> {
QuoteLineItem item = invocation.getArgument(0);
if (item.getId() == null) {
item.setId(lineItemId);
}
savedItems.clear();
savedItems.add(item);
return item;
});
when(quoteLineItemRepository.findByQuoteSessionIdOrderByCreatedAtAsc(sessionId)).thenAnswer(invocation -> List.copyOf(savedItems));
when(quoteSessionTotalsService.compute(any(), any())).thenReturn(
new QuoteSessionTotalsService.QuoteSessionTotals(
new BigDecimal("22.80"),
BigDecimal.ZERO,
BigDecimal.ZERO,
new BigDecimal("22.80"),
BigDecimal.ZERO,
BigDecimal.ZERO,
BigDecimal.ZERO,
new BigDecimal("2.00"),
new BigDecimal("24.80"),
BigDecimal.ZERO
)
);
when(quoteSessionResponseAssembler.assemble(any(), any(), any())).thenAnswer(invocation -> {
QuoteSession session = invocation.getArgument(0);
Map<String, Object> response = new HashMap<>();
response.put("session", session);
response.put("items", List.of());
response.put("grandTotalChf", new BigDecimal("24.80"));
return response;
});
ShopCartAddItemRequest payload = new ShopCartAddItemRequest();
payload.setShopProductVariantId(variantId);
payload.setQuantity(2);
ShopCartService.CartResult result = service.addItem(new MockHttpServletRequest(), payload);
assertEquals(sessionId, result.sessionId());
assertFalse(result.clearCookie());
assertEquals(new BigDecimal("24.80"), result.response().get("grandTotalChf"));
QuoteLineItem savedItem = savedItems.getFirst();
assertEquals("SHOP_PRODUCT", savedItem.getLineItemType());
assertEquals("Desk Cable Clip", savedItem.getDisplayName());
assertEquals("desk-cable-clip", savedItem.getOriginalFilename());
assertEquals(2, savedItem.getQuantity());
assertEquals("PLA", savedItem.getMaterialCode());
assertEquals("Coral Red", savedItem.getColorCode());
assertEquals("Desk Cable Clip", savedItem.getShopProductName());
assertEquals("Coral Red", savedItem.getShopVariantLabel());
assertEquals("Coral Red", savedItem.getShopVariantColorName());
assertAmountEquals("11.40", savedItem.getUnitPriceChf());
assertNull(savedItem.getStoredPath());
}
@Test
void loadCart_withExpiredCookieSession_shouldExpireSessionAndAskCookieClear() {
UUID sessionId = UUID.randomUUID();
QuoteSession session = new QuoteSession();
session.setId(sessionId);
session.setSessionType("SHOP_CART");
session.setStatus("ACTIVE");
session.setExpiresAt(OffsetDateTime.now().minusHours(1));
Map<String, Object> emptyResponse = new HashMap<>();
emptyResponse.put("session", null);
emptyResponse.put("items", List.of());
when(shopCartCookieService.hasCartCookie(any())).thenReturn(true);
when(shopCartCookieService.extractSessionId(any())).thenReturn(Optional.of(sessionId));
when(quoteSessionRepository.findByIdAndSessionType(sessionId, "SHOP_CART")).thenReturn(Optional.of(session));
when(quoteSessionRepository.save(any(QuoteSession.class))).thenAnswer(invocation -> invocation.getArgument(0));
when(quoteSessionResponseAssembler.emptyCart()).thenReturn(emptyResponse);
ShopCartService.CartResult result = service.loadCart(new MockHttpServletRequest());
assertTrue(result.clearCookie());
assertNull(result.sessionId());
assertEquals(emptyResponse, result.response());
assertEquals("EXPIRED", session.getStatus());
verify(quoteSessionRepository).save(session);
}
private ShopProductVariant buildVariant(UUID variantId) {
ShopCategory category = new ShopCategory();
category.setId(UUID.randomUUID());
category.setSlug("cable-management");
category.setName("Cable Management");
category.setIsActive(true);
ShopProduct product = new ShopProduct();
product.setId(UUID.randomUUID());
product.setCategory(category);
product.setSlug("desk-cable-clip");
product.setName("Desk Cable Clip");
product.setIsActive(true);
ShopProductVariant variant = new ShopProductVariant();
variant.setId(variantId);
variant.setProduct(product);
variant.setSku("DEMO-CLIP-CORAL");
variant.setVariantLabel("Coral Red");
variant.setColorName("Coral Red");
variant.setColorHex("#ff6b6b");
variant.setInternalMaterialCode("PLA");
variant.setPriceChf(new BigDecimal("11.40"));
variant.setIsActive(true);
variant.setIsDefault(false);
return variant;
}
private void assertAmountEquals(String expected, BigDecimal actual) {
assertTrue(new BigDecimal(expected).compareTo(actual) == 0,
"Expected " + expected + " but got " + actual);
}
}

View File

@@ -0,0 +1,116 @@
package com.printcalculator.service.shop;
import com.printcalculator.entity.ShopCategory;
import com.printcalculator.entity.ShopProduct;
import com.printcalculator.repository.ShopCategoryRepository;
import com.printcalculator.repository.ShopProductRepository;
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 java.time.Clock;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.List;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class ShopSitemapServiceTest {
@Mock
private ShopCategoryRepository shopCategoryRepository;
@Mock
private ShopProductRepository shopProductRepository;
private ShopSitemapService service;
@BeforeEach
void setUp() {
Clock fixedClock = Clock.fixed(Instant.parse("2026-03-11T10:00:00Z"), ZoneOffset.UTC);
service = new ShopSitemapService(
shopCategoryRepository,
shopProductRepository,
"https://3d-fab.ch/",
900,
fixedClock
);
}
@Test
void getShopSitemapXml_shouldGenerateLocalizedCategoryAndProductEntries() {
ShopCategory visibleCategory = new ShopCategory();
visibleCategory.setId(UUID.fromString("21111111-1111-1111-1111-111111111111"));
visibleCategory.setSlug("accessori");
visibleCategory.setIndexable(true);
visibleCategory.setIsActive(true);
visibleCategory.setUpdatedAt(OffsetDateTime.parse("2026-03-10T08:00:00Z"));
ShopCategory hiddenCategory = new ShopCategory();
hiddenCategory.setId(UUID.fromString("22222222-2222-2222-2222-222222222222"));
hiddenCategory.setSlug("bozza");
hiddenCategory.setIndexable(false);
hiddenCategory.setIsActive(true);
hiddenCategory.setUpdatedAt(OffsetDateTime.parse("2026-03-10T09:00:00Z"));
ShopProduct indexedProduct = new ShopProduct();
indexedProduct.setId(UUID.fromString("123e4567-e89b-12d3-a456-426614174000"));
indexedProduct.setCategory(visibleCategory);
indexedProduct.setSlug("supporto-bici");
indexedProduct.setNameIt("Supporto bici");
indexedProduct.setNameEn("Bike Holder");
indexedProduct.setNameDe("Fahrrad Halter");
indexedProduct.setNameFr("Support velo");
indexedProduct.setIndexable(true);
indexedProduct.setIsActive(true);
indexedProduct.setUpdatedAt(OffsetDateTime.parse("2026-03-11T07:30:00Z"));
ShopProduct hiddenProduct = new ShopProduct();
hiddenProduct.setId(UUID.fromString("33333333-3333-3333-3333-333333333333"));
hiddenProduct.setCategory(visibleCategory);
hiddenProduct.setSlug("draft");
hiddenProduct.setIndexable(false);
hiddenProduct.setIsActive(true);
hiddenProduct.setUpdatedAt(OffsetDateTime.parse("2026-03-11T08:00:00Z"));
when(shopCategoryRepository.findAllByIsActiveTrueOrderBySortOrderAscNameAsc())
.thenReturn(List.of(visibleCategory, hiddenCategory));
when(shopProductRepository.findAllByIsActiveTrueOrderByIsFeaturedDescSortOrderAscNameAsc())
.thenReturn(List.of(indexedProduct, hiddenProduct));
String xml = service.getShopSitemapXml();
assertTrue(xml.contains("<loc>https://3d-fab.ch/it/shop/accessori</loc>"));
assertTrue(xml.contains("hreflang=\"en\" href=\"https://3d-fab.ch/en/shop/accessori\""));
assertFalse(xml.contains("https://3d-fab.ch/it/shop/bozza"));
assertTrue(xml.contains("<loc>https://3d-fab.ch/it/shop/p/123e4567-supporto-bici</loc>"));
assertTrue(xml.contains("hreflang=\"en\" href=\"https://3d-fab.ch/en/shop/p/123e4567-bike-holder\""));
assertTrue(xml.contains("hreflang=\"de\" href=\"https://3d-fab.ch/de/shop/p/123e4567-fahrrad-halter\""));
assertTrue(xml.contains("hreflang=\"x-default\" href=\"https://3d-fab.ch/it/shop/p/123e4567-supporto-bici\""));
assertTrue(xml.contains("<lastmod>2026-03-11T07:30:00Z</lastmod>"));
assertFalse(xml.contains("33333333-draft"));
}
@Test
void getShopSitemapXml_shouldServeCachedPayloadWithinTtl() {
when(shopCategoryRepository.findAllByIsActiveTrueOrderBySortOrderAscNameAsc()).thenReturn(List.of());
when(shopProductRepository.findAllByIsActiveTrueOrderByIsFeaturedDescSortOrderAscNameAsc()).thenReturn(List.of());
String firstXml = service.getShopSitemapXml();
String secondXml = service.getShopSitemapXml();
assertTrue(firstXml.contains("<urlset"));
assertTrue(secondXml.contains("<urlset"));
verify(shopCategoryRepository, times(1)).findAllByIsActiveTrueOrderBySortOrderAscNameAsc();
verify(shopProductRepository, times(1)).findAllByIsActiveTrueOrderByIsFeaturedDescSortOrderAscNameAsc();
}
}

331
db.sql
View File

@@ -1007,6 +1007,337 @@ ALTER TABLE media_usage
ALTER TABLE media_usage ALTER TABLE media_usage
ADD COLUMN IF NOT EXISTS alt_text_fr text; ADD COLUMN IF NOT EXISTS alt_text_fr text;
CREATE TABLE IF NOT EXISTS shop_category
(
shop_category_id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
parent_category_id uuid REFERENCES shop_category (shop_category_id) ON DELETE SET NULL,
slug text NOT NULL UNIQUE,
name text NOT NULL,
description text,
seo_title text,
seo_description text,
og_title text,
og_description text,
indexable boolean NOT NULL DEFAULT true,
is_active boolean NOT NULL DEFAULT true,
sort_order integer NOT NULL DEFAULT 0,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT chk_shop_category_not_self_parent CHECK (
parent_category_id IS NULL OR parent_category_id <> shop_category_id
)
);
CREATE INDEX IF NOT EXISTS ix_shop_category_parent_sort
ON shop_category (parent_category_id, sort_order, created_at DESC);
CREATE INDEX IF NOT EXISTS ix_shop_category_active_sort
ON shop_category (is_active, sort_order, created_at DESC);
CREATE TABLE IF NOT EXISTS shop_product
(
shop_product_id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
shop_category_id uuid NOT NULL REFERENCES shop_category (shop_category_id),
slug text NOT NULL UNIQUE,
name text NOT NULL,
name_it text,
name_en text,
name_de text,
name_fr text,
excerpt text,
excerpt_it text,
excerpt_en text,
excerpt_de text,
excerpt_fr text,
description text,
description_it text,
description_en text,
description_de text,
description_fr text,
seo_title text,
seo_title_it text,
seo_title_en text,
seo_title_de text,
seo_title_fr text,
seo_description text,
seo_description_it text,
seo_description_en text,
seo_description_de text,
seo_description_fr text,
og_title text,
og_description text,
indexable boolean NOT NULL DEFAULT true,
is_featured boolean NOT NULL DEFAULT false,
is_active boolean NOT NULL DEFAULT true,
sort_order integer NOT NULL DEFAULT 0,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
ALTER TABLE shop_product
ADD COLUMN IF NOT EXISTS seo_title_it text,
ADD COLUMN IF NOT EXISTS seo_title_en text,
ADD COLUMN IF NOT EXISTS seo_title_de text,
ADD COLUMN IF NOT EXISTS seo_title_fr text,
ADD COLUMN IF NOT EXISTS seo_description_it text,
ADD COLUMN IF NOT EXISTS seo_description_en text,
ADD COLUMN IF NOT EXISTS seo_description_de text,
ADD COLUMN IF NOT EXISTS seo_description_fr text;
CREATE INDEX IF NOT EXISTS ix_shop_product_category_active_sort
ON shop_product (shop_category_id, is_active, sort_order, created_at DESC);
CREATE INDEX IF NOT EXISTS ix_shop_product_featured_sort
ON shop_product (is_featured, is_active, sort_order, created_at DESC);
ALTER TABLE shop_product
ADD COLUMN IF NOT EXISTS name_it text;
ALTER TABLE shop_product
ADD COLUMN IF NOT EXISTS name_en text;
ALTER TABLE shop_product
ADD COLUMN IF NOT EXISTS name_de text;
ALTER TABLE shop_product
ADD COLUMN IF NOT EXISTS name_fr text;
ALTER TABLE shop_product
ADD COLUMN IF NOT EXISTS excerpt_it text;
ALTER TABLE shop_product
ADD COLUMN IF NOT EXISTS excerpt_en text;
ALTER TABLE shop_product
ADD COLUMN IF NOT EXISTS excerpt_de text;
ALTER TABLE shop_product
ADD COLUMN IF NOT EXISTS excerpt_fr text;
ALTER TABLE shop_product
ADD COLUMN IF NOT EXISTS description_it text;
ALTER TABLE shop_product
ADD COLUMN IF NOT EXISTS description_en text;
ALTER TABLE shop_product
ADD COLUMN IF NOT EXISTS description_de text;
ALTER TABLE shop_product
ADD COLUMN IF NOT EXISTS description_fr text;
UPDATE shop_product
SET
name_it = COALESCE(NULLIF(btrim(name_it), ''), name),
name_en = COALESCE(NULLIF(btrim(name_en), ''), name),
name_de = COALESCE(NULLIF(btrim(name_de), ''), name),
name_fr = COALESCE(NULLIF(btrim(name_fr), ''), name),
excerpt_it = COALESCE(NULLIF(btrim(excerpt_it), ''), excerpt),
excerpt_en = COALESCE(NULLIF(btrim(excerpt_en), ''), excerpt),
excerpt_de = COALESCE(NULLIF(btrim(excerpt_de), ''), excerpt),
excerpt_fr = COALESCE(NULLIF(btrim(excerpt_fr), ''), excerpt),
description_it = COALESCE(NULLIF(btrim(description_it), ''), description),
description_en = COALESCE(NULLIF(btrim(description_en), ''), description),
description_de = COALESCE(NULLIF(btrim(description_de), ''), description),
description_fr = COALESCE(NULLIF(btrim(description_fr), ''), description)
WHERE
NULLIF(btrim(name_it), '') IS NULL
OR NULLIF(btrim(name_en), '') IS NULL
OR NULLIF(btrim(name_de), '') IS NULL
OR NULLIF(btrim(name_fr), '') IS NULL
OR (excerpt IS NOT NULL AND (
NULLIF(btrim(excerpt_it), '') IS NULL
OR NULLIF(btrim(excerpt_en), '') IS NULL
OR NULLIF(btrim(excerpt_de), '') IS NULL
OR NULLIF(btrim(excerpt_fr), '') IS NULL
))
OR (description IS NOT NULL AND (
NULLIF(btrim(description_it), '') IS NULL
OR NULLIF(btrim(description_en), '') IS NULL
OR NULLIF(btrim(description_de), '') IS NULL
OR NULLIF(btrim(description_fr), '') IS NULL
));
CREATE TABLE IF NOT EXISTS shop_product_variant
(
shop_product_variant_id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
shop_product_id uuid NOT NULL REFERENCES shop_product (shop_product_id) ON DELETE CASCADE,
sku text UNIQUE,
variant_label text NOT NULL,
color_name text NOT NULL,
color_hex text,
internal_material_code text NOT NULL,
price_chf numeric(12, 2) NOT NULL DEFAULT 0.00 CHECK (price_chf >= 0),
is_default boolean NOT NULL DEFAULT false,
is_active boolean NOT NULL DEFAULT true,
sort_order integer NOT NULL DEFAULT 0,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS ix_shop_product_variant_product_active_sort
ON shop_product_variant (shop_product_id, is_active, sort_order, created_at DESC);
CREATE INDEX IF NOT EXISTS ix_shop_product_variant_sku
ON shop_product_variant (sku);
CREATE TABLE IF NOT EXISTS shop_product_model_asset
(
shop_product_model_asset_id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
shop_product_id uuid NOT NULL UNIQUE REFERENCES shop_product (shop_product_id) ON DELETE CASCADE,
original_filename text NOT NULL,
stored_relative_path text NOT NULL,
stored_filename text NOT NULL,
file_size_bytes bigint CHECK (file_size_bytes >= 0),
mime_type text,
sha256_hex text,
bounding_box_x_mm numeric(10, 3),
bounding_box_y_mm numeric(10, 3),
bounding_box_z_mm numeric(10, 3),
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS ix_shop_product_model_asset_product
ON shop_product_model_asset (shop_product_id);
ALTER TABLE quote_sessions
ADD COLUMN IF NOT EXISTS session_type text NOT NULL DEFAULT 'PRINT_QUOTE';
CREATE INDEX IF NOT EXISTS ix_quote_sessions_session_type
ON quote_sessions (session_type);
ALTER TABLE quote_sessions
DROP CONSTRAINT IF EXISTS quote_sessions_session_type_check;
ALTER TABLE quote_sessions
ADD CONSTRAINT quote_sessions_session_type_check
CHECK (session_type IN ('PRINT_QUOTE', 'SHOP_CART'));
ALTER TABLE quote_line_items
ADD COLUMN IF NOT EXISTS line_item_type text NOT NULL DEFAULT 'PRINT_FILE';
ALTER TABLE quote_line_items
ADD COLUMN IF NOT EXISTS display_name text;
ALTER TABLE quote_line_items
ADD COLUMN IF NOT EXISTS shop_product_id uuid;
ALTER TABLE quote_line_items
ADD COLUMN IF NOT EXISTS shop_product_variant_id uuid;
ALTER TABLE quote_line_items
ADD COLUMN IF NOT EXISTS shop_product_slug text;
ALTER TABLE quote_line_items
ADD COLUMN IF NOT EXISTS shop_product_name text;
ALTER TABLE quote_line_items
ADD COLUMN IF NOT EXISTS shop_variant_label text;
ALTER TABLE quote_line_items
ADD COLUMN IF NOT EXISTS shop_variant_color_name text;
ALTER TABLE quote_line_items
ADD COLUMN IF NOT EXISTS shop_variant_color_hex text;
ALTER TABLE quote_line_items
ADD COLUMN IF NOT EXISTS stored_path text;
CREATE INDEX IF NOT EXISTS ix_quote_line_items_shop_product
ON quote_line_items (shop_product_id);
CREATE INDEX IF NOT EXISTS ix_quote_line_items_shop_product_variant
ON quote_line_items (shop_product_variant_id);
ALTER TABLE quote_line_items
DROP CONSTRAINT IF EXISTS quote_line_items_line_item_type_check;
ALTER TABLE quote_line_items
ADD CONSTRAINT quote_line_items_line_item_type_check
CHECK (line_item_type IN ('PRINT_FILE', 'SHOP_PRODUCT'));
ALTER TABLE quote_line_items
DROP CONSTRAINT IF EXISTS fk_quote_line_items_shop_product;
ALTER TABLE quote_line_items
ADD CONSTRAINT fk_quote_line_items_shop_product
FOREIGN KEY (shop_product_id) REFERENCES shop_product (shop_product_id);
ALTER TABLE quote_line_items
DROP CONSTRAINT IF EXISTS fk_quote_line_items_shop_product_variant;
ALTER TABLE quote_line_items
ADD CONSTRAINT fk_quote_line_items_shop_product_variant
FOREIGN KEY (shop_product_variant_id) REFERENCES shop_product_variant (shop_product_variant_id);
ALTER TABLE orders
ADD COLUMN IF NOT EXISTS source_type text NOT NULL DEFAULT 'CALCULATOR';
CREATE INDEX IF NOT EXISTS ix_orders_source_type
ON orders (source_type);
ALTER TABLE orders
DROP CONSTRAINT IF EXISTS orders_source_type_check;
ALTER TABLE orders
ADD CONSTRAINT orders_source_type_check
CHECK (source_type IN ('CALCULATOR', 'SHOP'));
ALTER TABLE order_items
ADD COLUMN IF NOT EXISTS item_type text NOT NULL DEFAULT 'PRINT_FILE';
ALTER TABLE order_items
ADD COLUMN IF NOT EXISTS display_name text;
ALTER TABLE order_items
ADD COLUMN IF NOT EXISTS shop_product_id uuid;
ALTER TABLE order_items
ADD COLUMN IF NOT EXISTS shop_product_variant_id uuid;
ALTER TABLE order_items
ADD COLUMN IF NOT EXISTS shop_product_slug text;
ALTER TABLE order_items
ADD COLUMN IF NOT EXISTS shop_product_name text;
ALTER TABLE order_items
ADD COLUMN IF NOT EXISTS shop_variant_label text;
ALTER TABLE order_items
ADD COLUMN IF NOT EXISTS shop_variant_color_name text;
ALTER TABLE order_items
ADD COLUMN IF NOT EXISTS shop_variant_color_hex text;
CREATE INDEX IF NOT EXISTS ix_order_items_shop_product
ON order_items (shop_product_id);
CREATE INDEX IF NOT EXISTS ix_order_items_shop_product_variant
ON order_items (shop_product_variant_id);
ALTER TABLE order_items
DROP CONSTRAINT IF EXISTS order_items_item_type_check;
ALTER TABLE order_items
ADD CONSTRAINT order_items_item_type_check
CHECK (item_type IN ('PRINT_FILE', 'SHOP_PRODUCT'));
ALTER TABLE order_items
DROP CONSTRAINT IF EXISTS fk_order_items_shop_product;
ALTER TABLE order_items
ADD CONSTRAINT fk_order_items_shop_product
FOREIGN KEY (shop_product_id) REFERENCES shop_product (shop_product_id);
ALTER TABLE order_items
DROP CONSTRAINT IF EXISTS fk_order_items_shop_product_variant;
ALTER TABLE order_items
ADD CONSTRAINT fk_order_items_shop_product_variant
FOREIGN KEY (shop_product_variant_id) REFERENCES shop_product_variant (shop_product_variant_id);
ALTER TABLE quote_sessions ALTER TABLE quote_sessions
DROP CONSTRAINT IF EXISTS fk_quote_sessions_source_request; DROP CONSTRAINT IF EXISTS fk_quote_sessions_source_request;

View File

@@ -32,8 +32,8 @@ services:
- TEMP_DIR=/app/temp - TEMP_DIR=/app/temp
- PROFILES_DIR=/app/profiles - PROFILES_DIR=/app/profiles
- MEDIA_STORAGE_ROOT=${MEDIA_STORAGE_ROOT:-/app/storage_media} - MEDIA_STORAGE_ROOT=${MEDIA_STORAGE_ROOT:-/app/storage_media}
- MEDIA_PUBLIC_BASE_URL=${MEDIA_PUBLIC_BASE_URL:-http://localhost:8080/media} - SHOP_STORAGE_ROOT=${SHOP_STORAGE_ROOT:-/app/storage_shop}
- MEDIA_FFMPEG_PATH=${MEDIA_FFMPEG_PATH:-ffmpeg} - MEDIA_FFMPEG_PATH=${MEDIA_FFMPEG_PATH:-/usr/local/bin/ffmpeg-media}
- MEDIA_UPLOAD_MAX_FILE_SIZE_BYTES=${MEDIA_UPLOAD_MAX_FILE_SIZE_BYTES:-26214400} - MEDIA_UPLOAD_MAX_FILE_SIZE_BYTES=${MEDIA_UPLOAD_MAX_FILE_SIZE_BYTES:-26214400}
restart: always restart: always
logging: logging:
@@ -47,6 +47,7 @@ services:
- /mnt/cache/appdata/print-calculator/${ENV}/storage_orders:/app/storage_orders - /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_requests:/app/storage_requests
- /mnt/cache/appdata/print-calculator/${ENV}/storage_media:/app/storage_media - /mnt/cache/appdata/print-calculator/${ENV}/storage_media:/app/storage_media
- /mnt/cache/appdata/print-calculator/${ENV}/storage_shop:/app/storage_shop
extra_hosts: extra_hosts:
- "host.docker.internal:host-gateway" - "host.docker.internal:host-gateway"

View File

@@ -1,14 +1,13 @@
# Stage 1: Build FROM node:22-alpine
FROM node:20 as build
WORKDIR /app WORKDIR /app
COPY package*.json ./ COPY package*.json ./
RUN npm install RUN npm ci --legacy-peer-deps
COPY . . COPY . .
RUN npm run build --configuration=production RUN npm run build -- --configuration=production
# Stage 2: Serve ENV NODE_ENV=production
FROM nginx:alpine ENV PORT=80
COPY --from=build /app/dist/frontend/browser /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80 EXPOSE 80
CMD ["node", "dist/frontend/server/server.mjs"]

View File

@@ -1,15 +1,15 @@
# Stage 1: Build FROM node:22-alpine
FROM node:20 as build
WORKDIR /app WORKDIR /app
COPY package*.json ./ COPY package*.json ./
RUN npm install RUN npm ci --legacy-peer-deps
COPY . . COPY . .
# Use development configuration to pick up environment.ts (localhost) # Use development configuration to pick up environment.ts (localhost)
RUN npm run build -- --configuration=development RUN npm run build -- --configuration=development
# Stage 2: Serve ENV NODE_ENV=development
FROM nginx:alpine ENV PORT=80
COPY --from=build /app/dist/frontend/browser /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80 EXPOSE 80
CMD ["node", "dist/frontend/server/server.mjs"]

View File

@@ -36,7 +36,12 @@
"@angular/material/prebuilt-themes/azure-blue.css", "@angular/material/prebuilt-themes/azure-blue.css",
"src/styles.scss" "src/styles.scss"
], ],
"scripts": [] "scripts": [],
"server": "src/main.server.ts",
"prerender": false,
"ssr": {
"entry": "src/server.ts"
}
}, },
"configurations": { "configurations": {
"production": { "production": {

File diff suppressed because it is too large Load Diff

View File

@@ -6,35 +6,41 @@
"start": "ng serve", "start": "ng serve",
"build": "ng build", "build": "ng build",
"watch": "ng build --watch --configuration development", "watch": "ng build --watch --configuration development",
"test": "ng test" "test": "ng test",
"serve:ssr:frontend": "node dist/frontend/server/server.mjs"
}, },
"private": true, "private": true,
"engines": { "engines": {
"node": "^22.0.0" "node": "^22.0.0"
}, },
"dependencies": { "dependencies": {
"@angular/cdk": "^19.2.19", "@angular/cdk": "19.2.19",
"@angular/common": "^19.2.18", "@angular/common": "19.2.19",
"@angular/compiler": "^19.2.18", "@angular/compiler": "19.2.19",
"@angular/core": "^19.2.18", "@angular/core": "19.2.19",
"@angular/forms": "^19.2.18", "@angular/forms": "19.2.19",
"@angular/material": "^19.2.19", "@angular/material": "19.2.19",
"@angular/platform-browser": "^19.2.18", "@angular/platform-browser": "19.2.19",
"@angular/platform-browser-dynamic": "^19.2.18", "@angular/platform-browser-dynamic": "19.2.19",
"@angular/router": "^19.2.18", "@angular/platform-server": "19.2.19",
"@angular/router": "19.2.19",
"@angular/ssr": "19.2.19",
"@ngx-translate/core": "^17.0.0", "@ngx-translate/core": "^17.0.0",
"@ngx-translate/http-loader": "^17.0.0", "@ngx-translate/http-loader": "^17.0.0",
"@types/three": "^0.182.0", "@types/three": "^0.182.0",
"express": "^4.18.2",
"rxjs": "~7.8.0", "rxjs": "~7.8.0",
"three": "^0.182.0", "three": "^0.182.0",
"tslib": "^2.3.0", "tslib": "^2.3.0",
"zone.js": "~0.15.0" "zone.js": "~0.15.0"
}, },
"devDependencies": { "devDependencies": {
"@angular-devkit/build-angular": "^19.2.19", "@angular-devkit/build-angular": "19.2.19",
"@angular/cli": "^19.2.19", "@angular/cli": "19.2.19",
"@angular/compiler-cli": "^19.2.18", "@angular/compiler-cli": "19.2.19",
"@types/express": "^4.17.17",
"@types/jasmine": "~5.1.0", "@types/jasmine": "~5.1.0",
"@types/node": "^18.18.0",
"jasmine-core": "~5.6.0", "jasmine-core": "~5.6.0",
"karma": "~6.4.0", "karma": "~6.4.0",
"karma-chrome-launcher": "~3.2.0", "karma-chrome-launcher": "~3.2.0",

View File

@@ -5,17 +5,19 @@ Disallow: /admin
Disallow: /admin/ Disallow: /admin/
Disallow: /*/admin Disallow: /*/admin
Disallow: /*/admin/ Disallow: /*/admin/
Disallow: /order
Disallow: /order/ Disallow: /order/
Disallow: /*/order
Disallow: /*/order/ Disallow: /*/order/
Disallow: /co
Disallow: /co/ Disallow: /co/
Disallow: /*/co
Disallow: /*/co/ Disallow: /*/co/
Disallow: /checkout Disallow: /checkout
Disallow: /checkout/ Disallow: /checkout/
Disallow: /checkout/cad
Disallow: /*/checkout Disallow: /*/checkout
Disallow: /*/checkout/ Disallow: /*/checkout/
Disallow: /shop Disallow: /*/checkout/cad
Disallow: /shop/
Disallow: /*/shop
Disallow: /*/shop/
Sitemap: https://3d-fab.ch/sitemap.xml Sitemap: https://3d-fab.ch/sitemap.xml

View File

@@ -0,0 +1,154 @@
<?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/shop</loc>
<xhtml:link rel="alternate" hreflang="it" href="https://3d-fab.ch/it/shop" />
<xhtml:link rel="alternate" hreflang="en" href="https://3d-fab.ch/en/shop" />
<xhtml:link rel="alternate" hreflang="de" href="https://3d-fab.ch/de/shop" />
<xhtml:link rel="alternate" hreflang="fr" href="https://3d-fab.ch/fr/shop" />
<xhtml:link rel="alternate" hreflang="x-default" href="https://3d-fab.ch/it/shop" />
<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>

View File

@@ -1,144 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<urlset <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" <sitemap>
xmlns:xhtml="http://www.w3.org/1999/xhtml" <loc>https://3d-fab.ch/sitemap-static.xml</loc>
> </sitemap>
<url> <sitemap>
<loc>https://3d-fab.ch/it</loc> <loc>https://3d-fab.ch/api/sitemap-shop.xml</loc>
<xhtml:link rel="alternate" hreflang="it" href="https://3d-fab.ch/it" /> </sitemap>
<xhtml:link rel="alternate" hreflang="en" href="https://3d-fab.ch/en" /> </sitemapindex>
<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>

View File

@@ -0,0 +1,9 @@
import { mergeApplicationConfig, ApplicationConfig } from '@angular/core';
import { provideServerRendering } from '@angular/platform-server';
import { appConfig } from './app.config';
const serverConfig: ApplicationConfig = {
providers: [provideServerRendering()],
};
export const config = mergeApplicationConfig(appConfig, serverConfig);

View File

@@ -17,6 +17,10 @@ import {
TranslateHttpLoader, TranslateHttpLoader,
} from '@ngx-translate/http-loader'; } from '@ngx-translate/http-loader';
import { adminAuthInterceptor } from './core/interceptors/admin-auth.interceptor'; import { adminAuthInterceptor } from './core/interceptors/admin-auth.interceptor';
import {
provideClientHydration,
withEventReplay,
} from '@angular/platform-browser';
export const appConfig: ApplicationConfig = { export const appConfig: ApplicationConfig = {
providers: [ providers: [
@@ -43,5 +47,6 @@ export const appConfig: ApplicationConfig = {
}, },
}), }),
), ),
provideClientHydration(withEventReplay()),
], ],
}; };

View File

@@ -1,4 +1,13 @@
import { Routes } from '@angular/router'; import { CanMatchFn, Routes } from '@angular/router';
const SUPPORTED_LANGS = new Set(['it', 'en', 'de', 'fr']);
const langPrefixCanMatch: CanMatchFn = (_route, segments) => {
if (segments.length === 0) {
return false;
}
return SUPPORTED_LANGS.has(segments[0].path.toLowerCase());
};
const appChildRoutes: Routes = [ const appChildRoutes: Routes = [
{ {
@@ -31,7 +40,6 @@ const appChildRoutes: Routes = [
seoTitle: 'Shop 3D fab', seoTitle: 'Shop 3D fab',
seoDescription: seoDescription:
'Catalogo prodotti stampati in 3D e soluzioni tecniche pronte all uso.', 'Catalogo prodotti stampati in 3D e soluzioni tecniche pronte all uso.',
seoRobots: 'noindex, nofollow',
}, },
}, },
{ {
@@ -117,6 +125,7 @@ const appChildRoutes: Routes = [
export const routes: Routes = [ export const routes: Routes = [
{ {
path: ':lang', path: ':lang',
canMatch: [langPrefixCanMatch],
loadComponent: () => loadComponent: () =>
import('./core/layout/layout.component').then((m) => m.LayoutComponent), import('./core/layout/layout.component').then((m) => m.LayoutComponent),
children: appChildRoutes, children: appChildRoutes,

View File

@@ -42,6 +42,35 @@
</nav> </nav>
<div class="actions"> <div class="actions">
<button
type="button"
class="cart-trigger"
[class.has-items]="cartItemCount() > 0"
[attr.aria-label]="'SHOP.CART_TITLE' | translate"
(click)="toggleCart()"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="20"
height="20"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="8" cy="21" r="1"></circle>
<circle cx="19" cy="21" r="1"></circle>
<path
d="M2.05 2h2l2.4 12.45a2 2 0 0 0 2 1.55h9.7a2 2 0 0 0 1.95-1.57L22 7H6"
></path>
</svg>
@if (cartItemCount() > 0) {
<span class="cart-badge">{{ cartItemCount() }}</span>
}
</button>
<select <select
class="lang-switch" class="lang-switch"
[value]="langService.selectedLang()" [value]="langService.selectedLang()"
@@ -71,4 +100,120 @@
</div> </div>
</div> </div>
</div> </div>
@if (isCartOpen()) {
<div class="cart-overlay" (click)="closeCart()">
<aside class="cart-panel" (click)="$event.stopPropagation()">
<div class="cart-panel-head">
<div>
<p class="cart-panel-kicker">{{ "SHOP.CART_TITLE" | translate }}</p>
<h2>{{ "SHOP.CART_SUMMARY_TITLE" | translate }}</h2>
</div>
<button
type="button"
class="cart-close"
[attr.aria-label]="'COMMON.BACK' | translate"
(click)="closeCart()"
>
×
</button>
</div>
@if (cartLoading() && !cart()) {
<p class="cart-state">{{ "SHOP.CART_LOADING" | translate }}</p>
} @else if (!cartHasItems()) {
<p class="cart-state">{{ "SHOP.CART_EMPTY" | translate }}</p>
} @else {
<div class="cart-lines">
@for (item of cartItems(); track trackByCartItem($index, item)) {
<article class="cart-line">
<div class="cart-line-copy">
<strong>{{ cartItemName(item) }}</strong>
@if (cartItemVariant(item); as variant) {
<span class="cart-line-meta">{{ variant }}</span>
}
@if (cartItemColor(item); as color) {
<span class="cart-line-color">
<span
class="color-dot"
[style.background-color]="cartItemColorHex(item)"
></span>
<span>{{ color }}</span>
</span>
}
</div>
<div class="cart-line-actions">
<div class="qty-control">
<button
type="button"
[disabled]="
cartMutating() && busyLineItemId() === item.id
"
(click)="decreaseQuantity(item)"
>
-
</button>
<span>{{ item.quantity }}</span>
<button
type="button"
[disabled]="
cartMutating() && busyLineItemId() === item.id
"
(click)="increaseQuantity(item)"
>
+
</button>
</div>
<strong class="line-total">{{
item.unitPriceChf * item.quantity | currency: "CHF"
}}</strong>
</div>
<button
type="button"
class="line-remove"
[disabled]="cartMutating() && busyLineItemId() === item.id"
(click)="removeItem(item)"
>
{{ "SHOP.REMOVE" | translate }}
</button>
</article>
}
</div>
<div class="cart-totals">
<div class="cart-total-row">
<span>{{ "SHOP.CART_SUBTOTAL" | translate }}</span>
<strong>{{
cart()?.itemsTotalChf || 0 | currency: "CHF"
}}</strong>
</div>
<div class="cart-total-row">
<span>{{ "SHOP.CART_SHIPPING" | translate }}</span>
<strong>{{
cart()?.shippingCostChf || 0 | currency: "CHF"
}}</strong>
</div>
<div class="cart-total-row cart-total-row-final">
<span>{{ "SHOP.CART_TOTAL" | translate }}</span>
<strong>{{
cart()?.grandTotalChf || 0 | currency: "CHF"
}}</strong>
</div>
</div>
<button
type="button"
class="checkout-link"
[disabled]="cartMutating()"
(click)="goToCheckout()"
>
{{ "SHOP.GO_TO_CHECKOUT" | translate }}
</button>
}
</aside>
</div>
}
</header> </header>

View File

@@ -46,6 +46,46 @@
gap: var(--space-4); gap: var(--space-4);
} }
.cart-trigger {
position: relative;
width: 2.5rem;
height: 2.5rem;
display: inline-flex;
align-items: center;
justify-content: center;
border: 1px solid var(--color-border);
border-radius: 999px;
background: var(--color-bg-card);
color: var(--color-text);
cursor: pointer;
transition:
border-color 0.18s ease,
background-color 0.18s ease;
}
.cart-trigger:hover,
.cart-trigger.has-items {
border-color: rgba(16, 24, 32, 0.2);
background: #f6f2e8;
}
.cart-badge {
position: absolute;
top: -0.15rem;
right: -0.2rem;
min-width: 1.15rem;
height: 1.15rem;
padding: 0 0.2rem;
display: inline-flex;
align-items: center;
justify-content: center;
border-radius: 999px;
background: var(--color-brand);
color: var(--color-neutral-900);
font-size: 0.68rem;
font-weight: 700;
}
.lang-switch { .lang-switch {
background-color: var(--color-bg-card); background-color: var(--color-bg-card);
border: 1px solid var(--color-border); border: 1px solid var(--color-border);
@@ -88,6 +128,176 @@
color: var(--color-text-muted); color: var(--color-text-muted);
} }
.cart-overlay {
position: fixed;
inset: 64px 0 0;
background: rgba(16, 24, 32, 0.16);
display: flex;
justify-content: flex-end;
z-index: 120;
}
.cart-panel {
width: min(26rem, 100%);
height: 100%;
display: grid;
grid-template-rows: auto 1fr auto;
gap: var(--space-5);
padding: var(--space-6);
border-left: 1px solid var(--color-border);
background: #fbfaf6;
box-shadow: -18px 0 40px rgba(16, 24, 32, 0.08);
overflow-y: auto;
}
.cart-panel-head {
display: flex;
align-items: start;
justify-content: space-between;
gap: var(--space-4);
}
.cart-panel-head h2 {
margin: 0.2rem 0 0;
font-size: 1.15rem;
}
.cart-panel-kicker {
margin: 0;
color: var(--color-text-muted);
text-transform: uppercase;
letter-spacing: 0.08em;
font-size: 0.72rem;
font-weight: 700;
}
.cart-close,
.line-remove {
border: 0;
background: transparent;
color: var(--color-text-muted);
cursor: pointer;
font: inherit;
}
.cart-close {
font-size: 1.5rem;
line-height: 1;
}
.cart-state {
margin: 0;
padding: 1rem;
border-radius: 0.9rem;
background: rgba(16, 24, 32, 0.04);
color: var(--color-text-muted);
}
.cart-lines {
display: grid;
align-content: start;
gap: var(--space-4);
}
.cart-line {
display: grid;
gap: var(--space-3);
padding-bottom: var(--space-4);
border-bottom: 1px solid var(--color-border);
}
.cart-line-copy {
display: grid;
gap: 0.25rem;
}
.cart-line-meta,
.cart-line-color {
color: var(--color-text-muted);
font-size: 0.86rem;
}
.cart-line-color {
display: inline-flex;
align-items: center;
gap: 0.4rem;
}
.color-dot {
width: 0.8rem;
height: 0.8rem;
border-radius: 50%;
border: 1px solid rgba(16, 24, 32, 0.12);
}
.cart-line-actions {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-3);
}
.qty-control {
display: inline-flex;
align-items: center;
gap: 0.4rem;
padding: 0.2rem;
border-radius: 999px;
border: 1px solid var(--color-border);
background: #fff;
}
.qty-control button {
width: 1.9rem;
height: 1.9rem;
border: 0;
border-radius: 50%;
background: rgba(16, 24, 32, 0.06);
color: var(--color-text);
cursor: pointer;
}
.qty-control span {
min-width: 1.4rem;
text-align: center;
font-weight: 600;
}
.line-total {
white-space: nowrap;
}
.cart-totals {
display: grid;
gap: 0.55rem;
padding-top: var(--space-4);
border-top: 1px solid var(--color-border);
}
.cart-total-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-3);
color: var(--color-text-muted);
}
.cart-total-row-final {
color: var(--color-text);
font-size: 1.02rem;
}
.checkout-link {
min-height: 3rem;
border: 0;
border-radius: 999px;
background: var(--color-text);
color: #fff;
font: inherit;
font-weight: 600;
cursor: pointer;
}
/* Mobile Toggle */ /* Mobile Toggle */
.mobile-toggle { .mobile-toggle {
display: none; display: none;
@@ -133,6 +343,14 @@
margin-left: auto; /* Push to right */ margin-left: auto; /* Push to right */
} }
.cart-overlay {
inset: 64px 0 0;
}
.cart-panel {
width: min(100%, 24rem);
}
.nav-links { .nav-links {
position: absolute; position: absolute;
top: 64px; top: 64px;
@@ -161,6 +379,11 @@
} }
} }
} }
.cart-line-actions {
align-items: start;
flex-direction: column;
}
} }
@keyframes slideDown { @keyframes slideDown {

View File

@@ -1,18 +1,48 @@
import { Component } from '@angular/core'; import { CommonModule } from '@angular/common';
import { RouterLink, RouterLinkActive } from '@angular/router'; import { Component, DestroyRef, computed, inject, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import {
NavigationStart,
Router,
RouterLink,
RouterLinkActive,
} from '@angular/router';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { LanguageService } from '../services/language.service'; import { LanguageService } from '../services/language.service';
import { routes } from '../../app.routes'; import { routes } from '../../app.routes';
import {
ShopCartItem,
ShopService,
} from '../../features/shop/services/shop.service';
import { finalize } from 'rxjs';
@Component({ @Component({
selector: 'app-navbar', selector: 'app-navbar',
standalone: true, standalone: true,
imports: [RouterLink, RouterLinkActive, TranslateModule], imports: [CommonModule, RouterLink, RouterLinkActive, TranslateModule],
templateUrl: './navbar.component.html', templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.scss'], styleUrls: ['./navbar.component.scss'],
}) })
export class NavbarComponent { export class NavbarComponent {
private readonly destroyRef = inject(DestroyRef);
private readonly router = inject(Router);
readonly shopService = inject(ShopService);
isMenuOpen = false; isMenuOpen = false;
readonly isCartOpen = signal(false);
readonly cartMutating = signal(false);
readonly busyLineItemId = signal<string | null>(null);
readonly cart = this.shopService.cart;
readonly cartLoading = this.shopService.cartLoading;
readonly cartItems = computed(() =>
(this.cart()?.items ?? []).filter(
(item) => item.lineItemType === 'SHOP_PRODUCT',
),
);
readonly cartHasItems = computed(() => this.cartItems().length > 0);
readonly cartItemCount = this.shopService.cartItemCount;
readonly languageOptions: Array<{ readonly languageOptions: Array<{
value: 'it' | 'en' | 'de' | 'fr'; value: 'it' | 'en' | 'de' | 'fr';
label: string; label: string;
@@ -23,7 +53,27 @@ export class NavbarComponent {
{ value: 'fr', label: 'FR' }, { value: 'fr', label: 'FR' },
]; ];
constructor(public langService: LanguageService) {} constructor(public langService: LanguageService) {
if (!this.shopService.cartLoaded()) {
this.shopService
.loadCart()
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe({
error: () => {
this.shopService.cart.set(null);
},
});
}
this.router.events
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((event) => {
if (event instanceof NavigationStart) {
this.closeMenu();
this.closeCart();
}
});
}
onLanguageChange(event: Event): void { onLanguageChange(event: Event): void {
const select = event.target as HTMLSelectElement; const select = event.target as HTMLSelectElement;
@@ -39,5 +89,89 @@ export class NavbarComponent {
this.isMenuOpen = false; this.isMenuOpen = false;
} }
toggleCart(): void {
this.closeMenu();
this.isCartOpen.update((open) => !open);
}
closeCart(): void {
this.isCartOpen.set(false);
}
increaseQuantity(item: ShopCartItem): void {
this.updateItemQuantity(item, (item.quantity ?? 0) + 1);
}
decreaseQuantity(item: ShopCartItem): void {
const nextQuantity = Math.max(1, (item.quantity ?? 1) - 1);
this.updateItemQuantity(item, nextQuantity);
}
removeItem(item: ShopCartItem): void {
this.cartMutating.set(true);
this.busyLineItemId.set(item.id);
this.shopService
.removeCartItem(item.id)
.pipe(
finalize(() => {
this.cartMutating.set(false);
this.busyLineItemId.set(null);
}),
takeUntilDestroyed(this.destroyRef),
)
.subscribe();
}
goToCheckout(): void {
const sessionId = this.shopService.cartSessionId();
if (!sessionId) {
return;
}
this.closeCart();
this.router.navigate(['/checkout'], {
queryParams: {
session: sessionId,
},
});
}
cartItemName(item: ShopCartItem): string {
return (
item.displayName || item.shopProductName || item.originalFilename || '-'
);
}
cartItemVariant(item: ShopCartItem): string | null {
return item.shopVariantLabel || item.shopVariantColorName || null;
}
cartItemColor(item: ShopCartItem): string | null {
return item.shopVariantColorName || item.colorCode || null;
}
cartItemColorHex(item: ShopCartItem): string {
return item.shopVariantColorHex || '#c9ced6';
}
trackByCartItem(_index: number, item: ShopCartItem): string {
return item.id;
}
private updateItemQuantity(item: ShopCartItem, quantity: number): void {
this.cartMutating.set(true);
this.busyLineItemId.set(item.id);
this.shopService
.updateCartItem(item.id, quantity)
.pipe(
finalize(() => {
this.cartMutating.set(false);
this.busyLineItemId.set(null);
}),
takeUntilDestroyed(this.destroyRef),
)
.subscribe();
}
protected readonly routes = routes; protected readonly routes = routes;
} }

View File

@@ -4,6 +4,14 @@ import { Title, Meta } from '@angular/platform-browser';
import { ActivatedRouteSnapshot, NavigationEnd, Router } from '@angular/router'; import { ActivatedRouteSnapshot, NavigationEnd, Router } from '@angular/router';
import { filter } from 'rxjs/operators'; import { filter } from 'rxjs/operators';
export interface PageSeoOverride {
title?: string | null;
description?: string | null;
robots?: string | null;
ogTitle?: string | null;
ogDescription?: string | null;
}
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root',
}) })
@@ -31,20 +39,44 @@ export class SeoService {
}); });
} }
applyPageSeo(override: PageSeoOverride): void {
const title = this.asString(override.title) ?? this.defaultTitle;
const description =
this.asString(override.description) ?? this.defaultDescription;
const robots = this.asString(override.robots) ?? 'index, follow';
const ogTitle = this.asString(override.ogTitle) ?? title;
const ogDescription = this.asString(override.ogDescription) ?? description;
this.applySeoValues(title, description, robots, ogTitle, ogDescription);
}
private applyRouteSeo(rootSnapshot: ActivatedRouteSnapshot): void { private applyRouteSeo(rootSnapshot: ActivatedRouteSnapshot): void {
const mergedData = this.getMergedRouteData(rootSnapshot); const mergedData = this.getMergedRouteData(rootSnapshot);
const title = this.asString(mergedData['seoTitle']) ?? this.defaultTitle; const title = this.asString(mergedData['seoTitle']) ?? this.defaultTitle;
const description = const description =
this.asString(mergedData['seoDescription']) ?? this.defaultDescription; this.asString(mergedData['seoDescription']) ?? this.defaultDescription;
const robots = this.asString(mergedData['seoRobots']) ?? 'index, follow'; const robots = this.asString(mergedData['seoRobots']) ?? 'index, follow';
const ogTitle = this.asString(mergedData['ogTitle']) ?? title;
const ogDescription =
this.asString(mergedData['ogDescription']) ?? description;
this.applySeoValues(title, description, robots, ogTitle, ogDescription);
}
private applySeoValues(
title: string,
description: string,
robots: string,
ogTitle: string,
ogDescription: string,
): void {
this.titleService.setTitle(title); this.titleService.setTitle(title);
this.metaService.updateTag({ name: 'description', content: description }); this.metaService.updateTag({ name: 'description', content: description });
this.metaService.updateTag({ name: 'robots', content: robots }); this.metaService.updateTag({ name: 'robots', content: robots });
this.metaService.updateTag({ property: 'og:title', content: title }); this.metaService.updateTag({ property: 'og:title', content: ogTitle });
this.metaService.updateTag({ this.metaService.updateTag({
property: 'og:description', property: 'og:description',
content: description, content: ogDescription,
}); });
this.metaService.updateTag({ property: 'og:type', content: 'website' }); this.metaService.updateTag({ property: 'og:type', content: 'website' });
this.metaService.updateTag({ name: 'twitter:card', content: 'summary' }); this.metaService.updateTag({ name: 'twitter:card', content: 'summary' });

View File

@@ -64,6 +64,13 @@ export const ADMIN_ROUTES: Routes = [
(m) => m.AdminHomeMediaComponent, (m) => m.AdminHomeMediaComponent,
), ),
}, },
{
path: 'shop',
loadComponent: () =>
import('./pages/admin-shop.component').then(
(m) => m.AdminShopComponent,
),
},
], ],
}, },
]; ];

View File

@@ -1,5 +1,5 @@
<section class="cad-page"> <section class="cad-page section-card">
<header class="page-header"> <header class="page-header section-header">
<div> <div>
<h1>Fatture CAD</h1> <h1>Fatture CAD</h1>
<p> <p>

View File

@@ -4,6 +4,13 @@
gap: var(--space-5); gap: var(--space-5);
} }
.section-header {
display: flex;
justify-content: space-between;
gap: var(--space-4);
align-items: flex-start;
}
.page-header { .page-header {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
@@ -131,6 +138,11 @@ td {
} }
@media (max-width: 880px) { @media (max-width: 880px) {
.section-header {
flex-direction: column;
align-items: stretch;
}
.page-header { .page-header {
flex-direction: column; flex-direction: column;
align-items: stretch; align-items: stretch;

View File

@@ -1,5 +1,5 @@
import { CommonModule } from '@angular/common'; import { CommonModule, isPlatformBrowser } from '@angular/common';
import { Component, OnInit, inject } from '@angular/core'; import { Component, OnInit, PLATFORM_ID, inject } from '@angular/core';
import { FormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms';
import { import {
AdminCadInvoice, AdminCadInvoice,
@@ -16,6 +16,7 @@ import { CopyOnClickDirective } from '../../../shared/directives/copy-on-click.d
styleUrl: './admin-cad-invoices.component.scss', styleUrl: './admin-cad-invoices.component.scss',
}) })
export class AdminCadInvoicesComponent implements OnInit { export class AdminCadInvoicesComponent implements OnInit {
private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
private readonly adminOperationsService = inject(AdminOperationsService); private readonly adminOperationsService = inject(AdminOperationsService);
private readonly adminOrdersService = inject(AdminOrdersService); private readonly adminOrdersService = inject(AdminOrdersService);
@@ -112,11 +113,17 @@ export class AdminCadInvoicesComponent implements OnInit {
} }
openCheckout(path: string): void { openCheckout(path: string): void {
if (!this.isBrowser) {
return;
}
const url = this.toCheckoutUrl(path); const url = this.toCheckoutUrl(path);
window.open(url, '_blank'); window.open(url, '_blank');
} }
copyCheckout(path: string): void { copyCheckout(path: string): void {
if (!this.isBrowser) {
return;
}
const url = this.toCheckoutUrl(path); const url = this.toCheckoutUrl(path);
navigator.clipboard?.writeText(url); navigator.clipboard?.writeText(url);
this.successMessage = 'Link checkout CAD copiato negli appunti.'; this.successMessage = 'Link checkout CAD copiato negli appunti.';
@@ -126,6 +133,9 @@ export class AdminCadInvoicesComponent implements OnInit {
if (!orderId) return; if (!orderId) return;
this.adminOrdersService.downloadOrderInvoice(orderId).subscribe({ this.adminOrdersService.downloadOrderInvoice(orderId).subscribe({
next: (blob) => { next: (blob) => {
if (!this.isBrowser) {
return;
}
const url = window.URL.createObjectURL(blob); const url = window.URL.createObjectURL(blob);
const a = document.createElement('a'); const a = document.createElement('a');
a.href = url; a.href = url;
@@ -142,10 +152,16 @@ export class AdminCadInvoicesComponent implements OnInit {
private toCheckoutUrl(path: string): string { private toCheckoutUrl(path: string): string {
const safePath = path.startsWith('/') ? path : `/${path}`; const safePath = path.startsWith('/') ? path : `/${path}`;
const lang = this.resolveLang(); const lang = this.resolveLang();
if (!this.isBrowser) {
return `/${lang}${safePath}`;
}
return `${window.location.origin}/${lang}${safePath}`; return `${window.location.origin}/${lang}${safePath}`;
} }
private resolveLang(): string { private resolveLang(): string {
if (!this.isBrowser) {
return 'it';
}
const firstSegment = window.location.pathname const firstSegment = window.location.pathname
.split('/') .split('/')
.filter(Boolean) .filter(Boolean)

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