Compare commits
127 Commits
465678f3e4
...
not-workin
| Author | SHA1 | Date | |
|---|---|---|---|
| 5f73924572 | |||
| 8edc4af645 | |||
| e1409d218b | |||
| 0c92f8b394 | |||
| 66de93a315 | |||
| b337db03c4 | |||
| 8c6c1e10b3 | |||
| eac3006512 | |||
| b26b582baf | |||
| 875c6ffd2d | |||
| 579ac3fcb6 | |||
| efa1371ffa | |||
| ab7f263aca | |||
| 49bae8e186 | |||
| e2872c730c | |||
| 86266b31ee | |||
| 5d0fb5fe6d | |||
| 91af8f4f9c | |||
| a96c28fb39 | |||
| 9b24ca529c | |||
| 6216d9a723 | |||
| 4aa3f6adf1 | |||
| 7baad738f5 | |||
| 9feceb9b3c | |||
| 304ed942b8 | |||
| 881bd87392 | |||
| 3a5e4e3427 | |||
| 8c82470401 | |||
| ef6a5278a7 | |||
| bb276b6504 | |||
| e351f2c05f | |||
| 165e12f216 | |||
| 475bfcc6fb | |||
| becb15da73 | |||
| 4d559901eb | |||
| 06a036810a | |||
| 0b29aebfcf | |||
| 961109b04c | |||
| b5bd68ed10 | |||
| 56fb504062 | |||
| f165d191be | |||
| e1d9823b51 | |||
| f829ccef4a | |||
| 59e881c3f4 | |||
| f5aa0f298e | |||
| 2eea773ee2 | |||
| 44f9408b22 | |||
| 044fba8d5a | |||
| 257c60fa5e | |||
| 5a84fb13c0 | |||
| 89d84ed369 | |||
| 9c3d5fae12 | |||
| 96ae9bb609 | |||
| 9cbd856ab6 | |||
| bb151ae835 | |||
| 7ebaff322c | |||
| e17da96c22 | |||
| 3e9745c7cc | |||
| 3da3e6c60c | |||
| 85b823d614 | |||
| d20d12c1f4 | |||
| ab5f6a609d | |||
| 5ba203a8d1 | |||
| 3ca3f8e466 | |||
| 5620f6a8eb | |||
| 1583ff479c | |||
| b7d81040e6 | |||
| b249cf2000 | |||
| dfc27da142 | |||
| dde92af857 | |||
| 7b92e63a49 | |||
| 8fac8ac892 | |||
| e5183590c5 | |||
| 3b4ef37e58 | |||
| eb4ad8b637 | |||
| f0e0f57e7c | |||
| 05e1c224f0 | |||
| f1636d9057 | |||
| 44d99b0a68 | |||
| 83b3008234 | |||
| 78af87ac3c | |||
| b3c0413b7c | |||
| 4f301b1652 | |||
| debf153f58 | |||
| f3d271ded2 | |||
| 13790f2055 | |||
| bcdeafe119 | |||
| 7978884ca6 | |||
| cb7b44073c | |||
| 99ae6db064 | |||
| fcf439e369 | |||
| cecdfacd33 | |||
| 5bc698815c | |||
| 73ccf8f4de | |||
| 0b4daed512 | |||
| 8a7d736aa9 | |||
| ce179cac62 | |||
| ab7b95a3d7 | |||
| da8e476485 | |||
| 810d5f6c0c | |||
| 8a75aed6d8 | |||
| a0efdc105d | |||
| 422d80a4d4 | |||
| db4df2573c | |||
| 2f7e8798d2 | |||
| d816eeda1d | |||
| af5b40021d | |||
| 653186e9d3 | |||
| c6ec937ea0 | |||
| 3aa644e9ee | |||
| 21cf8891b2 | |||
| ceeb831a41 | |||
| 316c74e299 | |||
| a5ff515fd7 | |||
| 6952090865 | |||
| 10e1fb49f4 | |||
| 32b9b2ef8d | |||
| 0a538b0d88 | |||
| 2c658d00c1 | |||
| 5a2da916fa | |||
| 82d1cf2c71 | |||
| 85d7315e30 | |||
| 179ba2b85c | |||
| ac8135aec8 | |||
| 74f040fa50 | |||
| 73fa36f9ec | |||
| 7fafabad42 |
@@ -2,136 +2,169 @@ name: Build, Test and Deploy
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- int
|
||||
- dev
|
||||
branches: [main, int, dev]
|
||||
|
||||
concurrency:
|
||||
group: print-calculator-${{ gitea.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
test-backend:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v3
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v4
|
||||
- name: Set up JDK 21
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
python-version: '3.10'
|
||||
java-version: '21'
|
||||
distribution: 'temurin'
|
||||
|
||||
- name: Install dependencies
|
||||
- name: Run Tests with Gradle
|
||||
run: |
|
||||
pip install -r backend/requirements.txt
|
||||
pip install pytest httpx
|
||||
|
||||
- name: Run Backend Tests
|
||||
run: |
|
||||
export PYTHONPATH=$PYTHONPATH:$(pwd)/backend
|
||||
pytest backend/tests
|
||||
cd backend
|
||||
chmod +x gradlew
|
||||
./gradlew test
|
||||
|
||||
build-and-push:
|
||||
needs: test-backend
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v3
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set Environment Variables
|
||||
- name: Set TAG + OWNER lowercase
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ "${{ gitea.ref }}" == "refs/heads/main" ]]; then
|
||||
echo "TAG=prod" >> $GITHUB_ENV
|
||||
echo "TAG=prod" >> "$GITHUB_ENV"
|
||||
elif [[ "${{ gitea.ref }}" == "refs/heads/int" ]]; then
|
||||
echo "TAG=int" >> $GITHUB_ENV
|
||||
echo "TAG=int" >> "$GITHUB_ENV"
|
||||
else
|
||||
echo "TAG=dev" >> $GITHUB_ENV
|
||||
echo "TAG=dev" >> "$GITHUB_ENV"
|
||||
fi
|
||||
|
||||
echo "OWNER_LOWER=$(echo '${{ gitea.repository_owner }}' | tr '[:upper:]' '[:lower:]')" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Ensure docker CLI exists
|
||||
shell: bash
|
||||
run: |
|
||||
if ! command -v docker >/dev/null 2>&1; then
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends docker.io
|
||||
fi
|
||||
docker version
|
||||
|
||||
- name: Login to Gitea Registry
|
||||
uses: docker/login-action@v2
|
||||
with:
|
||||
registry: ${{ secrets.REGISTRY_URL }}
|
||||
username: ${{ secrets.GITEA_USER }}
|
||||
password: ${{ secrets.GITEA_TOKEN }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
printf '%s' "${{ secrets.REGISTRY_TOKEN }}" | docker login "${{ secrets.REGISTRY_URL }}" \
|
||||
-u "${{ secrets.REGISTRY_USER }}" --password-stdin
|
||||
|
||||
- name: Build and Push Backend
|
||||
uses: docker/build-push-action@v4
|
||||
with:
|
||||
context: ./backend
|
||||
push: true
|
||||
tags: ${{ secrets.REGISTRY_URL }}/${{ gitea.repository_owner }}/print-calculator-backend:${{ env.TAG }}
|
||||
- name: Build & Push Backend
|
||||
shell: bash
|
||||
run: |
|
||||
BACKEND_IMAGE="${{ secrets.REGISTRY_URL }}/${{ env.OWNER_LOWER }}/print-calculator-backend:${{ env.TAG }}"
|
||||
docker build -t "$BACKEND_IMAGE" ./backend
|
||||
docker push "$BACKEND_IMAGE"
|
||||
|
||||
- name: Build and Push Frontend
|
||||
uses: docker/build-push-action@v4
|
||||
with:
|
||||
context: ./frontend
|
||||
push: true
|
||||
tags: ${{ secrets.REGISTRY_URL }}/${{ gitea.repository_owner }}/print-calculator-frontend:${{ env.TAG }}
|
||||
- name: Build & Push Frontend
|
||||
shell: bash
|
||||
run: |
|
||||
FRONTEND_IMAGE="${{ secrets.REGISTRY_URL }}/${{ env.OWNER_LOWER }}/print-calculator-frontend:${{ env.TAG }}"
|
||||
docker build -t "$FRONTEND_IMAGE" ./frontend
|
||||
docker push "$FRONTEND_IMAGE"
|
||||
|
||||
deploy:
|
||||
needs: build-and-push
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v3
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set Deployment Vars
|
||||
- name: Set ENV
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ "${{ gitea.ref }}" == "refs/heads/main" ]]; then
|
||||
echo "ENV=prod" >> $GITHUB_ENV
|
||||
echo "TAG=prod" >> $GITHUB_ENV
|
||||
echo "ENV=prod" >> "$GITHUB_ENV"
|
||||
elif [[ "${{ gitea.ref }}" == "refs/heads/int" ]]; then
|
||||
echo "ENV=int" >> $GITHUB_ENV
|
||||
echo "TAG=int" >> $GITHUB_ENV
|
||||
echo "ENV=int" >> "$GITHUB_ENV"
|
||||
else
|
||||
echo "ENV=dev" >> $GITHUB_ENV
|
||||
echo "TAG=dev" >> $GITHUB_ENV
|
||||
echo "ENV=dev" >> "$GITHUB_ENV"
|
||||
fi
|
||||
|
||||
- name: Create Remote Directory
|
||||
uses: appleboy/ssh-action@v0.1.10
|
||||
with:
|
||||
host: ${{ secrets.SERVER_HOST }}
|
||||
username: ${{ secrets.SERVER_USER }}
|
||||
key: ${{ secrets.SSH_PRIVATE_KEY }}
|
||||
script: mkdir -p /mnt/user/appdata/print-calculator/${{ env.ENV }}/
|
||||
- name: Setup SSH key
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
- name: Copy Compose File to Server
|
||||
uses: appleboy/scp-action@v0.1.4
|
||||
with:
|
||||
host: ${{ secrets.SERVER_HOST }}
|
||||
username: ${{ secrets.SERVER_USER }}
|
||||
key: ${{ secrets.SSH_PRIVATE_KEY }}
|
||||
source: "docker-compose.deploy.yml"
|
||||
target: "/mnt/user/appdata/print-calculator/${{ env.ENV }}/"
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends openssh-client
|
||||
|
||||
- name: Copy Env File to Server
|
||||
uses: appleboy/scp-action@v0.1.4
|
||||
with:
|
||||
host: ${{ secrets.SERVER_HOST }}
|
||||
username: ${{ secrets.SERVER_USER }}
|
||||
key: ${{ secrets.SSH_PRIVATE_KEY }}
|
||||
source: "deploy/envs/${{ env.ENV }}.env"
|
||||
target: "/mnt/user/appdata/print-calculator/${{ env.ENV }}/.env"
|
||||
mkdir -p ~/.ssh
|
||||
chmod 700 ~/.ssh
|
||||
|
||||
- name: Execute Remote Deployment
|
||||
uses: appleboy/ssh-action@v0.1.10
|
||||
with:
|
||||
host: ${{ secrets.SERVER_HOST }}
|
||||
username: ${{ secrets.SERVER_USER }}
|
||||
key: ${{ secrets.SSH_PRIVATE_KEY }}
|
||||
script: |
|
||||
cd /mnt/user/appdata/print-calculator/${{ env.ENV }}/
|
||||
# 1) Prende il secret base64 e rimuove spazi/newline/CR
|
||||
printf '%s' "${{ secrets.SSH_PRIVATE_KEY_B64 }}" | tr -d '\r\n\t ' > /tmp/key.b64
|
||||
|
||||
# 2) (debug sicuro) stampa solo la lunghezza della base64
|
||||
echo "b64_len=$(wc -c < /tmp/key.b64)"
|
||||
|
||||
# 3) Decodifica in chiave privata
|
||||
base64 -d /tmp/key.b64 > ~/.ssh/id_ed25519
|
||||
|
||||
# 4) Rimuove eventuali CRLF dentro la chiave (se proviene da Windows)
|
||||
tr -d '\r' < ~/.ssh/id_ed25519 > ~/.ssh/id_ed25519.clean
|
||||
mv ~/.ssh/id_ed25519.clean ~/.ssh/id_ed25519
|
||||
chmod 600 ~/.ssh/id_ed25519
|
||||
|
||||
# 5) Validazione: se fallisce qui, la chiave NON è valida/corrotta
|
||||
ssh-keygen -y -f ~/.ssh/id_ed25519 >/dev/null
|
||||
|
||||
ssh-keyscan -H "${{ secrets.SERVER_HOST }}" >> ~/.ssh/known_hosts 2>/dev/null
|
||||
|
||||
- name: Write env to server
|
||||
shell: bash
|
||||
run: |
|
||||
# 1. Start with the static env file content
|
||||
cat "deploy/envs/${{ env.ENV }}.env" > /tmp/full_env.env
|
||||
|
||||
# 2. Determine DB credentials
|
||||
if [[ "${{ env.ENV }}" == "prod" ]]; then
|
||||
DB_URL="${{ secrets.DB_URL_PROD }}"
|
||||
DB_USER="${{ secrets.DB_USERNAME_PROD }}"
|
||||
DB_PASS="${{ secrets.DB_PASSWORD_PROD }}"
|
||||
elif [[ "${{ env.ENV }}" == "int" ]]; then
|
||||
DB_URL="${{ secrets.DB_URL_INT }}"
|
||||
DB_USER="${{ secrets.DB_USERNAME_INT }}"
|
||||
DB_PASS="${{ secrets.DB_PASSWORD_INT }}"
|
||||
else
|
||||
DB_URL="${{ secrets.DB_URL_DEV }}"
|
||||
DB_USER="${{ secrets.DB_USERNAME_DEV }}"
|
||||
DB_PASS="${{ secrets.DB_PASSWORD_DEV }}"
|
||||
fi
|
||||
|
||||
# 3. Append DB credentials
|
||||
printf '\nDB_URL=%s\nDB_USERNAME=%s\nDB_PASSWORD=%s\n' \
|
||||
"$DB_URL" "$DB_USER" "$DB_PASS" >> /tmp/full_env.env
|
||||
|
||||
# 4. Debug: print content (for debug purposes)
|
||||
echo "Preparing to send env file with variables:"
|
||||
grep -v "PASSWORD" /tmp/full_env.env || true
|
||||
|
||||
# 5. Send to server
|
||||
ssh -i ~/.ssh/id_ed25519 -o BatchMode=yes "${{ secrets.SERVER_USER }}@${{ secrets.SERVER_HOST }}" \
|
||||
"setenv ${{ env.ENV }}" < /tmp/full_env.env
|
||||
|
||||
# Rename the copied env file to strictly '.env' so docker compose picks it up automatically
|
||||
mv ${{ env.ENV }}.env .env
|
||||
|
||||
# Login to registry
|
||||
echo ${{ secrets.GITEA_TOKEN }} | docker login ${{ secrets.REGISTRY_URL }} -u ${{ secrets.GITEA_USER }} --password-stdin
|
||||
|
||||
# Pull new images
|
||||
# We force reading from .env just to be safe, though default behavior does it too.
|
||||
docker compose --env-file .env -f docker-compose.deploy.yml pull
|
||||
|
||||
# Start/Update services
|
||||
# TAG is inside .env now, so we don't even need to pass it explicitly!
|
||||
docker compose --env-file .env -f docker-compose.deploy.yml up -d --remove-orphans
|
||||
|
||||
|
||||
- name: Trigger deploy on Unraid (forced command key)
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
# Aggiungiamo le opzioni di verbosità se dovesse fallire ancora,
|
||||
# e assicuriamoci che l'input sia pulito
|
||||
ssh -i ~/.ssh/id_ed25519 -o BatchMode=yes "${{ secrets.SERVER_USER }}@${{ secrets.SERVER_HOST }}" "deploy ${{ env.ENV }}"
|
||||
|
||||
6
.gitignore
vendored
6
.gitignore
vendored
@@ -35,3 +35,9 @@ replay_pid*
|
||||
.classpath
|
||||
.settings/
|
||||
.DS_Store
|
||||
|
||||
# Build Results
|
||||
target/
|
||||
build/
|
||||
.gradle/
|
||||
.mvn/
|
||||
|
||||
49
GEMINI.md
49
GEMINI.md
@@ -4,35 +4,42 @@ Questo file serve a dare contesto all'AI (Antigravity/Gemini) sulla struttura e
|
||||
|
||||
## Project Overview
|
||||
**Nome**: Print Calculator
|
||||
**Scopo**: Calcolare costi e tempi di stampa 3D da file STL.
|
||||
**Scopo**: Calcolare costi e tempi di stampa 3D da file STL in modo preciso tramite slicing reale.
|
||||
**Stack**:
|
||||
- **Backend**: Python (FastAPI), libreria `trimesh` per analisi geometrica.
|
||||
- **Frontend**: Angular 19 (TypeScript).
|
||||
- **Backend**: Java 21 (Spring Boot 3.4), PostgreSQL, Flyway.
|
||||
- **Frontend**: Angular 19 (TypeScript), Angular Material, Three.js per visualizzazione 3D.
|
||||
|
||||
## Architecture
|
||||
|
||||
### Backend (`/backend`)
|
||||
- **`main.py`**: Entrypoint dell'applicazione FastAPI.
|
||||
- Definisce l'API `POST /calculate/stl`.
|
||||
- Gestisce l'upload del file, invoca lo slicer e restituisce il preventivo.
|
||||
- Configura CORS per permettere chiamate dal frontend.
|
||||
- **`slicer.py`**: Wrappa l'eseguibile di **OrcaSlicer** per effettuare lo slicing reale del modello.
|
||||
- Gestisce i profili di stampa (Macchina, Processo, Filamento).
|
||||
- Crea configurazioni on-the-fly per supportare mesh di grandi dimensioni.
|
||||
- **`calculator.py`**: Analizza il G-Code generato.
|
||||
- `GCodeParser`: Estrae tempo di stampa e materiale usato dai metadati del G-Code.
|
||||
- `QuoteCalculator`: Applica i costi (orari, energia, materiale) per generare il prezzo finale.
|
||||
- **`BackendApplication.java`**: Entrypoint dell'applicazione Spring Boot.
|
||||
- **`controller/`**: Espone le API REST per l'upload e il calcolo dei preventivi.
|
||||
- **`service/SlicerService.java`**: Wrappa l'eseguibile di **OrcaSlicer** per effettuare lo slicing reale del modello.
|
||||
- Gestisce i profili di stampa (Macchina, Processo, Filamento) caricati da file JSON.
|
||||
- Crea configurazioni on-the-fly e invoca OrcaSlicer in modalità headless.
|
||||
- **`service/GCodeParser.java`**: Analizza il G-Code generato per estrarre tempo di stampa e peso del materiale dai metadati del file.
|
||||
- **`service/QuoteCalculator.java`**: Calcola il prezzo finale basandosi su politiche di prezzo salvate nel database.
|
||||
- Gestisce costi macchina a scaglioni (tiered pricing).
|
||||
- Calcola costi energetici basati sulla potenza della stampante e costo del kWh.
|
||||
- Applica markup percentuali e fee fissi per job.
|
||||
|
||||
### Frontend (`/frontend`)
|
||||
- Applicazione Angular standard.
|
||||
- Usa Angular Material.
|
||||
- Service per upload STL e visualizzazione preventivo.
|
||||
- Applicazione Angular 19 con architettura modulare (core, features, shared).
|
||||
- **Three.js**: Utilizzato per il rendering dei file STL caricati dall'utente.
|
||||
- **Angular Material**: Per l'interfaccia utente.
|
||||
- **ngx-translate**: Per il supporto multilingua.
|
||||
|
||||
## Key Concepts
|
||||
- **Real Slicing**: Il backend esegue un vero slicing usando OrcaSlicer in modalità headless. Questo garantisce stime di tempo e materiale estremamente precise, identiche a quelle che si otterrebbero preparando il file per la stampa.
|
||||
- **G-Code Parsing**: Invece di stimare geometricamente, l'applicazione legge direttamene i commenti generati dallo slicer nel G-Code (es. `estimated printing time`, `filament used`).
|
||||
- **Real Slicing**: Il backend esegue un vero slicing usando OrcaSlicer. Questo garantisce stime di tempo e materiale estremamente precise.
|
||||
- **Database-Driven Pricing**: A differenza di versioni precedenti, il calcolo del preventivo è ora guidato da entità DB (`PricingPolicy`, `PrinterMachine`, `FilamentVariant`).
|
||||
- **G-Code Metadata**: L'applicazione legge direttamene i commenti generati dallo slicer nel G-Code (es. `; estimated printing time`, `; filament used [g]`).
|
||||
|
||||
## Development Notes
|
||||
- Per eseguire il backend serve `uvicorn`.
|
||||
- Il frontend richiede `npm install` al primo avvio.
|
||||
- Le configurazioni di stampa (layer height, wall thickness, infill) sono attualmente hardcoded o con valori di default nel backend, ma potrebbero essere esposte come parametri API in futuro.
|
||||
- **Backend**: Richiede JDK 21. Si avvia con `./gradlew bootRun`.
|
||||
- **Database**: Richiede PostgreSQL. Le migrazioni sono gestite da Flyway.
|
||||
- **Frontend**: Richiede Node.js 22. Si avvia con `npm start`.
|
||||
- **OrcaSlicer**: Deve essere installato sul sistema e il percorso configurato in `application.properties` o tramite variabile d'ambiente `SLICER_PATH`.
|
||||
|
||||
## AI Agent Rules
|
||||
- **No Inline Code**: Tutti i componenti Angular DEVONO usare file separati per HTML (`templateUrl`) e SCSS (`styleUrl`). È vietato usare `template` o `styles` inline nel decoratore `@Component`.
|
||||
- **Spring Boot Conventions**: Seguire i pattern standard di Spring Boot (Service-Repository-Controller).
|
||||
|
||||
10
Makefile
10
Makefile
@@ -1,10 +0,0 @@
|
||||
.PHONY: install s
|
||||
install:
|
||||
@echo "Installing Backend dependencies..."
|
||||
cd backend && pip install -r requirements.txt || pip install fastapi uvicorn trimesh python-multipart numpy
|
||||
@echo "Installing Frontend dependencies..."
|
||||
cd frontend && npm install
|
||||
|
||||
start:
|
||||
@echo "Starting development environment..."
|
||||
./start.sh
|
||||
93
README.md
93
README.md
@@ -1,70 +1,67 @@
|
||||
# Print Calculator (OrcaSlicer Edition)
|
||||
|
||||
Un'applicazione Full Stack (Angular + Python/FastAPI) per calcolare preventivi di stampa 3D precisi utilizzando **OrcaSlicer** in modalità headless.
|
||||
Un'applicazione Full Stack (Angular + Spring Boot) per calcolare preventivi di stampa 3D precisi utilizzando **OrcaSlicer** in modalità headless.
|
||||
|
||||
## Funzionalità
|
||||
|
||||
* **Slicing Reale**: Usa il motore di OrcaSlicer per stimare tempo e materiale, non semplici approssimazioni geometriche.
|
||||
* **Preventivazione Completa**: Calcola costo materiale, ammortamento macchina, energia e ricarico.
|
||||
* **Configurabile**: Prezzi e parametri macchina modificabili via variabili d'ambiente.
|
||||
* **Docker Ready**: Tutto containerizzato per un facile deployment.
|
||||
* **Slicing Reale**: Usa il motore di OrcaSlicer per stimare tempo e materiale, garantendo la massima precisione.
|
||||
* **Preventivazione Database-Driven**: Calcolo basato su politiche di prezzo configurabili nel database (costo materiale, ammortamento macchina a scaglioni, energia e markup).
|
||||
* **Visualizzazione 3D**: Anteprima del file STL caricato tramite Three.js.
|
||||
* **Multi-Profilo**: Supporto per diverse stampanti, materiali e profili di processo.
|
||||
|
||||
## Stack Tecnologico
|
||||
|
||||
- **Backend**: Java 21, Spring Boot 3.4, PostgreSQL, Flyway.
|
||||
- **Frontend**: Angular 19, Angular Material, Three.js.
|
||||
- **Slicer**: OrcaSlicer (invocato via CLI).
|
||||
|
||||
## Prerequisiti
|
||||
|
||||
* Docker Desktop & Docker Compose installati.
|
||||
* **Java 21** installato.
|
||||
* **Node.js 22** e **npm** installati.
|
||||
* **PostgreSQL** attivo.
|
||||
* **OrcaSlicer** installato sul sistema.
|
||||
|
||||
## Avvio Rapido
|
||||
|
||||
1. Clona il repository.
|
||||
2. Esegui lo script di avvio o docker-compose:
|
||||
```bash
|
||||
docker-compose up --build
|
||||
```
|
||||
*Nota: La prima build impiegherà alcuni minuti per scaricare OrcaSlicer (~200MB) e compilare il Frontend.*
|
||||
### 1. Database
|
||||
Crea un database PostgreSQL chiamato `printcalc`. Le tabelle verranno create automaticamente al primo avvio tramite Flyway.
|
||||
|
||||
3. Accedi all'applicazione:
|
||||
* **Frontend**: [http://localhost](http://localhost)
|
||||
* **API Docs**: [http://localhost:8000/docs](http://localhost:8000/docs)
|
||||
### 2. Backend
|
||||
Configura il percorso di OrcaSlicer in `backend/src/main/resources/application.properties` o tramite la variabile d'ambiente `SLICER_PATH`.
|
||||
|
||||
## Configurazione Prezzi
|
||||
|
||||
Puoi modificare i prezzi nel file `docker-compose.yml` (sezione `environment` del servizio backend):
|
||||
|
||||
* `FILAMENT_COST_PER_KG`: Costo filamento al kg (es. 25.0).
|
||||
* `MACHINE_COST_PER_HOUR`: Costo orario macchina (ammortamento/manutenzione).
|
||||
* `ENERGY_COST_PER_KWH`: Costo energia elettrica.
|
||||
* `MARKUP_PERCENT`: Margine di profitto percentuale (es. 20 = +20%).
|
||||
|
||||
## Struttura del Progetto
|
||||
|
||||
* `/backend`: API Python FastAPI. Include Dockerfile che scarica OrcaSlicer AppImage.
|
||||
* `/frontend`: Applicazione Angular 19+ con Material Design.
|
||||
* `/backend/profiles`: Contiene i profili di slicing (.ini). Attualmente configurato per una stima generica simil-Bambu Lab A1.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Errore Download OrcaSlicer
|
||||
Se la build del backend fallisce durante il download di `OrcaSlicer.AppImage`, verifica la tua connessione internet o aggiorna l'URL nel `backend/Dockerfile`.
|
||||
|
||||
### Slicing Fallito (Costo 0 o Errore)
|
||||
Se l'API ritorna errore o valori nulli:
|
||||
1. Controlla che il file STL sia valido (manifold).
|
||||
2. Controlla i log del backend: `docker logs print-calculator-backend`.
|
||||
|
||||
## Sviluppo Locale (Senza Docker)
|
||||
|
||||
**Backend**:
|
||||
Richiede Linux (o WSL2) per eseguire l'AppImage di OrcaSlicer.
|
||||
```bash
|
||||
cd backend
|
||||
pip install -r requirements.txt
|
||||
# Assicurati di avere OrcaSlicer installato e nel PATH o aggiorna SLICER_PATH in slicer.py
|
||||
uvicorn main:app --reload
|
||||
./gradlew bootRun
|
||||
```
|
||||
|
||||
**Frontend**:
|
||||
### 3. Frontend
|
||||
```bash
|
||||
cd frontend
|
||||
npm install
|
||||
npm start
|
||||
```
|
||||
|
||||
Accedi a [http://localhost:4200](http://localhost:4200).
|
||||
|
||||
## Configurazione Prezzi
|
||||
|
||||
I prezzi non sono più gestiti tramite variabili d'ambiente fisse ma tramite tabelle nel database:
|
||||
- `pricing_policy`: Definisce markup, fee fissi e costi elettrici.
|
||||
- `pricing_policy_machine_hour_tier`: Definisce i costi orari delle macchine in base alla durata della stampa.
|
||||
- `printer_machine`: Anagrafica stampanti e consumi energetici.
|
||||
- `filament_material_type` / `filament_variant`: Listino prezzi materiali.
|
||||
|
||||
## Struttura del Progetto
|
||||
|
||||
* `/backend`: API Spring Boot.
|
||||
* `/frontend`: Applicazione Angular.
|
||||
* `/backend/profiles`: Contiene i file di configurazione per OrcaSlicer.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Percorso OrcaSlicer
|
||||
Assicurati che `slicer.path` punti al binario corretto. Su macOS è solitamente `/Applications/OrcaSlicer.app/Contents/MacOS/OrcaSlicer`. Su Linux è il percorso all'AppImage (estratta o meno).
|
||||
|
||||
### Database connection
|
||||
Verifica le credenziali in `application.properties`. Se usi Docker, puoi passare `DB_URL`, `DB_USERNAME` e `DB_PASSWORD` come variabili d'ambiente.
|
||||
|
||||
54
backend/.gitignore
vendored
Normal file
54
backend/.gitignore
vendored
Normal file
@@ -0,0 +1,54 @@
|
||||
/target/
|
||||
!.mvn/wrapper/maven-wrapper.jar
|
||||
!**/src/main/**/target/
|
||||
!**/src/test/**/target/
|
||||
target
|
||||
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbproject/public/
|
||||
/nbproject/project.properties
|
||||
/nbproject/project.xml
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
|
||||
### Gradle ###
|
||||
.gradle
|
||||
build/
|
||||
!gradle/wrapper/gradle-wrapper.jar
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
|
||||
### Java ###
|
||||
*.class
|
||||
*.log
|
||||
*.ctxt
|
||||
.mtj.tmp/
|
||||
*.jar
|
||||
*.war
|
||||
*.nar
|
||||
*.ear
|
||||
*.zip
|
||||
*.tar.gz
|
||||
*.rar
|
||||
|
||||
### Spring Boot ###
|
||||
HELP.md
|
||||
|
||||
!gradle/wrapper/gradle-wrapper.jar
|
||||
@@ -1,6 +1,17 @@
|
||||
FROM --platform=linux/amd64 python:3.10-slim-bookworm
|
||||
# Stage 1: Build Java JAR
|
||||
FROM eclipse-temurin:21-jdk-jammy AS build
|
||||
WORKDIR /app
|
||||
COPY gradle gradle
|
||||
COPY gradlew build.gradle settings.gradle ./
|
||||
# Download dependencies first to cache them
|
||||
RUN ./gradlew dependencies --no-daemon
|
||||
COPY src ./src
|
||||
RUN ./gradlew bootJar -x test --no-daemon
|
||||
|
||||
# Install system dependencies for OrcaSlicer (AppImage)
|
||||
# Stage 2: Runtime Environment
|
||||
FROM eclipse-temurin:21-jre-jammy
|
||||
|
||||
# Install system dependencies for OrcaSlicer
|
||||
RUN apt-get update && apt-get install -y \
|
||||
wget \
|
||||
p7zip-full \
|
||||
@@ -8,36 +19,36 @@ RUN apt-get update && apt-get install -y \
|
||||
libglib2.0-0 \
|
||||
libgtk-3-0 \
|
||||
libdbus-1-3 \
|
||||
libwebkit2gtk-4.1-0 \
|
||||
libwebkit2gtk-4.0-37 \
|
||||
libx11-xcb1 \
|
||||
libxcb-dri3-0 \
|
||||
libxtst6 \
|
||||
libnss3 \
|
||||
libatk-bridge2.0-0 \
|
||||
libxss1 \
|
||||
libasound2 \
|
||||
libgbm1 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Set working directory
|
||||
WORKDIR /app
|
||||
|
||||
# Download and extract OrcaSlicer
|
||||
# Using v2.2.0 as a stable recent release
|
||||
# We extract the AppImage to run it without FUSE
|
||||
# Install OrcaSlicer
|
||||
WORKDIR /opt
|
||||
RUN wget -q https://github.com/SoftFever/OrcaSlicer/releases/download/v2.2.0/OrcaSlicer_Linux_V2.2.0.AppImage -O OrcaSlicer.AppImage \
|
||||
&& 7z x OrcaSlicer.AppImage -o/opt/orcaslicer \
|
||||
&& chmod -R +x /opt/orcaslicer \
|
||||
&& rm OrcaSlicer.AppImage
|
||||
|
||||
# Add OrcaSlicer to PATH
|
||||
ENV PATH="/opt/orcaslicer/usr/bin:${PATH}"
|
||||
# Set Slicer Path env variable for Java app
|
||||
ENV SLICER_PATH="/opt/orcaslicer/AppRun"
|
||||
|
||||
# Install Python dependencies
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
WORKDIR /app
|
||||
# Copy JAR from build stage
|
||||
COPY --from=build /app/build/libs/*.jar app.jar
|
||||
# Copy profiles
|
||||
COPY profiles ./profiles
|
||||
|
||||
# Create directories for app and temp files
|
||||
RUN mkdir -p /app/temp /app/profiles
|
||||
EXPOSE 8080
|
||||
|
||||
# Copy application code
|
||||
COPY . .
|
||||
|
||||
# Expose port
|
||||
EXPOSE 8000
|
||||
|
||||
# Run the application
|
||||
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||
COPY entrypoint.sh .
|
||||
RUN chmod +x entrypoint.sh
|
||||
ENTRYPOINT ["./entrypoint.sh"]
|
||||
|
||||
@@ -1,137 +0,0 @@
|
||||
from fastapi import APIRouter, UploadFile, File, HTTPException, Form
|
||||
from models.quote_request import QuoteRequest, QuoteResponse
|
||||
from slicer import slicer_service
|
||||
from calculator import GCodeParser, QuoteCalculator
|
||||
from config import settings
|
||||
from profile_manager import ProfileManager
|
||||
import os
|
||||
import shutil
|
||||
import uuid
|
||||
import logging
|
||||
import json
|
||||
|
||||
router = APIRouter()
|
||||
logger = logging.getLogger("api")
|
||||
profile_manager = ProfileManager()
|
||||
|
||||
def cleanup_files(files: list):
|
||||
for f in files:
|
||||
try:
|
||||
if os.path.exists(f):
|
||||
os.remove(f)
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to delete temp file {f}: {e}")
|
||||
|
||||
def format_time(seconds: int) -> str:
|
||||
m, s = divmod(seconds, 60)
|
||||
h, m = divmod(m, 60)
|
||||
if h > 0:
|
||||
return f"{int(h)}h {int(m)}m"
|
||||
return f"{int(m)}m {int(s)}s"
|
||||
|
||||
@router.post("/quote", response_model=QuoteResponse)
|
||||
async def calculate_quote(
|
||||
file: UploadFile = File(...),
|
||||
# Compatible with form data if we parse manually or use specific dependencies.
|
||||
# FastAPI handling of mixed File + JSON/Form is tricky.
|
||||
# Easiest is to use Form(...) for fields.
|
||||
machine: str = Form("bambu_a1"),
|
||||
filament: str = Form("pla_basic"),
|
||||
quality: str = Form("standard"),
|
||||
layer_height: str = Form(None), # Form data comes as strings usually
|
||||
infill_density: int = Form(None),
|
||||
infill_pattern: str = Form(None),
|
||||
support_enabled: bool = Form(False),
|
||||
print_speed: int = Form(None)
|
||||
):
|
||||
"""
|
||||
Endpoint for calculating print quote.
|
||||
Accepts Multipart Form Data:
|
||||
- file: The STL file
|
||||
- machine, filament, quality: strings
|
||||
- other overrides
|
||||
"""
|
||||
if not file.filename.lower().endswith(".stl"):
|
||||
raise HTTPException(status_code=400, detail="Only .stl files are supported.")
|
||||
if machine != "bambu_a1":
|
||||
raise HTTPException(status_code=400, detail="Unsupported machine.")
|
||||
|
||||
req_id = str(uuid.uuid4())
|
||||
input_filename = f"{req_id}.stl"
|
||||
output_filename = f"{req_id}.gcode"
|
||||
|
||||
input_path = os.path.join(settings.TEMP_DIR, input_filename)
|
||||
output_path = os.path.join(settings.TEMP_DIR, output_filename)
|
||||
|
||||
try:
|
||||
# 1. Save File
|
||||
with open(input_path, "wb") as buffer:
|
||||
shutil.copyfileobj(file.file, buffer)
|
||||
|
||||
# 2. Build Overrides
|
||||
overrides = {}
|
||||
if layer_height is not None and layer_height != "":
|
||||
overrides["layer_height"] = layer_height
|
||||
if infill_density is not None:
|
||||
overrides["sparse_infill_density"] = f"{infill_density}%"
|
||||
if infill_pattern:
|
||||
overrides["sparse_infill_pattern"] = infill_pattern
|
||||
if support_enabled: overrides["enable_support"] = "1"
|
||||
if print_speed is not None:
|
||||
overrides["default_print_speed"] = str(print_speed)
|
||||
|
||||
# 3. Slice
|
||||
# Pass parameters to slicer service
|
||||
slicer_service.slice_stl(
|
||||
input_stl_path=input_path,
|
||||
output_gcode_path=output_path,
|
||||
machine=machine,
|
||||
filament=filament,
|
||||
quality=quality,
|
||||
overrides=overrides
|
||||
)
|
||||
|
||||
# 4. Parse
|
||||
stats = GCodeParser.parse_metadata(output_path)
|
||||
if stats["print_time_seconds"] == 0 and stats["filament_weight_g"] == 0:
|
||||
raise HTTPException(status_code=500, detail="Slicing returned empty stats.")
|
||||
|
||||
# 5. Calculate
|
||||
# We could allow filament cost override here too if passed in params
|
||||
quote = QuoteCalculator.calculate(stats)
|
||||
|
||||
return QuoteResponse(
|
||||
success=True,
|
||||
data={
|
||||
"print_time_seconds": stats["print_time_seconds"],
|
||||
"print_time_formatted": format_time(stats["print_time_seconds"]),
|
||||
"material_grams": stats["filament_weight_g"],
|
||||
"cost": {
|
||||
"material": quote["breakdown"]["material_cost"],
|
||||
"machine": quote["breakdown"]["machine_cost"],
|
||||
"energy": quote["breakdown"]["energy_cost"],
|
||||
"markup": quote["breakdown"]["markup_amount"],
|
||||
"total": quote["total_price"]
|
||||
},
|
||||
"parameters": {
|
||||
"machine": machine,
|
||||
"filament": filament,
|
||||
"quality": quality
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Quote error: {e}", exc_info=True)
|
||||
return QuoteResponse(success=False, error=str(e))
|
||||
|
||||
finally:
|
||||
cleanup_files([input_path, output_path])
|
||||
|
||||
@router.get("/profiles/available")
|
||||
def get_profiles():
|
||||
return {
|
||||
"machines": profile_manager.list_machines(),
|
||||
"filaments": profile_manager.list_filaments(),
|
||||
"processes": profile_manager.list_processes()
|
||||
}
|
||||
55
backend/build.gradle
Normal file
55
backend/build.gradle
Normal file
@@ -0,0 +1,55 @@
|
||||
plugins {
|
||||
id 'java'
|
||||
id 'application'
|
||||
id 'org.springframework.boot' version '3.4.1'
|
||||
id 'io.spring.dependency-management' version '1.1.7'
|
||||
}
|
||||
|
||||
group = 'com.printcalculator'
|
||||
version = '0.0.1-SNAPSHOT'
|
||||
|
||||
java {
|
||||
toolchain {
|
||||
languageVersion = JavaLanguageVersion.of(21)
|
||||
}
|
||||
}
|
||||
|
||||
application {
|
||||
mainClass = 'com.printcalculator.BackendApplication'
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation 'org.springframework.boot:spring-boot-starter-web'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
|
||||
implementation 'xyz.capybara:clamav-client:2.1.2'
|
||||
runtimeOnly 'org.postgresql:postgresql'
|
||||
developmentOnly 'org.springframework.boot:spring-boot-devtools'
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
testRuntimeOnly 'com.h2database:h2'
|
||||
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
|
||||
compileOnly 'org.projectlombok:lombok'
|
||||
annotationProcessor 'org.projectlombok:lombok'
|
||||
implementation 'io.github.openhtmltopdf:openhtmltopdf-pdfbox:1.1.37'
|
||||
implementation 'io.github.openhtmltopdf:openhtmltopdf-svg-support:1.1.37'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
|
||||
implementation 'net.codecrete.qrbill:qrbill-generator:3.4.0'
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
tasks.named('test') {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
|
||||
tasks.named('bootRun') {
|
||||
args = ["--spring.profiles.active=local"]
|
||||
}
|
||||
|
||||
application {
|
||||
applicationDefaultJvmArgs = ["-Dspring.profiles.active=local"]
|
||||
}
|
||||
@@ -1,174 +0,0 @@
|
||||
import re
|
||||
import os
|
||||
import logging
|
||||
from typing import Dict, Any, Optional
|
||||
from config import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class GCodeParser:
|
||||
@staticmethod
|
||||
def parse_metadata(gcode_path: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Parses the G-code to extract estimated time and material usage.
|
||||
Scans both the beginning (header) and end (footer) of the file.
|
||||
"""
|
||||
stats = {
|
||||
"print_time_seconds": 0,
|
||||
"filament_length_mm": 0,
|
||||
"filament_volume_mm3": 0,
|
||||
"filament_weight_g": 0,
|
||||
"slicer_estimated_cost": 0
|
||||
}
|
||||
|
||||
if not os.path.exists(gcode_path):
|
||||
logger.warning(f"GCode file not found for parsing: {gcode_path}")
|
||||
return stats
|
||||
|
||||
try:
|
||||
with open(gcode_path, 'r', encoding='utf-8', errors='ignore') as f:
|
||||
# Read header (first 500 lines)
|
||||
header_lines = [f.readline().strip() for _ in range(500) if f]
|
||||
|
||||
# Read footer (last 20KB)
|
||||
f.seek(0, 2)
|
||||
file_size = f.tell()
|
||||
read_len = min(file_size, 20480)
|
||||
f.seek(file_size - read_len)
|
||||
footer_lines = f.read().splitlines()
|
||||
|
||||
all_lines = header_lines + footer_lines
|
||||
|
||||
for line in all_lines:
|
||||
line = line.strip()
|
||||
if not line.startswith(";"):
|
||||
continue
|
||||
|
||||
GCodeParser._parse_line(line, stats)
|
||||
|
||||
# Fallback calculation
|
||||
if stats["filament_weight_g"] == 0 and stats["filament_length_mm"] > 0:
|
||||
GCodeParser._calculate_weight_fallback(stats)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error parsing G-code: {e}")
|
||||
|
||||
return stats
|
||||
|
||||
@staticmethod
|
||||
def _parse_line(line: str, stats: Dict[str, Any]):
|
||||
# Parse Time
|
||||
if "estimated printing time =" in line: # Header
|
||||
time_str = line.split("=")[1].strip()
|
||||
logger.info(f"Parsing time string (Header): '{time_str}'")
|
||||
stats["print_time_seconds"] = GCodeParser._parse_time_string(time_str)
|
||||
elif "total estimated time:" in line: # Footer
|
||||
parts = line.split("total estimated time:")
|
||||
if len(parts) > 1:
|
||||
time_str = parts[1].strip()
|
||||
logger.info(f"Parsing time string (Footer): '{time_str}'")
|
||||
stats["print_time_seconds"] = GCodeParser._parse_time_string(time_str)
|
||||
|
||||
# Parse Filament info
|
||||
if "filament used [g] =" in line:
|
||||
try:
|
||||
stats["filament_weight_g"] = float(line.split("=")[1].strip())
|
||||
except ValueError: pass
|
||||
|
||||
if "filament used [mm] =" in line:
|
||||
try:
|
||||
stats["filament_length_mm"] = float(line.split("=")[1].strip())
|
||||
except ValueError: pass
|
||||
|
||||
if "filament used [cm3] =" in line:
|
||||
try:
|
||||
# cm3 to mm3
|
||||
stats["filament_volume_mm3"] = float(line.split("=")[1].strip()) * 1000
|
||||
except ValueError: pass
|
||||
|
||||
@staticmethod
|
||||
def _calculate_weight_fallback(stats: Dict[str, Any]):
|
||||
# Assumes 1.75mm diameter and PLA density 1.24
|
||||
radius = 1.75 / 2
|
||||
volume_mm3 = 3.14159 * (radius ** 2) * stats["filament_length_mm"]
|
||||
volume_cm3 = volume_mm3 / 1000.0
|
||||
stats["filament_weight_g"] = volume_cm3 * 1.24
|
||||
|
||||
@staticmethod
|
||||
def _parse_time_string(time_str: str) -> int:
|
||||
"""
|
||||
Converts '1d 2h 3m 4s' or 'HH:MM:SS' to seconds.
|
||||
"""
|
||||
total_seconds = 0
|
||||
|
||||
# Try HH:MM:SS or MM:SS format
|
||||
if ':' in time_str:
|
||||
parts = time_str.split(':')
|
||||
parts = [int(p) for p in parts]
|
||||
if len(parts) == 3: # HH:MM:SS
|
||||
total_seconds = parts[0] * 3600 + parts[1] * 60 + parts[2]
|
||||
elif len(parts) == 2: # MM:SS
|
||||
total_seconds = parts[0] * 60 + parts[1]
|
||||
return total_seconds
|
||||
|
||||
# Original regex parsing for "1h 2m 3s"
|
||||
days = re.search(r'(\d+)d', time_str)
|
||||
hours = re.search(r'(\d+)h', time_str)
|
||||
mins = re.search(r'(\d+)m', time_str)
|
||||
secs = re.search(r'(\d+)s', time_str)
|
||||
|
||||
if days: total_seconds += int(days.group(1)) * 86400
|
||||
if hours: total_seconds += int(hours.group(1)) * 3600
|
||||
if mins: total_seconds += int(mins.group(1)) * 60
|
||||
if secs: total_seconds += int(secs.group(1))
|
||||
|
||||
return total_seconds
|
||||
|
||||
|
||||
class QuoteCalculator:
|
||||
@staticmethod
|
||||
def calculate(stats: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
Calculates the final quote based on parsed stats and settings.
|
||||
"""
|
||||
# 1. Material Cost
|
||||
# Cost per gram = (Cost per kg / 1000)
|
||||
material_cost = (stats["filament_weight_g"] / 1000.0) * settings.FILAMENT_COST_PER_KG
|
||||
|
||||
# 2. Machine Time Cost
|
||||
# Cost per second = (Cost per hour / 3600)
|
||||
print("ciaooo")
|
||||
print(stats["print_time_seconds"])
|
||||
print_time_hours = stats["print_time_seconds"] / 3600.0
|
||||
machine_cost = print_time_hours * settings.MACHINE_COST_PER_HOUR
|
||||
|
||||
# 3. Energy Cost
|
||||
# kWh = (Watts / 1000) * hours
|
||||
kwh_used = (settings.PRINTER_POWER_WATTS / 1000.0) * print_time_hours
|
||||
energy_cost = kwh_used * settings.ENERGY_COST_PER_KWH
|
||||
|
||||
# Subtotal
|
||||
subtotal = material_cost + machine_cost + energy_cost
|
||||
|
||||
# 4. Markup
|
||||
markup_factor = 1.0 + (settings.MARKUP_PERCENT / 100.0)
|
||||
total_price = subtotal * markup_factor
|
||||
|
||||
logger.info("Cost Calculation:")
|
||||
logger.info(f" - Use: {stats['filament_weight_g']:.2f}g @ {settings.FILAMENT_COST_PER_KG}€/kg = {material_cost:.2f}€")
|
||||
logger.info(f" - Time: {print_time_hours:.4f}h @ {settings.MACHINE_COST_PER_HOUR}€/h = {machine_cost:.2f}€")
|
||||
logger.info(f" - Power: {kwh_used:.4f}kWh @ {settings.ENERGY_COST_PER_KWH}€/kWh = {energy_cost:.2f}€")
|
||||
logger.info(f" - Subtotal: {subtotal:.2f}€")
|
||||
logger.info(f" - Total (Markup {settings.MARKUP_PERCENT}%): {total_price:.2f}€")
|
||||
|
||||
return {
|
||||
"breakdown": {
|
||||
"material_cost": round(material_cost, 2),
|
||||
"machine_cost": round(machine_cost, 2),
|
||||
"energy_cost": round(energy_cost, 2),
|
||||
"subtotal": round(subtotal, 2),
|
||||
"markup_amount": round(total_price - subtotal, 2)
|
||||
},
|
||||
"total_price": round(total_price, 2),
|
||||
"currency": "EUR"
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
import os
|
||||
import sys
|
||||
|
||||
class Settings:
|
||||
# Directories
|
||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
TEMP_DIR = os.environ.get("TEMP_DIR", os.path.join(BASE_DIR, "temp"))
|
||||
PROFILES_DIR = os.environ.get("PROFILES_DIR", os.path.join(BASE_DIR, "profiles"))
|
||||
|
||||
# Slicer Paths
|
||||
if sys.platform == "darwin":
|
||||
_DEFAULT_SLICER_PATH = "/Applications/OrcaSlicer.app/Contents/MacOS/OrcaSlicer"
|
||||
else:
|
||||
_DEFAULT_SLICER_PATH = "/opt/orcaslicer/AppRun"
|
||||
|
||||
SLICER_PATH = os.environ.get("SLICER_PATH", _DEFAULT_SLICER_PATH)
|
||||
ORCA_HOME = os.environ.get("ORCA_HOME", "/opt/orcaslicer")
|
||||
|
||||
# Defaults Profiles (Bambu A1)
|
||||
MACHINE_PROFILE = os.path.join(PROFILES_DIR, "Bambu_Lab_A1_machine.json")
|
||||
PROCESS_PROFILE = os.path.join(PROFILES_DIR, "Bambu_Process_0.20_Standard.json")
|
||||
FILAMENT_PROFILE = os.path.join(PROFILES_DIR, "Bambu_PLA_Basic.json")
|
||||
|
||||
# Pricing
|
||||
FILAMENT_COST_PER_KG = float(os.environ.get("FILAMENT_COST_PER_KG", 25.0))
|
||||
MACHINE_COST_PER_HOUR = float(os.environ.get("MACHINE_COST_PER_HOUR", 2.0))
|
||||
ENERGY_COST_PER_KWH = float(os.environ.get("ENERGY_COST_PER_KWH", 0.30))
|
||||
PRINTER_POWER_WATTS = float(os.environ.get("PRINTER_POWER_WATTS", 150.0))
|
||||
MARKUP_PERCENT = float(os.environ.get("MARKUP_PERCENT", 20.0))
|
||||
|
||||
settings = Settings()
|
||||
15
backend/entrypoint.sh
Normal file
15
backend/entrypoint.sh
Normal file
@@ -0,0 +1,15 @@
|
||||
#!/bin/sh
|
||||
echo "----------------------------------------------------------------"
|
||||
echo "Starting Backend Application"
|
||||
echo "DB_URL: $DB_URL"
|
||||
echo "DB_USERNAME: $DB_USERNAME"
|
||||
echo "SLICER_PATH: $SLICER_PATH"
|
||||
echo "--- ALL ENV VARS ---"
|
||||
env
|
||||
echo "----------------------------------------------------------------"
|
||||
|
||||
# Exec java with explicit properties from env
|
||||
exec java -jar app.jar \
|
||||
--spring.datasource.url="${DB_URL}" \
|
||||
--spring.datasource.username="${DB_USERNAME}" \
|
||||
--spring.datasource.password="${DB_PASSWORD}"
|
||||
BIN
backend/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
backend/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
7
backend/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
7
backend/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.1.0-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
248
backend/gradlew
vendored
Executable file
248
backend/gradlew
vendored
Executable file
@@ -0,0 +1,248 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
93
backend/gradlew.bat
vendored
Normal file
93
backend/gradlew.bat
vendored
Normal file
@@ -0,0 +1,93 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
@rem SPDX-License-Identifier: Apache-2.0
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
@@ -1,74 +0,0 @@
|
||||
import logging
|
||||
import os
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from config import settings
|
||||
from api.routes import router as api_router
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger("main")
|
||||
|
||||
app = FastAPI(title="Print Calculator API")
|
||||
|
||||
# CORS Setup
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# Ensure directories exist
|
||||
os.makedirs(settings.TEMP_DIR, exist_ok=True)
|
||||
|
||||
# Include Router
|
||||
app.include_router(api_router, prefix="/api")
|
||||
|
||||
# Legacy endpoint redirect or basic handler if needed for backward compatibility
|
||||
# The frontend likely calls /calculate/stl.
|
||||
# We should probably keep the old route or instruct user to update frontend.
|
||||
# But for this task, let's remap the old route to the new logic if possible,
|
||||
# or just expose the new route.
|
||||
# The user request said: "Creare api/routes.py ... @app.post('/api/quote')"
|
||||
# So we are creating a new endpoint.
|
||||
# Existing frontend might break?
|
||||
# The context says: "Currently uses hardcoded... Objective is to render system flexible... Frontend: Angular 19"
|
||||
# The user didn't explicitly ask to update the frontend, but the new API is at /api/quote.
|
||||
# I will keep the old "/calculate/stl" endpoint support by forwarding it or duplicating logic if critical,
|
||||
# OR I'll assume the user will handle frontend updates.
|
||||
# Better: I will alias the old route to the new one if parameters allow,
|
||||
# but the new one expects Form data with different names maybe?
|
||||
# Old: `/calculate/stl` just expected a file.
|
||||
# I'll enable a simplified version on the old route for backward compat using defaults.
|
||||
|
||||
from fastapi import UploadFile, File
|
||||
from api.routes import calculate_quote
|
||||
|
||||
@app.post("/calculate/stl")
|
||||
async def legacy_calculate(file: UploadFile = File(...)):
|
||||
"""Legacy endpoint compatibility"""
|
||||
# Call the new logic with defaults
|
||||
resp = await calculate_quote(file=file)
|
||||
if not resp.success:
|
||||
from fastapi import HTTPException
|
||||
raise HTTPException(status_code=500, detail=resp.error)
|
||||
|
||||
# Map Check response to old format
|
||||
data = resp.data
|
||||
return {
|
||||
"print_time_seconds": data.get("print_time_seconds", 0),
|
||||
"print_time_formatted": data.get("print_time_formatted", ""),
|
||||
"material_grams": data.get("material_grams", 0.0),
|
||||
"cost": data.get("cost", {}),
|
||||
"notes": ["Generated via Dynamic Slicer (Legacy Endpoint)"]
|
||||
}
|
||||
|
||||
@app.get("/health")
|
||||
def health_check():
|
||||
return {"status": "ok", "slicer": settings.SLICER_PATH}
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
uvicorn.run(app, host="0.0.0.0", port=8000)
|
||||
@@ -1,37 +0,0 @@
|
||||
from pydantic import BaseModel, Field, validator
|
||||
from typing import Optional, Literal, Dict, Any
|
||||
|
||||
class QuoteRequest(BaseModel):
|
||||
# File STL (base64 or path)
|
||||
file_path: Optional[str] = None
|
||||
file_base64: Optional[str] = None
|
||||
|
||||
# Parametri slicing
|
||||
machine: str = Field(default="bambu_a1", description="Machine type")
|
||||
filament: str = Field(default="pla_basic", description="Filament type")
|
||||
quality: Literal["draft", "standard", "fine"] = Field(default="standard")
|
||||
|
||||
# Parametri opzionali
|
||||
layer_height: Optional[float] = Field(None, ge=0.08, le=0.32)
|
||||
infill_density: Optional[int] = Field(None, ge=0, le=100)
|
||||
support_enabled: Optional[bool] = None
|
||||
print_speed: Optional[int] = Field(None, ge=20, le=300)
|
||||
|
||||
# Pricing overrides
|
||||
filament_cost_override: Optional[float] = None
|
||||
|
||||
@validator('machine')
|
||||
def validate_machine(cls, v):
|
||||
# This list should ideally be dynamic, but for validation purposes we start with known ones.
|
||||
# Logic in ProfileManager can be looser or strict.
|
||||
# For now, we allow the string through and let ProfileManager validate availability.
|
||||
return v
|
||||
|
||||
@validator('filament')
|
||||
def validate_filament(cls, v):
|
||||
return v
|
||||
|
||||
class QuoteResponse(BaseModel):
|
||||
success: bool
|
||||
data: Optional[Dict[str, Any]] = None
|
||||
error: Optional[str] = None
|
||||
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large
Load Diff
@@ -1,15 +0,0 @@
|
||||
from functools import lru_cache
|
||||
import hashlib
|
||||
from typing import Dict, Tuple
|
||||
|
||||
# We can't cache the profile manager instance itself easily if it's not a singleton,
|
||||
# but we can cache the result of a merge function if we pass simple types.
|
||||
# However, to avoid circular imports or complex dependency injection,
|
||||
# we will just provide a helper to generate cache keys and a holder for logic if needed.
|
||||
# For now, the ProfileManager will strictly determine *what* to merge.
|
||||
# Validating the cache strategy: since file I/O is the bottleneck, we want to cache the *content*.
|
||||
|
||||
def get_cache_key(machine: str, filament: str, process: str) -> str:
|
||||
"""Helper to create a unique cache key"""
|
||||
data = f"{machine}|{filament}|{process}"
|
||||
return hashlib.md5(data.encode()).hexdigest()
|
||||
@@ -1,193 +0,0 @@
|
||||
import os
|
||||
import json
|
||||
import logging
|
||||
from typing import Dict, List, Tuple, Optional
|
||||
from profile_cache import get_cache_key
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class ProfileManager:
|
||||
def __init__(self, profiles_root: str = "profiles"):
|
||||
# Assuming profiles_root is relative to backend or absolute
|
||||
if not os.path.isabs(profiles_root):
|
||||
base_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
self.profiles_root = os.path.join(base_dir, profiles_root)
|
||||
else:
|
||||
self.profiles_root = profiles_root
|
||||
|
||||
if not os.path.exists(self.profiles_root):
|
||||
logger.warning(f"Profiles root not found: {self.profiles_root}")
|
||||
|
||||
def get_profiles(self, machine: str, filament: str, process: str) -> Tuple[Dict, Dict, Dict]:
|
||||
"""
|
||||
Main entry point to get merged profiles.
|
||||
Args:
|
||||
machine: e.g. "Bambu Lab A1 0.4 nozzle"
|
||||
filament: e.g. "Bambu PLA Basic @BBL A1"
|
||||
process: e.g. "0.20mm Standard @BBL A1"
|
||||
"""
|
||||
# Try cache first (although specific logic is needed if we cache the *result* or the *files*)
|
||||
# Since we implemented a simple external cache helper, let's use it if we want,
|
||||
# but for now we will rely on internal logic or the lru_cache decorator on a helper method.
|
||||
# But wait, the `get_cached_profiles` in profile_cache.py calls `build_merged_profiles` which is logic WE need to implement.
|
||||
# So we should probably move the implementation here and have the cache wrapper call it,
|
||||
# OR just implement it here and wrap it.
|
||||
|
||||
return self._build_merged_profiles(machine, filament, process)
|
||||
|
||||
def _build_merged_profiles(self, machine_name: str, filament_name: str, process_name: str) -> Tuple[Dict, Dict, Dict]:
|
||||
# We need to find the files.
|
||||
# The naming convention in OrcaSlicer profiles usually involves the Vendor (e.g. BBL).
|
||||
# We might need a mapping or search.
|
||||
# For this implementation, we will assume we know the relative paths or search for them.
|
||||
|
||||
# Strategy: Search in all vendor subdirs for the specific JSON files.
|
||||
# Because names are usually unique enough or we can specify the expected vendor.
|
||||
# However, to be fast, we can map "machine_name" to a file path.
|
||||
|
||||
machine_file = self._find_profile_file(machine_name, "machine")
|
||||
filament_file = self._find_profile_file(filament_name, "filament")
|
||||
process_file = self._find_profile_file(process_name, "process")
|
||||
|
||||
if not machine_file:
|
||||
raise FileNotFoundError(f"Machine profile not found: {machine_name}")
|
||||
if not filament_file:
|
||||
raise FileNotFoundError(f"Filament profile not found: {filament_name}")
|
||||
if not process_file:
|
||||
raise FileNotFoundError(f"Process profile not found: {process_name}")
|
||||
|
||||
machine_profile = self._merge_chain(machine_file)
|
||||
filament_profile = self._merge_chain(filament_file)
|
||||
process_profile = self._merge_chain(process_file)
|
||||
|
||||
# Apply patches
|
||||
machine_profile = self._apply_patches(machine_profile, "machine")
|
||||
process_profile = self._apply_patches(process_profile, "process")
|
||||
|
||||
return machine_profile, process_profile, filament_profile
|
||||
|
||||
def _find_profile_file(self, profile_name: str, profile_type: str) -> Optional[str]:
|
||||
"""
|
||||
Searches for a profile file by name in the profiles directory.
|
||||
The name should match the filename (without .json possibly) or be a precise match.
|
||||
"""
|
||||
# Add .json if missing
|
||||
filename = profile_name if profile_name.endswith(".json") else f"{profile_name}.json"
|
||||
|
||||
for root, dirs, files in os.walk(self.profiles_root):
|
||||
if filename in files:
|
||||
# Check if it is in the correct type folder (machine, filament, process)
|
||||
# OrcaSlicer structure: Vendor/process/file.json
|
||||
# We optionally verify parent dir
|
||||
if os.path.basename(root) == profile_type or profile_type in root:
|
||||
return os.path.join(root, filename)
|
||||
|
||||
# Fallback: if we simply found it, maybe just return it?
|
||||
# Some common files might be in root or other places.
|
||||
# Let's return it if we are fairly sure.
|
||||
return os.path.join(root, filename)
|
||||
|
||||
return None
|
||||
|
||||
def _merge_chain(self, final_file_path: str) -> Dict:
|
||||
"""
|
||||
Resolves inheritance and merges.
|
||||
"""
|
||||
chain = []
|
||||
current_path = final_file_path
|
||||
|
||||
# 1. Build chain
|
||||
while current_path:
|
||||
chain.insert(0, current_path) # Prepend
|
||||
|
||||
with open(current_path, 'r', encoding='utf-8') as f:
|
||||
try:
|
||||
data = json.load(f)
|
||||
except json.JSONDecodeError as e:
|
||||
logger.error(f"Failed to decode JSON: {current_path}")
|
||||
raise e
|
||||
|
||||
inherits = data.get("inherits")
|
||||
if inherits:
|
||||
# Resolve inherited file
|
||||
# It is usually in the same directory or relative.
|
||||
# OrcaSlicer logic: checks same dir, then parent, etc.
|
||||
# Usually it's in the same directory.
|
||||
parent_dir = os.path.dirname(current_path)
|
||||
inherited_path = os.path.join(parent_dir, inherits)
|
||||
|
||||
# Special case: if not found, it might be in a common folder?
|
||||
# But OrcaSlicer usually keeps them local or in specific common dirs.
|
||||
if not os.path.exists(inherited_path) and not inherits.endswith(".json"):
|
||||
inherited_path += ".json"
|
||||
|
||||
if os.path.exists(inherited_path):
|
||||
current_path = inherited_path
|
||||
else:
|
||||
# Could be a system common file not in the same dir?
|
||||
# For simplicty, try to look up in the same generic type folder across the vendor?
|
||||
# Or just fail for now.
|
||||
# Often "fdm_machine_common.json" is at the Vendor root or similar?
|
||||
# Let's try searching recursively if not found in place.
|
||||
found = self._find_profile_file(inherits, "any") # "any" type
|
||||
if found:
|
||||
current_path = found
|
||||
else:
|
||||
logger.warning(f"Inherited profile '{inherits}' not found for '{current_path}' (Root: {self.profiles_root})")
|
||||
current_path = None
|
||||
else:
|
||||
current_path = None
|
||||
|
||||
# 2. Merge
|
||||
merged = {}
|
||||
for path in chain:
|
||||
with open(path, 'r', encoding='utf-8') as f:
|
||||
data = json.load(f)
|
||||
# Shallow update
|
||||
merged.update(data)
|
||||
|
||||
# Remove metadata
|
||||
merged.pop("inherits", None)
|
||||
|
||||
return merged
|
||||
|
||||
def _apply_patches(self, profile: Dict, profile_type: str) -> Dict:
|
||||
if profile_type == "machine":
|
||||
# Patch: G92 E0 to ensure extrusion reference text matches
|
||||
lcg = profile.get("layer_change_gcode", "")
|
||||
if "G92 E0" not in lcg:
|
||||
# Append neatly
|
||||
if lcg and not lcg.endswith("\n"):
|
||||
lcg += "\n"
|
||||
lcg += "G92 E0"
|
||||
profile["layer_change_gcode"] = lcg
|
||||
|
||||
# Patch: ensure printable height is sufficient?
|
||||
# Only if necessary. For now, trust the profile.
|
||||
|
||||
elif profile_type == "process":
|
||||
# Optional: Disable skirt/brim if we want a "clean" print estimation?
|
||||
# Actually, for accurate cost, we SHOULD include skirt/brim if the profile has it.
|
||||
pass
|
||||
|
||||
return profile
|
||||
|
||||
def list_machines(self) -> List[str]:
|
||||
# Simple helper to list available machine JSONs
|
||||
return self._list_profiles_by_type("machine")
|
||||
|
||||
def list_filaments(self) -> List[str]:
|
||||
return self._list_profiles_by_type("filament")
|
||||
|
||||
def list_processes(self) -> List[str]:
|
||||
return self._list_profiles_by_type("process")
|
||||
|
||||
def _list_profiles_by_type(self, ptype: str) -> List[str]:
|
||||
results = []
|
||||
for root, dirs, files in os.walk(self.profiles_root):
|
||||
if os.path.basename(root) == ptype:
|
||||
for f in files:
|
||||
if f.endswith(".json") and "common" not in f:
|
||||
results.append(f.replace(".json", ""))
|
||||
return sorted(results)
|
||||
@@ -1,24 +0,0 @@
|
||||
{
|
||||
"quality_to_process": {
|
||||
"draft": "0.28mm Extra Draft @BBL A1",
|
||||
"standard": "0.20mm Standard @BBL A1",
|
||||
"fine": "0.12mm Fine @BBL A1"
|
||||
},
|
||||
"filament_costs": {
|
||||
"pla_basic": 20.0,
|
||||
"petg_basic": 25.0,
|
||||
"abs_basic": 22.0,
|
||||
"tpu_95a": 35.0
|
||||
},
|
||||
"filament_to_profile": {
|
||||
"pla_basic": "Bambu PLA Basic @BBL A1",
|
||||
"petg_basic": "Bambu PETG Basic @BBL A1",
|
||||
"abs_basic": "Bambu ABS @BBL A1",
|
||||
"tpu_95a": "Bambu TPU 95A @BBL A1"
|
||||
},
|
||||
"machine_to_profile": {
|
||||
"bambu_a1": "Bambu Lab A1 0.4 nozzle",
|
||||
"bambu_x1": "Bambu Lab X1 Carbon 0.4 nozzle",
|
||||
"bambu_p1s": "Bambu Lab P1S 0.4 nozzle"
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
fastapi==0.109.0
|
||||
uvicorn==0.27.0
|
||||
python-multipart==0.0.6
|
||||
requests==2.31.0
|
||||
1
backend/settings.gradle
Normal file
1
backend/settings.gradle
Normal file
@@ -0,0 +1 @@
|
||||
rootProject.name = 'print-calculator-backend'
|
||||
@@ -1,154 +0,0 @@
|
||||
import subprocess
|
||||
import os
|
||||
import json
|
||||
import logging
|
||||
import shutil
|
||||
import tempfile
|
||||
from typing import Optional, Dict
|
||||
from config import settings
|
||||
from profile_manager import ProfileManager
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class SlicerService:
|
||||
def __init__(self):
|
||||
self.profile_manager = ProfileManager()
|
||||
|
||||
def slice_stl(
|
||||
self,
|
||||
input_stl_path: str,
|
||||
output_gcode_path: str,
|
||||
machine: str = "bambu_a1",
|
||||
filament: str = "pla_basic",
|
||||
quality: str = "standard",
|
||||
overrides: Optional[Dict] = None
|
||||
) -> bool:
|
||||
"""
|
||||
Runs OrcaSlicer in headless mode with dynamic profiles.
|
||||
"""
|
||||
if not os.path.exists(settings.SLICER_PATH):
|
||||
raise RuntimeError(f"Slicer executable not found at: {settings.SLICER_PATH}")
|
||||
|
||||
if not os.path.exists(input_stl_path):
|
||||
raise FileNotFoundError(f"STL file not found: {input_stl_path}")
|
||||
|
||||
# 1. Get Merged Profiles
|
||||
# Use simple mapping if the input is short code (bambu_a1) vs full name
|
||||
# For now, we assume the caller solves the mapping or passes full names?
|
||||
# Actually, the user wants "Bambu A1" from API to map to "Bambu Lab A1 0.4 nozzle"
|
||||
# We should use the mapping logic here or in the caller?
|
||||
# The implementation plan said "profile_mappings.json" maps keys.
|
||||
# It's better to handle mapping in the Service layer or Manager.
|
||||
# Let's load the mapping in the service for now, or use a helper.
|
||||
|
||||
# We'll use a helper method to resolve names to full profile names using the loaded mapping.
|
||||
machine_p, filament_p, quality_p = self._resolve_profile_names(machine, filament, quality)
|
||||
|
||||
try:
|
||||
m_profile, p_profile, f_profile = self.profile_manager.get_profiles(machine_p, filament_p, quality_p)
|
||||
except FileNotFoundError as e:
|
||||
logger.error(f"Profile error: {e}")
|
||||
raise RuntimeError(f"Profile generation failed: {e}")
|
||||
|
||||
# 2. Apply Overrides
|
||||
if overrides:
|
||||
p_profile = self._apply_overrides(p_profile, overrides)
|
||||
# Some overrides might apply to machine or filament, but mostly process.
|
||||
# E.g. layer_height is in process.
|
||||
|
||||
# 3. Write Temp Profiles
|
||||
# We create a temp dir for this slice job
|
||||
output_dir = os.path.dirname(output_gcode_path)
|
||||
# We keep temp profiles in a hidden folder or just temp
|
||||
# Using a context manager for temp dir might be safer but we need it for the subprocess duration
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
m_path = os.path.join(temp_dir, "machine.json")
|
||||
p_path = os.path.join(temp_dir, "process.json")
|
||||
f_path = os.path.join(temp_dir, "filament.json")
|
||||
|
||||
with open(m_path, 'w') as f: json.dump(m_profile, f)
|
||||
with open(p_path, 'w') as f: json.dump(p_profile, f)
|
||||
with open(f_path, 'w') as f: json.dump(f_profile, f)
|
||||
|
||||
# 4. Build Command
|
||||
command = self._build_slicer_command(input_stl_path, output_dir, m_path, p_path, f_path)
|
||||
|
||||
logger.info(f"Starting slicing for {input_stl_path} [M:{machine_p} F:{filament_p} Q:{quality_p}]")
|
||||
try:
|
||||
self._run_command(command)
|
||||
self._finalize_output(output_dir, input_stl_path, output_gcode_path)
|
||||
logger.info("Slicing completed successfully.")
|
||||
return True
|
||||
except subprocess.CalledProcessError as e:
|
||||
# Cleanup is automatic via tempfile, but we might want to preserve invalid gcode?
|
||||
raise RuntimeError(f"Slicing failed: {e.stderr if e.stderr else e.stdout}")
|
||||
|
||||
def _resolve_profile_names(self, m: str, f: str, q: str) -> tuple[str, str, str]:
|
||||
# Load mappings
|
||||
# Allow passing full names if they don't exist in mapping
|
||||
mapping_path = os.path.join(os.path.dirname(__file__), "profile_mappings.json")
|
||||
try:
|
||||
with open(mapping_path, 'r') as fp:
|
||||
mappings = json.load(fp)
|
||||
except Exception:
|
||||
logger.warning("Could not load profile_mappings.json, using inputs as raw names.")
|
||||
return m, f, q
|
||||
|
||||
m_real = mappings.get("machine_to_profile", {}).get(m, m)
|
||||
f_real = mappings.get("filament_to_profile", {}).get(f, f)
|
||||
q_real = mappings.get("quality_to_process", {}).get(q, q)
|
||||
|
||||
return m_real, f_real, q_real
|
||||
|
||||
def _apply_overrides(self, profile: Dict, overrides: Dict) -> Dict:
|
||||
for k, v in overrides.items():
|
||||
# OrcaSlicer values are often strings
|
||||
profile[k] = str(v)
|
||||
return profile
|
||||
|
||||
def _build_slicer_command(self, input_path: str, output_dir: str, m_path: str, p_path: str, f_path: str) -> list:
|
||||
# Settings format: "machine_file;process_file" (filament separate)
|
||||
settings_arg = f"{m_path};{p_path}"
|
||||
|
||||
return [
|
||||
settings.SLICER_PATH,
|
||||
"--load-settings", settings_arg,
|
||||
"--load-filaments", f_path,
|
||||
"--ensure-on-bed",
|
||||
"--arrange", "1",
|
||||
"--slice", "0",
|
||||
"--outputdir", output_dir,
|
||||
input_path
|
||||
]
|
||||
|
||||
def _run_command(self, command: list):
|
||||
# logging and running logic similar to before
|
||||
logger.debug(f"Exec: {' '.join(command)}")
|
||||
result = subprocess.run(
|
||||
command,
|
||||
check=False,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True
|
||||
)
|
||||
if result.returncode != 0:
|
||||
logger.error(f"Slicer Error: {result.stderr}")
|
||||
raise subprocess.CalledProcessError(
|
||||
result.returncode, command, output=result.stdout, stderr=result.stderr
|
||||
)
|
||||
|
||||
def _finalize_output(self, output_dir: str, input_path: str, target_path: str):
|
||||
input_basename = os.path.basename(input_path)
|
||||
expected_name = os.path.splitext(input_basename)[0] + ".gcode"
|
||||
generated_path = os.path.join(output_dir, expected_name)
|
||||
|
||||
if not os.path.exists(generated_path):
|
||||
alt_path = os.path.join(output_dir, "plate_1.gcode")
|
||||
if os.path.exists(alt_path):
|
||||
generated_path = alt_path
|
||||
|
||||
if os.path.exists(generated_path) and generated_path != target_path:
|
||||
shutil.move(generated_path, target_path)
|
||||
|
||||
slicer_service = SlicerService()
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.printcalculator;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
@SpringBootApplication
|
||||
@EnableTransactionManagement
|
||||
@EnableScheduling
|
||||
public class BackendApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(BackendApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.printcalculator.config;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
public class CorsConfig implements WebMvcConfigurer {
|
||||
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/**")
|
||||
.allowedOrigins(
|
||||
"http://localhost",
|
||||
"http://localhost:4200",
|
||||
"http://localhost:80",
|
||||
"http://127.0.0.1",
|
||||
"https://dev.3d-fab.ch",
|
||||
"https://int.3d-fab.ch",
|
||||
"https://3d-fab.ch"
|
||||
)
|
||||
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH")
|
||||
.allowedHeaders("*")
|
||||
.allowCredentials(true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package com.printcalculator.controller;
|
||||
|
||||
import com.printcalculator.entity.CustomQuoteRequest;
|
||||
import com.printcalculator.entity.CustomQuoteRequestAttachment;
|
||||
import com.printcalculator.repository.CustomQuoteRequestAttachmentRepository;
|
||||
import com.printcalculator.repository.CustomQuoteRequestRepository;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/custom-quote-requests")
|
||||
public class CustomQuoteRequestController {
|
||||
|
||||
private final CustomQuoteRequestRepository requestRepo;
|
||||
private final CustomQuoteRequestAttachmentRepository attachmentRepo;
|
||||
|
||||
private final com.printcalculator.service.StorageService storageService;
|
||||
|
||||
public CustomQuoteRequestController(CustomQuoteRequestRepository requestRepo,
|
||||
CustomQuoteRequestAttachmentRepository attachmentRepo,
|
||||
com.printcalculator.service.StorageService storageService) {
|
||||
this.requestRepo = requestRepo;
|
||||
this.attachmentRepo = attachmentRepo;
|
||||
this.storageService = storageService;
|
||||
}
|
||||
|
||||
// 1. Create Custom Quote Request
|
||||
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
@Transactional
|
||||
public ResponseEntity<CustomQuoteRequest> createCustomQuoteRequest(
|
||||
@RequestPart("request") com.printcalculator.dto.QuoteRequestDto requestDto,
|
||||
@RequestPart(value = "files", required = false) List<MultipartFile> files
|
||||
) throws IOException {
|
||||
|
||||
// 1. Create Request
|
||||
CustomQuoteRequest request = new CustomQuoteRequest();
|
||||
request.setRequestType(requestDto.getRequestType());
|
||||
request.setCustomerType(requestDto.getCustomerType());
|
||||
request.setEmail(requestDto.getEmail());
|
||||
request.setPhone(requestDto.getPhone());
|
||||
request.setName(requestDto.getName());
|
||||
request.setCompanyName(requestDto.getCompanyName());
|
||||
request.setContactPerson(requestDto.getContactPerson());
|
||||
request.setMessage(requestDto.getMessage());
|
||||
request.setStatus("PENDING");
|
||||
request.setCreatedAt(OffsetDateTime.now());
|
||||
request.setUpdatedAt(OffsetDateTime.now());
|
||||
|
||||
request = requestRepo.save(request);
|
||||
|
||||
// 2. Handle Attachments
|
||||
if (files != null && !files.isEmpty()) {
|
||||
if (files.size() > 15) {
|
||||
throw new IOException("Too many files. Max 15 allowed.");
|
||||
}
|
||||
|
||||
for (MultipartFile file : files) {
|
||||
if (file.isEmpty()) continue;
|
||||
|
||||
CustomQuoteRequestAttachment attachment = new CustomQuoteRequestAttachment();
|
||||
attachment.setRequest(request);
|
||||
attachment.setOriginalFilename(file.getOriginalFilename());
|
||||
attachment.setMimeType(file.getContentType());
|
||||
attachment.setFileSizeBytes(file.getSize());
|
||||
attachment.setCreatedAt(OffsetDateTime.now());
|
||||
|
||||
// Generate path
|
||||
UUID fileUuid = UUID.randomUUID();
|
||||
String ext = getExtension(file.getOriginalFilename());
|
||||
String storedFilename = fileUuid.toString() + "." + ext;
|
||||
|
||||
// Note: We don't have attachment ID yet.
|
||||
// We'll save attachment first to get ID.
|
||||
attachment.setStoredFilename(storedFilename);
|
||||
attachment.setStoredRelativePath("PENDING");
|
||||
|
||||
attachment = attachmentRepo.save(attachment);
|
||||
|
||||
String relativePath = "quote-requests/" + request.getId() + "/attachments/" + attachment.getId() + "/" + storedFilename;
|
||||
attachment.setStoredRelativePath(relativePath);
|
||||
attachmentRepo.save(attachment);
|
||||
|
||||
// Save file to disk via StorageService
|
||||
storageService.store(file, Paths.get(relativePath));
|
||||
}
|
||||
}
|
||||
|
||||
return ResponseEntity.ok(request);
|
||||
}
|
||||
|
||||
// 2. Get Request
|
||||
@GetMapping("/{id}")
|
||||
public ResponseEntity<CustomQuoteRequest> getCustomQuoteRequest(@PathVariable UUID id) {
|
||||
return requestRepo.findById(id)
|
||||
.map(ResponseEntity::ok)
|
||||
.orElse(ResponseEntity.notFound().build());
|
||||
}
|
||||
|
||||
// Helper
|
||||
private String getExtension(String filename) {
|
||||
if (filename == null) return "dat";
|
||||
int i = filename.lastIndexOf('.');
|
||||
if (i > 0) {
|
||||
return filename.substring(i + 1);
|
||||
}
|
||||
return "dat";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package com.printcalculator.controller;
|
||||
|
||||
import com.printcalculator.dto.OptionsResponse;
|
||||
import com.printcalculator.entity.FilamentMaterialType;
|
||||
import com.printcalculator.entity.FilamentVariant;
|
||||
import com.printcalculator.entity.*; // This line replaces specific entity imports
|
||||
import com.printcalculator.repository.FilamentMaterialTypeRepository;
|
||||
import com.printcalculator.repository.FilamentVariantRepository;
|
||||
import com.printcalculator.repository.LayerHeightOptionRepository;
|
||||
import com.printcalculator.repository.NozzleOptionRepository;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@RestController
|
||||
public class OptionsController {
|
||||
|
||||
private final FilamentMaterialTypeRepository materialRepo;
|
||||
private final FilamentVariantRepository variantRepo;
|
||||
private final LayerHeightOptionRepository layerHeightRepo;
|
||||
private final NozzleOptionRepository nozzleRepo;
|
||||
|
||||
public OptionsController(FilamentMaterialTypeRepository materialRepo,
|
||||
FilamentVariantRepository variantRepo,
|
||||
LayerHeightOptionRepository layerHeightRepo,
|
||||
NozzleOptionRepository nozzleRepo) {
|
||||
this.materialRepo = materialRepo;
|
||||
this.variantRepo = variantRepo;
|
||||
this.layerHeightRepo = layerHeightRepo;
|
||||
this.nozzleRepo = nozzleRepo;
|
||||
}
|
||||
|
||||
@GetMapping("/api/calculator/options")
|
||||
public ResponseEntity<OptionsResponse> getOptions() {
|
||||
// 1. Materials & Variants
|
||||
List<FilamentMaterialType> types = materialRepo.findAll();
|
||||
List<FilamentVariant> allVariants = variantRepo.findAll();
|
||||
|
||||
List<OptionsResponse.MaterialOption> materialOptions = types.stream()
|
||||
.map(type -> {
|
||||
List<OptionsResponse.VariantOption> variants = allVariants.stream()
|
||||
.filter(v -> v.getFilamentMaterialType().getId().equals(type.getId()) && v.getIsActive())
|
||||
.map(v -> new OptionsResponse.VariantOption(
|
||||
v.getVariantDisplayName(),
|
||||
v.getColorName(),
|
||||
getColorHex(v.getColorName()), // Need helper or store hex in DB
|
||||
v.getStockSpools().doubleValue() <= 0
|
||||
))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// Only include material if it has active variants
|
||||
if (variants.isEmpty()) return null;
|
||||
|
||||
return new OptionsResponse.MaterialOption(
|
||||
type.getMaterialCode(),
|
||||
type.getMaterialCode() + (type.getIsFlexible() ? " (Flexible)" : " (Standard)"),
|
||||
variants
|
||||
);
|
||||
})
|
||||
.filter(m -> m != null)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// Sort: PLA first, then PETG, then others alphabetically
|
||||
materialOptions.sort((a, b) -> {
|
||||
String codeA = a.code();
|
||||
String codeB = b.code();
|
||||
|
||||
if (codeA.equals("pla_basic")) return -1;
|
||||
if (codeB.equals("pla_basic")) return 1;
|
||||
|
||||
if (codeA.equals("petg_basic")) return -1;
|
||||
if (codeB.equals("petg_basic")) return 1;
|
||||
|
||||
return codeA.compareTo(codeB);
|
||||
});
|
||||
|
||||
// 2. Qualities (Static as per user request)
|
||||
List<OptionsResponse.QualityOption> qualities = List.of(
|
||||
new OptionsResponse.QualityOption("draft", "Draft"),
|
||||
new OptionsResponse.QualityOption("standard", "Standard"),
|
||||
new OptionsResponse.QualityOption("extra_fine", "High Definition")
|
||||
);
|
||||
|
||||
// 3. Infill Patterns (Static as per user request)
|
||||
List<OptionsResponse.InfillPatternOption> patterns = List.of(
|
||||
new OptionsResponse.InfillPatternOption("grid", "Grid"),
|
||||
new OptionsResponse.InfillPatternOption("gyroid", "Gyroid"),
|
||||
new OptionsResponse.InfillPatternOption("cubic", "Cubic")
|
||||
);
|
||||
|
||||
// 4. Layer Heights
|
||||
List<OptionsResponse.LayerHeightOptionDTO> layers = layerHeightRepo.findAll().stream()
|
||||
.filter(l -> l.getIsActive())
|
||||
.sorted(Comparator.comparing(LayerHeightOption::getLayerHeightMm))
|
||||
.map(l -> new OptionsResponse.LayerHeightOptionDTO(
|
||||
l.getLayerHeightMm().doubleValue(),
|
||||
String.format("%.2f mm", l.getLayerHeightMm())
|
||||
))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// 5. Nozzles
|
||||
List<OptionsResponse.NozzleOptionDTO> nozzles = nozzleRepo.findAll().stream()
|
||||
.filter(n -> n.getIsActive())
|
||||
.sorted(Comparator.comparing(NozzleOption::getNozzleDiameterMm))
|
||||
.map(n -> new OptionsResponse.NozzleOptionDTO(
|
||||
n.getNozzleDiameterMm().doubleValue(),
|
||||
String.format("%.1f mm%s", n.getNozzleDiameterMm(),
|
||||
n.getExtraNozzleChangeFeeChf().doubleValue() > 0
|
||||
? String.format(" (+ %.2f CHF)", n.getExtraNozzleChangeFeeChf())
|
||||
: " (Standard)")
|
||||
))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return ResponseEntity.ok(new OptionsResponse(materialOptions, qualities, patterns, layers, nozzles));
|
||||
}
|
||||
|
||||
// Temporary helper until we add hex to DB
|
||||
private String getColorHex(String colorName) {
|
||||
String lower = colorName.toLowerCase();
|
||||
if (lower.contains("black") || lower.contains("nero")) return "#1a1a1a";
|
||||
if (lower.contains("white") || lower.contains("bianco")) return "#f5f5f5";
|
||||
if (lower.contains("blue") || lower.contains("blu")) return "#1976d2";
|
||||
if (lower.contains("red") || lower.contains("rosso")) return "#d32f2f";
|
||||
if (lower.contains("green") || lower.contains("verde")) return "#388e3c";
|
||||
if (lower.contains("orange") || lower.contains("arancione")) return "#ffa726";
|
||||
if (lower.contains("grey") || lower.contains("gray") || lower.contains("grigio")) {
|
||||
if (lower.contains("dark") || lower.contains("scuro")) return "#424242";
|
||||
return "#bdbdbd";
|
||||
}
|
||||
if (lower.contains("purple") || lower.contains("viola")) return "#7b1fa2";
|
||||
if (lower.contains("yellow") || lower.contains("giallo")) return "#fbc02d";
|
||||
return "#9e9e9e"; // Default grey
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
package com.printcalculator.controller;
|
||||
|
||||
import com.printcalculator.dto.*;
|
||||
import com.printcalculator.entity.*;
|
||||
import com.printcalculator.repository.*;
|
||||
import com.printcalculator.service.InvoicePdfRenderingService;
|
||||
import com.printcalculator.service.OrderService;
|
||||
import com.printcalculator.service.QrBillService;
|
||||
import com.printcalculator.service.StorageService;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/orders")
|
||||
public class OrderController {
|
||||
|
||||
private final OrderService orderService;
|
||||
private final OrderRepository orderRepo;
|
||||
private final OrderItemRepository orderItemRepo;
|
||||
private final QuoteSessionRepository quoteSessionRepo;
|
||||
private final QuoteLineItemRepository quoteLineItemRepo;
|
||||
private final CustomerRepository customerRepo;
|
||||
private final StorageService storageService;
|
||||
private final InvoicePdfRenderingService invoiceService;
|
||||
private final QrBillService qrBillService;
|
||||
|
||||
|
||||
public OrderController(OrderService orderService,
|
||||
OrderRepository orderRepo,
|
||||
OrderItemRepository orderItemRepo,
|
||||
QuoteSessionRepository quoteSessionRepo,
|
||||
QuoteLineItemRepository quoteLineItemRepo,
|
||||
CustomerRepository customerRepo,
|
||||
StorageService storageService,
|
||||
InvoicePdfRenderingService invoiceService,
|
||||
QrBillService qrBillService) {
|
||||
this.orderService = orderService;
|
||||
this.orderRepo = orderRepo;
|
||||
this.orderItemRepo = orderItemRepo;
|
||||
this.quoteSessionRepo = quoteSessionRepo;
|
||||
this.quoteLineItemRepo = quoteLineItemRepo;
|
||||
this.customerRepo = customerRepo;
|
||||
this.storageService = storageService;
|
||||
this.invoiceService = invoiceService;
|
||||
this.qrBillService = qrBillService;
|
||||
}
|
||||
|
||||
|
||||
// 1. Create Order from Quote
|
||||
@PostMapping("/from-quote/{quoteSessionId}")
|
||||
@Transactional
|
||||
public ResponseEntity<OrderDto> createOrderFromQuote(
|
||||
@PathVariable UUID quoteSessionId,
|
||||
@RequestBody com.printcalculator.dto.CreateOrderRequest request
|
||||
) {
|
||||
Order order = orderService.createOrderFromQuote(quoteSessionId, request);
|
||||
List<OrderItem> items = orderItemRepo.findByOrder_Id(order.getId());
|
||||
return ResponseEntity.ok(convertToDto(order, items));
|
||||
}
|
||||
|
||||
@PostMapping(value = "/{orderId}/items/{orderItemId}/file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
@Transactional
|
||||
public ResponseEntity<Void> uploadOrderItemFile(
|
||||
@PathVariable UUID orderId,
|
||||
@PathVariable UUID orderItemId,
|
||||
@RequestParam("file") MultipartFile file
|
||||
) throws IOException {
|
||||
|
||||
OrderItem item = orderItemRepo.findById(orderItemId)
|
||||
.orElseThrow(() -> new RuntimeException("OrderItem not found"));
|
||||
|
||||
if (!item.getOrder().getId().equals(orderId)) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
String relativePath = item.getStoredRelativePath();
|
||||
if (relativePath == null || relativePath.equals("PENDING")) {
|
||||
String ext = getExtension(file.getOriginalFilename());
|
||||
String storedFilename = UUID.randomUUID().toString() + "." + ext;
|
||||
relativePath = "orders/" + orderId + "/3d-files/" + orderItemId + "/" + storedFilename;
|
||||
item.setStoredRelativePath(relativePath);
|
||||
item.setStoredFilename(storedFilename);
|
||||
}
|
||||
|
||||
storageService.store(file, Paths.get(relativePath));
|
||||
item.setFileSizeBytes(file.getSize());
|
||||
item.setMimeType(file.getContentType());
|
||||
orderItemRepo.save(item);
|
||||
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@GetMapping("/{orderId}")
|
||||
public ResponseEntity<OrderDto> getOrder(@PathVariable UUID orderId) {
|
||||
return orderRepo.findById(orderId)
|
||||
.map(o -> {
|
||||
List<OrderItem> items = orderItemRepo.findByOrder_Id(o.getId());
|
||||
return ResponseEntity.ok(convertToDto(o, items));
|
||||
})
|
||||
.orElse(ResponseEntity.notFound().build());
|
||||
}
|
||||
|
||||
@GetMapping("/{orderId}/invoice")
|
||||
public ResponseEntity<byte[]> getInvoice(@PathVariable UUID orderId) {
|
||||
Order order = orderRepo.findById(orderId)
|
||||
.orElseThrow(() -> new RuntimeException("Order not found"));
|
||||
|
||||
List<OrderItem> items = orderItemRepo.findByOrder_Id(orderId);
|
||||
|
||||
Map<String, Object> vars = new HashMap<>();
|
||||
vars.put("sellerDisplayName", "3D Fab Switzerland");
|
||||
vars.put("sellerAddressLine1", "Sede Ticino, Svizzera");
|
||||
vars.put("sellerAddressLine2", "Sede Bienne, Svizzera");
|
||||
vars.put("sellerEmail", "info@3dfab.ch");
|
||||
|
||||
vars.put("invoiceNumber", "INV-" + order.getId().toString().substring(0, 8).toUpperCase());
|
||||
vars.put("invoiceDate", order.getCreatedAt().format(DateTimeFormatter.ISO_LOCAL_DATE));
|
||||
vars.put("dueDate", order.getCreatedAt().plusDays(7).format(DateTimeFormatter.ISO_LOCAL_DATE));
|
||||
|
||||
String buyerName = order.getBillingCustomerType().equals("BUSINESS")
|
||||
? order.getBillingCompanyName()
|
||||
: order.getBillingFirstName() + " " + order.getBillingLastName();
|
||||
vars.put("buyerDisplayName", buyerName);
|
||||
vars.put("buyerAddressLine1", order.getBillingAddressLine1());
|
||||
vars.put("buyerAddressLine2", order.getBillingZip() + " " + order.getBillingCity() + ", " + order.getBillingCountryCode());
|
||||
|
||||
List<Map<String, Object>> invoiceLineItems = items.stream().map(i -> {
|
||||
Map<String, Object> line = new HashMap<>();
|
||||
line.put("description", "Stampa 3D: " + i.getOriginalFilename());
|
||||
line.put("quantity", i.getQuantity());
|
||||
line.put("unitPriceFormatted", String.format("CHF %.2f", i.getUnitPriceChf()));
|
||||
line.put("lineTotalFormatted", String.format("CHF %.2f", i.getLineTotalChf()));
|
||||
return line;
|
||||
}).collect(Collectors.toList());
|
||||
|
||||
Map<String, Object> setupLine = new HashMap<>();
|
||||
setupLine.put("description", "Costo Setup");
|
||||
setupLine.put("quantity", 1);
|
||||
setupLine.put("unitPriceFormatted", String.format("CHF %.2f", order.getSetupCostChf()));
|
||||
setupLine.put("lineTotalFormatted", String.format("CHF %.2f", order.getSetupCostChf()));
|
||||
invoiceLineItems.add(setupLine);
|
||||
|
||||
Map<String, Object> shippingLine = new HashMap<>();
|
||||
shippingLine.put("description", "Spedizione");
|
||||
shippingLine.put("quantity", 1);
|
||||
shippingLine.put("unitPriceFormatted", String.format("CHF %.2f", order.getShippingCostChf()));
|
||||
shippingLine.put("lineTotalFormatted", String.format("CHF %.2f", order.getShippingCostChf()));
|
||||
invoiceLineItems.add(shippingLine);
|
||||
|
||||
vars.put("invoiceLineItems", invoiceLineItems);
|
||||
vars.put("subtotalFormatted", String.format("CHF %.2f", order.getSubtotalChf()));
|
||||
vars.put("grandTotalFormatted", String.format("CHF %.2f", order.getTotalChf()));
|
||||
vars.put("paymentTermsText", "Pagamento entro 7 giorni via Bonifico o TWINT. Grazie.");
|
||||
|
||||
String qrBillSvg = new String(qrBillService.generateQrBillSvg(order), java.nio.charset.StandardCharsets.UTF_8);
|
||||
|
||||
// Strip XML declaration and DOCTYPE if present, as they validity break the embedding HTML page
|
||||
if (qrBillSvg.contains("<?xml")) {
|
||||
int svgStartIndex = qrBillSvg.indexOf("<svg");
|
||||
if (svgStartIndex != -1) {
|
||||
qrBillSvg = qrBillSvg.substring(svgStartIndex);
|
||||
}
|
||||
}
|
||||
|
||||
byte[] pdf = invoiceService.generateInvoicePdfBytesFromTemplate(vars, qrBillSvg);
|
||||
|
||||
return ResponseEntity.ok()
|
||||
.header("Content-Disposition", "attachment; filename=\"invoice-" + orderId + ".pdf\"")
|
||||
.contentType(MediaType.APPLICATION_PDF)
|
||||
.body(pdf);
|
||||
}
|
||||
|
||||
private String getExtension(String filename) {
|
||||
if (filename == null) return "stl";
|
||||
int i = filename.lastIndexOf('.');
|
||||
if (i > 0) {
|
||||
return filename.substring(i + 1);
|
||||
}
|
||||
return "stl";
|
||||
}
|
||||
|
||||
private OrderDto convertToDto(Order order, List<OrderItem> items) {
|
||||
OrderDto dto = new OrderDto();
|
||||
dto.setId(order.getId());
|
||||
dto.setStatus(order.getStatus());
|
||||
dto.setCustomerEmail(order.getCustomerEmail());
|
||||
dto.setCustomerPhone(order.getCustomerPhone());
|
||||
dto.setBillingCustomerType(order.getBillingCustomerType());
|
||||
dto.setCurrency(order.getCurrency());
|
||||
dto.setSetupCostChf(order.getSetupCostChf());
|
||||
dto.setShippingCostChf(order.getShippingCostChf());
|
||||
dto.setDiscountChf(order.getDiscountChf());
|
||||
dto.setSubtotalChf(order.getSubtotalChf());
|
||||
dto.setTotalChf(order.getTotalChf());
|
||||
dto.setCreatedAt(order.getCreatedAt());
|
||||
dto.setShippingSameAsBilling(order.getShippingSameAsBilling());
|
||||
|
||||
AddressDto billing = new AddressDto();
|
||||
billing.setFirstName(order.getBillingFirstName());
|
||||
billing.setLastName(order.getBillingLastName());
|
||||
billing.setCompanyName(order.getBillingCompanyName());
|
||||
billing.setContactPerson(order.getBillingContactPerson());
|
||||
billing.setAddressLine1(order.getBillingAddressLine1());
|
||||
billing.setAddressLine2(order.getBillingAddressLine2());
|
||||
billing.setZip(order.getBillingZip());
|
||||
billing.setCity(order.getBillingCity());
|
||||
billing.setCountryCode(order.getBillingCountryCode());
|
||||
dto.setBillingAddress(billing);
|
||||
|
||||
if (!order.getShippingSameAsBilling()) {
|
||||
AddressDto shipping = new AddressDto();
|
||||
shipping.setFirstName(order.getShippingFirstName());
|
||||
shipping.setLastName(order.getShippingLastName());
|
||||
shipping.setCompanyName(order.getShippingCompanyName());
|
||||
shipping.setContactPerson(order.getShippingContactPerson());
|
||||
shipping.setAddressLine1(order.getShippingAddressLine1());
|
||||
shipping.setAddressLine2(order.getShippingAddressLine2());
|
||||
shipping.setZip(order.getShippingZip());
|
||||
shipping.setCity(order.getShippingCity());
|
||||
shipping.setCountryCode(order.getShippingCountryCode());
|
||||
dto.setShippingAddress(shipping);
|
||||
}
|
||||
|
||||
List<OrderItemDto> itemDtos = items.stream().map(i -> {
|
||||
OrderItemDto idto = new OrderItemDto();
|
||||
idto.setId(i.getId());
|
||||
idto.setOriginalFilename(i.getOriginalFilename());
|
||||
idto.setMaterialCode(i.getMaterialCode());
|
||||
idto.setColorCode(i.getColorCode());
|
||||
idto.setQuantity(i.getQuantity());
|
||||
idto.setPrintTimeSeconds(i.getPrintTimeSeconds());
|
||||
idto.setMaterialGrams(i.getMaterialGrams());
|
||||
idto.setUnitPriceChf(i.getUnitPriceChf());
|
||||
idto.setLineTotalChf(i.getLineTotalChf());
|
||||
return idto;
|
||||
}).collect(Collectors.toList());
|
||||
dto.setItems(itemDtos);
|
||||
|
||||
return dto;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package com.printcalculator.controller;
|
||||
|
||||
import com.printcalculator.entity.PrinterMachine;
|
||||
import com.printcalculator.exception.ModelTooLargeException;
|
||||
import com.printcalculator.model.PrintStats;
|
||||
import com.printcalculator.model.QuoteResult;
|
||||
import com.printcalculator.model.StlBounds;
|
||||
import com.printcalculator.repository.PrinterMachineRepository;
|
||||
import com.printcalculator.service.QuoteCalculator;
|
||||
import com.printcalculator.service.ProfileManager;
|
||||
import com.printcalculator.service.SlicerService;
|
||||
import com.printcalculator.service.StlService;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
@RestController
|
||||
public class QuoteController {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(QuoteController.class.getName());
|
||||
|
||||
private final SlicerService slicerService;
|
||||
private final StlService stlService;
|
||||
private final QuoteCalculator quoteCalculator;
|
||||
private final PrinterMachineRepository machineRepo;
|
||||
private final ProfileManager profileManager;
|
||||
|
||||
// Defaults (using aliases defined in ProfileManager)
|
||||
private static final String DEFAULT_FILAMENT = "pla_basic";
|
||||
private static final String DEFAULT_PROCESS = "standard";
|
||||
|
||||
public QuoteController(SlicerService slicerService, StlService stlService, QuoteCalculator quoteCalculator, PrinterMachineRepository machineRepo, ProfileManager profileManager) {
|
||||
this.slicerService = slicerService;
|
||||
this.stlService = stlService;
|
||||
this.quoteCalculator = quoteCalculator;
|
||||
this.machineRepo = machineRepo;
|
||||
this.profileManager = profileManager;
|
||||
}
|
||||
|
||||
@PostMapping("/api/quote")
|
||||
public ResponseEntity<QuoteResult> calculateQuote(
|
||||
@RequestParam("file") MultipartFile file,
|
||||
@RequestParam(value = "filament", required = false, defaultValue = DEFAULT_FILAMENT) String filament,
|
||||
@RequestParam(value = "process", required = false) String process,
|
||||
@RequestParam(value = "quality", required = false) String quality,
|
||||
// Advanced Options
|
||||
@RequestParam(value = "infill_density", required = false) Integer infillDensity,
|
||||
@RequestParam(value = "infill_pattern", required = false) String infillPattern,
|
||||
@RequestParam(value = "layer_height", required = false) Double layerHeight,
|
||||
@RequestParam(value = "nozzle_diameter", required = false) Double nozzleDiameter,
|
||||
@RequestParam(value = "support_enabled", required = false, defaultValue = "false") Boolean supportEnabled
|
||||
) throws IOException {
|
||||
|
||||
// ... process selection logic ...
|
||||
String actualProcess = process;
|
||||
if (actualProcess == null || actualProcess.isEmpty()) {
|
||||
if (quality != null && !quality.isEmpty()) {
|
||||
actualProcess = quality;
|
||||
} else {
|
||||
actualProcess = DEFAULT_PROCESS;
|
||||
}
|
||||
}
|
||||
|
||||
// Prepare Overrides
|
||||
Map<String, String> processOverrides = new HashMap<>();
|
||||
Map<String, String> machineOverrides = new HashMap<>();
|
||||
|
||||
if (infillDensity != null) {
|
||||
processOverrides.put("sparse_infill_density", infillDensity + "%");
|
||||
}
|
||||
if (infillPattern != null && !infillPattern.isEmpty()) {
|
||||
processOverrides.put("sparse_infill_pattern", infillPattern);
|
||||
}
|
||||
if (layerHeight != null) {
|
||||
processOverrides.put("layer_height", String.valueOf(layerHeight));
|
||||
}
|
||||
if (supportEnabled != null) {
|
||||
processOverrides.put("enable_support", supportEnabled ? "1" : "0");
|
||||
if (supportEnabled) {
|
||||
processOverrides.put("support_threshold_angle", "45");
|
||||
}
|
||||
}
|
||||
|
||||
if (nozzleDiameter != null) {
|
||||
machineOverrides.put("nozzle_diameter", String.valueOf(nozzleDiameter));
|
||||
// Also need to ensure the printer profile is compatible or just override?
|
||||
// Usually nozzle diameter changes require a different printer profile or deep overrides.
|
||||
// For now, we trust the override key works on the base profile.
|
||||
}
|
||||
|
||||
return processRequest(file, filament, actualProcess, machineOverrides, processOverrides, nozzleDiameter);
|
||||
}
|
||||
|
||||
@PostMapping("/calculate/stl")
|
||||
public ResponseEntity<QuoteResult> legacyCalculate(
|
||||
@RequestParam("file") MultipartFile file
|
||||
) throws IOException {
|
||||
// Legacy endpoint uses defaults
|
||||
return processRequest(file, DEFAULT_FILAMENT, DEFAULT_PROCESS, null, null, null);
|
||||
}
|
||||
|
||||
private ResponseEntity<QuoteResult> processRequest(MultipartFile file, String filament, String process,
|
||||
Map<String, String> machineOverrides,
|
||||
Map<String, String> processOverrides,
|
||||
Double nozzleDiameter) throws IOException {
|
||||
if (file.isEmpty()) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
// Fetch Default Active Machine
|
||||
PrinterMachine machine = machineRepo.findFirstByIsActiveTrue()
|
||||
.orElseThrow(() -> new IOException("No active printer found in database"));
|
||||
|
||||
// Save uploaded file temporarily
|
||||
Path tempInput = Files.createTempFile("upload_", "_" + file.getOriginalFilename());
|
||||
com.printcalculator.model.StlShiftResult shift = null;
|
||||
try {
|
||||
file.transferTo(tempInput.toFile());
|
||||
|
||||
// Use profile from machine or fallback
|
||||
String slicerMachineProfile = machine.getSlicerMachineProfile();
|
||||
if (slicerMachineProfile == null || slicerMachineProfile.isEmpty()) {
|
||||
slicerMachineProfile = "bambu_a1";
|
||||
}
|
||||
slicerMachineProfile = profileManager.resolveMachineProfileName(slicerMachineProfile, nozzleDiameter);
|
||||
|
||||
// Validate model size against machine volume
|
||||
StlBounds bounds = validateModelSize(tempInput.toFile(), machine);
|
||||
|
||||
// Auto-center if needed
|
||||
shift = stlService.shiftToFitIfNeeded(
|
||||
tempInput.toFile(),
|
||||
bounds,
|
||||
machine.getBuildVolumeXMm(),
|
||||
machine.getBuildVolumeYMm(),
|
||||
machine.getBuildVolumeZMm()
|
||||
);
|
||||
java.io.File sliceInput = shift.shifted() ? shift.shiftedPath().toFile() : tempInput.toFile();
|
||||
if (shift.shifted()) {
|
||||
logger.info(String.format("Auto-centered STL by offset (mm): x=%.3f y=%.3f z=%.3f",
|
||||
shift.offsetX(), shift.offsetY(), shift.offsetZ()));
|
||||
}
|
||||
|
||||
PrintStats stats = slicerService.slice(sliceInput, slicerMachineProfile, filament, process, machineOverrides, processOverrides);
|
||||
|
||||
// Calculate Quote (Pass machine display name for pricing lookup)
|
||||
QuoteResult result = quoteCalculator.calculate(stats, machine.getPrinterDisplayName(), filament);
|
||||
|
||||
return ResponseEntity.ok(result);
|
||||
} finally {
|
||||
Files.deleteIfExists(tempInput);
|
||||
if (shift != null && shift.shifted()) {
|
||||
try {
|
||||
Files.deleteIfExists(shift.shiftedPath());
|
||||
} catch (Exception ignored) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private StlBounds validateModelSize(java.io.File stlFile, PrinterMachine machine) throws IOException {
|
||||
StlBounds bounds = stlService.readBounds(stlFile);
|
||||
double x = bounds.sizeX();
|
||||
double y = bounds.sizeY();
|
||||
double z = bounds.sizeZ();
|
||||
|
||||
int bx = machine.getBuildVolumeXMm();
|
||||
int by = machine.getBuildVolumeYMm();
|
||||
int bz = machine.getBuildVolumeZMm();
|
||||
|
||||
logger.info(String.format(
|
||||
"STL bounds (mm): min(%.3f,%.3f,%.3f) max(%.3f,%.3f,%.3f) size(%.3f,%.3f,%.3f) bed(%d,%d,%d)",
|
||||
bounds.minX(), bounds.minY(), bounds.minZ(),
|
||||
bounds.maxX(), bounds.maxY(), bounds.maxZ(),
|
||||
x, y, z, bx, by, bz
|
||||
));
|
||||
|
||||
double eps = 0.01;
|
||||
boolean fits = (x <= bx + eps && y <= by + eps && z <= bz + eps)
|
||||
|| (y <= bx + eps && x <= by + eps && z <= bz + eps);
|
||||
|
||||
if (!fits) {
|
||||
throw new ModelTooLargeException(x, y, z, bx, by, bz);
|
||||
}
|
||||
return bounds;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,468 @@
|
||||
package com.printcalculator.controller;
|
||||
|
||||
import com.printcalculator.entity.PrinterMachine;
|
||||
import com.printcalculator.entity.QuoteLineItem;
|
||||
import com.printcalculator.entity.QuoteSession;
|
||||
import com.printcalculator.exception.ModelTooLargeException;
|
||||
import com.printcalculator.model.PrintStats;
|
||||
import com.printcalculator.model.QuoteResult;
|
||||
import com.printcalculator.model.StlBounds;
|
||||
import com.printcalculator.repository.PrinterMachineRepository;
|
||||
import com.printcalculator.repository.QuoteLineItemRepository;
|
||||
import com.printcalculator.repository.QuoteSessionRepository;
|
||||
import com.printcalculator.service.QuoteCalculator;
|
||||
import com.printcalculator.service.ProfileManager;
|
||||
import com.printcalculator.service.SlicerService;
|
||||
import com.printcalculator.service.StlService;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.io.UrlResource;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/quote-sessions")
|
||||
|
||||
public class QuoteSessionController {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(QuoteSessionController.class.getName());
|
||||
|
||||
private final QuoteSessionRepository sessionRepo;
|
||||
private final QuoteLineItemRepository lineItemRepo;
|
||||
private final SlicerService slicerService;
|
||||
private final StlService stlService;
|
||||
private final QuoteCalculator quoteCalculator;
|
||||
private final ProfileManager profileManager;
|
||||
private final PrinterMachineRepository machineRepo;
|
||||
private final com.printcalculator.repository.PricingPolicyRepository pricingRepo;
|
||||
private final com.printcalculator.service.StorageService storageService;
|
||||
|
||||
// Defaults
|
||||
private static final String DEFAULT_FILAMENT = "pla_basic";
|
||||
private static final String DEFAULT_PROCESS = "standard";
|
||||
|
||||
public QuoteSessionController(QuoteSessionRepository sessionRepo,
|
||||
QuoteLineItemRepository lineItemRepo,
|
||||
SlicerService slicerService,
|
||||
StlService stlService,
|
||||
QuoteCalculator quoteCalculator,
|
||||
ProfileManager profileManager,
|
||||
PrinterMachineRepository machineRepo,
|
||||
com.printcalculator.repository.PricingPolicyRepository pricingRepo,
|
||||
com.printcalculator.service.StorageService storageService) {
|
||||
this.sessionRepo = sessionRepo;
|
||||
this.lineItemRepo = lineItemRepo;
|
||||
this.slicerService = slicerService;
|
||||
this.stlService = stlService;
|
||||
this.quoteCalculator = quoteCalculator;
|
||||
this.profileManager = profileManager;
|
||||
this.machineRepo = machineRepo;
|
||||
this.pricingRepo = pricingRepo;
|
||||
this.storageService = storageService;
|
||||
}
|
||||
|
||||
// 1. Start a new empty session
|
||||
@PostMapping(value = "")
|
||||
@Transactional
|
||||
public ResponseEntity<QuoteSession> createSession() {
|
||||
QuoteSession session = new QuoteSession();
|
||||
session.setStatus("ACTIVE");
|
||||
session.setPricingVersion("v1");
|
||||
// Default material/settings will be set when items are added or updated?
|
||||
// For now set safe defaults
|
||||
session.setMaterialCode("pla_basic");
|
||||
session.setSupportsEnabled(false);
|
||||
session.setCreatedAt(OffsetDateTime.now());
|
||||
session.setExpiresAt(OffsetDateTime.now().plusDays(30));
|
||||
|
||||
var policy = pricingRepo.findFirstByIsActiveTrueOrderByValidFromDesc();
|
||||
session.setSetupCostChf(policy != null ? policy.getFixedJobFeeChf() : BigDecimal.ZERO);
|
||||
|
||||
session = sessionRepo.save(session);
|
||||
return ResponseEntity.ok(session);
|
||||
}
|
||||
|
||||
// 2. Add item to existing session
|
||||
@PostMapping(value = "/{id}/line-items", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
@Transactional
|
||||
public ResponseEntity<QuoteLineItem> addItemToExistingSession(
|
||||
@PathVariable UUID id,
|
||||
@RequestPart("settings") com.printcalculator.dto.PrintSettingsDto settings,
|
||||
@RequestPart("file") MultipartFile file
|
||||
) throws IOException {
|
||||
QuoteSession session = sessionRepo.findById(id)
|
||||
.orElseThrow(() -> new RuntimeException("Session not found"));
|
||||
|
||||
QuoteLineItem item = addItemToSession(session, file, settings);
|
||||
return ResponseEntity.ok(item);
|
||||
}
|
||||
|
||||
// Helper to add item
|
||||
private QuoteLineItem addItemToSession(QuoteSession session, MultipartFile file, com.printcalculator.dto.PrintSettingsDto settings) throws IOException {
|
||||
if (file.isEmpty()) throw new IOException("File is empty");
|
||||
|
||||
// 1. Define Persistent Storage Path
|
||||
// Structure: quotes/{sessionId}/{uuid}.{ext} (inside storage root)
|
||||
|
||||
String originalFilename = file.getOriginalFilename();
|
||||
String ext = originalFilename != null && originalFilename.contains(".")
|
||||
? originalFilename.substring(originalFilename.lastIndexOf("."))
|
||||
: ".stl";
|
||||
|
||||
String storedFilename = UUID.randomUUID() + ext;
|
||||
Path relativePath = Paths.get("quotes", session.getId().toString(), storedFilename);
|
||||
|
||||
// Save file
|
||||
storageService.store(file, relativePath);
|
||||
|
||||
// Resolve absolute path for slicing and storage usage
|
||||
Path persistentPath = storageService.loadAsResource(relativePath).getFile().toPath();
|
||||
|
||||
com.printcalculator.model.StlShiftResult shift = null;
|
||||
try {
|
||||
// Apply Basic/Advanced Logic
|
||||
applyPrintSettings(settings);
|
||||
|
||||
// REAL SLICING
|
||||
// 1. Pick Machine (default to first active or specific)
|
||||
PrinterMachine machine = machineRepo.findFirstByIsActiveTrue()
|
||||
.orElseThrow(() -> new RuntimeException("No active printer found"));
|
||||
|
||||
// 2. Validate model size against machine volume
|
||||
StlBounds bounds = validateModelSize(persistentPath.toFile(), machine);
|
||||
|
||||
// 2b. Auto-center if needed (keeps the stored STL unchanged)
|
||||
shift = stlService.shiftToFitIfNeeded(
|
||||
persistentPath.toFile(),
|
||||
bounds,
|
||||
machine.getBuildVolumeXMm(),
|
||||
machine.getBuildVolumeYMm(),
|
||||
machine.getBuildVolumeZMm()
|
||||
);
|
||||
java.io.File sliceInput = shift.shifted() ? shift.shiftedPath().toFile() : persistentPath.toFile();
|
||||
if (shift.shifted()) {
|
||||
logger.info(String.format("Auto-centered STL by offset (mm): x=%.3f y=%.3f z=%.3f",
|
||||
shift.offsetX(), shift.offsetY(), shift.offsetZ()));
|
||||
}
|
||||
|
||||
// 3. Pick Profiles
|
||||
String machineProfile = machine.getSlicerMachineProfile();
|
||||
if (machineProfile == null || machineProfile.isBlank()) {
|
||||
machineProfile = machine.getPrinterDisplayName(); // e.g. "Bambu Lab A1 0.4 nozzle"
|
||||
}
|
||||
if (machineProfile == null || machineProfile.isBlank()) {
|
||||
machineProfile = "bambu_a1"; // final fallback (alias handled in ProfileManager)
|
||||
}
|
||||
machineProfile = profileManager.resolveMachineProfileName(machineProfile, settings.getNozzleDiameter());
|
||||
|
||||
String filamentProfile = "Generic " + (settings.getMaterial() != null ? settings.getMaterial().toUpperCase() : "PLA");
|
||||
// Mapping: "pla_basic" -> "Generic PLA", "petg_basic" -> "Generic PETG"
|
||||
if (settings.getMaterial() != null) {
|
||||
if (settings.getMaterial().toLowerCase().contains("pla")) filamentProfile = "Generic PLA";
|
||||
else if (settings.getMaterial().toLowerCase().contains("petg")) filamentProfile = "Generic PETG";
|
||||
else if (settings.getMaterial().toLowerCase().contains("tpu")) filamentProfile = "Generic TPU";
|
||||
else if (settings.getMaterial().toLowerCase().contains("abs")) filamentProfile = "Generic ABS";
|
||||
|
||||
// Update Session Material
|
||||
session.setMaterialCode(settings.getMaterial());
|
||||
} else {
|
||||
// Fallback if null?
|
||||
session.setMaterialCode("pla_basic");
|
||||
}
|
||||
|
||||
// Update Session Settings for Persistence
|
||||
if (settings.getNozzleDiameter() != null) session.setNozzleDiameterMm(BigDecimal.valueOf(settings.getNozzleDiameter()));
|
||||
if (settings.getLayerHeight() != null) session.setLayerHeightMm(BigDecimal.valueOf(settings.getLayerHeight()));
|
||||
if (settings.getInfillDensity() != null) session.setInfillPercent(settings.getInfillDensity().intValue());
|
||||
if (settings.getInfillPattern() != null) session.setInfillPattern(settings.getInfillPattern());
|
||||
if (settings.getSupportsEnabled() != null) session.setSupportsEnabled(settings.getSupportsEnabled());
|
||||
if (settings.getNotes() != null) session.setNotes(settings.getNotes());
|
||||
|
||||
// Save session updates
|
||||
sessionRepo.save(session);
|
||||
|
||||
String processProfile = "0.20mm Standard @BBL A1";
|
||||
// Mapping quality to process
|
||||
// "standard" -> "0.20mm Standard @BBL A1"
|
||||
// "draft" -> "0.28mm Extra Draft @BBL A1"
|
||||
// "high" -> "0.12mm Fine @BBL A1" (approx names, need to be exact for Orca)
|
||||
// Let's use robust defaults or simple overrides
|
||||
if (settings.getLayerHeight() != null) {
|
||||
if (settings.getLayerHeight() >= 0.28) processProfile = "0.28mm Extra Draft @BBL A1";
|
||||
else if (settings.getLayerHeight() <= 0.12) processProfile = "0.12mm Fine @BBL A1";
|
||||
}
|
||||
|
||||
// Build overrides map from settings
|
||||
// Build overrides map from settings
|
||||
Map<String, String> processOverrides = new HashMap<>();
|
||||
if (settings.getLayerHeight() != null) processOverrides.put("layer_height", String.valueOf(settings.getLayerHeight()));
|
||||
if (settings.getInfillDensity() != null) processOverrides.put("sparse_infill_density", settings.getInfillDensity() + "%");
|
||||
if (settings.getInfillPattern() != null) processOverrides.put("sparse_infill_pattern", settings.getInfillPattern());
|
||||
if (settings.getSupportsEnabled() != null) {
|
||||
processOverrides.put("enable_support", settings.getSupportsEnabled() ? "1" : "0");
|
||||
// If enabled, use a more permissive threshold (45 deg) by default
|
||||
// to avoid expensive supports on things that don't strictly need them
|
||||
if (settings.getSupportsEnabled()) {
|
||||
processOverrides.put("support_threshold_angle", "45");
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, String> machineOverrides = new HashMap<>();
|
||||
if (settings.getNozzleDiameter() != null) {
|
||||
machineOverrides.put("nozzle_diameter", String.valueOf(settings.getNozzleDiameter()));
|
||||
}
|
||||
|
||||
// 4. Slice (Use persistent path)
|
||||
PrintStats stats = slicerService.slice(
|
||||
sliceInput,
|
||||
machineProfile,
|
||||
filamentProfile,
|
||||
processProfile,
|
||||
machineOverrides, // machine overrides
|
||||
processOverrides
|
||||
);
|
||||
|
||||
// 5. Calculate Quote
|
||||
QuoteResult result = quoteCalculator.calculate(stats, machine.getPrinterDisplayName(), filamentProfile);
|
||||
|
||||
// 6. Create Line Item
|
||||
QuoteLineItem item = new QuoteLineItem();
|
||||
item.setQuoteSession(session);
|
||||
item.setOriginalFilename(file.getOriginalFilename());
|
||||
item.setStoredPath(persistentPath.toString()); // SAVE PATH
|
||||
item.setQuantity(1);
|
||||
item.setColorCode(settings.getColor() != null ? settings.getColor() : "#FFFFFF");
|
||||
item.setStatus("READY"); // or CALCULATED
|
||||
|
||||
item.setPrintTimeSeconds((int) stats.getPrintTimeSeconds());
|
||||
item.setMaterialGrams(BigDecimal.valueOf(stats.getFilamentWeightGrams()));
|
||||
item.setUnitPriceChf(BigDecimal.valueOf(result.getTotalPrice()));
|
||||
|
||||
// Store breakdown
|
||||
Map<String, Object> breakdown = new HashMap<>();
|
||||
breakdown.put("machine_cost", result.getTotalPrice() - result.getSetupCost()); // Approximation?
|
||||
// Better: QuoteResult could expose detailed breakdown. For now just storing what we have.
|
||||
breakdown.put("setup_fee", result.getSetupCost());
|
||||
item.setPricingBreakdown(breakdown);
|
||||
|
||||
// Dimensions from STL
|
||||
item.setBoundingBoxXMm(BigDecimal.valueOf(bounds.sizeX()));
|
||||
item.setBoundingBoxYMm(BigDecimal.valueOf(bounds.sizeY()));
|
||||
item.setBoundingBoxZMm(BigDecimal.valueOf(bounds.sizeZ()));
|
||||
|
||||
item.setCreatedAt(OffsetDateTime.now());
|
||||
item.setUpdatedAt(OffsetDateTime.now());
|
||||
|
||||
return lineItemRepo.save(item);
|
||||
|
||||
} catch (Exception e) {
|
||||
// Cleanup if failed
|
||||
try {
|
||||
storageService.delete(Paths.get("quotes", session.getId().toString(), storedFilename));
|
||||
} catch (Exception ignored) {}
|
||||
throw e;
|
||||
} finally {
|
||||
if (shift != null && shift.shifted()) {
|
||||
try {
|
||||
Files.deleteIfExists(shift.shiftedPath());
|
||||
} catch (Exception ignored) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private StlBounds validateModelSize(java.io.File stlFile, PrinterMachine machine) throws IOException {
|
||||
StlBounds bounds = stlService.readBounds(stlFile);
|
||||
double x = bounds.sizeX();
|
||||
double y = bounds.sizeY();
|
||||
double z = bounds.sizeZ();
|
||||
|
||||
int bx = machine.getBuildVolumeXMm();
|
||||
int by = machine.getBuildVolumeYMm();
|
||||
int bz = machine.getBuildVolumeZMm();
|
||||
|
||||
logger.info(String.format(
|
||||
"STL bounds (mm): min(%.3f,%.3f,%.3f) max(%.3f,%.3f,%.3f) size(%.3f,%.3f,%.3f) bed(%d,%d,%d)",
|
||||
bounds.minX(), bounds.minY(), bounds.minZ(),
|
||||
bounds.maxX(), bounds.maxY(), bounds.maxZ(),
|
||||
x, y, z, bx, by, bz
|
||||
));
|
||||
|
||||
double eps = 0.01;
|
||||
boolean fits = (x <= bx + eps && y <= by + eps && z <= bz + eps)
|
||||
|| (y <= bx + eps && x <= by + eps && z <= bz + eps);
|
||||
|
||||
if (!fits) {
|
||||
throw new ModelTooLargeException(x, y, z, bx, by, bz);
|
||||
}
|
||||
return bounds;
|
||||
}
|
||||
|
||||
private void applyPrintSettings(com.printcalculator.dto.PrintSettingsDto settings) {
|
||||
if ("BASIC".equalsIgnoreCase(settings.getComplexityMode())) {
|
||||
// Set defaults based on Quality
|
||||
String quality = settings.getQuality() != null ? settings.getQuality().toLowerCase() : "standard";
|
||||
|
||||
switch (quality) {
|
||||
case "draft":
|
||||
settings.setLayerHeight(0.28);
|
||||
settings.setInfillDensity(15.0);
|
||||
settings.setInfillPattern("grid");
|
||||
if (settings.getNozzleDiameter() == null) settings.setNozzleDiameter(0.4);
|
||||
break;
|
||||
case "high":
|
||||
settings.setLayerHeight(0.12);
|
||||
settings.setInfillDensity(20.0);
|
||||
settings.setInfillPattern("gyroid");
|
||||
if (settings.getNozzleDiameter() == null) settings.setNozzleDiameter(0.4);
|
||||
break;
|
||||
case "standard":
|
||||
default:
|
||||
settings.setLayerHeight(0.20);
|
||||
settings.setInfillDensity(20.0);
|
||||
settings.setInfillPattern("grid");
|
||||
if (settings.getNozzleDiameter() == null) settings.setNozzleDiameter(0.4);
|
||||
break;
|
||||
}
|
||||
if (settings.getSupportsEnabled() == null) settings.setSupportsEnabled(false);
|
||||
} else {
|
||||
// ADVANCED Mode: Use values from Frontend, set defaults if missing
|
||||
if (settings.getLayerHeight() == null) settings.setLayerHeight(0.20);
|
||||
if (settings.getInfillDensity() == null) settings.setInfillDensity(20.0);
|
||||
if (settings.getInfillPattern() == null) settings.setInfillPattern("grid");
|
||||
if (settings.getNozzleDiameter() == null) settings.setNozzleDiameter(0.4);
|
||||
if (settings.getSupportsEnabled() == null) settings.setSupportsEnabled(false);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Update Line Item
|
||||
@PatchMapping("/line-items/{lineItemId}")
|
||||
@Transactional
|
||||
public ResponseEntity<QuoteLineItem> updateLineItem(
|
||||
@PathVariable UUID lineItemId,
|
||||
@RequestBody Map<String, Object> updates
|
||||
) {
|
||||
QuoteLineItem item = lineItemRepo.findById(lineItemId)
|
||||
.orElseThrow(() -> new RuntimeException("Item not found"));
|
||||
|
||||
if (updates.containsKey("quantity")) {
|
||||
item.setQuantity((Integer) updates.get("quantity"));
|
||||
}
|
||||
if (updates.containsKey("color_code")) {
|
||||
item.setColorCode((String) updates.get("color_code"));
|
||||
}
|
||||
|
||||
// Recalculate price if needed?
|
||||
// For now, unit price is fixed in mock. Total is calculated on GET.
|
||||
|
||||
item.setUpdatedAt(OffsetDateTime.now());
|
||||
return ResponseEntity.ok(lineItemRepo.save(item));
|
||||
}
|
||||
|
||||
// 4. Delete Line Item
|
||||
@DeleteMapping("/{sessionId}/line-items/{lineItemId}")
|
||||
@Transactional
|
||||
public ResponseEntity<Void> deleteLineItem(
|
||||
@PathVariable UUID sessionId,
|
||||
@PathVariable UUID lineItemId
|
||||
) {
|
||||
// Verify item belongs to session?
|
||||
QuoteLineItem item = lineItemRepo.findById(lineItemId)
|
||||
.orElseThrow(() -> new RuntimeException("Item not found"));
|
||||
|
||||
if (!item.getQuoteSession().getId().equals(sessionId)) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
lineItemRepo.delete(item);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
// 5. Get Session (Session + Items + Total)
|
||||
@GetMapping("/{id}")
|
||||
public ResponseEntity<Map<String, Object>> getQuoteSession(@PathVariable UUID id) {
|
||||
QuoteSession session = sessionRepo.findById(id)
|
||||
.orElseThrow(() -> new RuntimeException("Session not found"));
|
||||
|
||||
List<QuoteLineItem> items = lineItemRepo.findByQuoteSessionId(id);
|
||||
|
||||
// Calculate Totals
|
||||
BigDecimal itemsTotal = BigDecimal.ZERO;
|
||||
for (QuoteLineItem item : items) {
|
||||
BigDecimal lineTotal = item.getUnitPriceChf().multiply(BigDecimal.valueOf(item.getQuantity()));
|
||||
itemsTotal = itemsTotal.add(lineTotal);
|
||||
}
|
||||
|
||||
BigDecimal setupFee = session.getSetupCostChf() != null ? session.getSetupCostChf() : BigDecimal.ZERO;
|
||||
BigDecimal grandTotal = itemsTotal.add(setupFee);
|
||||
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
response.put("session", session);
|
||||
response.put("items", items);
|
||||
response.put("itemsTotalChf", itemsTotal);
|
||||
response.put("grandTotalChf", grandTotal);
|
||||
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
|
||||
// 6. Download Line Item Content
|
||||
@GetMapping(value = "/{sessionId}/line-items/{lineItemId}/content")
|
||||
public ResponseEntity<org.springframework.core.io.Resource> downloadLineItemContent(
|
||||
@PathVariable UUID sessionId,
|
||||
@PathVariable UUID lineItemId
|
||||
) throws IOException {
|
||||
QuoteLineItem item = lineItemRepo.findById(lineItemId)
|
||||
.orElseThrow(() -> new RuntimeException("Item not found"));
|
||||
|
||||
if (!item.getQuoteSession().getId().equals(sessionId)) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
if (item.getStoredPath() == null) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
|
||||
Path path = Paths.get(item.getStoredPath());
|
||||
// Since storedPath is absolute, we can't directly use loadAsResource with it unless we resolve relative.
|
||||
// But loadAsResource expects relative path?
|
||||
// Actually FileSystemStorageService.loadAsResource uses rootLocation.resolve(path).
|
||||
// If path is absolute, resolve might fail or behave weirdly.
|
||||
// But wait, we stored absolute path in DB: item.setStoredPath(persistentPath.toString());
|
||||
// If we want to use storageService.loadAsResource, we need the relative path.
|
||||
// Or we just access the file directly if we trust the absolute path.
|
||||
// But we want to use StorageService abstraction.
|
||||
|
||||
// Option 1: Reconstruct relative path.
|
||||
// We know structure: quotes/{sessionId}/{filename}...
|
||||
// But filename is UUID+ext. We don't have storedFilename in QuoteLineItem easily?
|
||||
// QuoteLineItem doesn't seem to have storedFilename field, only storedPath.
|
||||
|
||||
// If we trust the file is on disk, we can use UrlResource directly here as before,
|
||||
// relying on the fact that storedPath is the absolute path to the file.
|
||||
// But we should verify it exists.
|
||||
|
||||
if (!Files.exists(path)) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
|
||||
org.springframework.core.io.Resource resource = new org.springframework.core.io.UrlResource(path.toUri());
|
||||
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.APPLICATION_OCTET_STREAM)
|
||||
.header(org.springframework.http.HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + item.getOriginalFilename() + "\"")
|
||||
.body(resource);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.printcalculator.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class AddressDto {
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
private String companyName;
|
||||
private String contactPerson;
|
||||
private String addressLine1;
|
||||
private String addressLine2;
|
||||
private String zip;
|
||||
private String city;
|
||||
private String countryCode;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.printcalculator.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class CreateOrderRequest {
|
||||
private CustomerDto customer;
|
||||
private AddressDto billingAddress;
|
||||
private AddressDto shippingAddress;
|
||||
private boolean shippingSameAsBilling;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.printcalculator.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class CustomerDto {
|
||||
private String email;
|
||||
private String phone;
|
||||
private String customerType; // "PRIVATE", "BUSINESS"
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.printcalculator.dto;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record OptionsResponse(
|
||||
List<MaterialOption> materials,
|
||||
List<QualityOption> qualities,
|
||||
List<InfillPatternOption> infillPatterns,
|
||||
List<LayerHeightOptionDTO> layerHeights,
|
||||
List<NozzleOptionDTO> nozzleDiameters
|
||||
) {
|
||||
public record MaterialOption(String code, String label, List<VariantOption> variants) {}
|
||||
public record VariantOption(String name, String colorName, String hexColor, boolean isOutOfStock) {}
|
||||
public record QualityOption(String id, String label) {}
|
||||
public record InfillPatternOption(String id, String label) {}
|
||||
public record LayerHeightOptionDTO(double value, String label) {}
|
||||
public record NozzleOptionDTO(double value, String label) {}
|
||||
}
|
||||
74
backend/src/main/java/com/printcalculator/dto/OrderDto.java
Normal file
74
backend/src/main/java/com/printcalculator/dto/OrderDto.java
Normal file
@@ -0,0 +1,74 @@
|
||||
package com.printcalculator.dto;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public class OrderDto {
|
||||
private UUID id;
|
||||
private String status;
|
||||
private String customerEmail;
|
||||
private String customerPhone;
|
||||
private String billingCustomerType;
|
||||
private AddressDto billingAddress;
|
||||
private AddressDto shippingAddress;
|
||||
private Boolean shippingSameAsBilling;
|
||||
private String currency;
|
||||
private BigDecimal setupCostChf;
|
||||
private BigDecimal shippingCostChf;
|
||||
private BigDecimal discountChf;
|
||||
private BigDecimal subtotalChf;
|
||||
private BigDecimal totalChf;
|
||||
private OffsetDateTime createdAt;
|
||||
private List<OrderItemDto> items;
|
||||
|
||||
// Getters and Setters
|
||||
public UUID getId() { return id; }
|
||||
public void setId(UUID id) { this.id = id; }
|
||||
|
||||
public String getStatus() { return status; }
|
||||
public void setStatus(String status) { this.status = status; }
|
||||
|
||||
public String getCustomerEmail() { return customerEmail; }
|
||||
public void setCustomerEmail(String customerEmail) { this.customerEmail = customerEmail; }
|
||||
|
||||
public String getCustomerPhone() { return customerPhone; }
|
||||
public void setCustomerPhone(String customerPhone) { this.customerPhone = customerPhone; }
|
||||
|
||||
public String getBillingCustomerType() { return billingCustomerType; }
|
||||
public void setBillingCustomerType(String billingCustomerType) { this.billingCustomerType = billingCustomerType; }
|
||||
|
||||
public AddressDto getBillingAddress() { return billingAddress; }
|
||||
public void setBillingAddress(AddressDto billingAddress) { this.billingAddress = billingAddress; }
|
||||
|
||||
public AddressDto getShippingAddress() { return shippingAddress; }
|
||||
public void setShippingAddress(AddressDto shippingAddress) { this.shippingAddress = shippingAddress; }
|
||||
|
||||
public Boolean getShippingSameAsBilling() { return shippingSameAsBilling; }
|
||||
public void setShippingSameAsBilling(Boolean shippingSameAsBilling) { this.shippingSameAsBilling = shippingSameAsBilling; }
|
||||
|
||||
public String getCurrency() { return currency; }
|
||||
public void setCurrency(String currency) { this.currency = currency; }
|
||||
|
||||
public BigDecimal getSetupCostChf() { return setupCostChf; }
|
||||
public void setSetupCostChf(BigDecimal setupCostChf) { this.setupCostChf = setupCostChf; }
|
||||
|
||||
public BigDecimal getShippingCostChf() { return shippingCostChf; }
|
||||
public void setShippingCostChf(BigDecimal shippingCostChf) { this.shippingCostChf = shippingCostChf; }
|
||||
|
||||
public BigDecimal getDiscountChf() { return discountChf; }
|
||||
public void setDiscountChf(BigDecimal discountChf) { this.discountChf = discountChf; }
|
||||
|
||||
public BigDecimal getSubtotalChf() { return subtotalChf; }
|
||||
public void setSubtotalChf(BigDecimal subtotalChf) { this.subtotalChf = subtotalChf; }
|
||||
|
||||
public BigDecimal getTotalChf() { return totalChf; }
|
||||
public void setTotalChf(BigDecimal totalChf) { this.totalChf = totalChf; }
|
||||
|
||||
public OffsetDateTime getCreatedAt() { return createdAt; }
|
||||
public void setCreatedAt(OffsetDateTime createdAt) { this.createdAt = createdAt; }
|
||||
|
||||
public List<OrderItemDto> getItems() { return items; }
|
||||
public void setItems(List<OrderItemDto> items) { this.items = items; }
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.printcalculator.dto;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.UUID;
|
||||
|
||||
public class OrderItemDto {
|
||||
private UUID id;
|
||||
private String originalFilename;
|
||||
private String materialCode;
|
||||
private String colorCode;
|
||||
private Integer quantity;
|
||||
private Integer printTimeSeconds;
|
||||
private BigDecimal materialGrams;
|
||||
private BigDecimal unitPriceChf;
|
||||
private BigDecimal lineTotalChf;
|
||||
|
||||
// Getters and Setters
|
||||
public UUID getId() { return id; }
|
||||
public void setId(UUID id) { this.id = id; }
|
||||
|
||||
public String getOriginalFilename() { return originalFilename; }
|
||||
public void setOriginalFilename(String originalFilename) { this.originalFilename = originalFilename; }
|
||||
|
||||
public String getMaterialCode() { return materialCode; }
|
||||
public void setMaterialCode(String materialCode) { this.materialCode = materialCode; }
|
||||
|
||||
public String getColorCode() { return colorCode; }
|
||||
public void setColorCode(String colorCode) { this.colorCode = colorCode; }
|
||||
|
||||
public Integer getQuantity() { return quantity; }
|
||||
public void setQuantity(Integer quantity) { this.quantity = quantity; }
|
||||
|
||||
public Integer getPrintTimeSeconds() { return printTimeSeconds; }
|
||||
public void setPrintTimeSeconds(Integer printTimeSeconds) { this.printTimeSeconds = printTimeSeconds; }
|
||||
|
||||
public BigDecimal getMaterialGrams() { return materialGrams; }
|
||||
public void setMaterialGrams(BigDecimal materialGrams) { this.materialGrams = materialGrams; }
|
||||
|
||||
public BigDecimal getUnitPriceChf() { return unitPriceChf; }
|
||||
public void setUnitPriceChf(BigDecimal unitPriceChf) { this.unitPriceChf = unitPriceChf; }
|
||||
|
||||
public BigDecimal getLineTotalChf() { return lineTotalChf; }
|
||||
public void setLineTotalChf(BigDecimal lineTotalChf) { this.lineTotalChf = lineTotalChf; }
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.printcalculator.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class PrintSettingsDto {
|
||||
// Mode: "BASIC" or "ADVANCED"
|
||||
private String complexityMode;
|
||||
|
||||
// Common
|
||||
private String material; // e.g. "PLA", "PETG"
|
||||
private String color; // e.g. "White", "#FFFFFF"
|
||||
|
||||
// Basic Mode
|
||||
private String quality; // "draft", "standard", "high"
|
||||
|
||||
// Advanced Mode (Optional in Basic)
|
||||
private Double layerHeight;
|
||||
private Double infillDensity;
|
||||
private String infillPattern;
|
||||
private Boolean supportsEnabled = true;
|
||||
private Double nozzleDiameter;
|
||||
private String notes;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.printcalculator.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class QuoteRequestDto {
|
||||
private String requestType; // "PRINT_SERVICE" or "DESIGN_SERVICE"
|
||||
private String customerType; // "PRIVATE" or "BUSINESS"
|
||||
private String email;
|
||||
private String phone;
|
||||
private String name;
|
||||
private String companyName;
|
||||
private String contactPerson;
|
||||
private String message;
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package com.printcalculator.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import org.hibernate.annotations.ColumnDefault;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "custom_quote_requests", indexes = {@Index(name = "ix_custom_quote_requests_status",
|
||||
columnList = "status")})
|
||||
public class CustomQuoteRequest {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
@Column(name = "request_id", nullable = false)
|
||||
private UUID id;
|
||||
|
||||
@Column(name = "request_type", nullable = false, length = Integer.MAX_VALUE)
|
||||
private String requestType;
|
||||
|
||||
@Column(name = "customer_type", nullable = false, length = Integer.MAX_VALUE)
|
||||
private String customerType;
|
||||
|
||||
@Column(name = "email", nullable = false, length = Integer.MAX_VALUE)
|
||||
private String email;
|
||||
|
||||
@Column(name = "phone", length = Integer.MAX_VALUE)
|
||||
private String phone;
|
||||
|
||||
@Column(name = "name", length = Integer.MAX_VALUE)
|
||||
private String name;
|
||||
|
||||
@Column(name = "company_name", length = Integer.MAX_VALUE)
|
||||
private String companyName;
|
||||
|
||||
@Column(name = "contact_person", length = Integer.MAX_VALUE)
|
||||
private String contactPerson;
|
||||
|
||||
@Column(name = "message", nullable = false, length = Integer.MAX_VALUE)
|
||||
private String message;
|
||||
|
||||
@Column(name = "status", nullable = false, length = Integer.MAX_VALUE)
|
||||
private String status;
|
||||
|
||||
@ColumnDefault("now()")
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private OffsetDateTime createdAt;
|
||||
|
||||
@ColumnDefault("now()")
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
private OffsetDateTime updatedAt;
|
||||
|
||||
public UUID getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(UUID id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getRequestType() {
|
||||
return requestType;
|
||||
}
|
||||
|
||||
public void setRequestType(String requestType) {
|
||||
this.requestType = requestType;
|
||||
}
|
||||
|
||||
public String getCustomerType() {
|
||||
return customerType;
|
||||
}
|
||||
|
||||
public void setCustomerType(String customerType) {
|
||||
this.customerType = customerType;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getPhone() {
|
||||
return phone;
|
||||
}
|
||||
|
||||
public void setPhone(String phone) {
|
||||
this.phone = phone;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getCompanyName() {
|
||||
return companyName;
|
||||
}
|
||||
|
||||
public void setCompanyName(String companyName) {
|
||||
this.companyName = companyName;
|
||||
}
|
||||
|
||||
public String getContactPerson() {
|
||||
return contactPerson;
|
||||
}
|
||||
|
||||
public void setContactPerson(String contactPerson) {
|
||||
this.contactPerson = contactPerson;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package com.printcalculator.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import org.hibernate.annotations.ColumnDefault;
|
||||
import org.hibernate.annotations.OnDelete;
|
||||
import org.hibernate.annotations.OnDeleteAction;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "custom_quote_request_attachments", indexes = {@Index(name = "ix_custom_quote_attachments_request",
|
||||
columnList = "request_id")})
|
||||
public class CustomQuoteRequestAttachment {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
@Column(name = "attachment_id", nullable = false)
|
||||
private UUID id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||
@OnDelete(action = OnDeleteAction.CASCADE)
|
||||
@JoinColumn(name = "request_id", nullable = false)
|
||||
private CustomQuoteRequest request;
|
||||
|
||||
@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;
|
||||
|
||||
@ColumnDefault("now()")
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private OffsetDateTime createdAt;
|
||||
|
||||
public UUID getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(UUID id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public CustomQuoteRequest getRequest() {
|
||||
return request;
|
||||
}
|
||||
|
||||
public void setRequest(CustomQuoteRequest request) {
|
||||
this.request = request;
|
||||
}
|
||||
|
||||
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 OffsetDateTime getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(OffsetDateTime createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
public void setCustomQuoteRequest(CustomQuoteRequest request) {
|
||||
}
|
||||
}
|
||||
126
backend/src/main/java/com/printcalculator/entity/Customer.java
Normal file
126
backend/src/main/java/com/printcalculator/entity/Customer.java
Normal file
@@ -0,0 +1,126 @@
|
||||
package com.printcalculator.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import org.hibernate.annotations.ColumnDefault;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "customers")
|
||||
public class Customer {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
@Column(name = "customer_id", nullable = false)
|
||||
private UUID id;
|
||||
|
||||
@Column(name = "customer_type", nullable = false, length = Integer.MAX_VALUE)
|
||||
private String customerType;
|
||||
|
||||
@Column(name = "email", nullable = false, length = Integer.MAX_VALUE)
|
||||
private String email;
|
||||
|
||||
@Column(name = "phone", length = Integer.MAX_VALUE)
|
||||
private String phone;
|
||||
|
||||
@Column(name = "first_name", length = Integer.MAX_VALUE)
|
||||
private String firstName;
|
||||
|
||||
@Column(name = "last_name", length = Integer.MAX_VALUE)
|
||||
private String lastName;
|
||||
|
||||
@Column(name = "company_name", length = Integer.MAX_VALUE)
|
||||
private String companyName;
|
||||
|
||||
@Column(name = "contact_person", length = Integer.MAX_VALUE)
|
||||
private String contactPerson;
|
||||
|
||||
@ColumnDefault("now()")
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private OffsetDateTime createdAt;
|
||||
|
||||
@ColumnDefault("now()")
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
private OffsetDateTime updatedAt;
|
||||
|
||||
public UUID getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(UUID id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getCustomerType() {
|
||||
return customerType;
|
||||
}
|
||||
|
||||
public void setCustomerType(String customerType) {
|
||||
this.customerType = customerType;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getPhone() {
|
||||
return phone;
|
||||
}
|
||||
|
||||
public void setPhone(String phone) {
|
||||
this.phone = phone;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public String getCompanyName() {
|
||||
return companyName;
|
||||
}
|
||||
|
||||
public void setCompanyName(String companyName) {
|
||||
this.companyName = companyName;
|
||||
}
|
||||
|
||||
public String getContactPerson() {
|
||||
return contactPerson;
|
||||
}
|
||||
|
||||
public void setContactPerson(String contactPerson) {
|
||||
this.contactPerson = contactPerson;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.printcalculator.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import org.hibernate.annotations.ColumnDefault;
|
||||
|
||||
@Entity
|
||||
@Table(name = "filament_material_type")
|
||||
public class FilamentMaterialType {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "filament_material_type_id", nullable = false)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "material_code", nullable = false, length = Integer.MAX_VALUE)
|
||||
private String materialCode;
|
||||
|
||||
@ColumnDefault("false")
|
||||
@Column(name = "is_flexible", nullable = false)
|
||||
private Boolean isFlexible;
|
||||
|
||||
@ColumnDefault("false")
|
||||
@Column(name = "is_technical", nullable = false)
|
||||
private Boolean isTechnical;
|
||||
|
||||
@Column(name = "technical_type_label", length = Integer.MAX_VALUE)
|
||||
private String technicalTypeLabel;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getMaterialCode() {
|
||||
return materialCode;
|
||||
}
|
||||
|
||||
public void setMaterialCode(String materialCode) {
|
||||
this.materialCode = materialCode;
|
||||
}
|
||||
|
||||
public Boolean getIsFlexible() {
|
||||
return isFlexible;
|
||||
}
|
||||
|
||||
public void setIsFlexible(Boolean isFlexible) {
|
||||
this.isFlexible = isFlexible;
|
||||
}
|
||||
|
||||
public Boolean getIsTechnical() {
|
||||
return isTechnical;
|
||||
}
|
||||
|
||||
public void setIsTechnical(Boolean isTechnical) {
|
||||
this.isTechnical = isTechnical;
|
||||
}
|
||||
|
||||
public String getTechnicalTypeLabel() {
|
||||
return technicalTypeLabel;
|
||||
}
|
||||
|
||||
public void setTechnicalTypeLabel(String technicalTypeLabel) {
|
||||
this.technicalTypeLabel = technicalTypeLabel;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package com.printcalculator.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import org.hibernate.annotations.ColumnDefault;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.OffsetDateTime;
|
||||
|
||||
@Entity
|
||||
@Table(name = "filament_variant")
|
||||
public class FilamentVariant {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "filament_variant_id", nullable = false)
|
||||
private Long id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||
@JoinColumn(name = "filament_material_type_id", nullable = false)
|
||||
private FilamentMaterialType filamentMaterialType;
|
||||
|
||||
@Column(name = "variant_display_name", nullable = false, length = Integer.MAX_VALUE)
|
||||
private String variantDisplayName;
|
||||
|
||||
@Column(name = "color_name", nullable = false, length = Integer.MAX_VALUE)
|
||||
private String colorName;
|
||||
|
||||
@ColumnDefault("false")
|
||||
@Column(name = "is_matte", nullable = false)
|
||||
private Boolean isMatte;
|
||||
|
||||
@ColumnDefault("false")
|
||||
@Column(name = "is_special", nullable = false)
|
||||
private Boolean isSpecial;
|
||||
|
||||
@Column(name = "cost_chf_per_kg", nullable = false, precision = 10, scale = 2)
|
||||
private BigDecimal costChfPerKg;
|
||||
|
||||
@ColumnDefault("0.000")
|
||||
@Column(name = "stock_spools", nullable = false, precision = 6, scale = 3)
|
||||
private BigDecimal stockSpools;
|
||||
|
||||
@ColumnDefault("1.000")
|
||||
@Column(name = "spool_net_kg", nullable = false, precision = 6, scale = 3)
|
||||
private BigDecimal spoolNetKg;
|
||||
|
||||
@ColumnDefault("true")
|
||||
@Column(name = "is_active", nullable = false)
|
||||
private Boolean isActive;
|
||||
|
||||
@ColumnDefault("now()")
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private OffsetDateTime createdAt;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public FilamentMaterialType getFilamentMaterialType() {
|
||||
return filamentMaterialType;
|
||||
}
|
||||
|
||||
public void setFilamentMaterialType(FilamentMaterialType filamentMaterialType) {
|
||||
this.filamentMaterialType = filamentMaterialType;
|
||||
}
|
||||
|
||||
public String getVariantDisplayName() {
|
||||
return variantDisplayName;
|
||||
}
|
||||
|
||||
public void setVariantDisplayName(String variantDisplayName) {
|
||||
this.variantDisplayName = variantDisplayName;
|
||||
}
|
||||
|
||||
public String getColorName() {
|
||||
return colorName;
|
||||
}
|
||||
|
||||
public void setColorName(String colorName) {
|
||||
this.colorName = colorName;
|
||||
}
|
||||
|
||||
public Boolean getIsMatte() {
|
||||
return isMatte;
|
||||
}
|
||||
|
||||
public void setIsMatte(Boolean isMatte) {
|
||||
this.isMatte = isMatte;
|
||||
}
|
||||
|
||||
public Boolean getIsSpecial() {
|
||||
return isSpecial;
|
||||
}
|
||||
|
||||
public void setIsSpecial(Boolean isSpecial) {
|
||||
this.isSpecial = isSpecial;
|
||||
}
|
||||
|
||||
public BigDecimal getCostChfPerKg() {
|
||||
return costChfPerKg;
|
||||
}
|
||||
|
||||
public void setCostChfPerKg(BigDecimal costChfPerKg) {
|
||||
this.costChfPerKg = costChfPerKg;
|
||||
}
|
||||
|
||||
public BigDecimal getStockSpools() {
|
||||
return stockSpools;
|
||||
}
|
||||
|
||||
public void setStockSpools(BigDecimal stockSpools) {
|
||||
this.stockSpools = stockSpools;
|
||||
}
|
||||
|
||||
public BigDecimal getSpoolNetKg() {
|
||||
return spoolNetKg;
|
||||
}
|
||||
|
||||
public void setSpoolNetKg(BigDecimal spoolNetKg) {
|
||||
this.spoolNetKg = spoolNetKg;
|
||||
}
|
||||
|
||||
public Boolean getIsActive() {
|
||||
return isActive;
|
||||
}
|
||||
|
||||
public void setIsActive(Boolean isActive) {
|
||||
this.isActive = isActive;
|
||||
}
|
||||
|
||||
public OffsetDateTime getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(OffsetDateTime createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.printcalculator.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
import org.hibernate.annotations.Immutable;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
@Entity
|
||||
@Immutable
|
||||
@Table(name = "filament_variant_stock_kg")
|
||||
public class FilamentVariantStockKg {
|
||||
@Id
|
||||
@Column(name = "filament_variant_id")
|
||||
private Long filamentVariantId;
|
||||
|
||||
@Column(name = "stock_spools", precision = 6, scale = 3)
|
||||
private BigDecimal stockSpools;
|
||||
|
||||
@Column(name = "spool_net_kg", precision = 6, scale = 3)
|
||||
private BigDecimal spoolNetKg;
|
||||
|
||||
@Column(name = "stock_kg")
|
||||
private BigDecimal stockKg;
|
||||
|
||||
public Long getFilamentVariantId() {
|
||||
return filamentVariantId;
|
||||
}
|
||||
|
||||
public BigDecimal getStockSpools() {
|
||||
return stockSpools;
|
||||
}
|
||||
|
||||
public BigDecimal getSpoolNetKg() {
|
||||
return spoolNetKg;
|
||||
}
|
||||
|
||||
public BigDecimal getStockKg() {
|
||||
return stockKg;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.printcalculator.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import org.hibernate.annotations.ColumnDefault;
|
||||
|
||||
@Entity
|
||||
@Table(name = "infill_pattern")
|
||||
public class InfillPattern {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "infill_pattern_id", nullable = false)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "pattern_code", nullable = false, length = Integer.MAX_VALUE)
|
||||
private String patternCode;
|
||||
|
||||
@Column(name = "display_name", nullable = false, length = Integer.MAX_VALUE)
|
||||
private String displayName;
|
||||
|
||||
@ColumnDefault("true")
|
||||
@Column(name = "is_active", nullable = false)
|
||||
private Boolean isActive;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getPatternCode() {
|
||||
return patternCode;
|
||||
}
|
||||
|
||||
public void setPatternCode(String patternCode) {
|
||||
this.patternCode = patternCode;
|
||||
}
|
||||
|
||||
public String getDisplayName() {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
public void setDisplayName(String displayName) {
|
||||
this.displayName = displayName;
|
||||
}
|
||||
|
||||
public Boolean getIsActive() {
|
||||
return isActive;
|
||||
}
|
||||
|
||||
public void setIsActive(Boolean isActive) {
|
||||
this.isActive = isActive;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.printcalculator.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import org.hibernate.annotations.ColumnDefault;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
@Entity
|
||||
@Table(name = "layer_height_option")
|
||||
public class LayerHeightOption {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "layer_height_option_id", nullable = false)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "layer_height_mm", nullable = false, precision = 5, scale = 3)
|
||||
private BigDecimal layerHeightMm;
|
||||
|
||||
@ColumnDefault("1.000")
|
||||
@Column(name = "time_multiplier", nullable = false, precision = 6, scale = 3)
|
||||
private BigDecimal timeMultiplier;
|
||||
|
||||
@ColumnDefault("true")
|
||||
@Column(name = "is_active", nullable = false)
|
||||
private Boolean isActive;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public BigDecimal getLayerHeightMm() {
|
||||
return layerHeightMm;
|
||||
}
|
||||
|
||||
public void setLayerHeightMm(BigDecimal layerHeightMm) {
|
||||
this.layerHeightMm = layerHeightMm;
|
||||
}
|
||||
|
||||
public BigDecimal getTimeMultiplier() {
|
||||
return timeMultiplier;
|
||||
}
|
||||
|
||||
public void setTimeMultiplier(BigDecimal timeMultiplier) {
|
||||
this.timeMultiplier = timeMultiplier;
|
||||
}
|
||||
|
||||
public Boolean getIsActive() {
|
||||
return isActive;
|
||||
}
|
||||
|
||||
public void setIsActive(Boolean isActive) {
|
||||
this.isActive = isActive;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.printcalculator.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import org.hibernate.annotations.ColumnDefault;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
@Entity
|
||||
@Table(name = "layer_height_profile")
|
||||
public class LayerHeightProfile {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "layer_height_profile_id", nullable = false)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "profile_name", nullable = false, length = Integer.MAX_VALUE)
|
||||
private String profileName;
|
||||
|
||||
@Column(name = "min_layer_height_mm", nullable = false, precision = 5, scale = 3)
|
||||
private BigDecimal minLayerHeightMm;
|
||||
|
||||
@Column(name = "max_layer_height_mm", nullable = false, precision = 5, scale = 3)
|
||||
private BigDecimal maxLayerHeightMm;
|
||||
|
||||
@Column(name = "default_layer_height_mm", nullable = false, precision = 5, scale = 3)
|
||||
private BigDecimal defaultLayerHeightMm;
|
||||
|
||||
@ColumnDefault("1.000")
|
||||
@Column(name = "time_multiplier", nullable = false, precision = 6, scale = 3)
|
||||
private BigDecimal timeMultiplier;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getProfileName() {
|
||||
return profileName;
|
||||
}
|
||||
|
||||
public void setProfileName(String profileName) {
|
||||
this.profileName = profileName;
|
||||
}
|
||||
|
||||
public BigDecimal getMinLayerHeightMm() {
|
||||
return minLayerHeightMm;
|
||||
}
|
||||
|
||||
public void setMinLayerHeightMm(BigDecimal minLayerHeightMm) {
|
||||
this.minLayerHeightMm = minLayerHeightMm;
|
||||
}
|
||||
|
||||
public BigDecimal getMaxLayerHeightMm() {
|
||||
return maxLayerHeightMm;
|
||||
}
|
||||
|
||||
public void setMaxLayerHeightMm(BigDecimal maxLayerHeightMm) {
|
||||
this.maxLayerHeightMm = maxLayerHeightMm;
|
||||
}
|
||||
|
||||
public BigDecimal getDefaultLayerHeightMm() {
|
||||
return defaultLayerHeightMm;
|
||||
}
|
||||
|
||||
public void setDefaultLayerHeightMm(BigDecimal defaultLayerHeightMm) {
|
||||
this.defaultLayerHeightMm = defaultLayerHeightMm;
|
||||
}
|
||||
|
||||
public BigDecimal getTimeMultiplier() {
|
||||
return timeMultiplier;
|
||||
}
|
||||
|
||||
public void setTimeMultiplier(BigDecimal timeMultiplier) {
|
||||
this.timeMultiplier = timeMultiplier;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.printcalculator.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import org.hibernate.annotations.ColumnDefault;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.OffsetDateTime;
|
||||
|
||||
@Entity
|
||||
@Table(name = "nozzle_option")
|
||||
public class NozzleOption {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "nozzle_option_id", nullable = false)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "nozzle_diameter_mm", nullable = false, precision = 4, scale = 2)
|
||||
private BigDecimal nozzleDiameterMm;
|
||||
|
||||
@ColumnDefault("0")
|
||||
@Column(name = "owned_quantity", nullable = false)
|
||||
private Integer ownedQuantity;
|
||||
|
||||
@ColumnDefault("0.00")
|
||||
@Column(name = "extra_nozzle_change_fee_chf", nullable = false, precision = 10, scale = 2)
|
||||
private BigDecimal extraNozzleChangeFeeChf;
|
||||
|
||||
@ColumnDefault("true")
|
||||
@Column(name = "is_active", nullable = false)
|
||||
private Boolean isActive;
|
||||
|
||||
@ColumnDefault("now()")
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private OffsetDateTime createdAt;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public BigDecimal getNozzleDiameterMm() {
|
||||
return nozzleDiameterMm;
|
||||
}
|
||||
|
||||
public void setNozzleDiameterMm(BigDecimal nozzleDiameterMm) {
|
||||
this.nozzleDiameterMm = nozzleDiameterMm;
|
||||
}
|
||||
|
||||
public Integer getOwnedQuantity() {
|
||||
return ownedQuantity;
|
||||
}
|
||||
|
||||
public void setOwnedQuantity(Integer ownedQuantity) {
|
||||
this.ownedQuantity = ownedQuantity;
|
||||
}
|
||||
|
||||
public BigDecimal getExtraNozzleChangeFeeChf() {
|
||||
return extraNozzleChangeFeeChf;
|
||||
}
|
||||
|
||||
public void setExtraNozzleChangeFeeChf(BigDecimal extraNozzleChangeFeeChf) {
|
||||
this.extraNozzleChangeFeeChf = extraNozzleChangeFeeChf;
|
||||
}
|
||||
|
||||
public Boolean getIsActive() {
|
||||
return isActive;
|
||||
}
|
||||
|
||||
public void setIsActive(Boolean isActive) {
|
||||
this.isActive = isActive;
|
||||
}
|
||||
|
||||
public OffsetDateTime getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(OffsetDateTime createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
}
|
||||
414
backend/src/main/java/com/printcalculator/entity/Order.java
Normal file
414
backend/src/main/java/com/printcalculator/entity/Order.java
Normal file
@@ -0,0 +1,414 @@
|
||||
package com.printcalculator.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import org.hibernate.annotations.ColumnDefault;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "orders", indexes = {@Index(name = "ix_orders_status",
|
||||
columnList = "status")})
|
||||
public class Order {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
@Column(name = "order_id", nullable = false)
|
||||
private UUID id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "source_quote_session_id")
|
||||
private QuoteSession sourceQuoteSession;
|
||||
|
||||
@Column(name = "status", nullable = false, length = Integer.MAX_VALUE)
|
||||
private String status;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "customer_id")
|
||||
private Customer customer;
|
||||
|
||||
@Column(name = "customer_email", nullable = false, length = Integer.MAX_VALUE)
|
||||
private String customerEmail;
|
||||
|
||||
@Column(name = "customer_phone", length = Integer.MAX_VALUE)
|
||||
private String customerPhone;
|
||||
|
||||
@Column(name = "billing_customer_type", nullable = false, length = Integer.MAX_VALUE)
|
||||
private String billingCustomerType;
|
||||
|
||||
@Column(name = "billing_first_name", length = Integer.MAX_VALUE)
|
||||
private String billingFirstName;
|
||||
|
||||
@Column(name = "billing_last_name", length = Integer.MAX_VALUE)
|
||||
private String billingLastName;
|
||||
|
||||
@Column(name = "billing_company_name", length = Integer.MAX_VALUE)
|
||||
private String billingCompanyName;
|
||||
|
||||
@Column(name = "billing_contact_person", length = Integer.MAX_VALUE)
|
||||
private String billingContactPerson;
|
||||
|
||||
@Column(name = "billing_address_line1", nullable = false, length = Integer.MAX_VALUE)
|
||||
private String billingAddressLine1;
|
||||
|
||||
@Column(name = "billing_address_line2", length = Integer.MAX_VALUE)
|
||||
private String billingAddressLine2;
|
||||
|
||||
@Column(name = "billing_zip", nullable = false, length = Integer.MAX_VALUE)
|
||||
private String billingZip;
|
||||
|
||||
@Column(name = "billing_city", nullable = false, length = Integer.MAX_VALUE)
|
||||
private String billingCity;
|
||||
|
||||
@ColumnDefault("'CH'")
|
||||
@Column(name = "billing_country_code", nullable = false, length = 2)
|
||||
private String billingCountryCode;
|
||||
|
||||
@ColumnDefault("true")
|
||||
@Column(name = "shipping_same_as_billing", nullable = false)
|
||||
private Boolean shippingSameAsBilling;
|
||||
|
||||
@Column(name = "shipping_first_name", length = Integer.MAX_VALUE)
|
||||
private String shippingFirstName;
|
||||
|
||||
@Column(name = "shipping_last_name", length = Integer.MAX_VALUE)
|
||||
private String shippingLastName;
|
||||
|
||||
@Column(name = "shipping_company_name", length = Integer.MAX_VALUE)
|
||||
private String shippingCompanyName;
|
||||
|
||||
@Column(name = "shipping_contact_person", length = Integer.MAX_VALUE)
|
||||
private String shippingContactPerson;
|
||||
|
||||
@Column(name = "shipping_address_line1", length = Integer.MAX_VALUE)
|
||||
private String shippingAddressLine1;
|
||||
|
||||
@Column(name = "shipping_address_line2", length = Integer.MAX_VALUE)
|
||||
private String shippingAddressLine2;
|
||||
|
||||
@Column(name = "shipping_zip", length = Integer.MAX_VALUE)
|
||||
private String shippingZip;
|
||||
|
||||
@Column(name = "shipping_city", length = Integer.MAX_VALUE)
|
||||
private String shippingCity;
|
||||
|
||||
@Column(name = "shipping_country_code", length = 2)
|
||||
private String shippingCountryCode;
|
||||
|
||||
@ColumnDefault("'CHF'")
|
||||
@Column(name = "currency", nullable = false, length = 3)
|
||||
private String currency;
|
||||
|
||||
@ColumnDefault("0.00")
|
||||
@Column(name = "setup_cost_chf", nullable = false, precision = 12, scale = 2)
|
||||
private BigDecimal setupCostChf;
|
||||
|
||||
@ColumnDefault("0.00")
|
||||
@Column(name = "shipping_cost_chf", nullable = false, precision = 12, scale = 2)
|
||||
private BigDecimal shippingCostChf;
|
||||
|
||||
@ColumnDefault("0.00")
|
||||
@Column(name = "discount_chf", nullable = false, precision = 12, scale = 2)
|
||||
private BigDecimal discountChf;
|
||||
|
||||
@ColumnDefault("0.00")
|
||||
@Column(name = "subtotal_chf", nullable = false, precision = 12, scale = 2)
|
||||
private BigDecimal subtotalChf;
|
||||
|
||||
@ColumnDefault("0.00")
|
||||
@Column(name = "total_chf", nullable = false, precision = 12, scale = 2)
|
||||
private BigDecimal totalChf;
|
||||
|
||||
@ColumnDefault("now()")
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private OffsetDateTime createdAt;
|
||||
|
||||
@ColumnDefault("now()")
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
private OffsetDateTime updatedAt;
|
||||
|
||||
@Column(name = "paid_at")
|
||||
private OffsetDateTime paidAt;
|
||||
|
||||
public UUID getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(UUID id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public QuoteSession getSourceQuoteSession() {
|
||||
return sourceQuoteSession;
|
||||
}
|
||||
|
||||
public void setSourceQuoteSession(QuoteSession sourceQuoteSession) {
|
||||
this.sourceQuoteSession = sourceQuoteSession;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public Customer getCustomer() {
|
||||
return customer;
|
||||
}
|
||||
|
||||
public void setCustomer(Customer customer) {
|
||||
this.customer = customer;
|
||||
}
|
||||
|
||||
public String getCustomerEmail() {
|
||||
return customerEmail;
|
||||
}
|
||||
|
||||
public void setCustomerEmail(String customerEmail) {
|
||||
this.customerEmail = customerEmail;
|
||||
}
|
||||
|
||||
public String getCustomerPhone() {
|
||||
return customerPhone;
|
||||
}
|
||||
|
||||
public void setCustomerPhone(String customerPhone) {
|
||||
this.customerPhone = customerPhone;
|
||||
}
|
||||
|
||||
public String getBillingCustomerType() {
|
||||
return billingCustomerType;
|
||||
}
|
||||
|
||||
public void setBillingCustomerType(String billingCustomerType) {
|
||||
this.billingCustomerType = billingCustomerType;
|
||||
}
|
||||
|
||||
public String getBillingFirstName() {
|
||||
return billingFirstName;
|
||||
}
|
||||
|
||||
public void setBillingFirstName(String billingFirstName) {
|
||||
this.billingFirstName = billingFirstName;
|
||||
}
|
||||
|
||||
public String getBillingLastName() {
|
||||
return billingLastName;
|
||||
}
|
||||
|
||||
public void setBillingLastName(String billingLastName) {
|
||||
this.billingLastName = billingLastName;
|
||||
}
|
||||
|
||||
public String getBillingCompanyName() {
|
||||
return billingCompanyName;
|
||||
}
|
||||
|
||||
public void setBillingCompanyName(String billingCompanyName) {
|
||||
this.billingCompanyName = billingCompanyName;
|
||||
}
|
||||
|
||||
public String getBillingContactPerson() {
|
||||
return billingContactPerson;
|
||||
}
|
||||
|
||||
public void setBillingContactPerson(String billingContactPerson) {
|
||||
this.billingContactPerson = billingContactPerson;
|
||||
}
|
||||
|
||||
public String getBillingAddressLine1() {
|
||||
return billingAddressLine1;
|
||||
}
|
||||
|
||||
public void setBillingAddressLine1(String billingAddressLine1) {
|
||||
this.billingAddressLine1 = billingAddressLine1;
|
||||
}
|
||||
|
||||
public String getBillingAddressLine2() {
|
||||
return billingAddressLine2;
|
||||
}
|
||||
|
||||
public void setBillingAddressLine2(String billingAddressLine2) {
|
||||
this.billingAddressLine2 = billingAddressLine2;
|
||||
}
|
||||
|
||||
public String getBillingZip() {
|
||||
return billingZip;
|
||||
}
|
||||
|
||||
public void setBillingZip(String billingZip) {
|
||||
this.billingZip = billingZip;
|
||||
}
|
||||
|
||||
public String getBillingCity() {
|
||||
return billingCity;
|
||||
}
|
||||
|
||||
public void setBillingCity(String billingCity) {
|
||||
this.billingCity = billingCity;
|
||||
}
|
||||
|
||||
public String getBillingCountryCode() {
|
||||
return billingCountryCode;
|
||||
}
|
||||
|
||||
public void setBillingCountryCode(String billingCountryCode) {
|
||||
this.billingCountryCode = billingCountryCode;
|
||||
}
|
||||
|
||||
public Boolean getShippingSameAsBilling() {
|
||||
return shippingSameAsBilling;
|
||||
}
|
||||
|
||||
public void setShippingSameAsBilling(Boolean shippingSameAsBilling) {
|
||||
this.shippingSameAsBilling = shippingSameAsBilling;
|
||||
}
|
||||
|
||||
public String getShippingFirstName() {
|
||||
return shippingFirstName;
|
||||
}
|
||||
|
||||
public void setShippingFirstName(String shippingFirstName) {
|
||||
this.shippingFirstName = shippingFirstName;
|
||||
}
|
||||
|
||||
public String getShippingLastName() {
|
||||
return shippingLastName;
|
||||
}
|
||||
|
||||
public void setShippingLastName(String shippingLastName) {
|
||||
this.shippingLastName = shippingLastName;
|
||||
}
|
||||
|
||||
public String getShippingCompanyName() {
|
||||
return shippingCompanyName;
|
||||
}
|
||||
|
||||
public void setShippingCompanyName(String shippingCompanyName) {
|
||||
this.shippingCompanyName = shippingCompanyName;
|
||||
}
|
||||
|
||||
public String getShippingContactPerson() {
|
||||
return shippingContactPerson;
|
||||
}
|
||||
|
||||
public void setShippingContactPerson(String shippingContactPerson) {
|
||||
this.shippingContactPerson = shippingContactPerson;
|
||||
}
|
||||
|
||||
public String getShippingAddressLine1() {
|
||||
return shippingAddressLine1;
|
||||
}
|
||||
|
||||
public void setShippingAddressLine1(String shippingAddressLine1) {
|
||||
this.shippingAddressLine1 = shippingAddressLine1;
|
||||
}
|
||||
|
||||
public String getShippingAddressLine2() {
|
||||
return shippingAddressLine2;
|
||||
}
|
||||
|
||||
public void setShippingAddressLine2(String shippingAddressLine2) {
|
||||
this.shippingAddressLine2 = shippingAddressLine2;
|
||||
}
|
||||
|
||||
public String getShippingZip() {
|
||||
return shippingZip;
|
||||
}
|
||||
|
||||
public void setShippingZip(String shippingZip) {
|
||||
this.shippingZip = shippingZip;
|
||||
}
|
||||
|
||||
public String getShippingCity() {
|
||||
return shippingCity;
|
||||
}
|
||||
|
||||
public void setShippingCity(String shippingCity) {
|
||||
this.shippingCity = shippingCity;
|
||||
}
|
||||
|
||||
public String getShippingCountryCode() {
|
||||
return shippingCountryCode;
|
||||
}
|
||||
|
||||
public void setShippingCountryCode(String shippingCountryCode) {
|
||||
this.shippingCountryCode = shippingCountryCode;
|
||||
}
|
||||
|
||||
public String getCurrency() {
|
||||
return currency;
|
||||
}
|
||||
|
||||
public void setCurrency(String currency) {
|
||||
this.currency = currency;
|
||||
}
|
||||
|
||||
public BigDecimal getSetupCostChf() {
|
||||
return setupCostChf;
|
||||
}
|
||||
|
||||
public void setSetupCostChf(BigDecimal setupCostChf) {
|
||||
this.setupCostChf = setupCostChf;
|
||||
}
|
||||
|
||||
public BigDecimal getShippingCostChf() {
|
||||
return shippingCostChf;
|
||||
}
|
||||
|
||||
public void setShippingCostChf(BigDecimal shippingCostChf) {
|
||||
this.shippingCostChf = shippingCostChf;
|
||||
}
|
||||
|
||||
public BigDecimal getDiscountChf() {
|
||||
return discountChf;
|
||||
}
|
||||
|
||||
public void setDiscountChf(BigDecimal discountChf) {
|
||||
this.discountChf = discountChf;
|
||||
}
|
||||
|
||||
public BigDecimal getSubtotalChf() {
|
||||
return subtotalChf;
|
||||
}
|
||||
|
||||
public void setSubtotalChf(BigDecimal subtotalChf) {
|
||||
this.subtotalChf = subtotalChf;
|
||||
}
|
||||
|
||||
public BigDecimal getTotalChf() {
|
||||
return totalChf;
|
||||
}
|
||||
|
||||
public void setTotalChf(BigDecimal totalChf) {
|
||||
this.totalChf = totalChf;
|
||||
}
|
||||
|
||||
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 OffsetDateTime getPaidAt() {
|
||||
return paidAt;
|
||||
}
|
||||
|
||||
public void setPaidAt(OffsetDateTime paidAt) {
|
||||
this.paidAt = paidAt;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
198
backend/src/main/java/com/printcalculator/entity/OrderItem.java
Normal file
198
backend/src/main/java/com/printcalculator/entity/OrderItem.java
Normal file
@@ -0,0 +1,198 @@
|
||||
package com.printcalculator.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import org.hibernate.annotations.ColumnDefault;
|
||||
import org.hibernate.annotations.OnDelete;
|
||||
import org.hibernate.annotations.OnDeleteAction;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "order_items", indexes = {@Index(name = "ix_order_items_order",
|
||||
columnList = "order_id")})
|
||||
public class OrderItem {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
@Column(name = "order_item_id", nullable = false)
|
||||
private UUID id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||
@OnDelete(action = OnDeleteAction.CASCADE)
|
||||
@JoinColumn(name = "order_id", nullable = false)
|
||||
private Order order;
|
||||
|
||||
@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 = "material_code", nullable = false, length = Integer.MAX_VALUE)
|
||||
private String materialCode;
|
||||
|
||||
@Column(name = "color_code", length = Integer.MAX_VALUE)
|
||||
private String colorCode;
|
||||
|
||||
@ColumnDefault("1")
|
||||
@Column(name = "quantity", nullable = false)
|
||||
private Integer quantity;
|
||||
|
||||
@Column(name = "print_time_seconds")
|
||||
private Integer printTimeSeconds;
|
||||
|
||||
@Column(name = "material_grams", precision = 12, scale = 2)
|
||||
private BigDecimal materialGrams;
|
||||
|
||||
@Column(name = "unit_price_chf", nullable = false, precision = 12, scale = 2)
|
||||
private BigDecimal unitPriceChf;
|
||||
|
||||
@Column(name = "line_total_chf", nullable = false, precision = 12, scale = 2)
|
||||
private BigDecimal lineTotalChf;
|
||||
|
||||
@ColumnDefault("now()")
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private OffsetDateTime createdAt;
|
||||
|
||||
public UUID getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(UUID id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Order getOrder() {
|
||||
return order;
|
||||
}
|
||||
|
||||
public void setOrder(Order order) {
|
||||
this.order = order;
|
||||
}
|
||||
|
||||
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 String getMaterialCode() {
|
||||
return materialCode;
|
||||
}
|
||||
|
||||
public void setMaterialCode(String materialCode) {
|
||||
this.materialCode = materialCode;
|
||||
}
|
||||
|
||||
public String getColorCode() {
|
||||
return colorCode;
|
||||
}
|
||||
|
||||
public void setColorCode(String colorCode) {
|
||||
this.colorCode = colorCode;
|
||||
}
|
||||
|
||||
public Integer getQuantity() {
|
||||
return quantity;
|
||||
}
|
||||
|
||||
public void setQuantity(Integer quantity) {
|
||||
this.quantity = quantity;
|
||||
}
|
||||
|
||||
public Integer getPrintTimeSeconds() {
|
||||
return printTimeSeconds;
|
||||
}
|
||||
|
||||
public void setPrintTimeSeconds(Integer printTimeSeconds) {
|
||||
this.printTimeSeconds = printTimeSeconds;
|
||||
}
|
||||
|
||||
public BigDecimal getMaterialGrams() {
|
||||
return materialGrams;
|
||||
}
|
||||
|
||||
public void setMaterialGrams(BigDecimal materialGrams) {
|
||||
this.materialGrams = materialGrams;
|
||||
}
|
||||
|
||||
public BigDecimal getUnitPriceChf() {
|
||||
return unitPriceChf;
|
||||
}
|
||||
|
||||
public void setUnitPriceChf(BigDecimal unitPriceChf) {
|
||||
this.unitPriceChf = unitPriceChf;
|
||||
}
|
||||
|
||||
public BigDecimal getLineTotalChf() {
|
||||
return lineTotalChf;
|
||||
}
|
||||
|
||||
public void setLineTotalChf(BigDecimal lineTotalChf) {
|
||||
this.lineTotalChf = lineTotalChf;
|
||||
}
|
||||
|
||||
public OffsetDateTime getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(OffsetDateTime createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
}
|
||||
146
backend/src/main/java/com/printcalculator/entity/Payment.java
Normal file
146
backend/src/main/java/com/printcalculator/entity/Payment.java
Normal file
@@ -0,0 +1,146 @@
|
||||
package com.printcalculator.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import org.hibernate.annotations.ColumnDefault;
|
||||
import org.hibernate.annotations.OnDelete;
|
||||
import org.hibernate.annotations.OnDeleteAction;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "payments", indexes = {
|
||||
@Index(name = "ix_payments_order",
|
||||
columnList = "order_id"),
|
||||
@Index(name = "ix_payments_reference",
|
||||
columnList = "payment_reference")})
|
||||
public class Payment {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
@Column(name = "payment_id", nullable = false)
|
||||
private UUID id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||
@OnDelete(action = OnDeleteAction.CASCADE)
|
||||
@JoinColumn(name = "order_id", nullable = false)
|
||||
private Order order;
|
||||
|
||||
@Column(name = "method", nullable = false, length = Integer.MAX_VALUE)
|
||||
private String method;
|
||||
|
||||
@Column(name = "status", nullable = false, length = Integer.MAX_VALUE)
|
||||
private String status;
|
||||
|
||||
@ColumnDefault("'CHF'")
|
||||
@Column(name = "currency", nullable = false, length = 3)
|
||||
private String currency;
|
||||
|
||||
@Column(name = "amount_chf", nullable = false, precision = 12, scale = 2)
|
||||
private BigDecimal amountChf;
|
||||
|
||||
@Column(name = "payment_reference", length = Integer.MAX_VALUE)
|
||||
private String paymentReference;
|
||||
|
||||
@Column(name = "provider_transaction_id", length = Integer.MAX_VALUE)
|
||||
private String providerTransactionId;
|
||||
|
||||
@Column(name = "qr_payload", length = Integer.MAX_VALUE)
|
||||
private String qrPayload;
|
||||
|
||||
@ColumnDefault("now()")
|
||||
@Column(name = "initiated_at", nullable = false)
|
||||
private OffsetDateTime initiatedAt;
|
||||
|
||||
@Column(name = "received_at")
|
||||
private OffsetDateTime receivedAt;
|
||||
|
||||
public UUID getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(UUID id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Order getOrder() {
|
||||
return order;
|
||||
}
|
||||
|
||||
public void setOrder(Order order) {
|
||||
this.order = order;
|
||||
}
|
||||
|
||||
public String getMethod() {
|
||||
return method;
|
||||
}
|
||||
|
||||
public void setMethod(String method) {
|
||||
this.method = method;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public String getCurrency() {
|
||||
return currency;
|
||||
}
|
||||
|
||||
public void setCurrency(String currency) {
|
||||
this.currency = currency;
|
||||
}
|
||||
|
||||
public BigDecimal getAmountChf() {
|
||||
return amountChf;
|
||||
}
|
||||
|
||||
public void setAmountChf(BigDecimal amountChf) {
|
||||
this.amountChf = amountChf;
|
||||
}
|
||||
|
||||
public String getPaymentReference() {
|
||||
return paymentReference;
|
||||
}
|
||||
|
||||
public void setPaymentReference(String paymentReference) {
|
||||
this.paymentReference = paymentReference;
|
||||
}
|
||||
|
||||
public String getProviderTransactionId() {
|
||||
return providerTransactionId;
|
||||
}
|
||||
|
||||
public void setProviderTransactionId(String providerTransactionId) {
|
||||
this.providerTransactionId = providerTransactionId;
|
||||
}
|
||||
|
||||
public String getQrPayload() {
|
||||
return qrPayload;
|
||||
}
|
||||
|
||||
public void setQrPayload(String qrPayload) {
|
||||
this.qrPayload = qrPayload;
|
||||
}
|
||||
|
||||
public OffsetDateTime getInitiatedAt() {
|
||||
return initiatedAt;
|
||||
}
|
||||
|
||||
public void setInitiatedAt(OffsetDateTime initiatedAt) {
|
||||
this.initiatedAt = initiatedAt;
|
||||
}
|
||||
|
||||
public OffsetDateTime getReceivedAt() {
|
||||
return receivedAt;
|
||||
}
|
||||
|
||||
public void setReceivedAt(OffsetDateTime receivedAt) {
|
||||
this.receivedAt = receivedAt;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package com.printcalculator.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import org.hibernate.annotations.ColumnDefault;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.OffsetDateTime;
|
||||
|
||||
@Entity
|
||||
@Table(name = "pricing_policy")
|
||||
public class PricingPolicy {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "pricing_policy_id", nullable = false)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "policy_name", nullable = false, length = Integer.MAX_VALUE)
|
||||
private String policyName;
|
||||
|
||||
@Column(name = "valid_from", nullable = false)
|
||||
private OffsetDateTime validFrom;
|
||||
|
||||
@Column(name = "valid_to")
|
||||
private OffsetDateTime validTo;
|
||||
|
||||
@Column(name = "electricity_cost_chf_per_kwh", nullable = false, precision = 10, scale = 6)
|
||||
private BigDecimal electricityCostChfPerKwh;
|
||||
|
||||
@ColumnDefault("20.000")
|
||||
@Column(name = "markup_percent", nullable = false, precision = 6, scale = 3)
|
||||
private BigDecimal markupPercent;
|
||||
|
||||
@ColumnDefault("0.00")
|
||||
@Column(name = "fixed_job_fee_chf", nullable = false, precision = 10, scale = 2)
|
||||
private BigDecimal fixedJobFeeChf;
|
||||
|
||||
@ColumnDefault("0.00")
|
||||
@Column(name = "nozzle_change_base_fee_chf", nullable = false, precision = 10, scale = 2)
|
||||
private BigDecimal nozzleChangeBaseFeeChf;
|
||||
|
||||
@ColumnDefault("0.00")
|
||||
@Column(name = "cad_cost_chf_per_hour", nullable = false, precision = 10, scale = 2)
|
||||
private BigDecimal cadCostChfPerHour;
|
||||
|
||||
@ColumnDefault("true")
|
||||
@Column(name = "is_active", nullable = false)
|
||||
private Boolean isActive;
|
||||
|
||||
@ColumnDefault("now()")
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private OffsetDateTime createdAt;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getPolicyName() {
|
||||
return policyName;
|
||||
}
|
||||
|
||||
public void setPolicyName(String policyName) {
|
||||
this.policyName = policyName;
|
||||
}
|
||||
|
||||
public OffsetDateTime getValidFrom() {
|
||||
return validFrom;
|
||||
}
|
||||
|
||||
public void setValidFrom(OffsetDateTime validFrom) {
|
||||
this.validFrom = validFrom;
|
||||
}
|
||||
|
||||
public OffsetDateTime getValidTo() {
|
||||
return validTo;
|
||||
}
|
||||
|
||||
public void setValidTo(OffsetDateTime validTo) {
|
||||
this.validTo = validTo;
|
||||
}
|
||||
|
||||
public BigDecimal getElectricityCostChfPerKwh() {
|
||||
return electricityCostChfPerKwh;
|
||||
}
|
||||
|
||||
public void setElectricityCostChfPerKwh(BigDecimal electricityCostChfPerKwh) {
|
||||
this.electricityCostChfPerKwh = electricityCostChfPerKwh;
|
||||
}
|
||||
|
||||
public BigDecimal getMarkupPercent() {
|
||||
return markupPercent;
|
||||
}
|
||||
|
||||
public void setMarkupPercent(BigDecimal markupPercent) {
|
||||
this.markupPercent = markupPercent;
|
||||
}
|
||||
|
||||
public BigDecimal getFixedJobFeeChf() {
|
||||
return fixedJobFeeChf;
|
||||
}
|
||||
|
||||
public void setFixedJobFeeChf(BigDecimal fixedJobFeeChf) {
|
||||
this.fixedJobFeeChf = fixedJobFeeChf;
|
||||
}
|
||||
|
||||
public BigDecimal getNozzleChangeBaseFeeChf() {
|
||||
return nozzleChangeBaseFeeChf;
|
||||
}
|
||||
|
||||
public void setNozzleChangeBaseFeeChf(BigDecimal nozzleChangeBaseFeeChf) {
|
||||
this.nozzleChangeBaseFeeChf = nozzleChangeBaseFeeChf;
|
||||
}
|
||||
|
||||
public BigDecimal getCadCostChfPerHour() {
|
||||
return cadCostChfPerHour;
|
||||
}
|
||||
|
||||
public void setCadCostChfPerHour(BigDecimal cadCostChfPerHour) {
|
||||
this.cadCostChfPerHour = cadCostChfPerHour;
|
||||
}
|
||||
|
||||
public Boolean getIsActive() {
|
||||
return isActive;
|
||||
}
|
||||
|
||||
public void setIsActive(Boolean isActive) {
|
||||
this.isActive = isActive;
|
||||
}
|
||||
|
||||
public OffsetDateTime getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(OffsetDateTime createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.printcalculator.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
@Entity
|
||||
@Table(name = "pricing_policy_machine_hour_tier")
|
||||
public class PricingPolicyMachineHourTier {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "pricing_policy_machine_hour_tier_id", nullable = false)
|
||||
private Long id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||
@JoinColumn(name = "pricing_policy_id", nullable = false)
|
||||
private PricingPolicy pricingPolicy;
|
||||
|
||||
@Column(name = "tier_start_hours", nullable = false, precision = 10, scale = 2)
|
||||
private BigDecimal tierStartHours;
|
||||
|
||||
@Column(name = "tier_end_hours", precision = 10, scale = 2)
|
||||
private BigDecimal tierEndHours;
|
||||
|
||||
@Column(name = "machine_cost_chf_per_hour", nullable = false, precision = 10, scale = 2)
|
||||
private BigDecimal machineCostChfPerHour;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public PricingPolicy getPricingPolicy() {
|
||||
return pricingPolicy;
|
||||
}
|
||||
|
||||
public void setPricingPolicy(PricingPolicy pricingPolicy) {
|
||||
this.pricingPolicy = pricingPolicy;
|
||||
}
|
||||
|
||||
public BigDecimal getTierStartHours() {
|
||||
return tierStartHours;
|
||||
}
|
||||
|
||||
public void setTierStartHours(BigDecimal tierStartHours) {
|
||||
this.tierStartHours = tierStartHours;
|
||||
}
|
||||
|
||||
public BigDecimal getTierEndHours() {
|
||||
return tierEndHours;
|
||||
}
|
||||
|
||||
public void setTierEndHours(BigDecimal tierEndHours) {
|
||||
this.tierEndHours = tierEndHours;
|
||||
}
|
||||
|
||||
public BigDecimal getMachineCostChfPerHour() {
|
||||
return machineCostChfPerHour;
|
||||
}
|
||||
|
||||
public void setMachineCostChfPerHour(BigDecimal machineCostChfPerHour) {
|
||||
this.machineCostChfPerHour = machineCostChfPerHour;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.printcalculator.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Table;
|
||||
import org.hibernate.annotations.Immutable;
|
||||
|
||||
import jakarta.persistence.Id;
|
||||
|
||||
@Entity
|
||||
@Immutable
|
||||
@Table(name = "printer_fleet_current")
|
||||
public class PrinterFleetCurrent {
|
||||
@Id
|
||||
@Column(name = "fleet_id")
|
||||
private Long id;
|
||||
|
||||
@Column(name = "weighted_average_power_watts")
|
||||
private Integer weightedAveragePowerWatts;
|
||||
|
||||
@Column(name = "fleet_max_build_x_mm")
|
||||
private Integer fleetMaxBuildXMm;
|
||||
|
||||
@Column(name = "fleet_max_build_y_mm")
|
||||
private Integer fleetMaxBuildYMm;
|
||||
|
||||
@Column(name = "fleet_max_build_z_mm")
|
||||
private Integer fleetMaxBuildZMm;
|
||||
|
||||
public Integer getWeightedAveragePowerWatts() {
|
||||
return weightedAveragePowerWatts;
|
||||
}
|
||||
|
||||
public Integer getFleetMaxBuildXMm() {
|
||||
return fleetMaxBuildXMm;
|
||||
}
|
||||
|
||||
public Integer getFleetMaxBuildYMm() {
|
||||
return fleetMaxBuildYMm;
|
||||
}
|
||||
|
||||
public Integer getFleetMaxBuildZMm() {
|
||||
return fleetMaxBuildZMm;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package com.printcalculator.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import org.hibernate.annotations.ColumnDefault;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.OffsetDateTime;
|
||||
|
||||
@Entity
|
||||
@Table(name = "printer_machine")
|
||||
public class PrinterMachine {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "printer_machine_id", nullable = false)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "printer_display_name", nullable = false, length = Integer.MAX_VALUE)
|
||||
private String printerDisplayName;
|
||||
|
||||
@Column(name = "build_volume_x_mm", nullable = false)
|
||||
private Integer buildVolumeXMm;
|
||||
|
||||
@Column(name = "build_volume_y_mm", nullable = false)
|
||||
private Integer buildVolumeYMm;
|
||||
|
||||
@Column(name = "build_volume_z_mm", nullable = false)
|
||||
private Integer buildVolumeZMm;
|
||||
|
||||
@Column(name = "power_watts", nullable = false)
|
||||
private Integer powerWatts;
|
||||
|
||||
@ColumnDefault("1.000")
|
||||
@Column(name = "fleet_weight", nullable = false, precision = 6, scale = 3)
|
||||
private BigDecimal fleetWeight;
|
||||
|
||||
@ColumnDefault("true")
|
||||
@Column(name = "is_active", nullable = false)
|
||||
private Boolean isActive;
|
||||
|
||||
@ColumnDefault("now()")
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private OffsetDateTime createdAt;
|
||||
|
||||
@Column(name = "slicer_machine_profile")
|
||||
private String slicerMachineProfile;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getPrinterDisplayName() {
|
||||
return printerDisplayName;
|
||||
}
|
||||
|
||||
public void setPrinterDisplayName(String printerDisplayName) {
|
||||
this.printerDisplayName = printerDisplayName;
|
||||
}
|
||||
|
||||
public String getSlicerMachineProfile() {
|
||||
return slicerMachineProfile;
|
||||
}
|
||||
|
||||
public void setSlicerMachineProfile(String slicerMachineProfile) {
|
||||
this.slicerMachineProfile = slicerMachineProfile;
|
||||
}
|
||||
|
||||
public Integer getBuildVolumeXMm() {
|
||||
return buildVolumeXMm;
|
||||
}
|
||||
|
||||
public void setBuildVolumeXMm(Integer buildVolumeXMm) {
|
||||
this.buildVolumeXMm = buildVolumeXMm;
|
||||
}
|
||||
|
||||
public Integer getBuildVolumeYMm() {
|
||||
return buildVolumeYMm;
|
||||
}
|
||||
|
||||
public void setBuildVolumeYMm(Integer buildVolumeYMm) {
|
||||
this.buildVolumeYMm = buildVolumeYMm;
|
||||
}
|
||||
|
||||
public Integer getBuildVolumeZMm() {
|
||||
return buildVolumeZMm;
|
||||
}
|
||||
|
||||
public void setBuildVolumeZMm(Integer buildVolumeZMm) {
|
||||
this.buildVolumeZMm = buildVolumeZMm;
|
||||
}
|
||||
|
||||
public Integer getPowerWatts() {
|
||||
return powerWatts;
|
||||
}
|
||||
|
||||
public void setPowerWatts(Integer powerWatts) {
|
||||
this.powerWatts = powerWatts;
|
||||
}
|
||||
|
||||
public BigDecimal getFleetWeight() {
|
||||
return fleetWeight;
|
||||
}
|
||||
|
||||
public void setFleetWeight(BigDecimal fleetWeight) {
|
||||
this.fleetWeight = fleetWeight;
|
||||
}
|
||||
|
||||
public Boolean getIsActive() {
|
||||
return isActive;
|
||||
}
|
||||
|
||||
public void setIsActive(Boolean isActive) {
|
||||
this.isActive = isActive;
|
||||
}
|
||||
|
||||
public OffsetDateTime getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(OffsetDateTime createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
package com.printcalculator.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import org.hibernate.annotations.ColumnDefault;
|
||||
import org.hibernate.annotations.JdbcTypeCode;
|
||||
import org.hibernate.annotations.OnDelete;
|
||||
import org.hibernate.annotations.OnDeleteAction;
|
||||
import org.hibernate.type.SqlTypes;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "quote_line_items", indexes = {@Index(name = "ix_quote_line_items_session",
|
||||
columnList = "quote_session_id")})
|
||||
public class QuoteLineItem {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
@Column(name = "quote_line_item_id", nullable = false)
|
||||
private UUID id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||
@OnDelete(action = OnDeleteAction.CASCADE)
|
||||
@JoinColumn(name = "quote_session_id", nullable = false)
|
||||
@com.fasterxml.jackson.annotation.JsonIgnore
|
||||
private QuoteSession quoteSession;
|
||||
|
||||
@Column(name = "status", nullable = false, length = Integer.MAX_VALUE)
|
||||
private String status;
|
||||
|
||||
@Column(name = "original_filename", nullable = false, length = Integer.MAX_VALUE)
|
||||
private String originalFilename;
|
||||
|
||||
@ColumnDefault("1")
|
||||
@Column(name = "quantity", nullable = false)
|
||||
private Integer quantity;
|
||||
|
||||
@Column(name = "color_code", length = Integer.MAX_VALUE)
|
||||
private String colorCode;
|
||||
|
||||
@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;
|
||||
|
||||
@Column(name = "print_time_seconds")
|
||||
private Integer printTimeSeconds;
|
||||
|
||||
@Column(name = "material_grams", precision = 12, scale = 2)
|
||||
private BigDecimal materialGrams;
|
||||
|
||||
@Column(name = "unit_price_chf", precision = 12, scale = 2)
|
||||
private BigDecimal unitPriceChf;
|
||||
|
||||
@JdbcTypeCode(SqlTypes.JSON)
|
||||
@Column(name = "pricing_breakdown")
|
||||
private Map<String, Object> pricingBreakdown;
|
||||
|
||||
@Column(name = "error_message", length = Integer.MAX_VALUE)
|
||||
private String errorMessage;
|
||||
|
||||
@Column(name = "stored_path", length = Integer.MAX_VALUE)
|
||||
private String storedPath;
|
||||
|
||||
@ColumnDefault("now()")
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private OffsetDateTime createdAt;
|
||||
|
||||
@ColumnDefault("now()")
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
private OffsetDateTime updatedAt;
|
||||
|
||||
public UUID getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(UUID id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public QuoteSession getQuoteSession() {
|
||||
return quoteSession;
|
||||
}
|
||||
|
||||
public void setQuoteSession(QuoteSession quoteSession) {
|
||||
this.quoteSession = quoteSession;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public String getOriginalFilename() {
|
||||
return originalFilename;
|
||||
}
|
||||
|
||||
public void setOriginalFilename(String originalFilename) {
|
||||
this.originalFilename = originalFilename;
|
||||
}
|
||||
|
||||
public Integer getQuantity() {
|
||||
return quantity;
|
||||
}
|
||||
|
||||
public void setQuantity(Integer quantity) {
|
||||
this.quantity = quantity;
|
||||
}
|
||||
|
||||
public String getColorCode() {
|
||||
return colorCode;
|
||||
}
|
||||
|
||||
public void setColorCode(String colorCode) {
|
||||
this.colorCode = colorCode;
|
||||
}
|
||||
|
||||
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 Integer getPrintTimeSeconds() {
|
||||
return printTimeSeconds;
|
||||
}
|
||||
|
||||
public void setPrintTimeSeconds(Integer printTimeSeconds) {
|
||||
this.printTimeSeconds = printTimeSeconds;
|
||||
}
|
||||
|
||||
public BigDecimal getMaterialGrams() {
|
||||
return materialGrams;
|
||||
}
|
||||
|
||||
public void setMaterialGrams(BigDecimal materialGrams) {
|
||||
this.materialGrams = materialGrams;
|
||||
}
|
||||
|
||||
public BigDecimal getUnitPriceChf() {
|
||||
return unitPriceChf;
|
||||
}
|
||||
|
||||
public void setUnitPriceChf(BigDecimal unitPriceChf) {
|
||||
this.unitPriceChf = unitPriceChf;
|
||||
}
|
||||
|
||||
public Map<String, Object> getPricingBreakdown() {
|
||||
return pricingBreakdown;
|
||||
}
|
||||
|
||||
public void setPricingBreakdown(Map<String, Object> pricingBreakdown) {
|
||||
this.pricingBreakdown = pricingBreakdown;
|
||||
}
|
||||
|
||||
public String getErrorMessage() {
|
||||
return errorMessage;
|
||||
}
|
||||
|
||||
public void setErrorMessage(String errorMessage) {
|
||||
this.errorMessage = errorMessage;
|
||||
}
|
||||
|
||||
public String getStoredPath() {
|
||||
return storedPath;
|
||||
}
|
||||
|
||||
public void setStoredPath(String storedPath) {
|
||||
this.storedPath = storedPath;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
package com.printcalculator.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import org.hibernate.annotations.ColumnDefault;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "quote_sessions", indexes = {
|
||||
@Index(name = "ix_quote_sessions_status",
|
||||
columnList = "status"),
|
||||
@Index(name = "ix_quote_sessions_expires_at",
|
||||
columnList = "expires_at")})
|
||||
public class QuoteSession {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
@Column(name = "quote_session_id", nullable = false)
|
||||
private UUID id;
|
||||
|
||||
@Column(name = "status", nullable = false, length = Integer.MAX_VALUE)
|
||||
private String status;
|
||||
|
||||
@Column(name = "pricing_version", nullable = false, length = Integer.MAX_VALUE)
|
||||
private String pricingVersion;
|
||||
|
||||
@Column(name = "material_code", nullable = false, length = Integer.MAX_VALUE)
|
||||
private String materialCode;
|
||||
|
||||
@Column(name = "nozzle_diameter_mm", precision = 5, scale = 2)
|
||||
private BigDecimal nozzleDiameterMm;
|
||||
|
||||
@Column(name = "layer_height_mm", precision = 6, scale = 3)
|
||||
private BigDecimal layerHeightMm;
|
||||
|
||||
@Column(name = "infill_pattern", length = Integer.MAX_VALUE)
|
||||
private String infillPattern;
|
||||
|
||||
@Column(name = "infill_percent")
|
||||
private Integer infillPercent;
|
||||
|
||||
@ColumnDefault("false")
|
||||
@Column(name = "supports_enabled", nullable = false)
|
||||
private Boolean supportsEnabled;
|
||||
|
||||
@Column(name = "notes", length = Integer.MAX_VALUE)
|
||||
private String notes;
|
||||
|
||||
@ColumnDefault("0.00")
|
||||
@Column(name = "setup_cost_chf", nullable = false, precision = 12, scale = 2)
|
||||
private BigDecimal setupCostChf;
|
||||
|
||||
@ColumnDefault("now()")
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private OffsetDateTime createdAt;
|
||||
|
||||
@Column(name = "expires_at", nullable = false)
|
||||
private OffsetDateTime expiresAt;
|
||||
|
||||
@Column(name = "converted_order_id")
|
||||
private UUID convertedOrderId;
|
||||
|
||||
public UUID getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(UUID id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public String getPricingVersion() {
|
||||
return pricingVersion;
|
||||
}
|
||||
|
||||
public void setPricingVersion(String pricingVersion) {
|
||||
this.pricingVersion = pricingVersion;
|
||||
}
|
||||
|
||||
public String getMaterialCode() {
|
||||
return materialCode;
|
||||
}
|
||||
|
||||
public void setMaterialCode(String materialCode) {
|
||||
this.materialCode = materialCode;
|
||||
}
|
||||
|
||||
public BigDecimal getNozzleDiameterMm() {
|
||||
return nozzleDiameterMm;
|
||||
}
|
||||
|
||||
public void setNozzleDiameterMm(BigDecimal nozzleDiameterMm) {
|
||||
this.nozzleDiameterMm = nozzleDiameterMm;
|
||||
}
|
||||
|
||||
public BigDecimal getLayerHeightMm() {
|
||||
return layerHeightMm;
|
||||
}
|
||||
|
||||
public void setLayerHeightMm(BigDecimal layerHeightMm) {
|
||||
this.layerHeightMm = layerHeightMm;
|
||||
}
|
||||
|
||||
public String getInfillPattern() {
|
||||
return infillPattern;
|
||||
}
|
||||
|
||||
public void setInfillPattern(String infillPattern) {
|
||||
this.infillPattern = infillPattern;
|
||||
}
|
||||
|
||||
public Integer getInfillPercent() {
|
||||
return infillPercent;
|
||||
}
|
||||
|
||||
public void setInfillPercent(Integer infillPercent) {
|
||||
this.infillPercent = infillPercent;
|
||||
}
|
||||
|
||||
public Boolean getSupportsEnabled() {
|
||||
return supportsEnabled;
|
||||
}
|
||||
|
||||
public void setSupportsEnabled(Boolean supportsEnabled) {
|
||||
this.supportsEnabled = supportsEnabled;
|
||||
}
|
||||
|
||||
public String getNotes() {
|
||||
return notes;
|
||||
}
|
||||
|
||||
public void setNotes(String notes) {
|
||||
this.notes = notes;
|
||||
}
|
||||
|
||||
public BigDecimal getSetupCostChf() {
|
||||
return setupCostChf;
|
||||
}
|
||||
|
||||
public void setSetupCostChf(BigDecimal setupCostChf) {
|
||||
this.setupCostChf = setupCostChf;
|
||||
}
|
||||
|
||||
public OffsetDateTime getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(OffsetDateTime createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
public OffsetDateTime getExpiresAt() {
|
||||
return expiresAt;
|
||||
}
|
||||
|
||||
public void setExpiresAt(OffsetDateTime expiresAt) {
|
||||
this.expiresAt = expiresAt;
|
||||
}
|
||||
|
||||
public UUID getConvertedOrderId() {
|
||||
return convertedOrderId;
|
||||
}
|
||||
|
||||
public void setConvertedOrderId(UUID convertedOrderId) {
|
||||
this.convertedOrderId = convertedOrderId;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.printcalculator.exception;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.multipart.MaxUploadSizeExceededException;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
|
||||
@ControllerAdvice
|
||||
@Slf4j
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
@ExceptionHandler(StorageException.class)
|
||||
public ResponseEntity<?> handleStorageException(StorageException exc) {
|
||||
// Log the full exception for internal debugging
|
||||
log.error("Storage Exception occurred", exc);
|
||||
|
||||
Map<String, String> response = new HashMap<>();
|
||||
|
||||
// Check for specific virus case
|
||||
if (exc.getMessage() != null && exc.getMessage().contains("antivirus scanner")) {
|
||||
response.put("error", "Security Violation");
|
||||
// Safe message for client
|
||||
response.put("message", "File rejected by security policy.");
|
||||
response.put("code", "VIRUS_DETECTED");
|
||||
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(response);
|
||||
}
|
||||
|
||||
// Generic fallback for other storage errors to avoid leaking internal paths/details
|
||||
response.put("error", "Storage Operation Failed");
|
||||
response.put("message", "Unable to process the file upload.");
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
|
||||
}
|
||||
|
||||
@ExceptionHandler(MaxUploadSizeExceededException.class)
|
||||
public ResponseEntity<?> handleMaxSizeException(MaxUploadSizeExceededException exc) {
|
||||
Map<String, String> response = new HashMap<>();
|
||||
response.put("error", "File too large");
|
||||
response.put("message", "The uploaded file exceeds the maximum allowed size.");
|
||||
return ResponseEntity.status(HttpStatus.PAYLOAD_TOO_LARGE).body(response);
|
||||
}
|
||||
|
||||
@ExceptionHandler(ModelTooLargeException.class)
|
||||
public ResponseEntity<?> handleModelTooLarge(ModelTooLargeException exc) {
|
||||
Map<String, String> response = new HashMap<>();
|
||||
response.put("error", "Model too large");
|
||||
response.put("code", "MODEL_TOO_LARGE");
|
||||
response.put("message", String.format(
|
||||
"Model size %.2fx%.2fx%.2f mm exceeds build volume %dx%dx%d mm.",
|
||||
exc.getModelX(), exc.getModelY(), exc.getModelZ(),
|
||||
exc.getBuildX(), exc.getBuildY(), exc.getBuildZ()
|
||||
));
|
||||
response.put("model_x_mm", formatMm(exc.getModelX()));
|
||||
response.put("model_y_mm", formatMm(exc.getModelY()));
|
||||
response.put("model_z_mm", formatMm(exc.getModelZ()));
|
||||
response.put("build_x_mm", String.valueOf(exc.getBuildX()));
|
||||
response.put("build_y_mm", String.valueOf(exc.getBuildY()));
|
||||
response.put("build_z_mm", String.valueOf(exc.getBuildZ()));
|
||||
return ResponseEntity.unprocessableEntity().body(response);
|
||||
}
|
||||
|
||||
private String formatMm(double value) {
|
||||
return BigDecimal.valueOf(value).setScale(2, RoundingMode.HALF_UP).toPlainString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.printcalculator.exception;
|
||||
|
||||
public class ModelTooLargeException extends RuntimeException {
|
||||
private final double modelX;
|
||||
private final double modelY;
|
||||
private final double modelZ;
|
||||
private final int buildX;
|
||||
private final int buildY;
|
||||
private final int buildZ;
|
||||
|
||||
public ModelTooLargeException(double modelX, double modelY, double modelZ,
|
||||
int buildX, int buildY, int buildZ) {
|
||||
super("Model size exceeds build volume");
|
||||
this.modelX = modelX;
|
||||
this.modelY = modelY;
|
||||
this.modelZ = modelZ;
|
||||
this.buildX = buildX;
|
||||
this.buildY = buildY;
|
||||
this.buildZ = buildZ;
|
||||
}
|
||||
|
||||
public double getModelX() {
|
||||
return modelX;
|
||||
}
|
||||
|
||||
public double getModelY() {
|
||||
return modelY;
|
||||
}
|
||||
|
||||
public double getModelZ() {
|
||||
return modelZ;
|
||||
}
|
||||
|
||||
public int getBuildX() {
|
||||
return buildX;
|
||||
}
|
||||
|
||||
public int getBuildY() {
|
||||
return buildY;
|
||||
}
|
||||
|
||||
public int getBuildZ() {
|
||||
return buildZ;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.printcalculator.exception;
|
||||
|
||||
public class StorageException extends RuntimeException {
|
||||
|
||||
public StorageException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public StorageException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.printcalculator.model;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@Builder
|
||||
public class PrintStats {
|
||||
private long printTimeSeconds;
|
||||
private String printTimeFormatted;
|
||||
private double filamentWeightGrams;
|
||||
private double filamentLengthMm;
|
||||
|
||||
// Breakdown if available
|
||||
private Double modelWeightGrams;
|
||||
private Double supportWeightGrams;
|
||||
|
||||
// Legacy constructor for compatibility
|
||||
public PrintStats(long printTimeSeconds, String printTimeFormatted, double filamentWeightGrams, double filamentLengthMm) {
|
||||
this.printTimeSeconds = printTimeSeconds;
|
||||
this.printTimeFormatted = printTimeFormatted;
|
||||
this.filamentWeightGrams = filamentWeightGrams;
|
||||
this.filamentLengthMm = filamentLengthMm;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.printcalculator.model;
|
||||
|
||||
public class QuoteResult {
|
||||
private double totalPrice;
|
||||
private String currency;
|
||||
private PrintStats stats;
|
||||
private double setupCost;
|
||||
|
||||
public QuoteResult(double totalPrice, String currency, PrintStats stats, double setupCost) {
|
||||
this.totalPrice = totalPrice;
|
||||
this.currency = currency;
|
||||
this.stats = stats;
|
||||
this.setupCost = setupCost;
|
||||
}
|
||||
|
||||
public double getTotalPrice() {
|
||||
return totalPrice;
|
||||
}
|
||||
|
||||
public String getCurrency() {
|
||||
return currency;
|
||||
}
|
||||
|
||||
public PrintStats getStats() {
|
||||
return stats;
|
||||
}
|
||||
|
||||
public double getSetupCost() {
|
||||
return setupCost;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.printcalculator.model;
|
||||
|
||||
public record StlBounds(double minX, double minY, double minZ,
|
||||
double maxX, double maxY, double maxZ) {
|
||||
public double sizeX() {
|
||||
return maxX - minX;
|
||||
}
|
||||
|
||||
public double sizeY() {
|
||||
return maxY - minY;
|
||||
}
|
||||
|
||||
public double sizeZ() {
|
||||
return maxZ - minZ;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.printcalculator.model;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
public record StlShiftResult(Path shiftedPath,
|
||||
double offsetX,
|
||||
double offsetY,
|
||||
double offsetZ,
|
||||
boolean shifted) {
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.printcalculator.repository;
|
||||
|
||||
import com.printcalculator.entity.CustomQuoteRequestAttachment;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public interface CustomQuoteRequestAttachmentRepository extends JpaRepository<CustomQuoteRequestAttachment, UUID> {
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.printcalculator.repository;
|
||||
|
||||
import com.printcalculator.entity.CustomQuoteRequest;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public interface CustomQuoteRequestRepository extends JpaRepository<CustomQuoteRequest, UUID> {
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.printcalculator.repository;
|
||||
|
||||
import com.printcalculator.entity.Customer;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface CustomerRepository extends JpaRepository<Customer, UUID> {
|
||||
Optional<Customer> findByEmail(String email);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.printcalculator.repository;
|
||||
|
||||
import com.printcalculator.entity.FilamentMaterialType;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public interface FilamentMaterialTypeRepository extends JpaRepository<FilamentMaterialType, Long> {
|
||||
Optional<FilamentMaterialType> findByMaterialCode(String materialCode);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.printcalculator.repository;
|
||||
|
||||
import com.printcalculator.entity.FilamentVariant;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import com.printcalculator.entity.FilamentMaterialType;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface FilamentVariantRepository extends JpaRepository<FilamentVariant, Long> {
|
||||
// We try to match by color name if possible, or get first active
|
||||
Optional<FilamentVariant> findByFilamentMaterialTypeAndColorName(FilamentMaterialType type, String colorName);
|
||||
Optional<FilamentVariant> findFirstByFilamentMaterialTypeAndIsActiveTrue(FilamentMaterialType type);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.printcalculator.repository;
|
||||
|
||||
import com.printcalculator.entity.FilamentVariantStockKg;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface FilamentVariantStockKgRepository extends JpaRepository<FilamentVariantStockKg, Long> {
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.printcalculator.repository;
|
||||
|
||||
import com.printcalculator.entity.InfillPattern;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface InfillPatternRepository extends JpaRepository<InfillPattern, Long> {
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.printcalculator.repository;
|
||||
|
||||
import com.printcalculator.entity.LayerHeightOption;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface LayerHeightOptionRepository extends JpaRepository<LayerHeightOption, Long> {
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.printcalculator.repository;
|
||||
|
||||
import com.printcalculator.entity.LayerHeightProfile;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface LayerHeightProfileRepository extends JpaRepository<LayerHeightProfile, Long> {
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.printcalculator.repository;
|
||||
|
||||
import com.printcalculator.entity.NozzleOption;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface NozzleOptionRepository extends JpaRepository<NozzleOption, Long> {
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.printcalculator.repository;
|
||||
|
||||
import com.printcalculator.entity.OrderItem;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface OrderItemRepository extends JpaRepository<OrderItem, UUID> {
|
||||
List<OrderItem> findByOrder_Id(UUID orderId);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.printcalculator.repository;
|
||||
|
||||
import com.printcalculator.entity.Order;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public interface OrderRepository extends JpaRepository<Order, UUID> {
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.printcalculator.repository;
|
||||
|
||||
import com.printcalculator.entity.Payment;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public interface PaymentRepository extends JpaRepository<Payment, UUID> {
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.printcalculator.repository;
|
||||
|
||||
import com.printcalculator.entity.PricingPolicyMachineHourTier;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import com.printcalculator.entity.PricingPolicy;
|
||||
import java.util.List;
|
||||
|
||||
public interface PricingPolicyMachineHourTierRepository extends JpaRepository<PricingPolicyMachineHourTier, Long> {
|
||||
List<PricingPolicyMachineHourTier> findAllByPricingPolicyOrderByTierStartHoursAsc(PricingPolicy pricingPolicy);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.printcalculator.repository;
|
||||
|
||||
import com.printcalculator.entity.PricingPolicy;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface PricingPolicyRepository extends JpaRepository<PricingPolicy, Long> {
|
||||
PricingPolicy findFirstByIsActiveTrueOrderByValidFromDesc();
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.printcalculator.repository;
|
||||
|
||||
import com.printcalculator.entity.PrinterFleetCurrent;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface PrinterFleetCurrentRepository extends JpaRepository<PrinterFleetCurrent, Long> {
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.printcalculator.repository;
|
||||
|
||||
import com.printcalculator.entity.PrinterMachine;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public interface PrinterMachineRepository extends JpaRepository<PrinterMachine, Long> {
|
||||
Optional<PrinterMachine> findByPrinterDisplayName(String printerDisplayName);
|
||||
Optional<PrinterMachine> findFirstByIsActiveTrue();
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.printcalculator.repository;
|
||||
|
||||
import com.printcalculator.entity.QuoteLineItem;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface QuoteLineItemRepository extends JpaRepository<QuoteLineItem, UUID> {
|
||||
List<QuoteLineItem> findByQuoteSessionId(UUID quoteSessionId);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.printcalculator.repository;
|
||||
|
||||
import com.printcalculator.entity.QuoteSession;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface QuoteSessionRepository extends JpaRepository<QuoteSession, UUID> {
|
||||
List<QuoteSession> findByCreatedAtBefore(java.time.OffsetDateTime cutoff);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.printcalculator.service;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import xyz.capybara.clamav.ClamavClient;
|
||||
import xyz.capybara.clamav.commands.scan.result.ScanResult;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
public class ClamAVService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ClamAVService.class);
|
||||
|
||||
private final ClamavClient clamavClient;
|
||||
private final boolean enabled;
|
||||
|
||||
public ClamAVService(
|
||||
@Value("${clamav.host:clamav}") String host,
|
||||
@Value("${clamav.port:3310}") int port,
|
||||
@Value("${clamav.enabled:false}") boolean enabled
|
||||
) {
|
||||
this.enabled = enabled;
|
||||
if (!enabled) {
|
||||
logger.info("ClamAV is DISABLED");
|
||||
this.clamavClient = null;
|
||||
return;
|
||||
}
|
||||
logger.info("Initializing ClamAV client at {}:{}", host, port);
|
||||
ClamavClient client = null;
|
||||
try {
|
||||
client = new ClamavClient(host, port);
|
||||
} catch (Exception e) {
|
||||
logger.error("Failed to initialize ClamAV client: " + e.getMessage());
|
||||
}
|
||||
this.clamavClient = client;
|
||||
}
|
||||
|
||||
public boolean scan(InputStream inputStream) {
|
||||
if (!enabled || clamavClient == null) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
ScanResult result = clamavClient.scan(inputStream);
|
||||
if (result instanceof ScanResult.OK) {
|
||||
return true;
|
||||
} else if (result instanceof ScanResult.VirusFound) {
|
||||
Map<String, Collection<String>> viruses = ((ScanResult.VirusFound) result).getFoundViruses();
|
||||
logger.warn("VIRUS DETECTED: {}", viruses);
|
||||
return false;
|
||||
} else {
|
||||
logger.warn("Unknown scan result: {}. Allowing file (FAIL-OPEN)", result);
|
||||
return true;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("Error scanning file with ClamAV. Allowing file (FAIL-OPEN)", e);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package com.printcalculator.service;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.io.UrlResource;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import com.printcalculator.exception.StorageException;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.MalformedURLException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
|
||||
@Service
|
||||
public class FileSystemStorageService implements StorageService {
|
||||
|
||||
private final Path rootLocation;
|
||||
private final ClamAVService clamAVService;
|
||||
|
||||
public FileSystemStorageService(@Value("${storage.location:storage_orders}") String storageLocation, ClamAVService clamAVService) {
|
||||
this.rootLocation = Paths.get(storageLocation);
|
||||
this.clamAVService = clamAVService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init() {
|
||||
try {
|
||||
Files.createDirectories(rootLocation);
|
||||
} catch (IOException e) {
|
||||
throw new StorageException("Could not initialize storage", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void store(MultipartFile file, Path destinationRelativePath) throws IOException {
|
||||
Path destinationFile = this.rootLocation.resolve(destinationRelativePath).normalize().toAbsolutePath();
|
||||
if (!destinationFile.getParent().startsWith(this.rootLocation.toAbsolutePath())) {
|
||||
throw new StorageException("Cannot store file outside current directory.");
|
||||
}
|
||||
|
||||
// 1. Salva prima il file su disco per evitare problemi di stream con file grandi
|
||||
Files.createDirectories(destinationFile.getParent());
|
||||
file.transferTo(destinationFile.toFile());
|
||||
|
||||
// 2. Scansiona il file appena salvato aprendo un nuovo stream
|
||||
try (InputStream inputStream = new FileInputStream(destinationFile.toFile())) {
|
||||
if (!clamAVService.scan(inputStream)) {
|
||||
// Se infetto, cancella il file e solleva eccezione
|
||||
Files.deleteIfExists(destinationFile);
|
||||
throw new StorageException("File rejected by antivirus scanner.");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
if (e instanceof StorageException) throw e;
|
||||
// Se l'antivirus fallisce per motivi tecnici, lasciamo il file (fail-open come concordato)
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void store(Path source, Path destinationRelativePath) throws IOException {
|
||||
Path destinationFile = this.rootLocation.resolve(destinationRelativePath).normalize().toAbsolutePath();
|
||||
if (!destinationFile.getParent().startsWith(this.rootLocation.toAbsolutePath())) {
|
||||
throw new StorageException("Cannot store file outside current directory.");
|
||||
}
|
||||
Files.createDirectories(destinationFile.getParent());
|
||||
Files.copy(source, destinationFile, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(Path path) throws IOException {
|
||||
Path file = rootLocation.resolve(path);
|
||||
Files.deleteIfExists(file);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Resource loadAsResource(Path path) throws IOException {
|
||||
try {
|
||||
Path file = rootLocation.resolve(path);
|
||||
Resource resource = new UrlResource(file.toUri());
|
||||
if (resource.exists() || resource.isReadable()) {
|
||||
return resource;
|
||||
} else {
|
||||
throw new RuntimeException("Could not read file: " + path);
|
||||
}
|
||||
} catch (MalformedURLException e) {
|
||||
throw new RuntimeException("Could not read file: " + path, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package com.printcalculator.service;
|
||||
|
||||
import com.printcalculator.model.PrintStats;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Service
|
||||
public class GCodeParser {
|
||||
|
||||
// OrcaSlicer/BambuStudio format
|
||||
// ; estimated printing time = 1h 2m 3s
|
||||
// ; filament used [g] = 12.34
|
||||
// ; filament used [mm] = 1234.56
|
||||
private static final Pattern TOTAL_ESTIMATED_TIME_PATTERN = Pattern.compile(
|
||||
";\\s*.*total\\s+estimated\\s+time\\s*[:=]\\s*([^;]+)",
|
||||
Pattern.CASE_INSENSITIVE);
|
||||
private static final Pattern MODEL_PRINTING_TIME_PATTERN = Pattern.compile(
|
||||
";\\s*.*model\\s+printing\\s+time\\s*[:=]\\s*([^;]+)",
|
||||
Pattern.CASE_INSENSITIVE);
|
||||
private static final Pattern TIME_PATTERN = Pattern.compile(
|
||||
";\\s*(?:estimated\\s+printing\\s+time|estimated\\s+print\\s+time|print\\s+time).*?[:=]\\s*(.*)",
|
||||
Pattern.CASE_INSENSITIVE);
|
||||
private static final Pattern FILAMENT_G_PATTERN = Pattern.compile(";\\s*filament used \\[g\\]\\s*=\\s*([^;\\(\\n\\r]+)(?:\\s*\\(([^,]+) model,\\s*([^ ]+) support\\))?");
|
||||
private static final Pattern FILAMENT_MM_PATTERN = Pattern.compile(";\\s*filament used \\[mm\\]\\s*=\\s*(.*)");
|
||||
|
||||
public PrintStats parse(File gcodeFile) throws IOException {
|
||||
long seconds = 0;
|
||||
double weightG = 0;
|
||||
double lengthMm = 0;
|
||||
Double modelWeightG = null;
|
||||
Double supportWeightG = null;
|
||||
String timeFormatted = "";
|
||||
|
||||
try (BufferedReader reader = new BufferedReader(new FileReader(gcodeFile))) {
|
||||
String line;
|
||||
|
||||
// Scan entire file as metadata is often at the end
|
||||
while ((line = reader.readLine()) != null) {
|
||||
line = line.trim();
|
||||
|
||||
// OrcaSlicer comments start with ;
|
||||
if (!line.startsWith(";")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (line.toLowerCase().contains("estimated printing time")) {
|
||||
System.out.println("DEBUG: Found potential time line: '" + line + "'");
|
||||
}
|
||||
|
||||
Matcher totalTimeMatcher = TOTAL_ESTIMATED_TIME_PATTERN.matcher(line);
|
||||
if (totalTimeMatcher.find()) {
|
||||
timeFormatted = totalTimeMatcher.group(1).trim();
|
||||
seconds = parseTimeString(timeFormatted);
|
||||
System.out.println("GCodeParser: Found total estimated time: " + timeFormatted + " (" + seconds + "s)");
|
||||
continue;
|
||||
}
|
||||
|
||||
Matcher modelTimeMatcher = MODEL_PRINTING_TIME_PATTERN.matcher(line);
|
||||
if (modelTimeMatcher.find()) {
|
||||
timeFormatted = modelTimeMatcher.group(1).trim();
|
||||
seconds = parseTimeString(timeFormatted);
|
||||
System.out.println("GCodeParser: Found model printing time: " + timeFormatted + " (" + seconds + "s)");
|
||||
continue;
|
||||
}
|
||||
|
||||
Matcher timeMatcher = TIME_PATTERN.matcher(line);
|
||||
if (timeMatcher.find()) {
|
||||
timeFormatted = timeMatcher.group(1).trim();
|
||||
seconds = parseTimeString(timeFormatted);
|
||||
System.out.println("GCodeParser: Found time: " + timeFormatted + " (" + seconds + "s)");
|
||||
}
|
||||
|
||||
Matcher weightMatcher = FILAMENT_G_PATTERN.matcher(line);
|
||||
if (weightMatcher.find()) {
|
||||
try {
|
||||
weightG = Double.parseDouble(weightMatcher.group(1).trim());
|
||||
System.out.println("GCodeParser: Found total weight: " + weightG + "g");
|
||||
|
||||
// Check if we have groups 2 and 3 for breakdown
|
||||
if (weightMatcher.groupCount() >= 3 && weightMatcher.group(2) != null) {
|
||||
modelWeightG = Double.parseDouble(weightMatcher.group(2).trim());
|
||||
supportWeightG = Double.parseDouble(weightMatcher.group(3).trim());
|
||||
System.out.println("GCodeParser: Found breakdown - Model: " + modelWeightG + "g, Support: " + supportWeightG + "g");
|
||||
}
|
||||
} catch (NumberFormatException ignored) {}
|
||||
}
|
||||
|
||||
Matcher lengthMatcher = FILAMENT_MM_PATTERN.matcher(line);
|
||||
if (lengthMatcher.find()) {
|
||||
try {
|
||||
lengthMm = Double.parseDouble(lengthMatcher.group(1).trim());
|
||||
System.out.println("GCodeParser: Found length: " + lengthMm + "mm");
|
||||
} catch (NumberFormatException ignored) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return PrintStats.builder()
|
||||
.printTimeSeconds(seconds)
|
||||
.printTimeFormatted(timeFormatted)
|
||||
.filamentWeightGrams(weightG)
|
||||
.filamentLengthMm(lengthMm)
|
||||
.modelWeightGrams(modelWeightG)
|
||||
.supportWeightGrams(supportWeightG)
|
||||
.build();
|
||||
}
|
||||
|
||||
private long parseTimeString(String timeStr) {
|
||||
// Formats: "1d 2h 3m 4s", "1h 20m 10s", "01:23:45", "12:34"
|
||||
String lower = timeStr.toLowerCase();
|
||||
double totalSeconds = 0;
|
||||
boolean matched = false;
|
||||
|
||||
Matcher d = Pattern.compile("(\\d+(?:\\.\\d+)?)\\s*d").matcher(lower);
|
||||
if (d.find()) {
|
||||
totalSeconds += Double.parseDouble(d.group(1)) * 86400;
|
||||
matched = true;
|
||||
}
|
||||
|
||||
Matcher h = Pattern.compile("(\\d+(?:\\.\\d+)?)\\s*h").matcher(lower);
|
||||
if (h.find()) {
|
||||
totalSeconds += Double.parseDouble(h.group(1)) * 3600;
|
||||
matched = true;
|
||||
}
|
||||
|
||||
Matcher m = Pattern.compile("(\\d+(?:\\.\\d+)?)\\s*m").matcher(lower);
|
||||
if (m.find()) {
|
||||
totalSeconds += Double.parseDouble(m.group(1)) * 60;
|
||||
matched = true;
|
||||
}
|
||||
|
||||
Matcher s = Pattern.compile("(\\d+(?:\\.\\d+)?)\\s*s").matcher(lower);
|
||||
if (s.find()) {
|
||||
totalSeconds += Double.parseDouble(s.group(1));
|
||||
matched = true;
|
||||
}
|
||||
|
||||
if (matched) {
|
||||
return Math.round(totalSeconds);
|
||||
}
|
||||
|
||||
long daySeconds = 0;
|
||||
Matcher dayPrefix = Pattern.compile("(\\d+)\\s*d").matcher(lower);
|
||||
if (dayPrefix.find()) {
|
||||
daySeconds = Long.parseLong(dayPrefix.group(1)) * 86400;
|
||||
}
|
||||
|
||||
Matcher hms = Pattern.compile("(\\d{1,2}):(\\d{2}):(\\d{2})").matcher(lower);
|
||||
if (hms.find()) {
|
||||
long hours = Long.parseLong(hms.group(1));
|
||||
long minutes = Long.parseLong(hms.group(2));
|
||||
long seconds = Long.parseLong(hms.group(3));
|
||||
return daySeconds + hours * 3600 + minutes * 60 + seconds;
|
||||
}
|
||||
|
||||
Matcher ms = Pattern.compile("(\\d{1,2}):(\\d{2})").matcher(lower);
|
||||
if (ms.find()) {
|
||||
long minutes = Long.parseLong(ms.group(1));
|
||||
long seconds = Long.parseLong(ms.group(2));
|
||||
return daySeconds + minutes * 60 + seconds;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.printcalculator.service;
|
||||
|
||||
import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
|
||||
import com.openhtmltopdf.svgsupport.BatikSVGDrawer;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.thymeleaf.TemplateEngine;
|
||||
import org.thymeleaf.context.Context;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
public class InvoicePdfRenderingService {
|
||||
|
||||
private final TemplateEngine thymeleafTemplateEngine;
|
||||
|
||||
public InvoicePdfRenderingService(TemplateEngine thymeleafTemplateEngine) {
|
||||
this.thymeleafTemplateEngine = thymeleafTemplateEngine;
|
||||
}
|
||||
|
||||
public byte[] generateInvoicePdfBytesFromTemplate(Map<String, Object> invoiceTemplateVariables, String qrBillSvg) {
|
||||
try {
|
||||
Context thymeleafContextWithInvoiceData = new Context(Locale.ITALY);
|
||||
thymeleafContextWithInvoiceData.setVariables(invoiceTemplateVariables);
|
||||
thymeleafContextWithInvoiceData.setVariable("qrBillSvg", qrBillSvg);
|
||||
|
||||
String renderedInvoiceHtml = thymeleafTemplateEngine.process("invoice", thymeleafContextWithInvoiceData);
|
||||
|
||||
String classpathBaseUrlForHtmlResources = new ClassPathResource("templates/").getURL().toExternalForm();
|
||||
|
||||
ByteArrayOutputStream generatedPdfByteArrayOutputStream = new ByteArrayOutputStream();
|
||||
|
||||
PdfRendererBuilder openHtmlToPdfRendererBuilder = new PdfRendererBuilder();
|
||||
openHtmlToPdfRendererBuilder.useFastMode();
|
||||
openHtmlToPdfRendererBuilder.useSVGDrawer(new BatikSVGDrawer());
|
||||
openHtmlToPdfRendererBuilder.withHtmlContent(renderedInvoiceHtml, classpathBaseUrlForHtmlResources);
|
||||
openHtmlToPdfRendererBuilder.toStream(generatedPdfByteArrayOutputStream);
|
||||
openHtmlToPdfRendererBuilder.run();
|
||||
|
||||
return generatedPdfByteArrayOutputStream.toByteArray();
|
||||
} catch (Exception pdfGenerationException) {
|
||||
throw new IllegalStateException("PDF invoice generation failed", pdfGenerationException);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
package com.printcalculator.service;
|
||||
|
||||
import com.printcalculator.dto.AddressDto;
|
||||
import com.printcalculator.dto.CreateOrderRequest;
|
||||
import com.printcalculator.entity.*;
|
||||
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 org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
public class OrderService {
|
||||
|
||||
private final OrderRepository orderRepo;
|
||||
private final OrderItemRepository orderItemRepo;
|
||||
private final QuoteSessionRepository quoteSessionRepo;
|
||||
private final QuoteLineItemRepository quoteLineItemRepo;
|
||||
private final CustomerRepository customerRepo;
|
||||
private final StorageService storageService;
|
||||
private final InvoicePdfRenderingService invoiceService;
|
||||
private final QrBillService qrBillService;
|
||||
|
||||
public OrderService(OrderRepository orderRepo,
|
||||
OrderItemRepository orderItemRepo,
|
||||
QuoteSessionRepository quoteSessionRepo,
|
||||
QuoteLineItemRepository quoteLineItemRepo,
|
||||
CustomerRepository customerRepo,
|
||||
StorageService storageService,
|
||||
InvoicePdfRenderingService invoiceService,
|
||||
QrBillService qrBillService) {
|
||||
this.orderRepo = orderRepo;
|
||||
this.orderItemRepo = orderItemRepo;
|
||||
this.quoteSessionRepo = quoteSessionRepo;
|
||||
this.quoteLineItemRepo = quoteLineItemRepo;
|
||||
this.customerRepo = customerRepo;
|
||||
this.storageService = storageService;
|
||||
this.invoiceService = invoiceService;
|
||||
this.qrBillService = qrBillService;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Order createOrderFromQuote(UUID quoteSessionId, CreateOrderRequest request) {
|
||||
QuoteSession session = quoteSessionRepo.findById(quoteSessionId)
|
||||
.orElseThrow(() -> new RuntimeException("Quote Session not found"));
|
||||
|
||||
if (session.getConvertedOrderId() != null) {
|
||||
throw new IllegalStateException("Quote session already converted to order");
|
||||
}
|
||||
|
||||
Customer customer = customerRepo.findByEmail(request.getCustomer().getEmail())
|
||||
.orElseGet(() -> {
|
||||
Customer newC = new Customer();
|
||||
newC.setEmail(request.getCustomer().getEmail());
|
||||
newC.setCustomerType(request.getCustomer().getCustomerType());
|
||||
newC.setCreatedAt(OffsetDateTime.now());
|
||||
newC.setUpdatedAt(OffsetDateTime.now());
|
||||
return customerRepo.save(newC);
|
||||
});
|
||||
|
||||
customer.setPhone(request.getCustomer().getPhone());
|
||||
customer.setCustomerType(request.getCustomer().getCustomerType());
|
||||
customer.setUpdatedAt(OffsetDateTime.now());
|
||||
customerRepo.save(customer);
|
||||
|
||||
Order order = new Order();
|
||||
order.setSourceQuoteSession(session);
|
||||
order.setCustomer(customer);
|
||||
order.setCustomerEmail(request.getCustomer().getEmail());
|
||||
order.setCustomerPhone(request.getCustomer().getPhone());
|
||||
order.setStatus("PENDING_PAYMENT");
|
||||
order.setCreatedAt(OffsetDateTime.now());
|
||||
order.setUpdatedAt(OffsetDateTime.now());
|
||||
order.setCurrency("CHF");
|
||||
|
||||
order.setBillingCustomerType(request.getCustomer().getCustomerType());
|
||||
if (request.getBillingAddress() != null) {
|
||||
order.setBillingFirstName(request.getBillingAddress().getFirstName());
|
||||
order.setBillingLastName(request.getBillingAddress().getLastName());
|
||||
order.setBillingCompanyName(request.getBillingAddress().getCompanyName());
|
||||
order.setBillingContactPerson(request.getBillingAddress().getContactPerson());
|
||||
order.setBillingAddressLine1(request.getBillingAddress().getAddressLine1());
|
||||
order.setBillingAddressLine2(request.getBillingAddress().getAddressLine2());
|
||||
order.setBillingZip(request.getBillingAddress().getZip());
|
||||
order.setBillingCity(request.getBillingAddress().getCity());
|
||||
order.setBillingCountryCode(request.getBillingAddress().getCountryCode() != null ? request.getBillingAddress().getCountryCode() : "CH");
|
||||
}
|
||||
|
||||
order.setShippingSameAsBilling(request.isShippingSameAsBilling());
|
||||
if (!request.isShippingSameAsBilling() && request.getShippingAddress() != null) {
|
||||
order.setShippingFirstName(request.getShippingAddress().getFirstName());
|
||||
order.setShippingLastName(request.getShippingAddress().getLastName());
|
||||
order.setShippingCompanyName(request.getShippingAddress().getCompanyName());
|
||||
order.setShippingContactPerson(request.getShippingAddress().getContactPerson());
|
||||
order.setShippingAddressLine1(request.getShippingAddress().getAddressLine1());
|
||||
order.setShippingAddressLine2(request.getShippingAddress().getAddressLine2());
|
||||
order.setShippingZip(request.getShippingAddress().getZip());
|
||||
order.setShippingCity(request.getShippingAddress().getCity());
|
||||
order.setShippingCountryCode(request.getShippingAddress().getCountryCode() != null ? request.getShippingAddress().getCountryCode() : "CH");
|
||||
} else {
|
||||
order.setShippingFirstName(order.getBillingFirstName());
|
||||
order.setShippingLastName(order.getBillingLastName());
|
||||
order.setShippingCompanyName(order.getBillingCompanyName());
|
||||
order.setShippingContactPerson(order.getBillingContactPerson());
|
||||
order.setShippingAddressLine1(order.getBillingAddressLine1());
|
||||
order.setShippingAddressLine2(order.getBillingAddressLine2());
|
||||
order.setShippingZip(order.getBillingZip());
|
||||
order.setShippingCity(order.getBillingCity());
|
||||
order.setShippingCountryCode(order.getBillingCountryCode());
|
||||
}
|
||||
|
||||
List<QuoteLineItem> quoteItems = quoteLineItemRepo.findByQuoteSessionId(quoteSessionId);
|
||||
|
||||
BigDecimal subtotal = BigDecimal.ZERO;
|
||||
order.setSubtotalChf(BigDecimal.ZERO);
|
||||
order.setTotalChf(BigDecimal.ZERO);
|
||||
order.setDiscountChf(BigDecimal.ZERO);
|
||||
order.setSetupCostChf(session.getSetupCostChf() != null ? session.getSetupCostChf() : BigDecimal.ZERO);
|
||||
order.setShippingCostChf(BigDecimal.valueOf(9.00));
|
||||
|
||||
order = orderRepo.save(order);
|
||||
|
||||
List<OrderItem> savedItems = new ArrayList<>();
|
||||
|
||||
for (QuoteLineItem qItem : quoteItems) {
|
||||
OrderItem oItem = new OrderItem();
|
||||
oItem.setOrder(order);
|
||||
oItem.setOriginalFilename(qItem.getOriginalFilename());
|
||||
oItem.setQuantity(qItem.getQuantity());
|
||||
oItem.setColorCode(qItem.getColorCode());
|
||||
oItem.setMaterialCode(session.getMaterialCode());
|
||||
|
||||
oItem.setUnitPriceChf(qItem.getUnitPriceChf());
|
||||
oItem.setLineTotalChf(qItem.getUnitPriceChf().multiply(BigDecimal.valueOf(qItem.getQuantity())));
|
||||
oItem.setPrintTimeSeconds(qItem.getPrintTimeSeconds());
|
||||
oItem.setMaterialGrams(qItem.getMaterialGrams());
|
||||
|
||||
UUID fileUuid = UUID.randomUUID();
|
||||
String ext = getExtension(qItem.getOriginalFilename());
|
||||
String storedFilename = fileUuid.toString() + "." + ext;
|
||||
|
||||
oItem.setStoredFilename(storedFilename);
|
||||
oItem.setStoredRelativePath("PENDING");
|
||||
oItem.setMimeType("application/octet-stream");
|
||||
oItem.setCreatedAt(OffsetDateTime.now());
|
||||
|
||||
oItem = orderItemRepo.save(oItem);
|
||||
|
||||
String relativePath = "orders/" + order.getId() + "/3d-files/" + oItem.getId() + "/" + storedFilename;
|
||||
oItem.setStoredRelativePath(relativePath);
|
||||
|
||||
if (qItem.getStoredPath() != null) {
|
||||
try {
|
||||
Path sourcePath = Paths.get(qItem.getStoredPath());
|
||||
if (Files.exists(sourcePath)) {
|
||||
storageService.store(sourcePath, Paths.get(relativePath));
|
||||
oItem.setFileSizeBytes(Files.size(sourcePath));
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
oItem = orderItemRepo.save(oItem);
|
||||
savedItems.add(oItem);
|
||||
subtotal = subtotal.add(oItem.getLineTotalChf());
|
||||
}
|
||||
|
||||
order.setSubtotalChf(subtotal);
|
||||
if (order.getShippingCostChf() == null) {
|
||||
order.setShippingCostChf(BigDecimal.valueOf(9.00));
|
||||
}
|
||||
|
||||
BigDecimal total = subtotal.add(order.getSetupCostChf()).add(order.getShippingCostChf()).subtract(order.getDiscountChf() != null ? order.getDiscountChf() : BigDecimal.ZERO);
|
||||
order.setTotalChf(total);
|
||||
|
||||
session.setConvertedOrderId(order.getId());
|
||||
session.setStatus("CONVERTED");
|
||||
quoteSessionRepo.save(session);
|
||||
|
||||
// Generate Invoice and QR Bill
|
||||
generateAndSaveDocuments(order, savedItems);
|
||||
|
||||
return orderRepo.save(order);
|
||||
}
|
||||
|
||||
private void generateAndSaveDocuments(Order order, List<OrderItem> items) {
|
||||
try {
|
||||
// 1. Generate QR Bill
|
||||
byte[] qrBillSvgBytes = qrBillService.generateQrBillSvg(order);
|
||||
String qrBillSvg = new String(qrBillSvgBytes, StandardCharsets.UTF_8);
|
||||
|
||||
// Strip XML declaration and DOCTYPE if present, as they validity break the embedding HTML page
|
||||
if (qrBillSvg.contains("<?xml")) {
|
||||
int svgStartIndex = qrBillSvg.indexOf("<svg");
|
||||
if (svgStartIndex != -1) {
|
||||
qrBillSvg = qrBillSvg.substring(svgStartIndex);
|
||||
}
|
||||
}
|
||||
|
||||
// Save QR Bill SVG
|
||||
String qrRelativePath = "orders/" + order.getId() + "/documents/qr-bill.svg";
|
||||
saveFileBytes(qrBillSvgBytes, qrRelativePath);
|
||||
|
||||
// 2. Prepare Invoice Variables
|
||||
Map<String, Object> vars = new HashMap<>();
|
||||
vars.put("sellerDisplayName", "3D Fab Switzerland");
|
||||
vars.put("sellerAddressLine1", "Sede Ticino, Svizzera");
|
||||
vars.put("sellerAddressLine2", "Sede Bienne, Svizzera");
|
||||
vars.put("sellerEmail", "info@3dfab.ch");
|
||||
|
||||
vars.put("invoiceNumber", "INV-" + order.getId().toString().substring(0, 8).toUpperCase());
|
||||
vars.put("invoiceDate", order.getCreatedAt().format(DateTimeFormatter.ISO_LOCAL_DATE));
|
||||
vars.put("dueDate", order.getCreatedAt().plusDays(7).format(DateTimeFormatter.ISO_LOCAL_DATE));
|
||||
|
||||
String buyerName = "BUSINESS".equals(order.getBillingCustomerType())
|
||||
? order.getBillingCompanyName()
|
||||
: order.getBillingFirstName() + " " + order.getBillingLastName();
|
||||
vars.put("buyerDisplayName", buyerName);
|
||||
vars.put("buyerAddressLine1", order.getBillingAddressLine1());
|
||||
vars.put("buyerAddressLine2", order.getBillingZip() + " " + order.getBillingCity() + ", " + order.getBillingCountryCode());
|
||||
|
||||
List<Map<String, Object>> invoiceLineItems = items.stream().map(i -> {
|
||||
Map<String, Object> line = new HashMap<>();
|
||||
line.put("description", "Stampa 3D: " + i.getOriginalFilename());
|
||||
line.put("quantity", i.getQuantity());
|
||||
line.put("unitPriceFormatted", String.format("CHF %.2f", i.getUnitPriceChf()));
|
||||
line.put("lineTotalFormatted", String.format("CHF %.2f", i.getLineTotalChf()));
|
||||
return line;
|
||||
}).collect(Collectors.toList());
|
||||
|
||||
Map<String, Object> setupLine = new HashMap<>();
|
||||
setupLine.put("description", "Costo Setup");
|
||||
setupLine.put("quantity", 1);
|
||||
setupLine.put("unitPriceFormatted", String.format("CHF %.2f", order.getSetupCostChf()));
|
||||
setupLine.put("lineTotalFormatted", String.format("CHF %.2f", order.getSetupCostChf()));
|
||||
invoiceLineItems.add(setupLine);
|
||||
|
||||
Map<String, Object> shippingLine = new HashMap<>();
|
||||
shippingLine.put("description", "Spedizione");
|
||||
shippingLine.put("quantity", 1);
|
||||
shippingLine.put("unitPriceFormatted", String.format("CHF %.2f", order.getShippingCostChf()));
|
||||
shippingLine.put("lineTotalFormatted", String.format("CHF %.2f", order.getShippingCostChf()));
|
||||
invoiceLineItems.add(shippingLine);
|
||||
|
||||
vars.put("invoiceLineItems", invoiceLineItems);
|
||||
vars.put("subtotalFormatted", String.format("CHF %.2f", order.getSubtotalChf()));
|
||||
vars.put("grandTotalFormatted", String.format("CHF %.2f", order.getTotalChf()));
|
||||
vars.put("paymentTermsText", "Appena riceviamo il pagamento l'ordine entrerà nella coda di stampa. Grazie per la fiducia");
|
||||
|
||||
// 3. Generate PDF
|
||||
byte[] pdfBytes = invoiceService.generateInvoicePdfBytesFromTemplate(vars, qrBillSvg);
|
||||
|
||||
// Save PDF
|
||||
String pdfRelativePath = "orders/" + order.getId() + "/documents/invoice-" + order.getId() + ".pdf";
|
||||
saveFileBytes(pdfBytes, pdfRelativePath);
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
// Don't fail the order if document generation fails, but log it
|
||||
// TODO: Better error handling
|
||||
}
|
||||
}
|
||||
|
||||
private void saveFileBytes(byte[] content, String relativePath) {
|
||||
// Since StorageService takes paths, we might need to write to temp first or check if it supports bytes/streams
|
||||
// Simulating via temp file for now as StorageService.store takes a Path
|
||||
try {
|
||||
Path tempFile = Files.createTempFile("print-calc-upload", ".tmp");
|
||||
Files.write(tempFile, content);
|
||||
storageService.store(tempFile, Paths.get(relativePath));
|
||||
Files.delete(tempFile);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Failed to save file " + relativePath, e);
|
||||
}
|
||||
}
|
||||
|
||||
private String getExtension(String filename) {
|
||||
if (filename == null) return "stl";
|
||||
int i = filename.lastIndexOf('.');
|
||||
if (i > 0) {
|
||||
return filename.substring(i + 1);
|
||||
}
|
||||
return "stl";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package com.printcalculator.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Iterator;
|
||||
import java.util.Optional;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.stream.Stream;
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
import java.math.BigDecimal;
|
||||
|
||||
@Service
|
||||
public class ProfileManager {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(ProfileManager.class.getName());
|
||||
private final String profilesRoot;
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
private final Map<String, String> profileAliases;
|
||||
|
||||
public ProfileManager(@Value("${profiles.root:profiles}") String profilesRoot, ObjectMapper mapper) {
|
||||
this.profilesRoot = profilesRoot;
|
||||
this.mapper = mapper;
|
||||
this.profileAliases = new HashMap<>();
|
||||
initializeAliases();
|
||||
}
|
||||
|
||||
private void initializeAliases() {
|
||||
// Machine Aliases
|
||||
profileAliases.put("bambu_a1", "Bambu Lab A1 0.4 nozzle");
|
||||
|
||||
// Material Aliases
|
||||
profileAliases.put("pla_basic", "Bambu PLA Basic @BBL A1");
|
||||
profileAliases.put("petg_basic", "Bambu PETG Basic @BBL A1");
|
||||
profileAliases.put("tpu_95a", "Bambu TPU 95A @BBL A1");
|
||||
|
||||
// Quality/Process Aliases
|
||||
profileAliases.put("draft", "0.24mm Draft @BBL A1");
|
||||
profileAliases.put("standard", "0.20mm Standard @BBL A1"); // or 0.20mm Standard @BBL A1
|
||||
profileAliases.put("extra_fine", "0.08mm High Quality @BBL A1");
|
||||
|
||||
// Additional aliases from error logs
|
||||
profileAliases.put("Bambu_Process_0.20_Standard", "0.20mm Standard @BBL A1");
|
||||
}
|
||||
|
||||
public ObjectNode getMergedProfile(String profileName, String type) throws IOException {
|
||||
Path profilePath = findProfileFile(profileName, type);
|
||||
if (profilePath == null) {
|
||||
throw new IOException("Profile not found: " + profileName);
|
||||
}
|
||||
return resolveInheritance(profilePath);
|
||||
}
|
||||
|
||||
public String resolveMachineProfileName(String machineName, Double nozzleDiameter) {
|
||||
String resolvedName = profileAliases.getOrDefault(machineName, machineName);
|
||||
if (nozzleDiameter == null) return resolvedName;
|
||||
|
||||
String base = resolvedName.replaceAll("\\s*\\d+(?:\\.\\d+)?\\s*nozzle$", "").trim();
|
||||
String formatted = BigDecimal.valueOf(nozzleDiameter).stripTrailingZeros().toPlainString();
|
||||
String candidate = base + " " + formatted + " nozzle";
|
||||
|
||||
Path exists = findProfileFile(candidate, "machine");
|
||||
return exists != null ? candidate : resolvedName;
|
||||
}
|
||||
|
||||
private Path findProfileFile(String name, String type) {
|
||||
// Check aliases first
|
||||
String resolvedName = profileAliases.getOrDefault(name, name);
|
||||
|
||||
// Simple search: look for name.json in the profiles_root recursively
|
||||
// Type could be "machine", "process", "filament" to narrow down, but for now global search
|
||||
String filename = resolvedName.endsWith(".json") ? resolvedName : resolvedName + ".json";
|
||||
|
||||
try (Stream<Path> stream = Files.walk(Paths.get(profilesRoot))) {
|
||||
Optional<Path> found = stream
|
||||
.filter(p -> p.getFileName().toString().equals(filename))
|
||||
.findFirst();
|
||||
return found.orElse(null);
|
||||
} catch (IOException e) {
|
||||
logger.severe("Error searching for profile: " + e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private ObjectNode resolveInheritance(Path currentPath) throws IOException {
|
||||
// 1. Load current
|
||||
JsonNode currentNode = mapper.readTree(currentPath.toFile());
|
||||
|
||||
// 2. Check inherits
|
||||
if (currentNode.has("inherits")) {
|
||||
String parentName = currentNode.get("inherits").asText();
|
||||
// Try to find parent in same directory or standard search
|
||||
Path parentPath = currentPath.getParent().resolve(parentName);
|
||||
if (!Files.exists(parentPath)) {
|
||||
// If not in same dir, search globally
|
||||
parentPath = findProfileFile(parentName, "any");
|
||||
}
|
||||
|
||||
if (parentPath != null && Files.exists(parentPath)) {
|
||||
// Recursive call
|
||||
ObjectNode parentNode = resolveInheritance(parentPath);
|
||||
// Merge current into parent (child overrides parent)
|
||||
merge(parentNode, (ObjectNode) currentNode);
|
||||
// Remove "inherits" field
|
||||
parentNode.remove("inherits");
|
||||
return parentNode;
|
||||
} else {
|
||||
logger.warning("Inherited profile not found: " + parentName + " for " + currentPath);
|
||||
}
|
||||
}
|
||||
|
||||
if (currentNode instanceof ObjectNode) {
|
||||
return (ObjectNode) currentNode;
|
||||
} else {
|
||||
// Should verify it is an object
|
||||
return (ObjectNode) currentNode;
|
||||
}
|
||||
}
|
||||
|
||||
// Shallow merge suitable for OrcaSlicer profiles
|
||||
private void merge(ObjectNode mainNode, ObjectNode updateNode) {
|
||||
Iterator<String> fieldNames = updateNode.fieldNames();
|
||||
while (fieldNames.hasNext()) {
|
||||
String fieldName = fieldNames.next();
|
||||
JsonNode jsonNode = updateNode.get(fieldName);
|
||||
// Replace standard fields
|
||||
mainNode.set(fieldName, jsonNode);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.printcalculator.service;
|
||||
|
||||
import com.printcalculator.entity.Order;
|
||||
import net.codecrete.qrbill.generator.Bill;
|
||||
import net.codecrete.qrbill.generator.GraphicsFormat;
|
||||
import net.codecrete.qrbill.generator.QRBill;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
@Service
|
||||
public class QrBillService {
|
||||
|
||||
public byte[] generateQrBillSvg(Order order) {
|
||||
Bill bill = createBillFromOrder(order);
|
||||
return QRBill.generate(bill);
|
||||
}
|
||||
|
||||
public Bill createBillFromOrder(Order order) {
|
||||
Bill bill = new Bill();
|
||||
|
||||
// Creditor (Merchant)
|
||||
bill.setAccount("CH7409000000154821581"); // TODO: Configurable IBAN
|
||||
bill.setCreditor(createAddress(
|
||||
"Küng, Joe",
|
||||
"Via G. Pioda 29a",
|
||||
"6710",
|
||||
"Biasca",
|
||||
"CH"
|
||||
));
|
||||
|
||||
// Debtor (Customer)
|
||||
String debtorName;
|
||||
if ("BUSINESS".equals(order.getBillingCustomerType())) {
|
||||
debtorName = order.getBillingCompanyName();
|
||||
} else {
|
||||
debtorName = order.getBillingFirstName() + " " + order.getBillingLastName();
|
||||
}
|
||||
|
||||
bill.setDebtor(createAddress(
|
||||
debtorName,
|
||||
order.getBillingAddressLine1(), // Assuming simple address for now. Splitting might be needed if street/house number are separate
|
||||
order.getBillingZip(),
|
||||
order.getBillingCity(),
|
||||
order.getBillingCountryCode()
|
||||
));
|
||||
|
||||
// Amount
|
||||
bill.setAmount(order.getTotalChf());
|
||||
bill.setCurrency("CHF");
|
||||
|
||||
// Reference
|
||||
// bill.setReference(QRBill.createCreditorReference("...")); // If using QRR
|
||||
bill.setUnstructuredMessage("Order " + order.getId());
|
||||
|
||||
return bill;
|
||||
}
|
||||
|
||||
private net.codecrete.qrbill.generator.Address createAddress(String name, String street, String zip, String city, String country) {
|
||||
net.codecrete.qrbill.generator.Address address = new net.codecrete.qrbill.generator.Address();
|
||||
address.setName(name);
|
||||
address.setStreet(street);
|
||||
address.setPostalCode(zip);
|
||||
address.setTown(city);
|
||||
address.setCountryCode(country);
|
||||
return address;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package com.printcalculator.service;
|
||||
|
||||
|
||||
import com.printcalculator.entity.FilamentMaterialType;
|
||||
import com.printcalculator.entity.FilamentVariant;
|
||||
import com.printcalculator.entity.PricingPolicy;
|
||||
import com.printcalculator.entity.PricingPolicyMachineHourTier;
|
||||
import com.printcalculator.entity.PrinterMachine;
|
||||
import com.printcalculator.model.PrintStats;
|
||||
import com.printcalculator.model.QuoteResult;
|
||||
import com.printcalculator.repository.FilamentMaterialTypeRepository;
|
||||
import com.printcalculator.repository.FilamentVariantRepository;
|
||||
import com.printcalculator.repository.PricingPolicyMachineHourTierRepository;
|
||||
import com.printcalculator.repository.PricingPolicyRepository;
|
||||
import com.printcalculator.repository.PrinterMachineRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class QuoteCalculator {
|
||||
|
||||
private final PricingPolicyRepository pricingRepo;
|
||||
private final PricingPolicyMachineHourTierRepository tierRepo;
|
||||
private final PrinterMachineRepository machineRepo;
|
||||
private final FilamentMaterialTypeRepository materialRepo;
|
||||
private final FilamentVariantRepository variantRepo;
|
||||
|
||||
public QuoteCalculator(PricingPolicyRepository pricingRepo,
|
||||
PricingPolicyMachineHourTierRepository tierRepo,
|
||||
PrinterMachineRepository machineRepo,
|
||||
FilamentMaterialTypeRepository materialRepo,
|
||||
FilamentVariantRepository variantRepo) {
|
||||
this.pricingRepo = pricingRepo;
|
||||
this.tierRepo = tierRepo;
|
||||
this.machineRepo = machineRepo;
|
||||
this.materialRepo = materialRepo;
|
||||
this.variantRepo = variantRepo;
|
||||
}
|
||||
|
||||
public QuoteResult calculate(PrintStats stats, String machineName, String filamentProfileName) {
|
||||
// 1. Fetch Active Policy
|
||||
PricingPolicy policy = pricingRepo.findFirstByIsActiveTrueOrderByValidFromDesc();
|
||||
if (policy == null) {
|
||||
throw new RuntimeException("No active pricing policy found");
|
||||
}
|
||||
|
||||
// 2. Fetch Machine Info
|
||||
// Map "bambu_a1" -> "BambuLab A1" or similar?
|
||||
// Ideally we should use the display name from DB.
|
||||
// For now, if machineName is a code, we might need a mapping or just fuzzy search.
|
||||
// Let's assume machineName is mapped or we search by display name.
|
||||
// If not found, fallback to first active.
|
||||
PrinterMachine machine = machineRepo.findByPrinterDisplayName(machineName).orElse(null);
|
||||
if (machine == null) {
|
||||
// Try "BambuLab A1" if code was "bambu_a1" logic or just get first active
|
||||
machine = machineRepo.findFirstByIsActiveTrue()
|
||||
.orElseThrow(() -> new RuntimeException("No active printer found"));
|
||||
}
|
||||
|
||||
// 3. Fetch Filament Info
|
||||
// filamentProfileName might be "bambu_pla_basic_black" or "Generic PLA"
|
||||
// We try to extract material code (PLA, PETG)
|
||||
String materialCode = detectMaterialCode(filamentProfileName);
|
||||
FilamentMaterialType materialType = materialRepo.findByMaterialCode(materialCode)
|
||||
.orElseThrow(() -> new RuntimeException("Unknown material type: " + materialCode));
|
||||
|
||||
// Try to find specific variant (e.g. by color if we could parse it)
|
||||
// For now, get default/first active variant for this material
|
||||
FilamentVariant variant = variantRepo.findFirstByFilamentMaterialTypeAndIsActiveTrue(materialType)
|
||||
.orElseThrow(() -> new RuntimeException("No active variant for material: " + materialCode));
|
||||
|
||||
|
||||
// --- CALCULATIONS ---
|
||||
|
||||
// Material Cost: (weight / 1000) * costPerKg
|
||||
// DISCOUNTED Support material to avoid penalizing users for default supports
|
||||
BigDecimal weightToCharge;
|
||||
if (stats.getModelWeightGrams() != null && stats.getSupportWeightGrams() != null) {
|
||||
// Charge 100% for model + 20% for support
|
||||
weightToCharge = BigDecimal.valueOf(stats.getModelWeightGrams())
|
||||
.add(BigDecimal.valueOf(stats.getSupportWeightGrams()).multiply(BigDecimal.valueOf(0.2)));
|
||||
} else {
|
||||
weightToCharge = BigDecimal.valueOf(stats.getFilamentWeightGrams());
|
||||
}
|
||||
|
||||
BigDecimal weightKg = weightToCharge.divide(BigDecimal.valueOf(1000), 4, RoundingMode.HALF_UP);
|
||||
BigDecimal materialCost = weightKg.multiply(variant.getCostChfPerKg());
|
||||
|
||||
// Machine Cost: Tiered
|
||||
BigDecimal totalHours = BigDecimal.valueOf(stats.getPrintTimeSeconds()).divide(BigDecimal.valueOf(3600), 4, RoundingMode.HALF_UP);
|
||||
BigDecimal machineCost = calculateMachineCost(policy, totalHours);
|
||||
|
||||
// Energy Cost: (watts / 1000) * hours * costPerKwh
|
||||
BigDecimal kw = BigDecimal.valueOf(machine.getPowerWatts()).divide(BigDecimal.valueOf(1000), 4, RoundingMode.HALF_UP);
|
||||
BigDecimal kwh = kw.multiply(totalHours);
|
||||
BigDecimal energyCost = kwh.multiply(policy.getElectricityCostChfPerKwh());
|
||||
|
||||
// Subtotal (Costs + Fixed Fees)
|
||||
BigDecimal fixedFee = policy.getFixedJobFeeChf();
|
||||
BigDecimal subtotal = materialCost.add(machineCost).add(energyCost).add(fixedFee);
|
||||
|
||||
// Markup
|
||||
// Markup is percentage (e.g. 20.0)
|
||||
BigDecimal markupFactor = BigDecimal.ONE.add(policy.getMarkupPercent().divide(BigDecimal.valueOf(100), 4, RoundingMode.HALF_UP));
|
||||
BigDecimal totalPrice = subtotal.multiply(markupFactor).setScale(2, RoundingMode.HALF_UP);
|
||||
|
||||
return new QuoteResult(totalPrice.doubleValue(), "CHF", stats, fixedFee.doubleValue());
|
||||
}
|
||||
|
||||
private BigDecimal calculateMachineCost(PricingPolicy policy, BigDecimal hours) {
|
||||
List<PricingPolicyMachineHourTier> tiers = tierRepo.findAllByPricingPolicyOrderByTierStartHoursAsc(policy);
|
||||
if (tiers.isEmpty()) {
|
||||
return BigDecimal.ZERO; // Should not happen if DB is correct
|
||||
}
|
||||
|
||||
BigDecimal remainingHours = hours;
|
||||
BigDecimal totalCost = BigDecimal.ZERO;
|
||||
BigDecimal processedHours = BigDecimal.ZERO;
|
||||
|
||||
for (PricingPolicyMachineHourTier tier : tiers) {
|
||||
if (remainingHours.compareTo(BigDecimal.ZERO) <= 0) break;
|
||||
|
||||
BigDecimal tierStart = tier.getTierStartHours();
|
||||
BigDecimal tierEnd = tier.getTierEndHours(); // can be null for infinity
|
||||
|
||||
// Determine duration in this tier
|
||||
// Valid duration in this tier = (min(tierEnd, totalHours) - tierStart)
|
||||
// But logic is simpler: we consume hours sequentially?
|
||||
// "0-10h @ 2CHF, 10-20h @ 1.5CHF" implies:
|
||||
// 5h job -> 5 * 2
|
||||
// 15h job -> 10 * 2 + 5 * 1.5
|
||||
|
||||
BigDecimal tierDuration;
|
||||
|
||||
// Max hours applicable in this tier relative to 0
|
||||
BigDecimal tierLimit = (tierEnd != null) ? tierEnd : BigDecimal.valueOf(Long.MAX_VALUE);
|
||||
|
||||
// The amount of hours falling into this bucket
|
||||
// Upper bound for this calculation is min(totalHours, tierLimit)
|
||||
// Lower bound is tierStart
|
||||
// So hours in this bucket = max(0, min(totalHours, tierLimit) - tierStart)
|
||||
|
||||
BigDecimal upper = hours.min(tierLimit);
|
||||
BigDecimal lower = tierStart;
|
||||
|
||||
if (upper.compareTo(lower) > 0) {
|
||||
BigDecimal hoursInTier = upper.subtract(lower);
|
||||
totalCost = totalCost.add(hoursInTier.multiply(tier.getMachineCostChfPerHour()));
|
||||
}
|
||||
}
|
||||
|
||||
return totalCost;
|
||||
}
|
||||
|
||||
private String detectMaterialCode(String profileName) {
|
||||
String lower = profileName.toLowerCase();
|
||||
if (lower.contains("petg")) return "PETG";
|
||||
if (lower.contains("tpu")) return "TPU";
|
||||
if (lower.contains("abs")) return "ABS";
|
||||
if (lower.contains("nylon")) return "Nylon";
|
||||
if (lower.contains("asa")) return "ASA";
|
||||
// Default to PLA
|
||||
return "PLA";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.printcalculator.service;
|
||||
|
||||
import com.printcalculator.entity.QuoteSession;
|
||||
import com.printcalculator.repository.QuoteSessionRepository;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@Service
|
||||
public class SessionCleanupService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(SessionCleanupService.class);
|
||||
private final QuoteSessionRepository sessionRepository;
|
||||
|
||||
public SessionCleanupService(QuoteSessionRepository sessionRepository) {
|
||||
this.sessionRepository = sessionRepository;
|
||||
}
|
||||
|
||||
// Run every day at 3 AM
|
||||
@Scheduled(cron = "0 0 3 * * ?")
|
||||
@Transactional
|
||||
public void cleanupOldSessions() {
|
||||
logger.info("Starting session cleanup job...");
|
||||
|
||||
OffsetDateTime cutoff = OffsetDateTime.now().minusDays(15);
|
||||
List<QuoteSession> oldSessions = sessionRepository.findByCreatedAtBefore(cutoff);
|
||||
|
||||
int deletedCount = 0;
|
||||
for (QuoteSession session : oldSessions) {
|
||||
// We only delete sessions that are NOT ordered?
|
||||
// The user request was "delete old ones".
|
||||
// Safest is to check status if we had one.
|
||||
// QuoteSession entity has 'status' field.
|
||||
// Let's assume we delete 'PENDING' or similar, but maybe we just delete all old inputs?
|
||||
// "rimangono in memoria... cancella quelle vecchie di 7 giorni".
|
||||
// Implementation plan said: status != 'ORDERED'.
|
||||
|
||||
// User specified statuses: ACTIVE, EXPIRED, CONVERTED.
|
||||
// We should NOT delete sessions that have been converted to an order.
|
||||
if ("CONVERTED".equals(session.getStatus())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
// Delete ACTIVE or EXPIRED sessions older than 7 days
|
||||
deleteSessionFiles(session.getId().toString());
|
||||
sessionRepository.delete(session);
|
||||
deletedCount++;
|
||||
} catch (Exception e) {
|
||||
logger.error("Failed to cleanup session {}", session.getId(), e);
|
||||
}
|
||||
}
|
||||
|
||||
logger.info("Session cleanup job finished. Deleted {} sessions.", deletedCount);
|
||||
}
|
||||
|
||||
private void deleteSessionFiles(String sessionId) {
|
||||
Path sessionDir = Paths.get("storage_quotes", sessionId);
|
||||
if (Files.exists(sessionDir)) {
|
||||
try (Stream<Path> walk = Files.walk(sessionDir)) {
|
||||
walk.sorted(java.util.Comparator.reverseOrder())
|
||||
.map(Path::toFile)
|
||||
.forEach(java.io.File::delete);
|
||||
} catch (IOException e) {
|
||||
logger.error("Failed to delete directory: {}", sessionDir, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package com.printcalculator.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.printcalculator.model.PrintStats;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@Service
|
||||
public class SlicerService {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(SlicerService.class.getName());
|
||||
|
||||
private final String slicerPath;
|
||||
private final ProfileManager profileManager;
|
||||
private final GCodeParser gCodeParser;
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
public SlicerService(
|
||||
@Value("${slicer.path}") String slicerPath,
|
||||
ProfileManager profileManager,
|
||||
GCodeParser gCodeParser,
|
||||
ObjectMapper mapper) {
|
||||
this.slicerPath = slicerPath;
|
||||
this.profileManager = profileManager;
|
||||
this.gCodeParser = gCodeParser;
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
public PrintStats slice(File inputStl, String machineName, String filamentName, String processName,
|
||||
Map<String, String> machineOverrides, Map<String, String> processOverrides) throws IOException {
|
||||
ObjectNode machineProfile = profileManager.getMergedProfile(machineName, "machine");
|
||||
ObjectNode filamentProfile = profileManager.getMergedProfile(filamentName, "filament");
|
||||
ObjectNode processProfile = profileManager.getMergedProfile(processName, "process");
|
||||
|
||||
if (machineOverrides != null) machineOverrides.forEach(machineProfile::put);
|
||||
if (processOverrides != null) processOverrides.forEach(processProfile::put);
|
||||
|
||||
Path tempDir = Files.createTempDirectory("slicer_job_");
|
||||
|
||||
try {
|
||||
File mFile = tempDir.resolve("machine.json").toFile();
|
||||
File fFile = tempDir.resolve("filament.json").toFile();
|
||||
File pFile = tempDir.resolve("process.json").toFile();
|
||||
|
||||
mapper.writeValue(mFile, machineProfile);
|
||||
mapper.writeValue(fFile, filamentProfile);
|
||||
mapper.writeValue(pFile, processProfile);
|
||||
|
||||
List<String> command = new ArrayList<>();
|
||||
command.add(slicerPath);
|
||||
|
||||
command.add("--load-settings");
|
||||
command.add(mFile.getAbsolutePath());
|
||||
command.add("--load-settings");
|
||||
command.add(pFile.getAbsolutePath());
|
||||
command.add("--load-filaments");
|
||||
command.add(fFile.getAbsolutePath());
|
||||
|
||||
command.add("--ensure-on-bed");
|
||||
command.add("--arrange");
|
||||
command.add("1");
|
||||
command.add("--outputdir");
|
||||
command.add(tempDir.toAbsolutePath().toString());
|
||||
|
||||
command.add("--slice");
|
||||
command.add("0");
|
||||
|
||||
command.add(inputStl.getAbsolutePath());
|
||||
|
||||
logger.info("Executing Slicer: " + String.join(" ", command));
|
||||
|
||||
runSlicerCommand(command, tempDir);
|
||||
|
||||
try (Stream<Path> s = Files.list(tempDir)) {
|
||||
Optional<Path> found = s.filter(p -> p.toString().endsWith(".gcode")).findFirst();
|
||||
if (found.isPresent()) return gCodeParser.parse(found.get().toFile());
|
||||
else throw new IOException("No GCode found in " + tempDir);
|
||||
}
|
||||
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
protected void runSlicerCommand(List<String> command, Path tempDir) throws IOException, InterruptedException {
|
||||
ProcessBuilder pb = new ProcessBuilder(command);
|
||||
pb.directory(tempDir.toFile());
|
||||
|
||||
Map<String, String> env = pb.environment();
|
||||
env.put("HOME", "/tmp");
|
||||
env.put("QT_QPA_PLATFORM", "offscreen");
|
||||
|
||||
Process process = pb.start();
|
||||
if (!process.waitFor(5, TimeUnit.MINUTES)) {
|
||||
process.destroy();
|
||||
throw new IOException("Slicer timeout");
|
||||
}
|
||||
|
||||
if (process.exitValue() != 0) {
|
||||
String out = new String(process.getInputStream().readAllBytes());
|
||||
String err = new String(process.getErrorStream().readAllBytes());
|
||||
throw new IOException("Slicer failed with exit code " + process.exitValue() + "\nERR: " + err + "\nOUT: " + out);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
package com.printcalculator.service;
|
||||
|
||||
import com.printcalculator.model.StlBounds;
|
||||
import com.printcalculator.model.StlShiftResult;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.io.RandomAccessFile;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Locale;
|
||||
|
||||
@Service
|
||||
public class StlService {
|
||||
|
||||
public StlBounds readBounds(File stlFile) throws IOException {
|
||||
long size = stlFile.length();
|
||||
if (size >= 84 && isBinaryStl(stlFile, size)) {
|
||||
return readBinaryBounds(stlFile);
|
||||
}
|
||||
return readAsciiBounds(stlFile);
|
||||
}
|
||||
|
||||
public StlShiftResult shiftToFitIfNeeded(File stlFile, StlBounds bounds,
|
||||
int bedX, int bedY, int bedZ) throws IOException {
|
||||
double sizeX = bounds.sizeX();
|
||||
double sizeY = bounds.sizeY();
|
||||
double sizeZ = bounds.sizeZ();
|
||||
|
||||
double targetMinX = (bedX - sizeX) / 2.0;
|
||||
double targetMinY = (bedY - sizeY) / 2.0;
|
||||
double targetMinZ = 0.0;
|
||||
|
||||
double offsetX = targetMinX - bounds.minX();
|
||||
double offsetY = targetMinY - bounds.minY();
|
||||
double offsetZ = targetMinZ - bounds.minZ();
|
||||
|
||||
boolean needsShift = Math.abs(offsetX) > 1e-6 || Math.abs(offsetY) > 1e-6 || Math.abs(offsetZ) > 1e-6;
|
||||
if (!needsShift) {
|
||||
return new StlShiftResult(null, offsetX, offsetY, offsetZ, false);
|
||||
}
|
||||
|
||||
Path shiftedPath = Files.createTempFile("stl_shifted_", ".stl");
|
||||
writeShifted(stlFile, shiftedPath.toFile(), offsetX, offsetY, offsetZ);
|
||||
return new StlShiftResult(shiftedPath, offsetX, offsetY, offsetZ, true);
|
||||
}
|
||||
|
||||
private boolean isBinaryStl(File stlFile, long size) throws IOException {
|
||||
try (RandomAccessFile raf = new RandomAccessFile(stlFile, "r")) {
|
||||
raf.seek(80);
|
||||
long triangleCount = readLEUInt32(raf);
|
||||
long expected = 84L + triangleCount * 50L;
|
||||
return expected == size;
|
||||
}
|
||||
}
|
||||
|
||||
private StlBounds readBinaryBounds(File stlFile) throws IOException {
|
||||
try (RandomAccessFile raf = new RandomAccessFile(stlFile, "r")) {
|
||||
raf.seek(80);
|
||||
long triangleCount = readLEUInt32(raf);
|
||||
raf.seek(84);
|
||||
|
||||
BoundsAccumulator acc = new BoundsAccumulator();
|
||||
for (long i = 0; i < triangleCount; i++) {
|
||||
// skip normal
|
||||
readLEFloat(raf);
|
||||
readLEFloat(raf);
|
||||
readLEFloat(raf);
|
||||
// 3 vertices
|
||||
acc.accept(readLEFloat(raf), readLEFloat(raf), readLEFloat(raf));
|
||||
acc.accept(readLEFloat(raf), readLEFloat(raf), readLEFloat(raf));
|
||||
acc.accept(readLEFloat(raf), readLEFloat(raf), readLEFloat(raf));
|
||||
// skip attribute byte count
|
||||
raf.skipBytes(2);
|
||||
}
|
||||
return acc.toBounds();
|
||||
}
|
||||
}
|
||||
|
||||
private StlBounds readAsciiBounds(File stlFile) throws IOException {
|
||||
BoundsAccumulator acc = new BoundsAccumulator();
|
||||
try (BufferedReader reader = Files.newBufferedReader(stlFile.toPath(), StandardCharsets.US_ASCII)) {
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
line = line.trim();
|
||||
if (!line.startsWith("vertex")) continue;
|
||||
String[] parts = line.split("\\s+");
|
||||
if (parts.length < 4) continue;
|
||||
double x = Double.parseDouble(parts[1]);
|
||||
double y = Double.parseDouble(parts[2]);
|
||||
double z = Double.parseDouble(parts[3]);
|
||||
acc.accept(x, y, z);
|
||||
}
|
||||
}
|
||||
return acc.toBounds();
|
||||
}
|
||||
|
||||
private void writeShifted(File input, File output, double offsetX, double offsetY, double offsetZ) throws IOException {
|
||||
long size = input.length();
|
||||
if (size >= 84 && isBinaryStl(input, size)) {
|
||||
writeShiftedBinary(input, output, offsetX, offsetY, offsetZ);
|
||||
} else {
|
||||
writeShiftedAscii(input, output, offsetX, offsetY, offsetZ);
|
||||
}
|
||||
}
|
||||
|
||||
private void writeShiftedAscii(File input, File output, double offsetX, double offsetY, double offsetZ) throws IOException {
|
||||
try (BufferedReader reader = Files.newBufferedReader(input.toPath(), StandardCharsets.US_ASCII);
|
||||
BufferedWriter writer = Files.newBufferedWriter(output.toPath(), StandardCharsets.US_ASCII)) {
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
String trimmed = line.trim();
|
||||
if (!trimmed.startsWith("vertex")) {
|
||||
writer.write(line);
|
||||
writer.newLine();
|
||||
continue;
|
||||
}
|
||||
String[] parts = trimmed.split("\\s+");
|
||||
if (parts.length < 4) {
|
||||
writer.write(line);
|
||||
writer.newLine();
|
||||
continue;
|
||||
}
|
||||
double x = Double.parseDouble(parts[1]) + offsetX;
|
||||
double y = Double.parseDouble(parts[2]) + offsetY;
|
||||
double z = Double.parseDouble(parts[3]) + offsetZ;
|
||||
int idx = line.indexOf("vertex");
|
||||
String indent = idx > 0 ? line.substring(0, idx) : "";
|
||||
writer.write(indent + String.format(Locale.US, "vertex %.6f %.6f %.6f", x, y, z));
|
||||
writer.newLine();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void writeShiftedBinary(File input, File output, double offsetX, double offsetY, double offsetZ) throws IOException {
|
||||
try (RandomAccessFile raf = new RandomAccessFile(input, "r");
|
||||
OutputStream out = new FileOutputStream(output)) {
|
||||
byte[] header = new byte[80];
|
||||
raf.readFully(header);
|
||||
out.write(header);
|
||||
|
||||
long triangleCount = readLEUInt32(raf);
|
||||
writeLEUInt32(out, triangleCount);
|
||||
|
||||
for (long i = 0; i < triangleCount; i++) {
|
||||
// normal
|
||||
writeLEFloat(out, readLEFloat(raf));
|
||||
writeLEFloat(out, readLEFloat(raf));
|
||||
writeLEFloat(out, readLEFloat(raf));
|
||||
|
||||
// vertices
|
||||
writeLEFloat(out, (float) (readLEFloat(raf) + offsetX));
|
||||
writeLEFloat(out, (float) (readLEFloat(raf) + offsetY));
|
||||
writeLEFloat(out, (float) (readLEFloat(raf) + offsetZ));
|
||||
|
||||
writeLEFloat(out, (float) (readLEFloat(raf) + offsetX));
|
||||
writeLEFloat(out, (float) (readLEFloat(raf) + offsetY));
|
||||
writeLEFloat(out, (float) (readLEFloat(raf) + offsetZ));
|
||||
|
||||
writeLEFloat(out, (float) (readLEFloat(raf) + offsetX));
|
||||
writeLEFloat(out, (float) (readLEFloat(raf) + offsetY));
|
||||
writeLEFloat(out, (float) (readLEFloat(raf) + offsetZ));
|
||||
|
||||
// attribute byte count
|
||||
int b1 = raf.read();
|
||||
int b2 = raf.read();
|
||||
if ((b1 | b2) < 0) throw new IOException("Unexpected EOF while reading STL");
|
||||
out.write(b1);
|
||||
out.write(b2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private long readLEUInt32(RandomAccessFile raf) throws IOException {
|
||||
int b1 = raf.read();
|
||||
int b2 = raf.read();
|
||||
int b3 = raf.read();
|
||||
int b4 = raf.read();
|
||||
if ((b1 | b2 | b3 | b4) < 0) throw new IOException("Unexpected EOF while reading STL");
|
||||
return ((long) b1 & 0xFF)
|
||||
| (((long) b2 & 0xFF) << 8)
|
||||
| (((long) b3 & 0xFF) << 16)
|
||||
| (((long) b4 & 0xFF) << 24);
|
||||
}
|
||||
|
||||
private int readLEInt(RandomAccessFile raf) throws IOException {
|
||||
int b1 = raf.read();
|
||||
int b2 = raf.read();
|
||||
int b3 = raf.read();
|
||||
int b4 = raf.read();
|
||||
if ((b1 | b2 | b3 | b4) < 0) throw new IOException("Unexpected EOF while reading STL");
|
||||
return (b1 & 0xFF)
|
||||
| ((b2 & 0xFF) << 8)
|
||||
| ((b3 & 0xFF) << 16)
|
||||
| ((b4 & 0xFF) << 24);
|
||||
}
|
||||
|
||||
private float readLEFloat(RandomAccessFile raf) throws IOException {
|
||||
return Float.intBitsToFloat(readLEInt(raf));
|
||||
}
|
||||
|
||||
private void writeLEUInt32(OutputStream out, long value) throws IOException {
|
||||
out.write((int) (value & 0xFF));
|
||||
out.write((int) ((value >> 8) & 0xFF));
|
||||
out.write((int) ((value >> 16) & 0xFF));
|
||||
out.write((int) ((value >> 24) & 0xFF));
|
||||
}
|
||||
|
||||
private void writeLEFloat(OutputStream out, float value) throws IOException {
|
||||
int bits = Float.floatToIntBits(value);
|
||||
out.write(bits & 0xFF);
|
||||
out.write((bits >> 8) & 0xFF);
|
||||
out.write((bits >> 16) & 0xFF);
|
||||
out.write((bits >> 24) & 0xFF);
|
||||
}
|
||||
|
||||
private static class BoundsAccumulator {
|
||||
private boolean hasPoint = false;
|
||||
private double minX;
|
||||
private double minY;
|
||||
private double minZ;
|
||||
private double maxX;
|
||||
private double maxY;
|
||||
private double maxZ;
|
||||
|
||||
void accept(double x, double y, double z) {
|
||||
if (!hasPoint) {
|
||||
minX = maxX = x;
|
||||
minY = maxY = y;
|
||||
minZ = maxZ = z;
|
||||
hasPoint = true;
|
||||
return;
|
||||
}
|
||||
if (x < minX) minX = x;
|
||||
if (y < minY) minY = y;
|
||||
if (z < minZ) minZ = z;
|
||||
if (x > maxX) maxX = x;
|
||||
if (y > maxY) maxY = y;
|
||||
if (z > maxZ) maxZ = z;
|
||||
}
|
||||
|
||||
StlBounds toBounds() throws IOException {
|
||||
if (!hasPoint) {
|
||||
throw new IOException("STL appears to contain no vertices");
|
||||
}
|
||||
return new StlBounds(minX, minY, minZ, maxX, maxY, maxZ);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.printcalculator.service;
|
||||
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import java.nio.file.Path;
|
||||
import java.io.IOException;
|
||||
|
||||
public interface StorageService {
|
||||
void init();
|
||||
void store(MultipartFile file, Path destination) throws IOException;
|
||||
void store(Path source, Path destination) throws IOException;
|
||||
void delete(Path path) throws IOException;
|
||||
Resource loadAsResource(Path path) throws IOException;
|
||||
}
|
||||
26
backend/src/main/resources/application.properties
Normal file
26
backend/src/main/resources/application.properties
Normal file
@@ -0,0 +1,26 @@
|
||||
spring.application.name=backend
|
||||
server.port=8000
|
||||
|
||||
# Database Configuration
|
||||
spring.datasource.url=${DB_URL:jdbc:postgresql://localhost:5432/printcalc}
|
||||
spring.datasource.username=${DB_USERNAME:printcalc}
|
||||
spring.datasource.password=${DB_PASSWORD:printcalc_secret}
|
||||
spring.jpa.hibernate.ddl-auto=update
|
||||
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
|
||||
|
||||
|
||||
# Slicer Configuration
|
||||
# Map SLICER_PATH env var if present (default to /opt/orcaslicer/AppRun or Mac path)
|
||||
slicer.path=${SLICER_PATH:/Applications/OrcaSlicer.app/Contents/MacOS/OrcaSlicer}
|
||||
profiles.root=${PROFILES_DIR:profiles}
|
||||
|
||||
|
||||
# File Upload Limits
|
||||
spring.servlet.multipart.max-file-size=200MB
|
||||
spring.servlet.multipart.max-request-size=200MB
|
||||
|
||||
# ClamAV Configuration
|
||||
clamav.host=${CLAMAV_HOST:clamav}
|
||||
clamav.port=${CLAMAV_PORT:3310}
|
||||
clamav.enabled=${CLAMAV_ENABLED:false}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user