Compare commits
65 Commits
10e1fb49f4
...
int
| Author | SHA1 | Date | |
|---|---|---|---|
| 4f4e3def35 | |||
| bb151ae835 | |||
| 7ebaff322c | |||
| e17da96c22 | |||
| 3e9745c7cc | |||
| 3da3e6c60c | |||
| 85b823d614 | |||
| d20d12c1f4 | |||
| ab5f6a609d | |||
| 5ba203a8d1 | |||
| 3ca3f8e466 | |||
| 5620f6a8eb | |||
| 1583ff479c | |||
| b7d81040e6 | |||
| b249cf2000 | |||
| dfc27da142 | |||
| dde92af857 | |||
| 7b92e63a49 | |||
| 8fac8ac892 | |||
| e5183590c5 | |||
| a219825b28 | |||
| 3b4ef37e58 | |||
| eb4ad8b637 | |||
| f0e0f57e7c | |||
| 150563a8f5 | |||
| 05e1c224f0 | |||
| f1636d9057 | |||
| 44d99b0a68 | |||
| 83b3008234 | |||
| 78af87ac3c | |||
| b3c0413b7c | |||
| 4f301b1652 | |||
| debf153f58 | |||
| f3d271ded2 | |||
| 13790f2055 | |||
| bcdeafe119 | |||
| 7978884ca6 | |||
| cb7b44073c | |||
| 99ae6db064 | |||
| fcf439e369 | |||
| cecdfacd33 | |||
| 5bc698815c | |||
| 53e141f8ad | |||
| 73ccf8f4de | |||
| 0b4daed512 | |||
| 8a7d736aa9 | |||
| ce179cac62 | |||
| ab7b95a3d7 | |||
| da8e476485 | |||
| 810d5f6c0c | |||
| 8a75aed6d8 | |||
| a0efdc105d | |||
| 422d80a4d4 | |||
| db4df2573c | |||
| 2f7e8798d2 | |||
| d816eeda1d | |||
| af5b40021d | |||
| 653186e9d3 | |||
| c6ec937ea0 | |||
| 3aa644e9ee | |||
| 21cf8891b2 | |||
| ceeb831a41 | |||
| 316c74e299 | |||
| a5ff515fd7 | |||
| 6952090865 |
@@ -15,17 +15,27 @@ jobs:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
# Evito actions/setup-python (spesso fragile su act_runner)
|
||||
- name: Install Python deps + run tests
|
||||
shell: bash
|
||||
- name: Set up JDK 21
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
java-version: '21'
|
||||
distribution: 'temurin'
|
||||
|
||||
- name: Cache Gradle
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.gradle/caches
|
||||
~/.gradle/wrapper
|
||||
key: gradle-${{ runner.os }}-${{ hashFiles('backend/gradle/wrapper/gradle-wrapper.properties', 'backend/**/*.gradle*', 'backend/gradle.properties') }}
|
||||
restore-keys: |
|
||||
gradle-${{ runner.os }}-
|
||||
|
||||
- name: Run Tests with Gradle
|
||||
run: |
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends python3 python3-pip
|
||||
python3 -m pip install --upgrade pip
|
||||
python3 -m pip install -r backend/requirements.txt
|
||||
python3 -m pip install pytest httpx
|
||||
export PYTHONPATH="${PYTHONPATH}:$(pwd)/backend"
|
||||
pytest backend/tests
|
||||
cd backend
|
||||
chmod +x gradlew
|
||||
./gradlew test
|
||||
|
||||
build-and-push:
|
||||
needs: test-backend
|
||||
@@ -81,6 +91,9 @@ jobs:
|
||||
needs: build-and-push
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set ENV
|
||||
shell: bash
|
||||
run: |
|
||||
@@ -92,7 +105,7 @@ jobs:
|
||||
echo "ENV=dev" >> "$GITHUB_ENV"
|
||||
fi
|
||||
|
||||
- name: Trigger deploy on Unraid (forced command key)
|
||||
- name: Setup SSH key
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
@@ -120,9 +133,48 @@ jobs:
|
||||
# 5) Validazione: se fallisce qui, la chiave NON è valida/corrotta
|
||||
ssh-keygen -y -f ~/.ssh/id_ed25519 >/dev/null
|
||||
|
||||
# ... (resto del codice uguale)
|
||||
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
|
||||
|
||||
|
||||
|
||||
- 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 }}" "${{ env.ENV }}"
|
||||
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/
|
||||
|
||||
@@ -36,3 +36,7 @@ Questo file serve a dare contesto all'AI (Antigravity/Gemini) sulla struttura e
|
||||
- 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.
|
||||
|
||||
## 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`.
|
||||
|
||||
|
||||
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
|
||||
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 (same as before)
|
||||
RUN apt-get update && apt-get install -y \
|
||||
wget \
|
||||
p7zip-full \
|
||||
@@ -8,36 +19,28 @@ 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 \
|
||||
&& 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()
|
||||
}
|
||||
44
backend/build.gradle
Normal file
44
backend/build.gradle
Normal file
@@ -0,0 +1,44 @@
|
||||
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'
|
||||
runtimeOnly 'org.postgresql:postgresql'
|
||||
developmentOnly 'org.springframework.boot:spring-boot-devtools'
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
|
||||
}
|
||||
|
||||
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,13 @@
|
||||
package com.printcalculator;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class BackendApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(BackendApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
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")
|
||||
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
|
||||
.allowedHeaders("*")
|
||||
.allowCredentials(true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
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());
|
||||
|
||||
// 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,127 @@
|
||||
package com.printcalculator.controller;
|
||||
|
||||
import com.printcalculator.entity.PrinterMachine;
|
||||
import com.printcalculator.model.PrintStats;
|
||||
import com.printcalculator.model.QuoteResult;
|
||||
import com.printcalculator.repository.PrinterMachineRepository;
|
||||
import com.printcalculator.service.QuoteCalculator;
|
||||
import com.printcalculator.service.SlicerService;
|
||||
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;
|
||||
|
||||
@RestController
|
||||
public class QuoteController {
|
||||
|
||||
private final SlicerService slicerService;
|
||||
private final QuoteCalculator quoteCalculator;
|
||||
private final PrinterMachineRepository machineRepo;
|
||||
|
||||
// Defaults (using aliases defined in ProfileManager)
|
||||
private static final String DEFAULT_FILAMENT = "pla_basic";
|
||||
private static final String DEFAULT_PROCESS = "standard";
|
||||
|
||||
public QuoteController(SlicerService slicerService, QuoteCalculator quoteCalculator, PrinterMachineRepository machineRepo) {
|
||||
this.slicerService = slicerService;
|
||||
this.quoteCalculator = quoteCalculator;
|
||||
this.machineRepo = machineRepo;
|
||||
}
|
||||
|
||||
@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) 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 (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);
|
||||
}
|
||||
|
||||
@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);
|
||||
}
|
||||
|
||||
private ResponseEntity<QuoteResult> processRequest(MultipartFile file, String filament, String process,
|
||||
Map<String, String> machineOverrides,
|
||||
Map<String, String> processOverrides) 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());
|
||||
try {
|
||||
file.transferTo(tempInput.toFile());
|
||||
|
||||
String slicerMachineProfile = "bambu_a1"; // TODO: Add to PrinterMachine entity
|
||||
|
||||
PrintStats stats = slicerService.slice(tempInput.toFile(), 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);
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return ResponseEntity.internalServerError().build();
|
||||
} finally {
|
||||
Files.deleteIfExists(tempInput);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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) {}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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,116 @@
|
||||
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;
|
||||
|
||||
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 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,8 @@
|
||||
package com.printcalculator.model;
|
||||
|
||||
public record PrintStats(
|
||||
long printTimeSeconds,
|
||||
String printTimeFormatted,
|
||||
double filamentWeightGrams,
|
||||
double 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,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.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.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,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,155 @@
|
||||
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*(.*)");
|
||||
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;
|
||||
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 weight: " + weightG + "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 new PrintStats(seconds, timeFormatted, weightG, lengthMm);
|
||||
}
|
||||
|
||||
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,126 @@
|
||||
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;
|
||||
|
||||
@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);
|
||||
}
|
||||
|
||||
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,158 @@
|
||||
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
|
||||
BigDecimal weightKg = BigDecimal.valueOf(stats.filamentWeightGrams()).divide(BigDecimal.valueOf(1000), 4, RoundingMode.HALF_UP);
|
||||
BigDecimal materialCost = weightKg.multiply(variant.getCostChfPerKg());
|
||||
|
||||
// Machine Cost: Tiered
|
||||
BigDecimal totalHours = BigDecimal.valueOf(stats.printTimeSeconds()).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,146 @@
|
||||
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.concurrent.TimeUnit;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
@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 {
|
||||
// 1. Prepare Profiles
|
||||
ObjectNode machineProfile = profileManager.getMergedProfile(machineName, "machine");
|
||||
ObjectNode filamentProfile = profileManager.getMergedProfile(filamentName, "filament");
|
||||
ObjectNode processProfile = profileManager.getMergedProfile(processName, "process");
|
||||
|
||||
// Apply Overrides
|
||||
if (machineOverrides != null) {
|
||||
machineOverrides.forEach(machineProfile::put);
|
||||
}
|
||||
if (processOverrides != null) {
|
||||
processOverrides.forEach(processProfile::put);
|
||||
}
|
||||
|
||||
// 2. Create Temp Dir
|
||||
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);
|
||||
|
||||
// 3. Build Command
|
||||
// --load-settings "machine.json;process.json" --load-filaments "filament.json"
|
||||
List<String> command = new ArrayList<>();
|
||||
command.add(slicerPath);
|
||||
|
||||
// Load machine settings
|
||||
command.add("--load-settings");
|
||||
command.add(mFile.getAbsolutePath());
|
||||
|
||||
// Load process settings
|
||||
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"); // force arrange
|
||||
command.add("--slice");
|
||||
command.add("0"); // slice plate 0
|
||||
command.add("--outputdir");
|
||||
command.add(tempDir.toAbsolutePath().toString());
|
||||
// Need to handle Mac structure for console if needed?
|
||||
// Usually the binary at Contents/MacOS/OrcaSlicer works fine as console app.
|
||||
|
||||
command.add(inputStl.getAbsolutePath());
|
||||
|
||||
logger.info("Executing Slicer: " + String.join(" ", command));
|
||||
|
||||
// 4. Run Process
|
||||
ProcessBuilder pb = new ProcessBuilder(command);
|
||||
pb.directory(tempDir.toFile());
|
||||
// pb.inheritIO(); // Useful for debugging, but maybe capture instead?
|
||||
|
||||
Process process = pb.start();
|
||||
boolean finished = process.waitFor(5, TimeUnit.MINUTES);
|
||||
|
||||
if (!finished) {
|
||||
process.destroy();
|
||||
throw new IOException("Slicer timed out");
|
||||
}
|
||||
|
||||
if (process.exitValue() != 0) {
|
||||
// Read stderr
|
||||
String error = new String(process.getErrorStream().readAllBytes());
|
||||
throw new IOException("Slicer failed with exit code " + process.exitValue() + ": " + error);
|
||||
}
|
||||
|
||||
// 5. Find Output GCode
|
||||
// Usually [basename].gcode or plate_1.gcode
|
||||
String basename = inputStl.getName();
|
||||
if (basename.toLowerCase().endsWith(".stl")) {
|
||||
basename = basename.substring(0, basename.length() - 4);
|
||||
}
|
||||
|
||||
File gcodeFile = tempDir.resolve(basename + ".gcode").toFile();
|
||||
if (!gcodeFile.exists()) {
|
||||
// Try plate_1.gcode fallback
|
||||
File alt = tempDir.resolve("plate_1.gcode").toFile();
|
||||
if (alt.exists()) {
|
||||
gcodeFile = alt;
|
||||
} else {
|
||||
throw new IOException("GCode output not found in " + tempDir);
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Parse Results
|
||||
return gCodeParser.parse(gcodeFile);
|
||||
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("Interrupted during slicing", e);
|
||||
} finally {
|
||||
// Cleanup temp dir
|
||||
// In production we should delete, for debugging we might want to keep?
|
||||
// Let's delete for now on success.
|
||||
// recursiveDelete(tempDir);
|
||||
// Leaving it effectively "leaks" temp, but safer for persistent debugging?
|
||||
// Implementation detail: Use a utility to clean up.
|
||||
}
|
||||
}
|
||||
}
|
||||
20
backend/src/main/resources/application.properties
Normal file
20
backend/src/main/resources/application.properties
Normal file
@@ -0,0 +1,20 @@
|
||||
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
|
||||
@@ -0,0 +1,113 @@
|
||||
package com.printcalculator.service;
|
||||
|
||||
import com.printcalculator.model.PrintStats;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class GCodeParserTest {
|
||||
|
||||
@Test
|
||||
void parse_validGcode_returnsCorrectStats() throws IOException {
|
||||
// Arrange
|
||||
File tempFile = File.createTempFile("test", ".gcode");
|
||||
try (FileWriter writer = new FileWriter(tempFile)) {
|
||||
writer.write("; generated by OrcaSlicer\n");
|
||||
writer.write("; estimated printing time = 1h 2m 3s\n");
|
||||
writer.write("; filament used [g] = 10.5\n");
|
||||
writer.write("; filament used [mm] = 3000.0\n");
|
||||
}
|
||||
|
||||
GCodeParser parser = new GCodeParser();
|
||||
|
||||
// Act
|
||||
PrintStats stats = parser.parse(tempFile);
|
||||
|
||||
// Assert
|
||||
assertEquals(3723, stats.printTimeSeconds()); // 3600 + 120 + 3
|
||||
assertEquals("1h 2m 3s", stats.printTimeFormatted());
|
||||
assertEquals(10.5, stats.filamentWeightGrams(), 0.001);
|
||||
assertEquals(3000.0, stats.filamentLengthMm(), 0.001);
|
||||
|
||||
tempFile.delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void parse_footerGcode_returnsCorrectStats() throws IOException {
|
||||
// Arrange
|
||||
File tempFile = File.createTempFile("test_footer", ".gcode");
|
||||
try (FileWriter writer = new FileWriter(tempFile)) {
|
||||
writer.write("; header\n");
|
||||
// ... many lines ...
|
||||
writer.write("; filament used [g] = 5.0\n");
|
||||
writer.write("; estimated printing time = 12m 30s\n");
|
||||
}
|
||||
|
||||
GCodeParser parser = new GCodeParser();
|
||||
PrintStats stats = parser.parse(tempFile);
|
||||
|
||||
assertEquals(750, stats.printTimeSeconds()); // 12*60 + 30
|
||||
assertEquals(5.0, stats.filamentWeightGrams(), 0.001);
|
||||
|
||||
tempFile.delete();
|
||||
}
|
||||
@Test
|
||||
void parse_withExtraTextInTimeLine_returnsCorrectStats() throws IOException {
|
||||
// Arrange
|
||||
File tempFile = File.createTempFile("test_extra", ".gcode");
|
||||
try (FileWriter writer = new FileWriter(tempFile)) {
|
||||
writer.write("; generated by OrcaSlicer\n");
|
||||
// Simulate the variation that was causing issues
|
||||
writer.write("; estimated printing time (normal mode) = 1h 2m 3s\n");
|
||||
writer.write("; filament used [g] = 10.5\n");
|
||||
writer.write("; filament used [mm] = 3000.0\n");
|
||||
}
|
||||
|
||||
GCodeParser parser = new GCodeParser();
|
||||
PrintStats stats = parser.parse(tempFile);
|
||||
|
||||
assertEquals(3723L, stats.printTimeSeconds());
|
||||
assertEquals("1h 2m 3s", stats.printTimeFormatted());
|
||||
|
||||
tempFile.delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void parse_colonFormattedTime_returnsCorrectStats() throws IOException {
|
||||
File tempFile = File.createTempFile("test_colon", ".gcode");
|
||||
try (FileWriter writer = new FileWriter(tempFile)) {
|
||||
writer.write("; generated by OrcaSlicer\n");
|
||||
writer.write("; print time: 01:02:03\n");
|
||||
writer.write("; filament used [g] = 7.5\n");
|
||||
}
|
||||
|
||||
GCodeParser parser = new GCodeParser();
|
||||
PrintStats stats = parser.parse(tempFile);
|
||||
|
||||
assertEquals(3723L, stats.printTimeSeconds());
|
||||
assertEquals("01:02:03", stats.printTimeFormatted());
|
||||
|
||||
tempFile.delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void parse_totalEstimatedTimeInline_returnsCorrectStats() throws IOException {
|
||||
File tempFile = File.createTempFile("test_total", ".gcode");
|
||||
try (FileWriter writer = new FileWriter(tempFile)) {
|
||||
writer.write("; generated by OrcaSlicer\n");
|
||||
writer.write("; model printing time: 5m 17s; total estimated time: 5m 21s\n");
|
||||
writer.write("; filament used [g] = 2.0\n");
|
||||
}
|
||||
|
||||
GCodeParser parser = new GCodeParser();
|
||||
PrintStats stats = parser.parse(tempFile);
|
||||
|
||||
assertEquals(321L, stats.printTimeSeconds());
|
||||
assertEquals("5m 21s", stats.printTimeFormatted());
|
||||
|
||||
tempFile.delete();
|
||||
}
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
solid cube
|
||||
facet normal 0 0 -1
|
||||
outer loop
|
||||
vertex 0 0 0
|
||||
vertex 10 0 0
|
||||
vertex 10 10 0
|
||||
endloop
|
||||
endfacet
|
||||
facet normal 0 0 -1
|
||||
outer loop
|
||||
vertex 0 0 0
|
||||
vertex 10 10 0
|
||||
vertex 0 10 0
|
||||
endloop
|
||||
endfacet
|
||||
facet normal 0 0 1
|
||||
outer loop
|
||||
vertex 0 0 10
|
||||
vertex 0 10 10
|
||||
vertex 10 10 10
|
||||
endloop
|
||||
endfacet
|
||||
facet normal 0 0 1
|
||||
outer loop
|
||||
vertex 0 0 10
|
||||
vertex 10 10 10
|
||||
vertex 10 0 10
|
||||
endloop
|
||||
endfacet
|
||||
facet normal 0 -1 0
|
||||
outer loop
|
||||
vertex 0 0 0
|
||||
vertex 0 0 10
|
||||
vertex 10 0 10
|
||||
endloop
|
||||
endfacet
|
||||
facet normal 0 -1 0
|
||||
outer loop
|
||||
vertex 0 0 0
|
||||
vertex 10 0 10
|
||||
vertex 10 0 0
|
||||
endloop
|
||||
endfacet
|
||||
facet normal 1 0 0
|
||||
outer loop
|
||||
vertex 10 0 0
|
||||
vertex 10 0 10
|
||||
vertex 10 10 10
|
||||
endloop
|
||||
endfacet
|
||||
facet normal 1 0 0
|
||||
outer loop
|
||||
vertex 10 0 0
|
||||
vertex 10 10 10
|
||||
vertex 10 10 0
|
||||
endloop
|
||||
endfacet
|
||||
facet normal 0 1 0
|
||||
outer loop
|
||||
vertex 10 10 0
|
||||
vertex 10 10 10
|
||||
vertex 0 10 10
|
||||
endloop
|
||||
endfacet
|
||||
facet normal 0 1 0
|
||||
outer loop
|
||||
vertex 10 10 0
|
||||
vertex 0 10 10
|
||||
vertex 0 10 0
|
||||
endloop
|
||||
endfacet
|
||||
facet normal -1 0 0
|
||||
outer loop
|
||||
vertex 0 10 0
|
||||
vertex 0 10 10
|
||||
vertex 0 0 10
|
||||
endloop
|
||||
endfacet
|
||||
facet normal -1 0 0
|
||||
outer loop
|
||||
vertex 0 10 0
|
||||
vertex 0 0 10
|
||||
vertex 0 0 0
|
||||
endloop
|
||||
endfacet
|
||||
endsolid cube
|
||||
@@ -1,58 +0,0 @@
|
||||
import sys
|
||||
import os
|
||||
import unittest
|
||||
import json
|
||||
|
||||
# Add backend to path
|
||||
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
|
||||
|
||||
from profile_manager import ProfileManager
|
||||
from profile_cache import get_cache_key
|
||||
|
||||
class TestProfileManager(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.pm = ProfileManager(profiles_root="profiles")
|
||||
|
||||
def test_list_machines(self):
|
||||
machines = self.pm.list_machines()
|
||||
print(f"Found machines: {len(machines)}")
|
||||
self.assertTrue(len(machines) > 0, "No machines found")
|
||||
# Check for a known machine
|
||||
self.assertTrue(any("Bambu Lab A1" in m for m in machines), "Bambu Lab A1 should be in the list")
|
||||
|
||||
def test_find_profile(self):
|
||||
# We know "Bambu Lab A1 0.4 nozzle" should exist (based on user context and mappings)
|
||||
# It might be in profiles/BBL/machine/
|
||||
path = self.pm._find_profile_file("Bambu Lab A1 0.4 nozzle", "machine")
|
||||
self.assertIsNotNone(path, "Could not find Bambu Lab A1 machine profile")
|
||||
print(f"Found profile at: {path}")
|
||||
|
||||
def test_scan_profiles_inheritance(self):
|
||||
# Pick a profile we expect to inherit stuff
|
||||
# e.g. "Bambu Lab A1 0.4 nozzle" inherits "fdm_bbl_3dp_001_common" which inherits "fdm_machine_common"
|
||||
merged, _, _ = self.pm.get_profiles(
|
||||
"Bambu Lab A1 0.4 nozzle",
|
||||
"Bambu PLA Basic @BBL A1",
|
||||
"0.20mm Standard @BBL A1"
|
||||
)
|
||||
|
||||
self.assertIsNotNone(merged)
|
||||
# Check if inherits is gone
|
||||
self.assertNotIn("inherits", merged)
|
||||
# Check if patch applied (G92 E0)
|
||||
self.assertIn("G92 E0", merged.get("layer_change_gcode", ""))
|
||||
|
||||
# Check specific key from base
|
||||
# "printer_technology": "FFF" is usually in common
|
||||
# We can't be 100% sure of keys without seeing file, but let's check something likely
|
||||
self.assertTrue("nozzle_diameter" in merged or "extruder_clearance_height_to_lid" in merged or "printable_height" in merged)
|
||||
|
||||
def test_mappings_resolution(self):
|
||||
# Test if the slicer service would resolve correctly?
|
||||
# We can just test the manager with mapped names if the manager supported it,
|
||||
# but the manager deals with explicit names.
|
||||
# Integration test handles the mapping.
|
||||
pass
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
366
db.sql
Normal file
366
db.sql
Normal file
@@ -0,0 +1,366 @@
|
||||
create table printer_machine
|
||||
(
|
||||
printer_machine_id bigserial primary key,
|
||||
printer_display_name text not null unique,
|
||||
|
||||
build_volume_x_mm integer not null check (build_volume_x_mm > 0),
|
||||
build_volume_y_mm integer not null check (build_volume_y_mm > 0),
|
||||
build_volume_z_mm integer not null check (build_volume_z_mm > 0),
|
||||
|
||||
power_watts integer not null check (power_watts > 0),
|
||||
|
||||
fleet_weight numeric(6, 3) not null default 1.000,
|
||||
|
||||
is_active boolean not null default true,
|
||||
created_at timestamptz not null default now()
|
||||
);
|
||||
|
||||
create view printer_fleet_current as
|
||||
select 1 as fleet_id,
|
||||
case
|
||||
when sum(fleet_weight) = 0 then null
|
||||
else round(sum(power_watts * fleet_weight) / sum(fleet_weight))::integer
|
||||
end as weighted_average_power_watts,
|
||||
max(build_volume_x_mm) as fleet_max_build_x_mm,
|
||||
max(build_volume_y_mm) as fleet_max_build_y_mm,
|
||||
max(build_volume_z_mm) as fleet_max_build_z_mm
|
||||
from printer_machine
|
||||
where is_active = true;
|
||||
|
||||
|
||||
|
||||
create table filament_material_type
|
||||
(
|
||||
filament_material_type_id bigserial primary key,
|
||||
material_code text not null unique, -- PLA, PETG, TPU, ASA...
|
||||
is_flexible boolean not null default false, -- sì/no
|
||||
is_technical boolean not null default false, -- sì/no
|
||||
technical_type_label text -- es: "alta temperatura", "rinforzato", ecc.
|
||||
);
|
||||
|
||||
create table filament_variant
|
||||
(
|
||||
filament_variant_id bigserial primary key,
|
||||
filament_material_type_id bigint not null references filament_material_type (filament_material_type_id),
|
||||
|
||||
variant_display_name text not null, -- es: "PLA Nero Opaco BrandX"
|
||||
color_name text not null, -- Nero, Bianco, ecc.
|
||||
is_matte boolean not null default false,
|
||||
is_special boolean not null default false,
|
||||
|
||||
cost_chf_per_kg numeric(10, 2) not null,
|
||||
|
||||
-- Stock espresso in rotoli anche frazionati
|
||||
stock_spools numeric(6, 3) not null default 0.000,
|
||||
spool_net_kg numeric(6, 3) not null default 1.000,
|
||||
|
||||
is_active boolean not null default true,
|
||||
created_at timestamptz not null default now(),
|
||||
|
||||
unique (filament_material_type_id, variant_display_name)
|
||||
);
|
||||
|
||||
-- (opzionale) kg disponibili calcolati
|
||||
create view filament_variant_stock_kg as
|
||||
select filament_variant_id,
|
||||
stock_spools,
|
||||
spool_net_kg,
|
||||
(stock_spools * spool_net_kg) as stock_kg
|
||||
from filament_variant;
|
||||
|
||||
|
||||
|
||||
create table pricing_policy
|
||||
(
|
||||
pricing_policy_id bigserial primary key,
|
||||
|
||||
policy_name text not null, -- es: "2026 Q1", "Default", ecc.
|
||||
|
||||
-- validità temporale (consiglio: valid_to esclusiva)
|
||||
valid_from timestamptz not null,
|
||||
valid_to timestamptz,
|
||||
|
||||
electricity_cost_chf_per_kwh numeric(10, 6) not null,
|
||||
markup_percent numeric(6, 3) not null default 20.000,
|
||||
|
||||
fixed_job_fee_chf numeric(10, 2) not null default 0.00, -- "costo fisso"
|
||||
nozzle_change_base_fee_chf numeric(10, 2) not null default 0.00, -- base cambio ugello, se vuoi
|
||||
cad_cost_chf_per_hour numeric(10, 2) not null default 0.00,
|
||||
|
||||
is_active boolean not null default true,
|
||||
created_at timestamptz not null default now()
|
||||
);
|
||||
|
||||
create table pricing_policy_machine_hour_tier
|
||||
(
|
||||
pricing_policy_machine_hour_tier_id bigserial primary key,
|
||||
pricing_policy_id bigint not null references pricing_policy (pricing_policy_id),
|
||||
|
||||
tier_start_hours numeric(10, 2) not null,
|
||||
tier_end_hours numeric(10, 2), -- null = infinito
|
||||
machine_cost_chf_per_hour numeric(10, 2) not null,
|
||||
|
||||
constraint chk_tier_start_non_negative check (tier_start_hours >= 0),
|
||||
constraint chk_tier_end_gt_start check (tier_end_hours is null or tier_end_hours > tier_start_hours)
|
||||
);
|
||||
|
||||
create index idx_pricing_policy_validity
|
||||
on pricing_policy (valid_from, valid_to);
|
||||
|
||||
create index idx_pricing_tier_lookup
|
||||
on pricing_policy_machine_hour_tier (pricing_policy_id, tier_start_hours);
|
||||
|
||||
|
||||
create table nozzle_option
|
||||
(
|
||||
nozzle_option_id bigserial primary key,
|
||||
nozzle_diameter_mm numeric(4, 2) not null unique, -- 0.4, 0.6, 0.8...
|
||||
|
||||
owned_quantity integer not null default 0 check (owned_quantity >= 0),
|
||||
|
||||
-- extra costo specifico oltre ad eventuale base fee della pricing_policy
|
||||
extra_nozzle_change_fee_chf numeric(10, 2) not null default 0.00,
|
||||
|
||||
is_active boolean not null default true,
|
||||
created_at timestamptz not null default now()
|
||||
);
|
||||
|
||||
|
||||
create table layer_height_option
|
||||
(
|
||||
layer_height_option_id bigserial primary key,
|
||||
layer_height_mm numeric(5, 3) not null unique, -- 0.12, 0.20, 0.28...
|
||||
|
||||
-- opzionale: moltiplicatore costo/tempo (es: 0.12 costa di più)
|
||||
time_multiplier numeric(6, 3) not null default 1.000,
|
||||
|
||||
is_active boolean not null default true
|
||||
);
|
||||
|
||||
create table layer_height_profile
|
||||
(
|
||||
layer_height_profile_id bigserial primary key,
|
||||
profile_name text not null unique, -- "Standard", "Fine", ecc.
|
||||
|
||||
min_layer_height_mm numeric(5, 3) not null,
|
||||
max_layer_height_mm numeric(5, 3) not null,
|
||||
default_layer_height_mm numeric(5, 3) not null,
|
||||
|
||||
time_multiplier numeric(6, 3) not null default 1.000,
|
||||
|
||||
constraint chk_layer_range check (max_layer_height_mm >= min_layer_height_mm)
|
||||
);
|
||||
|
||||
|
||||
begin;
|
||||
|
||||
set timezone = 'Europe/Zurich';
|
||||
|
||||
is_active = excluded.is_active;
|
||||
|
||||
|
||||
-- =========================================================
|
||||
-- 1) Pricing policy (valori ESATTI da Excel)
|
||||
-- Valid from: 2026-01-01, valid_to: NULL
|
||||
-- =========================================================
|
||||
insert into pricing_policy (
|
||||
policy_name,
|
||||
valid_from,
|
||||
valid_to,
|
||||
electricity_cost_chf_per_kwh,
|
||||
markup_percent,
|
||||
fixed_job_fee_chf,
|
||||
nozzle_change_base_fee_chf,
|
||||
cad_cost_chf_per_hour,
|
||||
is_active
|
||||
) values (
|
||||
'Excel Tariffe 2026-01-01',
|
||||
'2026-01-01 00:00:00+01'::timestamptz,
|
||||
null,
|
||||
0.156, -- Costo elettricità CHF/kWh (Excel)
|
||||
0.000, -- Markup non specificato -> 0 (puoi cambiarlo dopo)
|
||||
1.00, -- Costo fisso macchina CHF (Excel)
|
||||
0.00, -- Base cambio ugello: non specificato -> 0
|
||||
25.00, -- Tariffa CAD CHF/h (Excel)
|
||||
true
|
||||
)
|
||||
on conflict do nothing;
|
||||
|
||||
-- scaglioni tariffa stampa (Excel)
|
||||
insert into pricing_policy_machine_hour_tier (
|
||||
pricing_policy_id,
|
||||
tier_start_hours,
|
||||
tier_end_hours,
|
||||
machine_cost_chf_per_hour
|
||||
)
|
||||
select
|
||||
p.pricing_policy_id,
|
||||
tiers.tier_start_hours,
|
||||
tiers.tier_end_hours,
|
||||
tiers.machine_cost_chf_per_hour
|
||||
from pricing_policy p
|
||||
cross join (
|
||||
values
|
||||
(0.00::numeric, 10.00::numeric, 2.00::numeric), -- 0–10 h
|
||||
(10.00::numeric, 20.00::numeric, 1.40::numeric), -- 10–20 h
|
||||
(20.00::numeric, null::numeric, 0.50::numeric) -- >20 h
|
||||
) as tiers(tier_start_hours, tier_end_hours, machine_cost_chf_per_hour)
|
||||
where p.policy_name = 'Excel Tariffe 2026-01-01'
|
||||
on conflict do nothing;
|
||||
|
||||
|
||||
-- =========================================================
|
||||
-- 2) Stampante: BambuLab A1
|
||||
-- =========================================================
|
||||
insert into printer_machine (
|
||||
printer_display_name,
|
||||
build_volume_x_mm,
|
||||
build_volume_y_mm,
|
||||
build_volume_z_mm,
|
||||
power_watts,
|
||||
fleet_weight,
|
||||
is_active
|
||||
) values (
|
||||
'BambuLab A1',
|
||||
256,
|
||||
256,
|
||||
256,
|
||||
150, -- hai detto "150, 140": qui ho messo 150
|
||||
1.000,
|
||||
true
|
||||
)
|
||||
on conflict (printer_display_name) do update
|
||||
set
|
||||
build_volume_x_mm = excluded.build_volume_x_mm,
|
||||
build_volume_y_mm = excluded.build_volume_y_mm,
|
||||
build_volume_z_mm = excluded.build_volume_z_mm,
|
||||
power_watts = excluded.power_watts,
|
||||
fleet_weight = excluded.fleet_weight,
|
||||
is_active = excluded.is_active;
|
||||
|
||||
|
||||
-- =========================================================
|
||||
-- 3) Material types (da Excel) - per ora niente technical
|
||||
-- =========================================================
|
||||
insert into filament_material_type (
|
||||
material_code,
|
||||
is_flexible,
|
||||
is_technical,
|
||||
technical_type_label
|
||||
) values
|
||||
('PLA', false, false, null),
|
||||
('PETG', false, false, null),
|
||||
('TPU', true, false, null),
|
||||
('ABS', false, false, null),
|
||||
('Nylon', false, false, null),
|
||||
('Carbon PLA', false, false, null)
|
||||
on conflict (material_code) do update
|
||||
set
|
||||
is_flexible = excluded.is_flexible,
|
||||
is_technical = excluded.is_technical,
|
||||
technical_type_label = excluded.technical_type_label;
|
||||
|
||||
|
||||
-- =========================================================
|
||||
-- 4) Filament variants (PLA colori) - costi da Excel
|
||||
-- Excel: PLA = 18 CHF/kg, TPU = 42 CHF/kg (non inserito perché quantità non chiara)
|
||||
-- Stock in "rotoli" (3 = 3 kg se spool_net_kg=1)
|
||||
-- =========================================================
|
||||
|
||||
-- helper: ID PLA
|
||||
with pla as (
|
||||
select filament_material_type_id
|
||||
from filament_material_type
|
||||
where material_code = 'PLA'
|
||||
)
|
||||
insert into filament_variant (
|
||||
filament_material_type_id,
|
||||
variant_display_name,
|
||||
color_name,
|
||||
is_matte,
|
||||
is_special,
|
||||
cost_chf_per_kg,
|
||||
stock_spools,
|
||||
spool_net_kg,
|
||||
is_active
|
||||
)
|
||||
select
|
||||
pla.filament_material_type_id,
|
||||
v.variant_display_name,
|
||||
v.color_name,
|
||||
v.is_matte,
|
||||
v.is_special,
|
||||
18.00, -- PLA da Excel
|
||||
v.stock_spools,
|
||||
1.000,
|
||||
true
|
||||
from pla
|
||||
cross join (
|
||||
values
|
||||
('PLA Bianco', 'Bianco', false, false, 3.000::numeric),
|
||||
('PLA Nero', 'Nero', false, false, 3.000::numeric),
|
||||
('PLA Blu', 'Blu', false, false, 1.000::numeric),
|
||||
('PLA Arancione', 'Arancione', false, false, 1.000::numeric),
|
||||
('PLA Grigio', 'Grigio', false, false, 1.000::numeric),
|
||||
('PLA Grigio Scuro', 'Grigio scuro', false, false, 1.000::numeric),
|
||||
('PLA Grigio Chiaro', 'Grigio chiaro', false, false, 1.000::numeric),
|
||||
('PLA Viola', 'Viola', false, false, 1.000::numeric)
|
||||
) as v(variant_display_name, color_name, is_matte, is_special, stock_spools)
|
||||
on conflict (filament_material_type_id, variant_display_name) do update
|
||||
set
|
||||
color_name = excluded.color_name,
|
||||
is_matte = excluded.is_matte,
|
||||
is_special = excluded.is_special,
|
||||
cost_chf_per_kg = excluded.cost_chf_per_kg,
|
||||
stock_spools = excluded.stock_spools,
|
||||
spool_net_kg = excluded.spool_net_kg,
|
||||
is_active = excluded.is_active;
|
||||
|
||||
|
||||
-- =========================================================
|
||||
-- 5) Ugelli
|
||||
-- 0.4 standard (0 extra), 0.6 con attivazione 50 CHF
|
||||
-- =========================================================
|
||||
insert into nozzle_option (
|
||||
nozzle_diameter_mm,
|
||||
owned_quantity,
|
||||
extra_nozzle_change_fee_chf,
|
||||
is_active
|
||||
) values
|
||||
(0.40, 1, 0.00, true),
|
||||
(0.60, 1, 50.00, true)
|
||||
on conflict (nozzle_diameter_mm) do update
|
||||
set
|
||||
owned_quantity = excluded.owned_quantity,
|
||||
extra_nozzle_change_fee_chf = excluded.extra_nozzle_change_fee_chf,
|
||||
is_active = excluded.is_active;
|
||||
|
||||
|
||||
-- =========================================================
|
||||
-- 6) Layer heights (opzioni)
|
||||
-- =========================================================
|
||||
insert into layer_height_option (
|
||||
layer_height_mm,
|
||||
time_multiplier,
|
||||
is_active
|
||||
) values
|
||||
(0.080, 1.000, true),
|
||||
(0.120, 1.000, true),
|
||||
(0.160, 1.000, true),
|
||||
(0.200, 1.000, true),
|
||||
(0.240, 1.000, true),
|
||||
(0.280, 1.000, true)
|
||||
on conflict (layer_height_mm) do update
|
||||
set
|
||||
time_multiplier = excluded.time_multiplier,
|
||||
is_active = excluded.is_active;
|
||||
|
||||
commit;
|
||||
|
||||
|
||||
|
||||
|
||||
-- Sostituisci __MULTIPLIER__ con il tuo valore (es. 1.10)
|
||||
update layer_height_option
|
||||
set time_multiplier = 0.1
|
||||
where layer_height_mm = 0.080;
|
||||
@@ -1,5 +1,5 @@
|
||||
REGISTRY_URL=git.joekung.ch
|
||||
REPO_OWNER=JoeKung
|
||||
REPO_OWNER=joekung
|
||||
ENV=dev
|
||||
TAG=dev
|
||||
|
||||
@@ -7,9 +7,4 @@ TAG=dev
|
||||
BACKEND_PORT=18002
|
||||
FRONTEND_PORT=18082
|
||||
|
||||
# Application Config
|
||||
FILAMENT_COST_PER_KG=22.0
|
||||
MACHINE_COST_PER_HOUR=2.50
|
||||
ENERGY_COST_PER_KWH=0.30
|
||||
PRINTER_POWER_WATTS=150
|
||||
MARKUP_PERCENT=20
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
REGISTRY_URL=git.joekung.ch
|
||||
REPO_OWNER=JoeKung
|
||||
REPO_OWNER=joekung
|
||||
ENV=int
|
||||
TAG=int
|
||||
|
||||
@@ -7,9 +7,4 @@ TAG=int
|
||||
BACKEND_PORT=18001
|
||||
FRONTEND_PORT=18081
|
||||
|
||||
# Application Config
|
||||
FILAMENT_COST_PER_KG=22.0
|
||||
MACHINE_COST_PER_HOUR=2.50
|
||||
ENERGY_COST_PER_KWH=0.30
|
||||
PRINTER_POWER_WATTS=150
|
||||
MARKUP_PERCENT=20
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
REGISTRY_URL=git.joekung.ch
|
||||
REPO_OWNER=JoeKung
|
||||
REPO_OWNER=joekung
|
||||
ENV=prod
|
||||
TAG=prod
|
||||
|
||||
@@ -7,9 +7,4 @@ TAG=prod
|
||||
BACKEND_PORT=8000
|
||||
FRONTEND_PORT=80
|
||||
|
||||
# Application Config
|
||||
FILAMENT_COST_PER_KG=22.0
|
||||
MACHINE_COST_PER_HOUR=2.50
|
||||
ENERGY_COST_PER_KWH=0.30
|
||||
PRINTER_POWER_WATTS=150
|
||||
MARKUP_PERCENT=20
|
||||
|
||||
|
||||
@@ -7,28 +7,29 @@ services:
|
||||
container_name: print-calculator-backend-${ENV}
|
||||
ports:
|
||||
- "${BACKEND_PORT}:8000"
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
- FILAMENT_COST_PER_KG=${FILAMENT_COST_PER_KG}
|
||||
- MACHINE_COST_PER_HOUR=${MACHINE_COST_PER_HOUR}
|
||||
- ENERGY_COST_PER_KWH=${ENERGY_COST_PER_KWH}
|
||||
- PRINTER_POWER_WATTS=${PRINTER_POWER_WATTS}
|
||||
- MARKUP_PERCENT=${MARKUP_PERCENT}
|
||||
- DB_URL=${DB_URL}
|
||||
- DB_USERNAME=${DB_USERNAME}
|
||||
- DB_PASSWORD=${DB_PASSWORD}
|
||||
- TEMP_DIR=/app/temp
|
||||
- PROFILES_DIR=/app/profiles
|
||||
restart: unless-stopped
|
||||
restart: always
|
||||
volumes:
|
||||
- backend_profiles_${ENV}:/app/profiles
|
||||
|
||||
|
||||
frontend:
|
||||
image: ${REGISTRY_URL}/${REPO_OWNER}/print-calculator-frontend:${TAG}
|
||||
container_name: print-calculator-frontend-${ENV}
|
||||
ports:
|
||||
- "${FRONTEND_PORT}:8008"
|
||||
- "${FRONTEND_PORT}:80"
|
||||
depends_on:
|
||||
- backend
|
||||
restart: unless-stopped
|
||||
restart: always
|
||||
|
||||
volumes:
|
||||
backend_profiles_prod:
|
||||
backend_profiles_int:
|
||||
backend_profiles_dev:
|
||||
backend_profiles_dev:
|
||||
|
||||
@@ -9,6 +9,10 @@ services:
|
||||
ports:
|
||||
- "8000:8000"
|
||||
environment:
|
||||
- DB_URL=jdbc:postgresql://db:5432/printcalc
|
||||
- DB_USERNAME=printcalc
|
||||
- DB_PASSWORD=printcalc_secret
|
||||
- SPRING_PROFILES_ACTIVE=local
|
||||
- FILAMENT_COST_PER_KG=22.0
|
||||
- MACHINE_COST_PER_HOUR=2.50
|
||||
- ENERGY_COST_PER_KWH=0.30
|
||||
@@ -16,13 +20,34 @@ services:
|
||||
- MARKUP_PERCENT=20
|
||||
- TEMP_DIR=/app/temp
|
||||
- PROFILES_DIR=/app/profiles
|
||||
depends_on:
|
||||
- db
|
||||
restart: unless-stopped
|
||||
|
||||
frontend:
|
||||
build: ./frontend
|
||||
build:
|
||||
context: ./frontend
|
||||
dockerfile: Dockerfile.dev
|
||||
container_name: print-calculator-frontend
|
||||
ports:
|
||||
- "80:80"
|
||||
depends_on:
|
||||
- backend
|
||||
- db
|
||||
restart: unless-stopped
|
||||
|
||||
db:
|
||||
image: postgres:15-alpine
|
||||
container_name: print-calculator-db
|
||||
environment:
|
||||
- POSTGRES_USER=printcalc
|
||||
- POSTGRES_PASSWORD=printcalc_secret
|
||||
- POSTGRES_DB=printcalc
|
||||
ports:
|
||||
- "5432:5432"
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
|
||||
15
frontend/Dockerfile.dev
Normal file
15
frontend/Dockerfile.dev
Normal file
@@ -0,0 +1,15 @@
|
||||
# Stage 1: Build
|
||||
FROM node:20 as build
|
||||
|
||||
WORKDIR /app
|
||||
COPY package*.json ./
|
||||
RUN npm install
|
||||
COPY . .
|
||||
# Use development configuration to pick up environment.ts (localhost)
|
||||
RUN npm run build -- --configuration=development
|
||||
|
||||
# Stage 2: Serve
|
||||
FROM nginx:alpine
|
||||
COPY --from=build /app/dist/frontend/browser /usr/share/nginx/html
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
EXPOSE 80
|
||||
@@ -70,6 +70,17 @@
|
||||
"optimization": false,
|
||||
"extractLicenses": false,
|
||||
"sourceMap": true
|
||||
},
|
||||
"local": {
|
||||
"fileReplacements": [
|
||||
{
|
||||
"replace": "src/environments/environment.ts",
|
||||
"with": "src/environments/environment.local.ts"
|
||||
}
|
||||
],
|
||||
"optimization": false,
|
||||
"extractLicenses": false,
|
||||
"sourceMap": true
|
||||
}
|
||||
},
|
||||
|
||||
@@ -83,6 +94,9 @@
|
||||
},
|
||||
"development": {
|
||||
"buildTarget": "frontend:build:development"
|
||||
},
|
||||
"local": {
|
||||
"buildTarget": "frontend:build:local"
|
||||
}
|
||||
},
|
||||
"defaultConfiguration": "development"
|
||||
|
||||
0
frontend/src/app/app.component.scss
Normal file
0
frontend/src/app/app.component.scss
Normal file
@@ -5,6 +5,7 @@ import { RouterOutlet } from '@angular/router';
|
||||
selector: 'app-root',
|
||||
standalone: true,
|
||||
imports: [RouterOutlet],
|
||||
template: `<router-outlet></router-outlet>`
|
||||
templateUrl: './app.component.html',
|
||||
styleUrl: './app.component.scss'
|
||||
})
|
||||
export class AppComponent {}
|
||||
|
||||
@@ -2,8 +2,8 @@ import { ApplicationConfig, provideZoneChangeDetection, importProvidersFrom } fr
|
||||
import { provideRouter, withComponentInputBinding, withViewTransitions } from '@angular/router';
|
||||
import { routes } from './app.routes';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { TranslateModule } from '@ngx-translate/core';
|
||||
import { provideTranslateHttpLoader } from '@ngx-translate/http-loader';
|
||||
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
|
||||
import { provideTranslateHttpLoader, TranslateHttpLoader } from '@ngx-translate/http-loader';
|
||||
|
||||
export const appConfig: ApplicationConfig = {
|
||||
providers: [
|
||||
@@ -16,7 +16,11 @@ export const appConfig: ApplicationConfig = {
|
||||
}),
|
||||
importProvidersFrom(
|
||||
TranslateModule.forRoot({
|
||||
defaultLanguage: 'it'
|
||||
defaultLanguage: 'it',
|
||||
loader: {
|
||||
provide: TranslateLoader,
|
||||
useClass: TranslateHttpLoader
|
||||
}
|
||||
})
|
||||
)
|
||||
]
|
||||
|
||||
@@ -10,7 +10,7 @@ export const routes: Routes = [
|
||||
loadComponent: () => import('./features/home/home.component').then(m => m.HomeComponent)
|
||||
},
|
||||
{
|
||||
path: 'cal',
|
||||
path: 'calculator',
|
||||
loadChildren: () => import('./features/calculator/calculator.routes').then(m => m.CALCULATOR_ROUTES)
|
||||
},
|
||||
{
|
||||
@@ -20,6 +20,14 @@ export const routes: Routes = [
|
||||
{
|
||||
path: 'about',
|
||||
loadChildren: () => import('./features/about/about.routes').then(m => m.ABOUT_ROUTES)
|
||||
},
|
||||
{
|
||||
path: 'contact',
|
||||
loadChildren: () => import('./features/contact/contact.routes').then(m => m.CONTACT_ROUTES)
|
||||
},
|
||||
{
|
||||
path: '',
|
||||
loadChildren: () => import('./features/legal/legal.routes').then(m => m.LEGAL_ROUTES)
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
41
frontend/src/app/core/constants/colors.const.ts
Normal file
41
frontend/src/app/core/constants/colors.const.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
export interface ColorOption {
|
||||
label: string;
|
||||
value: string;
|
||||
hex: string;
|
||||
outOfStock?: boolean;
|
||||
}
|
||||
|
||||
export interface ColorCategory {
|
||||
name: string; // 'Glossy' | 'Matte'
|
||||
colors: ColorOption[];
|
||||
}
|
||||
|
||||
export const PRODUCT_COLORS: ColorCategory[] = [
|
||||
{
|
||||
name: 'Lucidi', // Glossy
|
||||
colors: [
|
||||
{ label: 'Black', value: 'Black', hex: '#1a1a1a' }, // Not pure black for visibility
|
||||
{ label: 'White', value: 'White', hex: '#f5f5f5' },
|
||||
{ label: 'Red', value: 'Red', hex: '#d32f2f', outOfStock: true },
|
||||
{ label: 'Blue', value: 'Blue', hex: '#1976d2' },
|
||||
{ label: 'Green', value: 'Green', hex: '#388e3c' },
|
||||
{ label: 'Yellow', value: 'Yellow', hex: '#fbc02d' }
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'Opachi', // Matte
|
||||
colors: [
|
||||
{ label: 'Matte Black', value: 'Matte Black', hex: '#2c2c2c' }, // Lighter charcoal for matte
|
||||
{ label: 'Matte White', value: 'Matte White', hex: '#e0e0e0' },
|
||||
{ label: 'Matte Gray', value: 'Matte Gray', hex: '#757575' }
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
export function getColorHex(value: string): string {
|
||||
for (const cat of PRODUCT_COLORS) {
|
||||
const found = cat.colors.find(c => c.value === value);
|
||||
if (found) return found.hex;
|
||||
}
|
||||
return '#facf0a'; // Default Brand Color if not found
|
||||
}
|
||||
21
frontend/src/app/core/layout/footer.component.html
Normal file
21
frontend/src/app/core/layout/footer.component.html
Normal file
@@ -0,0 +1,21 @@
|
||||
<footer class="footer">
|
||||
<div class="container footer-inner">
|
||||
<div class="col">
|
||||
<span class="brand">3D fab</span>
|
||||
<p class="copyright">© 2026 3D fab.</p>
|
||||
</div>
|
||||
|
||||
<div class="col links">
|
||||
<a routerLink="/privacy">{{ 'FOOTER.PRIVACY' | translate }}</a>
|
||||
<a routerLink="/terms">{{ 'FOOTER.TERMS' | translate }}</a>
|
||||
<a routerLink="/contact">{{ 'FOOTER.CONTACT' | translate }}</a>
|
||||
</div>
|
||||
|
||||
<div class="col social">
|
||||
<!-- Social Placeholders -->
|
||||
<div class="social-icon"></div>
|
||||
<div class="social-icon"></div>
|
||||
<div class="social-icon"></div>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
59
frontend/src/app/core/layout/footer.component.scss
Normal file
59
frontend/src/app/core/layout/footer.component.scss
Normal file
@@ -0,0 +1,59 @@
|
||||
@use '../../../styles/patterns';
|
||||
|
||||
.footer {
|
||||
background: var(--color-neutral-900);
|
||||
color: var(--color-neutral-50);
|
||||
padding: var(--space-8) 0 var(--space-4);
|
||||
font-size: 0.9rem;
|
||||
position: relative;
|
||||
margin-top: auto; /* Push to bottom if content is short */
|
||||
// Cross Hatch Pattern
|
||||
&::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
@include patterns.pattern-cross-hatch(var(--color-neutral-50), 20px, 1px);
|
||||
opacity: 0.05;
|
||||
pointer-events: none;
|
||||
}
|
||||
}
|
||||
.footer-inner {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: var(--space-6);
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.footer-inner {
|
||||
flex-direction: column;
|
||||
text-align: center;
|
||||
gap: var(--space-8);
|
||||
}
|
||||
|
||||
.links {
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
}
|
||||
|
||||
.brand { font-weight: 700; color: white; display: block; margin-bottom: var(--space-2); }
|
||||
.copyright { font-size: 0.875rem; color: var(--color-secondary-500); margin: 0; }
|
||||
|
||||
.links {
|
||||
display: flex;
|
||||
gap: var(--space-6);
|
||||
a {
|
||||
color: var(--color-neutral-300);
|
||||
font-size: 0.875rem;
|
||||
transition: color 0.2s;
|
||||
&:hover { color: white; text-decoration: underline; }
|
||||
}
|
||||
}
|
||||
|
||||
.social { display: flex; gap: var(--space-3); }
|
||||
.social-icon {
|
||||
width: 24px; height: 24px;
|
||||
background-color: var(--color-neutral-800);
|
||||
border-radius: 50%;
|
||||
}
|
||||
@@ -6,60 +6,7 @@ import { RouterLink } from '@angular/router';
|
||||
selector: 'app-footer',
|
||||
standalone: true,
|
||||
imports: [TranslateModule, RouterLink],
|
||||
template: `
|
||||
<footer class="footer">
|
||||
<div class="container footer-inner">
|
||||
<div class="col">
|
||||
<span class="brand">3D fab</span>
|
||||
<p class="copyright">© 2026 3D fab.</p>
|
||||
</div>
|
||||
|
||||
<div class="col links">
|
||||
<a routerLink="/privacy">{{ 'FOOTER.PRIVACY' | translate }}</a>
|
||||
<a routerLink="/terms">{{ 'FOOTER.TERMS' | translate }}</a>
|
||||
<a routerLink="/about">{{ 'FOOTER.CONTACT' | translate }}</a>
|
||||
</div>
|
||||
|
||||
<div class="col social">
|
||||
<!-- Social Placeholders -->
|
||||
<div class="social-icon"></div>
|
||||
<div class="social-icon"></div>
|
||||
<div class="social-icon"></div>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
`,
|
||||
styles: [`
|
||||
.footer {
|
||||
background-color: var(--color-neutral-900);
|
||||
color: var(--color-neutral-300);
|
||||
padding: var(--space-8) 0;
|
||||
margin-top: auto; /* Push to bottom if content is short */
|
||||
}
|
||||
.footer-inner {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
.brand { font-weight: 700; color: white; display: block; margin-bottom: var(--space-2); }
|
||||
.copyright { font-size: 0.875rem; color: var(--color-secondary-500); margin: 0; }
|
||||
|
||||
.links {
|
||||
display: flex;
|
||||
gap: var(--space-6);
|
||||
a {
|
||||
color: var(--color-neutral-300);
|
||||
font-size: 0.875rem;
|
||||
&:hover { color: white; text-decoration: underline; }
|
||||
}
|
||||
}
|
||||
|
||||
.social { display: flex; gap: var(--space-3); }
|
||||
.social-icon {
|
||||
width: 24px; height: 24px;
|
||||
background-color: var(--color-neutral-800);
|
||||
border-radius: 50%;
|
||||
}
|
||||
`]
|
||||
templateUrl: './footer.component.html',
|
||||
styleUrls: ['./footer.component.scss']
|
||||
})
|
||||
export class FooterComponent {}
|
||||
|
||||
7
frontend/src/app/core/layout/layout.component.html
Normal file
7
frontend/src/app/core/layout/layout.component.html
Normal file
@@ -0,0 +1,7 @@
|
||||
<div class="layout-wrapper">
|
||||
<app-navbar></app-navbar>
|
||||
<main class="main-content">
|
||||
<router-outlet></router-outlet>
|
||||
</main>
|
||||
<app-footer></app-footer>
|
||||
</div>
|
||||
9
frontend/src/app/core/layout/layout.component.scss
Normal file
9
frontend/src/app/core/layout/layout.component.scss
Normal file
@@ -0,0 +1,9 @@
|
||||
.layout-wrapper {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 100vh;
|
||||
}
|
||||
.main-content {
|
||||
flex: 1;
|
||||
padding-bottom: var(--space-12);
|
||||
}
|
||||
@@ -7,25 +7,7 @@ import { FooterComponent } from './footer.component';
|
||||
selector: 'app-layout',
|
||||
standalone: true,
|
||||
imports: [RouterOutlet, NavbarComponent, FooterComponent],
|
||||
template: `
|
||||
<div class="layout-wrapper">
|
||||
<app-navbar></app-navbar>
|
||||
<main class="main-content">
|
||||
<router-outlet></router-outlet>
|
||||
</main>
|
||||
<app-footer></app-footer>
|
||||
</div>
|
||||
`,
|
||||
styles: [`
|
||||
.layout-wrapper {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 100vh;
|
||||
}
|
||||
.main-content {
|
||||
flex: 1;
|
||||
padding-bottom: var(--space-12);
|
||||
}
|
||||
`]
|
||||
templateUrl: './layout.component.html',
|
||||
styleUrl: './layout.component.scss'
|
||||
})
|
||||
export class LayoutComponent {}
|
||||
|
||||
29
frontend/src/app/core/layout/navbar.component.html
Normal file
29
frontend/src/app/core/layout/navbar.component.html
Normal file
@@ -0,0 +1,29 @@
|
||||
<header class="navbar">
|
||||
<div class="container navbar-inner">
|
||||
<a routerLink="/" class="brand">3D <span class="highlight">fab</span></a>
|
||||
|
||||
<div class="mobile-toggle" (click)="toggleMenu()" [class.active]="isMenuOpen">
|
||||
<span></span>
|
||||
<span></span>
|
||||
<span></span>
|
||||
</div>
|
||||
|
||||
<nav class="nav-links" [class.open]="isMenuOpen">
|
||||
<a routerLink="/" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}" (click)="closeMenu()">{{ 'NAV.HOME' | translate }}</a>
|
||||
<a routerLink="/calculator/basic" routerLinkActive="active" [routerLinkActiveOptions]="{exact: false}" (click)="closeMenu()">{{ 'NAV.CALCULATOR' | translate }}</a>
|
||||
<a routerLink="/shop" routerLinkActive="active" (click)="closeMenu()">{{ 'NAV.SHOP' | translate }}</a>
|
||||
<a routerLink="/about" routerLinkActive="active" (click)="closeMenu()">{{ 'NAV.ABOUT' | translate }}</a>
|
||||
<a routerLink="/contact" routerLinkActive="active" (click)="closeMenu()">{{ 'NAV.CONTACT' | translate }}</a>
|
||||
</nav>
|
||||
|
||||
<div class="actions">
|
||||
<button class="lang-switch" (click)="toggleLang()">
|
||||
{{ langService.currentLang() === 'it' ? 'EN' : 'IT' }}
|
||||
</button>
|
||||
|
||||
<div class="icon-placeholder">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle></svg>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
141
frontend/src/app/core/layout/navbar.component.scss
Normal file
141
frontend/src/app/core/layout/navbar.component.scss
Normal file
@@ -0,0 +1,141 @@
|
||||
.navbar {
|
||||
height: 64px;
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
background-color: var(--color-bg-card);
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 100;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
.navbar-inner {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
.brand {
|
||||
font-size: 1.25rem;
|
||||
font-weight: 700;
|
||||
color: var(--color-text);
|
||||
text-decoration: none;
|
||||
}
|
||||
.highlight { color: var(--color-brand); }
|
||||
|
||||
.nav-links {
|
||||
display: flex;
|
||||
gap: var(--space-6);
|
||||
|
||||
a {
|
||||
color: var(--color-text-muted);
|
||||
font-weight: 500;
|
||||
text-decoration: none;
|
||||
transition: color 0.2s;
|
||||
|
||||
&:hover, &.active {
|
||||
color: var(--color-brand);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-4);
|
||||
}
|
||||
|
||||
.lang-switch {
|
||||
background: none;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius-sm);
|
||||
padding: 2px 6px;
|
||||
cursor: pointer;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
color: var(--color-text-muted);
|
||||
&:hover { color: var(--color-text); border-color: var(--color-text); }
|
||||
}
|
||||
|
||||
.icon-placeholder {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 50%;
|
||||
background-color: var(--color-neutral-100);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
/* Mobile Toggle */
|
||||
.mobile-toggle {
|
||||
display: none;
|
||||
flex-direction: column;
|
||||
justify-content: space-between;
|
||||
width: 24px;
|
||||
height: 18px;
|
||||
cursor: pointer;
|
||||
z-index: 101;
|
||||
|
||||
span {
|
||||
display: block;
|
||||
height: 2px;
|
||||
width: 100%;
|
||||
background-color: var(--color-text);
|
||||
border-radius: 2px;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
&.active {
|
||||
span:nth-child(1) { transform: translateY(8px) rotate(45deg); }
|
||||
span:nth-child(2) { opacity: 0; }
|
||||
span:nth-child(3) { transform: translateY(-8px) rotate(-45deg); }
|
||||
}
|
||||
}
|
||||
|
||||
/* Responsive Design */
|
||||
@media (max-width: 768px) {
|
||||
.mobile-toggle {
|
||||
display: flex;
|
||||
order: 2; /* Place after actions */
|
||||
margin-left: var(--space-4);
|
||||
}
|
||||
|
||||
.actions {
|
||||
order: 1; /* Place before toggle */
|
||||
margin-left: auto; /* Push to right */
|
||||
}
|
||||
|
||||
.nav-links {
|
||||
position: absolute;
|
||||
top: 64px;
|
||||
left: 0;
|
||||
right: 0;
|
||||
background-color: var(--color-bg-card);
|
||||
flex-direction: column;
|
||||
padding: var(--space-4);
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
gap: var(--space-4);
|
||||
display: none;
|
||||
z-index: 1000;
|
||||
|
||||
&.open {
|
||||
display: flex;
|
||||
animation: slideDown 0.3s ease forwards;
|
||||
}
|
||||
|
||||
a {
|
||||
font-size: 1.1rem;
|
||||
padding: var(--space-2) 0;
|
||||
border-bottom: 1px solid var(--color-neutral-100);
|
||||
|
||||
&:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes slideDown {
|
||||
from { opacity: 0; transform: translateY(-10px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
@@ -8,104 +8,24 @@ import { AppButtonComponent } from '../../shared/components/app-button/app-butto
|
||||
selector: 'app-navbar',
|
||||
standalone: true,
|
||||
imports: [RouterLink, RouterLinkActive, TranslateModule],
|
||||
template: `
|
||||
<header class="navbar">
|
||||
<div class="container navbar-inner">
|
||||
<a routerLink="/" class="brand">3D <span class="highlight">fab</span></a>
|
||||
|
||||
<nav class="nav-links">
|
||||
<a routerLink="/cal" routerLinkActive="active" [routerLinkActiveOptions]="{exact: false}">{{ 'NAV.CALCULATOR' | translate }}</a>
|
||||
<a routerLink="/shop" routerLinkActive="active">{{ 'NAV.SHOP' | translate }}</a>
|
||||
<a routerLink="/about" routerLinkActive="active">{{ 'NAV.ABOUT' | translate }}</a>
|
||||
</nav>
|
||||
|
||||
<div class="actions">
|
||||
<button class="lang-switch" (click)="toggleLang()">
|
||||
{{ langService.currentLang() === 'it' ? 'EN' : 'IT' }}
|
||||
</button>
|
||||
|
||||
<div class="icon-placeholder">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle></svg>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
`,
|
||||
styles: [`
|
||||
.navbar {
|
||||
height: 64px;
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
background-color: var(--color-bg-card);
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 100;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
.navbar-inner {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
.brand {
|
||||
font-size: 1.25rem;
|
||||
font-weight: 700;
|
||||
color: var(--color-text);
|
||||
text-decoration: none;
|
||||
}
|
||||
.highlight { color: var(--color-brand); }
|
||||
|
||||
.nav-links {
|
||||
display: flex;
|
||||
gap: var(--space-6);
|
||||
|
||||
a {
|
||||
color: var(--color-text-muted);
|
||||
font-weight: 500;
|
||||
text-decoration: none;
|
||||
transition: color 0.2s;
|
||||
|
||||
&:hover, &.active {
|
||||
color: var(--color-brand);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-4);
|
||||
}
|
||||
|
||||
.lang-switch {
|
||||
background: none;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius-sm);
|
||||
padding: 2px 6px;
|
||||
cursor: pointer;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
color: var(--color-text-muted);
|
||||
&:hover { color: var(--color-text); border-color: var(--color-text); }
|
||||
}
|
||||
|
||||
.icon-placeholder {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 50%;
|
||||
background-color: var(--color-neutral-100);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
`]
|
||||
templateUrl: './navbar.component.html',
|
||||
styleUrls: ['./navbar.component.scss']
|
||||
})
|
||||
export class NavbarComponent {
|
||||
isMenuOpen = false;
|
||||
|
||||
constructor(public langService: LanguageService) {}
|
||||
|
||||
toggleLang() {
|
||||
const newLang = this.langService.currentLang() === 'it' ? 'en' : 'it';
|
||||
this.langService.switchLang(newLang);
|
||||
}
|
||||
|
||||
toggleMenu() {
|
||||
this.isMenuOpen = !this.isMenuOpen;
|
||||
}
|
||||
|
||||
closeMenu() {
|
||||
this.isMenuOpen = false;
|
||||
}
|
||||
}
|
||||
|
||||
44
frontend/src/app/features/about/about-page.component.html
Normal file
44
frontend/src/app/features/about/about-page.component.html
Normal file
@@ -0,0 +1,44 @@
|
||||
<section class="about-section">
|
||||
<div class="container split-layout">
|
||||
|
||||
<!-- Left Column: Content -->
|
||||
<div class="text-content">
|
||||
<p class="eyebrow">{{ 'ABOUT.EYEBROW' | translate }}</p>
|
||||
<h1>{{ 'ABOUT.TITLE' | translate }}</h1>
|
||||
<p class="subtitle">{{ 'ABOUT.SUBTITLE' | translate }}</p>
|
||||
|
||||
<div class="divider"></div>
|
||||
|
||||
<p class="description">{{ 'ABOUT.HOW_TEXT' | translate }}</p>
|
||||
|
||||
<div class="tags-container">
|
||||
<span class="tag">{{ 'ABOUT.PILL_1' | translate }}</span>
|
||||
<span class="tag">{{ 'ABOUT.PILL_2' | translate }}</span>
|
||||
<span class="tag">{{ 'ABOUT.PILL_3' | translate }}</span>
|
||||
<span class="tag">{{ 'ABOUT.SERVICE_1' | translate }}</span>
|
||||
<span class="tag">{{ 'ABOUT.SERVICE_2' | translate }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Right Column: Visuals -->
|
||||
<div class="visual-content">
|
||||
<div class="photo-card card-1">
|
||||
<div class="placeholder-img"></div>
|
||||
<div class="member-info">
|
||||
<span class="member-name">Member 1</span>
|
||||
<span class="member-role">Founder</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="photo-card card-2">
|
||||
<div class="placeholder-img"></div>
|
||||
<div class="member-info">
|
||||
<span class="member-name">Member 2</span>
|
||||
<span class="member-role">Co-Founder</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<app-locations></app-locations>
|
||||
157
frontend/src/app/features/about/about-page.component.scss
Normal file
157
frontend/src/app/features/about/about-page.component.scss
Normal file
@@ -0,0 +1,157 @@
|
||||
.about-section {
|
||||
padding: 6rem 0;
|
||||
background: var(--color-bg);
|
||||
min-height: 80vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.split-layout {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr;
|
||||
gap: 4rem;
|
||||
align-items: center;
|
||||
text-align: center; /* Center on mobile */
|
||||
|
||||
@media(min-width: 992px) {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 6rem;
|
||||
text-align: left; /* Reset to left on desktop */
|
||||
}
|
||||
}
|
||||
|
||||
/* Left Column */
|
||||
.text-content {
|
||||
/* text-align: left; Removed to inherit from parent */
|
||||
}
|
||||
|
||||
.eyebrow {
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.15em;
|
||||
font-size: 0.875rem;
|
||||
color: var(--color-primary-500);
|
||||
font-weight: 700;
|
||||
margin-bottom: var(--space-2);
|
||||
display: block;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 3rem;
|
||||
line-height: 1.1;
|
||||
margin-bottom: var(--space-4);
|
||||
color: var(--color-text-main);
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
font-size: 1.25rem;
|
||||
color: var(--color-text-muted);
|
||||
margin-bottom: var(--space-6);
|
||||
font-weight: 300;
|
||||
}
|
||||
|
||||
.divider {
|
||||
height: 4px;
|
||||
width: 60px;
|
||||
background: var(--color-primary-500);
|
||||
border-radius: 2px;
|
||||
margin-bottom: var(--space-6);
|
||||
/* Center divider on mobile */
|
||||
margin-left: auto;
|
||||
margin-right: auto;
|
||||
|
||||
@media(min-width: 992px) {
|
||||
margin-left: 0;
|
||||
margin-right: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.description {
|
||||
font-size: 1.1rem;
|
||||
line-height: 1.7;
|
||||
color: var(--color-text-main);
|
||||
margin-bottom: var(--space-8);
|
||||
}
|
||||
|
||||
.tags-container {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.75rem;
|
||||
justify-content: center; /* Center tags on mobile */
|
||||
|
||||
@media(min-width: 992px) {
|
||||
justify-content: flex-start;
|
||||
}
|
||||
}
|
||||
|
||||
.tag {
|
||||
padding: 0.5rem 1rem;
|
||||
border-radius: 99px;
|
||||
background: var(--color-surface-card);
|
||||
border: 1px solid var(--color-border);
|
||||
color: var(--color-text-main);
|
||||
font-weight: 500;
|
||||
font-size: 0.9rem;
|
||||
box-shadow: var(--shadow-sm);
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.tag:hover {
|
||||
transform: translateY(-2px);
|
||||
border-color: var(--color-primary-500);
|
||||
color: var(--color-primary-500);
|
||||
box-shadow: var(--shadow-md);
|
||||
}
|
||||
|
||||
/* Right Column */
|
||||
.visual-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
gap: 2rem;
|
||||
|
||||
@media(min-width: 768px) {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
align-items: start;
|
||||
justify-items: center;
|
||||
}
|
||||
}
|
||||
|
||||
.photo-card {
|
||||
background: var(--color-surface-card);
|
||||
padding: 1rem;
|
||||
border-radius: var(--radius-lg);
|
||||
box-shadow: var(--shadow-lg);
|
||||
width: 100%;
|
||||
max-width: 260px;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.placeholder-img {
|
||||
width: 100%;
|
||||
aspect-ratio: 3/4;
|
||||
background: linear-gradient(45deg, var(--color-neutral-200), var(--color-neutral-100));
|
||||
border-radius: var(--radius-md);
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.member-info {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.member-name {
|
||||
display: block;
|
||||
font-weight: 700;
|
||||
color: var(--color-text-main);
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.member-role {
|
||||
display: block;
|
||||
font-size: 0.85rem;
|
||||
color: var(--color-text-muted);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
@@ -1,96 +1,13 @@
|
||||
import { Component } from '@angular/core';
|
||||
import { TranslateModule } from '@ngx-translate/core';
|
||||
import { ContactFormComponent } from './components/contact-form/contact-form.component';
|
||||
import { AppCardComponent } from '../../shared/components/app-card/app-card.component';
|
||||
import { AppLocationsComponent } from '../../shared/components/app-locations/app-locations.component';
|
||||
|
||||
@Component({
|
||||
selector: 'app-about-page',
|
||||
standalone: true,
|
||||
imports: [TranslateModule, ContactFormComponent, AppCardComponent],
|
||||
template: `
|
||||
<section class="about-hero">
|
||||
<div class="container">
|
||||
<p class="eyebrow">{{ 'ABOUT.EYEBROW' | translate }}</p>
|
||||
<h1>{{ 'ABOUT.TITLE' | translate }}</h1>
|
||||
<p class="subtitle">{{ 'ABOUT.SUBTITLE' | translate }}</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div class="container content">
|
||||
<div class="info">
|
||||
<h2>{{ 'ABOUT.HOW_TITLE' | translate }}</h2>
|
||||
<p>{{ 'ABOUT.HOW_TEXT' | translate }}</p>
|
||||
|
||||
<div class="pill-list">
|
||||
<span>{{ 'ABOUT.PILL_1' | translate }}</span>
|
||||
<span>{{ 'ABOUT.PILL_2' | translate }}</span>
|
||||
<span>{{ 'ABOUT.PILL_3' | translate }}</span>
|
||||
</div>
|
||||
|
||||
<h3>{{ 'ABOUT.SERVICES_TITLE' | translate }}</h3>
|
||||
<ul class="steps">
|
||||
<li>{{ 'ABOUT.SERVICE_1' | translate }}</li>
|
||||
<li>{{ 'ABOUT.SERVICE_2' | translate }}</li>
|
||||
<li>{{ 'ABOUT.SERVICE_3' | translate }}</li>
|
||||
<li>{{ 'ABOUT.SERVICE_4' | translate }}</li>
|
||||
</ul>
|
||||
|
||||
<h3>{{ 'ABOUT.TARGET_TITLE' | translate }}</h3>
|
||||
<p class="text-muted">{{ 'ABOUT.TARGET_TEXT' | translate }}</p>
|
||||
</div>
|
||||
|
||||
<div class="contact">
|
||||
<app-card>
|
||||
<h2>{{ 'ABOUT.CONTACT_US' | translate }}</h2>
|
||||
<app-contact-form></app-contact-form>
|
||||
</app-card>
|
||||
</div>
|
||||
</div>
|
||||
`,
|
||||
styles: [`
|
||||
.about-hero {
|
||||
padding: 5rem 0 3.5rem;
|
||||
background: var(--color-bg);
|
||||
text-align: center;
|
||||
}
|
||||
.eyebrow {
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.12em;
|
||||
font-size: 0.75rem;
|
||||
color: var(--color-secondary-600);
|
||||
font-weight: 600;
|
||||
margin-bottom: var(--space-3);
|
||||
}
|
||||
.subtitle {
|
||||
color: var(--color-text-muted);
|
||||
max-width: 640px;
|
||||
margin: var(--space-3) auto 0;
|
||||
}
|
||||
.content {
|
||||
display: grid;
|
||||
gap: var(--space-12);
|
||||
padding: 3rem 0 5rem;
|
||||
@media(min-width: 768px) { grid-template-columns: 1fr 1fr; }
|
||||
}
|
||||
.steps {
|
||||
padding-left: var(--space-4);
|
||||
li { margin-bottom: var(--space-2); color: var(--color-text-muted); }
|
||||
}
|
||||
.pill-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
margin: var(--space-4) 0 var(--space-6);
|
||||
}
|
||||
.pill-list span {
|
||||
padding: 0.35rem 0.75rem;
|
||||
border-radius: 999px;
|
||||
background: var(--color-neutral-100);
|
||||
border: 1px solid var(--color-border);
|
||||
font-size: 0.85rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
.text-muted { color: var(--color-text-muted); }
|
||||
`]
|
||||
imports: [TranslateModule, AppLocationsComponent],
|
||||
templateUrl: './about-page.component.html',
|
||||
styleUrl: './about-page.component.scss'
|
||||
})
|
||||
export class AboutPageComponent {}
|
||||
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
import { Component, signal } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||
import { TranslateModule } from '@ngx-translate/core';
|
||||
import { AppInputComponent } from '../../../../shared/components/app-input/app-input.component';
|
||||
import { AppButtonComponent } from '../../../../shared/components/app-button/app-button.component';
|
||||
|
||||
@Component({
|
||||
selector: 'app-contact-form',
|
||||
standalone: true,
|
||||
imports: [CommonModule, ReactiveFormsModule, TranslateModule, AppInputComponent, AppButtonComponent],
|
||||
template: `
|
||||
<form [formGroup]="form" (ngSubmit)="onSubmit()">
|
||||
<app-input formControlName="name" label="Nome" placeholder="Il tuo nome"></app-input>
|
||||
<app-input formControlName="email" type="email" label="Email" placeholder="tuo@email.com"></app-input>
|
||||
|
||||
<div class="form-group">
|
||||
<label>Messaggio</label>
|
||||
<textarea formControlName="message" class="form-control" rows="4"></textarea>
|
||||
</div>
|
||||
|
||||
<div class="actions">
|
||||
<app-button type="submit" [disabled]="form.invalid || sent()">
|
||||
{{ sent() ? 'Inviato!' : ('ABOUT.SEND' | translate) }}
|
||||
</app-button>
|
||||
</div>
|
||||
</form>
|
||||
`,
|
||||
styles: [`
|
||||
.form-group { display: flex; flex-direction: column; margin-bottom: var(--space-4); }
|
||||
label { font-size: 0.875rem; font-weight: 500; margin-bottom: var(--space-2); color: var(--color-text); }
|
||||
.form-control {
|
||||
padding: 0.5rem 0.75rem;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius-md);
|
||||
width: 100%;
|
||||
background: var(--color-bg-card);
|
||||
color: var(--color-text);
|
||||
font-family: inherit;
|
||||
&:focus { outline: none; border-color: var(--color-brand); }
|
||||
}
|
||||
`]
|
||||
})
|
||||
export class ContactFormComponent {
|
||||
form: FormGroup;
|
||||
sent = signal(false);
|
||||
|
||||
constructor(private fb: FormBuilder) {
|
||||
this.form = this.fb.group({
|
||||
name: ['', Validators.required],
|
||||
email: ['', [Validators.required, Validators.email]],
|
||||
message: ['', Validators.required]
|
||||
});
|
||||
}
|
||||
|
||||
onSubmit() {
|
||||
if (this.form.valid) {
|
||||
// Mock submit
|
||||
this.sent.set(true);
|
||||
setTimeout(() => {
|
||||
this.sent.set(false);
|
||||
this.form.reset();
|
||||
}, 3000);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
<div class="container hero">
|
||||
<h1>{{ 'CALC.TITLE' | translate }}</h1>
|
||||
<p class="subtitle">{{ 'CALC.SUBTITLE' | translate }}</p>
|
||||
|
||||
@if (error()) {
|
||||
<app-alert type="error">{{ 'CALC.ERROR_GENERIC' | translate }}</app-alert>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (step() === 'success') {
|
||||
<div class="container hero">
|
||||
<app-success-state context="calc" (action)="onNewQuote()"></app-success-state>
|
||||
</div>
|
||||
} @else if (step() === 'details' && result()) {
|
||||
<div class="container">
|
||||
<app-user-details
|
||||
[quote]="result()!"
|
||||
(submitOrder)="onSubmitOrder($event)"
|
||||
(cancel)="onCancelDetails()">
|
||||
</app-user-details>
|
||||
</div>
|
||||
} @else {
|
||||
<div class="container content-grid">
|
||||
<!-- Left Column: Input -->
|
||||
<div class="col-input">
|
||||
<app-card>
|
||||
<div class="mode-selector">
|
||||
<div class="mode-option"
|
||||
[class.active]="mode() === 'easy'"
|
||||
(click)="mode.set('easy')">
|
||||
{{ 'CALC.MODE_EASY' | translate }}
|
||||
</div>
|
||||
<div class="mode-option"
|
||||
[class.active]="mode() === 'advanced'"
|
||||
(click)="mode.set('advanced')">
|
||||
{{ 'CALC.MODE_ADVANCED' | translate }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<app-upload-form
|
||||
#uploadForm
|
||||
[mode]="mode()"
|
||||
[loading]="loading()"
|
||||
[uploadProgress]="uploadProgress()"
|
||||
(submitRequest)="onCalculate($event)"
|
||||
></app-upload-form>
|
||||
</app-card>
|
||||
</div>
|
||||
|
||||
<!-- Right Column: Result or Info -->
|
||||
<div class="col-result" #resultCol>
|
||||
|
||||
@if (loading()) {
|
||||
<app-card class="loading-state">
|
||||
<div class="loader-content">
|
||||
<div class="spinner"></div>
|
||||
<h3 class="loading-title">Analisi in corso...</h3>
|
||||
<p class="loading-text">Stiamo analizzando la geometria e calcolando il percorso utensile.</p>
|
||||
</div>
|
||||
</app-card>
|
||||
} @else if (result()) {
|
||||
<app-quote-result
|
||||
[result]="result()!"
|
||||
(consult)="onConsult()"
|
||||
(proceed)="onProceed()"
|
||||
(itemChange)="uploadForm.updateItemQuantityByName($event.fileName, $event.quantity)"
|
||||
></app-quote-result>
|
||||
} @else {
|
||||
<app-card>
|
||||
<h3>{{ 'CALC.BENEFITS_TITLE' | translate }}</h3>
|
||||
<ul class="benefits">
|
||||
<li>{{ 'CALC.BENEFITS_1' | translate }}</li>
|
||||
<li>{{ 'CALC.BENEFITS_2' | translate }}</li>
|
||||
<li>{{ 'CALC.BENEFITS_3' | translate }}</li>
|
||||
</ul>
|
||||
</app-card>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
.hero { padding: var(--space-12) 0; text-align: center; }
|
||||
.subtitle { font-size: 1.25rem; color: var(--color-text-muted); max-width: 600px; margin: 0 auto; }
|
||||
|
||||
.content-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr;
|
||||
gap: var(--space-6);
|
||||
@media(min-width: 768px) {
|
||||
grid-template-columns: 1.5fr 1fr;
|
||||
gap: var(--space-8);
|
||||
}
|
||||
}
|
||||
|
||||
.centered-col {
|
||||
align-self: flex-start; /* Default */
|
||||
@media(min-width: 768px) {
|
||||
align-self: center;
|
||||
}
|
||||
}
|
||||
|
||||
.col-input {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.col-result {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
/* Stretch only the loading card so the spinner stays centered */
|
||||
.col-result > .loading-state {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* Mode Selector (Segmented Control style) */
|
||||
.mode-selector {
|
||||
display: flex;
|
||||
background-color: var(--color-neutral-100);
|
||||
border-radius: var(--radius-md);
|
||||
padding: 4px;
|
||||
margin-bottom: var(--space-6);
|
||||
gap: 4px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.mode-option {
|
||||
flex: 1;
|
||||
text-align: center;
|
||||
padding: 8px 16px;
|
||||
border-radius: var(--radius-sm);
|
||||
cursor: pointer;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
color: var(--color-text-muted);
|
||||
transition: all 0.2s ease;
|
||||
user-select: none;
|
||||
|
||||
&:hover { color: var(--color-text); }
|
||||
|
||||
&.active {
|
||||
background-color: var(--color-brand);
|
||||
color: #000;
|
||||
font-weight: 600;
|
||||
box-shadow: 0 1px 2px rgba(0,0,0,0.05);
|
||||
}
|
||||
}
|
||||
|
||||
.benefits { padding-left: var(--space-4); color: var(--color-text-muted); line-height: 2; }
|
||||
|
||||
|
||||
.loader-content {
|
||||
text-align: center;
|
||||
max-width: 300px;
|
||||
margin: 0 auto;
|
||||
|
||||
/* Center content vertically within the stretched card */
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.loading-title {
|
||||
font-size: 1.1rem;
|
||||
font-weight: 600;
|
||||
margin: var(--space-4) 0 var(--space-2);
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.loading-text {
|
||||
font-size: 0.9rem;
|
||||
color: var(--color-text-muted);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.spinner {
|
||||
border: 3px solid var(--color-neutral-200);
|
||||
border-left-color: var(--color-brand);
|
||||
border-radius: 50%;
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
animation: spin 1s linear infinite;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
0% { transform: rotate(0deg); }
|
||||
100% { transform: rotate(360deg); }
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, signal } from '@angular/core';
|
||||
import { Component, signal, ViewChild, ElementRef, OnInit } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { TranslateModule } from '@ngx-translate/core';
|
||||
|
||||
@@ -6,116 +6,73 @@ import { AppCardComponent } from '../../shared/components/app-card/app-card.comp
|
||||
import { AppAlertComponent } from '../../shared/components/app-alert/app-alert.component';
|
||||
import { UploadFormComponent } from './components/upload-form/upload-form.component';
|
||||
import { QuoteResultComponent } from './components/quote-result/quote-result.component';
|
||||
import { QuoteEstimatorService, QuoteRequest, QuoteResult } from './services/quote-estimator.service';
|
||||
import { QuoteRequest, QuoteResult, QuoteEstimatorService } from './services/quote-estimator.service';
|
||||
import { UserDetailsComponent } from './components/user-details/user-details.component';
|
||||
import { SuccessStateComponent } from '../../shared/components/success-state/success-state.component';
|
||||
import { Router, ActivatedRoute } from '@angular/router';
|
||||
|
||||
@Component({
|
||||
selector: 'app-calculator-page',
|
||||
standalone: true,
|
||||
imports: [CommonModule, TranslateModule, AppCardComponent, AppAlertComponent, UploadFormComponent, QuoteResultComponent],
|
||||
template: `
|
||||
<div class="container hero">
|
||||
<h1>{{ 'CALC.TITLE' | translate }}</h1>
|
||||
<p class="subtitle">{{ 'CALC.SUBTITLE' | translate }}</p>
|
||||
</div>
|
||||
|
||||
<div class="container content-grid">
|
||||
<!-- Left Column: Input -->
|
||||
<div class="col-input">
|
||||
<app-card>
|
||||
<div class="tabs-wrapper">
|
||||
<div class="sub-tabs">
|
||||
<span
|
||||
class="mode-switch"
|
||||
[class.active]="mode() === 'easy'"
|
||||
(click)="mode.set('easy')">
|
||||
{{ 'CALC.MODE_EASY' | translate }}
|
||||
</span>
|
||||
<span class="divider">/</span>
|
||||
<span
|
||||
class="mode-switch"
|
||||
[class.active]="mode() === 'advanced'"
|
||||
(click)="mode.set('advanced')">
|
||||
{{ 'CALC.MODE_ADVANCED' | translate }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<app-upload-form
|
||||
[mode]="mode()"
|
||||
[loading]="loading()"
|
||||
(submitRequest)="onCalculate($event)"
|
||||
></app-upload-form>
|
||||
</app-card>
|
||||
</div>
|
||||
|
||||
<!-- Right Column: Result or Info -->
|
||||
<div class="col-result">
|
||||
@if (error()) {
|
||||
<app-alert type="error">Si è verificato un errore durante il calcolo del preventivo.</app-alert>
|
||||
}
|
||||
|
||||
@if (result()) {
|
||||
<app-quote-result [result]="result()!"></app-quote-result>
|
||||
} @else {
|
||||
<app-card>
|
||||
<h3>{{ 'CALC.BENEFITS_TITLE' | translate }}</h3>
|
||||
<ul class="benefits">
|
||||
<li>{{ 'CALC.BENEFITS_1' | translate }}</li>
|
||||
<li>{{ 'CALC.BENEFITS_2' | translate }}</li>
|
||||
<li>{{ 'CALC.BENEFITS_3' | translate }}</li>
|
||||
</ul>
|
||||
</app-card>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
`,
|
||||
styles: [`
|
||||
.hero { padding: var(--space-12) 0; text-align: center; }
|
||||
.subtitle { font-size: 1.25rem; color: var(--color-text-muted); max-width: 600px; margin: 0 auto; }
|
||||
|
||||
.content-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr;
|
||||
gap: var(--space-8);
|
||||
@media(min-width: 768px) {
|
||||
grid-template-columns: 1.5fr 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
.tabs-wrapper {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: var(--space-6);
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
padding-bottom: var(--space-2);
|
||||
}
|
||||
|
||||
.sub-tabs { font-size: 0.875rem; color: var(--color-text-muted); }
|
||||
.mode-switch { cursor: pointer; &:hover { color: var(--color-text); } }
|
||||
.mode-switch.active { font-weight: 700; color: var(--color-brand); }
|
||||
.divider { margin: 0 var(--space-2); }
|
||||
|
||||
.benefits { padding-left: var(--space-4); color: var(--color-text-muted); line-height: 2; }
|
||||
`]
|
||||
imports: [CommonModule, TranslateModule, AppCardComponent, AppAlertComponent, UploadFormComponent, QuoteResultComponent, UserDetailsComponent, SuccessStateComponent],
|
||||
templateUrl: './calculator-page.component.html',
|
||||
styleUrl: './calculator-page.component.scss'
|
||||
})
|
||||
export class CalculatorPageComponent {
|
||||
export class CalculatorPageComponent implements OnInit {
|
||||
mode = signal<any>('easy');
|
||||
step = signal<'upload' | 'quote' | 'details' | 'success'>('upload');
|
||||
|
||||
loading = signal(false);
|
||||
uploadProgress = signal(0);
|
||||
result = signal<QuoteResult | null>(null);
|
||||
error = signal<boolean>(false);
|
||||
|
||||
orderSuccess = signal(false);
|
||||
|
||||
@ViewChild('uploadForm') uploadForm!: UploadFormComponent;
|
||||
@ViewChild('resultCol') resultCol!: ElementRef;
|
||||
|
||||
constructor(private estimator: QuoteEstimatorService) {}
|
||||
constructor(
|
||||
private estimator: QuoteEstimatorService,
|
||||
private router: Router,
|
||||
private route: ActivatedRoute
|
||||
) {}
|
||||
|
||||
ngOnInit() {
|
||||
this.route.data.subscribe(data => {
|
||||
if (data['mode']) {
|
||||
this.mode.set(data['mode']);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onCalculate(req: QuoteRequest) {
|
||||
// ... (logic remains the same, simplified for diff)
|
||||
this.currentRequest = req;
|
||||
this.loading.set(true);
|
||||
this.uploadProgress.set(0);
|
||||
this.error.set(false);
|
||||
this.result.set(null);
|
||||
|
||||
this.orderSuccess.set(false);
|
||||
|
||||
// Auto-scroll on mobile to make analysis visible
|
||||
setTimeout(() => {
|
||||
if (this.resultCol && window.innerWidth < 768) {
|
||||
this.resultCol.nativeElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||
}
|
||||
}, 100);
|
||||
|
||||
this.estimator.calculate(req).subscribe({
|
||||
next: (res) => {
|
||||
this.result.set(res);
|
||||
this.loading.set(false);
|
||||
next: (event) => {
|
||||
if (typeof event === 'number') {
|
||||
this.uploadProgress.set(event);
|
||||
} else {
|
||||
// It's the result
|
||||
this.result.set(event as QuoteResult);
|
||||
this.loading.set(false);
|
||||
this.uploadProgress.set(100);
|
||||
this.step.set('quote');
|
||||
}
|
||||
},
|
||||
error: () => {
|
||||
this.error.set(true);
|
||||
@@ -123,4 +80,58 @@ export class CalculatorPageComponent {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onProceed() {
|
||||
this.step.set('details');
|
||||
}
|
||||
|
||||
onCancelDetails() {
|
||||
this.step.set('quote');
|
||||
}
|
||||
|
||||
onSubmitOrder(orderData: any) {
|
||||
console.log('Order Submitted:', orderData);
|
||||
this.orderSuccess.set(true);
|
||||
this.step.set('success');
|
||||
}
|
||||
|
||||
onNewQuote() {
|
||||
this.step.set('upload');
|
||||
this.result.set(null);
|
||||
this.orderSuccess.set(false);
|
||||
this.mode.set('easy'); // Reset to default
|
||||
}
|
||||
|
||||
private currentRequest: QuoteRequest | null = null;
|
||||
|
||||
onConsult() {
|
||||
if (!this.currentRequest) return;
|
||||
|
||||
const req = this.currentRequest;
|
||||
let details = `Richiesta Preventivo:\n`;
|
||||
details += `- Materiale: ${req.material}\n`;
|
||||
details += `- Qualità: ${req.quality}\n`;
|
||||
|
||||
details += `- File:\n`;
|
||||
req.items.forEach(item => {
|
||||
details += ` * ${item.file.name} (Qtà: ${item.quantity}`;
|
||||
if (item.color) {
|
||||
details += `, Colore: ${item.color}`;
|
||||
}
|
||||
details += `)\n`;
|
||||
});
|
||||
|
||||
if (req.mode === 'advanced') {
|
||||
if (req.infillDensity) details += `- Infill: ${req.infillDensity}%\n`;
|
||||
}
|
||||
|
||||
if (req.notes) details += `\nNote: ${req.notes}`;
|
||||
|
||||
this.estimator.setPendingConsultation({
|
||||
files: req.items.map(i => i.file),
|
||||
message: details
|
||||
});
|
||||
|
||||
this.router.navigate(['/contact']);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,5 +2,7 @@ import { Routes } from '@angular/router';
|
||||
import { CalculatorPageComponent } from './calculator-page.component';
|
||||
|
||||
export const CALCULATOR_ROUTES: Routes = [
|
||||
{ path: '', component: CalculatorPageComponent }
|
||||
{ path: '', redirectTo: 'basic', pathMatch: 'full' },
|
||||
{ path: 'basic', component: CalculatorPageComponent, data: { mode: 'easy' } },
|
||||
{ path: 'advanced', component: CalculatorPageComponent, data: { mode: 'advanced' } }
|
||||
];
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
<app-card>
|
||||
<h3 class="title">{{ 'CALC.RESULT' | translate }}</h3>
|
||||
|
||||
<!-- Summary Grid (NOW ON TOP) -->
|
||||
<div class="result-grid">
|
||||
<app-summary-card
|
||||
class="item full-width"
|
||||
[label]="'CALC.COST' | translate"
|
||||
[large]="true"
|
||||
[highlight]="true">
|
||||
{{ totals().price | currency:result().currency }}
|
||||
</app-summary-card>
|
||||
|
||||
<app-summary-card [label]="'CALC.TIME' | translate">
|
||||
{{ totals().hours }}h {{ totals().minutes }}m
|
||||
</app-summary-card>
|
||||
|
||||
<app-summary-card [label]="'CALC.MATERIAL' | translate">
|
||||
{{ totals().weight }}g
|
||||
</app-summary-card>
|
||||
</div>
|
||||
|
||||
<div class="setup-note">
|
||||
<small>* Include {{ result().setupCost | currency:result().currency }} Setup Cost</small>
|
||||
</div>
|
||||
|
||||
@if (result().notes) {
|
||||
<div class="notes-section">
|
||||
<label>{{ 'CALC.NOTES' | translate }}:</label>
|
||||
<p>{{ result().notes }}</p>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="divider"></div>
|
||||
|
||||
<!-- Detailed Items List (NOW ON BOTTOM) -->
|
||||
<div class="items-list">
|
||||
@for (item of items(); track item.fileName; let i = $index) {
|
||||
<div class="item-row">
|
||||
<div class="item-info">
|
||||
<span class="file-name">{{ item.fileName }}</span>
|
||||
<span class="file-details">
|
||||
{{ (item.unitTime / 3600) | number:'1.1-1' }}h | {{ item.unitWeight | number:'1.0-0' }}g
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="item-controls">
|
||||
<div class="qty-control">
|
||||
<label>Qtà:</label>
|
||||
<input
|
||||
type="number"
|
||||
min="1"
|
||||
[ngModel]="item.quantity"
|
||||
(ngModelChange)="updateQuantity(i, $event)"
|
||||
class="qty-input">
|
||||
</div>
|
||||
<div class="item-price">
|
||||
{{ (item.unitPrice * item.quantity) | currency:result().currency }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="actions">
|
||||
<app-button variant="outline" (click)="consult.emit()">
|
||||
{{ 'QUOTE.CONSULT' | translate }}
|
||||
</app-button>
|
||||
|
||||
<app-button (click)="proceed.emit()">
|
||||
{{ 'QUOTE.PROCEED_ORDER' | translate }}
|
||||
</app-button>
|
||||
</div>
|
||||
</app-card>
|
||||
@@ -0,0 +1,109 @@
|
||||
.title { margin-bottom: var(--space-6); text-align: center; }
|
||||
|
||||
.divider {
|
||||
height: 1px;
|
||||
background: var(--color-border);
|
||||
margin: var(--space-4) 0;
|
||||
}
|
||||
|
||||
.items-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
margin-bottom: var(--space-4);
|
||||
}
|
||||
|
||||
.item-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: var(--space-3);
|
||||
background: var(--color-neutral-50);
|
||||
border-radius: var(--radius-md);
|
||||
border: 1px solid var(--color-border);
|
||||
}
|
||||
|
||||
.item-info {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
flex: 1; /* Ensure it takes available space */
|
||||
}
|
||||
|
||||
.file-name { font-weight: 500; font-size: 0.9rem; color: var(--color-text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.file-details { font-size: 0.8rem; color: var(--color-text-muted); }
|
||||
|
||||
.item-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-4);
|
||||
}
|
||||
|
||||
.qty-control {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
|
||||
label { font-size: 0.8rem; color: var(--color-text-muted); }
|
||||
}
|
||||
|
||||
.qty-input {
|
||||
width: 60px;
|
||||
padding: 4px 8px;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius-sm);
|
||||
text-align: center;
|
||||
&:focus { outline: none; border-color: var(--color-brand); }
|
||||
}
|
||||
|
||||
.item-price {
|
||||
font-weight: 600;
|
||||
min-width: 60px;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.result-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr;
|
||||
gap: var(--space-3);
|
||||
margin-bottom: var(--space-2);
|
||||
|
||||
@media(min-width: 500px) {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: var(--space-4);
|
||||
}
|
||||
}
|
||||
.full-width { grid-column: span 2; }
|
||||
|
||||
.setup-note {
|
||||
text-align: center;
|
||||
margin-bottom: var(--space-6);
|
||||
color: var(--color-text-muted);
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.actions { display: flex; flex-direction: column; gap: var(--space-3); }
|
||||
|
||||
.notes-section {
|
||||
margin-top: var(--space-4);
|
||||
margin-bottom: var(--space-4);
|
||||
padding: var(--space-3);
|
||||
background: var(--color-neutral-50);
|
||||
border-radius: var(--radius-md);
|
||||
border: 1px solid var(--color-border);
|
||||
|
||||
label {
|
||||
font-weight: 500;
|
||||
font-size: 0.9rem;
|
||||
color: var(--color-text-muted);
|
||||
display: block;
|
||||
margin-bottom: var(--space-2);
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
font-size: 0.95rem;
|
||||
color: var(--color-text);
|
||||
white-space: pre-wrap; /* Preserve line breaks */
|
||||
}
|
||||
}
|
||||
@@ -1,56 +1,74 @@
|
||||
import { Component, input, output } from '@angular/core';
|
||||
import { Component, input, output, signal, computed, effect } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { TranslateModule } from '@ngx-translate/core';
|
||||
import { AppCardComponent } from '../../../../shared/components/app-card/app-card.component';
|
||||
import { AppButtonComponent } from '../../../../shared/components/app-button/app-button.component';
|
||||
import { SummaryCardComponent } from '../../../../shared/components/summary-card/summary-card.component';
|
||||
import { QuoteResult } from '../../services/quote-estimator.service';
|
||||
import { QuoteResult, QuoteItem } from '../../services/quote-estimator.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-quote-result',
|
||||
standalone: true,
|
||||
imports: [CommonModule, TranslateModule, AppCardComponent, AppButtonComponent, SummaryCardComponent],
|
||||
template: `
|
||||
<app-card>
|
||||
<h3 class="title">{{ 'CALC.RESULT' | translate }}</h3>
|
||||
|
||||
<div class="result-grid">
|
||||
<app-summary-card
|
||||
class="item full-width"
|
||||
[label]="'CALC.COST' | translate"
|
||||
[large]="true"
|
||||
[highlight]="true">
|
||||
{{ result().price | currency:result().currency }}
|
||||
</app-summary-card>
|
||||
|
||||
<app-summary-card [label]="'CALC.TIME' | translate">
|
||||
{{ result().printTimeHours }}h
|
||||
</app-summary-card>
|
||||
|
||||
<app-summary-card [label]="'CALC.MATERIAL' | translate">
|
||||
{{ result().materialUsageGrams }}g
|
||||
</app-summary-card>
|
||||
</div>
|
||||
|
||||
<div class="actions">
|
||||
<app-button variant="primary" [fullWidth]="true">{{ 'CALC.ORDER' | translate }}</app-button>
|
||||
<app-button variant="outline" [fullWidth]="true">{{ 'CALC.CONSULT' | translate }}</app-button>
|
||||
</div>
|
||||
</app-card>
|
||||
`,
|
||||
styles: [`
|
||||
.title { margin-bottom: var(--space-6); text-align: center; }
|
||||
.result-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: var(--space-4);
|
||||
margin-bottom: var(--space-6);
|
||||
}
|
||||
.full-width { grid-column: span 2; }
|
||||
|
||||
.actions { display: flex; flex-direction: column; gap: var(--space-3); }
|
||||
`]
|
||||
imports: [CommonModule, FormsModule, TranslateModule, AppCardComponent, AppButtonComponent, SummaryCardComponent],
|
||||
templateUrl: './quote-result.component.html',
|
||||
styleUrl: './quote-result.component.scss'
|
||||
})
|
||||
export class QuoteResultComponent {
|
||||
result = input.required<QuoteResult>();
|
||||
consult = output<void>();
|
||||
proceed = output<void>();
|
||||
itemChange = output<{fileName: string, quantity: number}>();
|
||||
|
||||
// Local mutable state for items to handle quantity changes
|
||||
items = signal<QuoteItem[]>([]);
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
// Initialize local items when result inputs change
|
||||
// We map to new objects to avoid mutating the input directly if it was a reference
|
||||
this.items.set(this.result().items.map(i => ({...i})));
|
||||
}, { allowSignalWrites: true });
|
||||
}
|
||||
|
||||
updateQuantity(index: number, newQty: number | string) {
|
||||
const qty = typeof newQty === 'string' ? parseInt(newQty, 10) : newQty;
|
||||
if (qty < 1 || isNaN(qty)) return;
|
||||
|
||||
this.items.update(current => {
|
||||
const updated = [...current];
|
||||
updated[index] = { ...updated[index], quantity: qty };
|
||||
return updated;
|
||||
});
|
||||
|
||||
this.itemChange.emit({
|
||||
fileName: this.items()[index].fileName,
|
||||
quantity: qty
|
||||
});
|
||||
}
|
||||
|
||||
totals = computed(() => {
|
||||
const currentItems = this.items();
|
||||
const setup = this.result().setupCost;
|
||||
|
||||
let price = setup;
|
||||
let time = 0;
|
||||
let weight = 0;
|
||||
|
||||
currentItems.forEach(i => {
|
||||
price += i.unitPrice * i.quantity;
|
||||
time += i.unitTime * i.quantity;
|
||||
weight += i.unitWeight * i.quantity;
|
||||
});
|
||||
|
||||
const hours = Math.floor(time / 3600);
|
||||
const minutes = Math.ceil((time % 3600) / 60);
|
||||
|
||||
return {
|
||||
price: Math.round(price * 100) / 100,
|
||||
hours,
|
||||
minutes,
|
||||
weight: Math.ceil(weight)
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
<form [formGroup]="form" (ngSubmit)="onSubmit()">
|
||||
|
||||
<div class="section">
|
||||
@if (selectedFile()) {
|
||||
<div class="viewer-wrapper">
|
||||
<app-stl-viewer
|
||||
[file]="selectedFile()"
|
||||
[color]="getSelectedFileColor()">
|
||||
</app-stl-viewer>
|
||||
<!-- Close button removed as requested -->
|
||||
</div>
|
||||
}
|
||||
|
||||
<!-- Initial Dropzone (Visible only when no files) -->
|
||||
@if (items().length === 0) {
|
||||
<app-dropzone
|
||||
[label]="'CALC.UPLOAD_LABEL' | translate"
|
||||
[subtext]="'CALC.UPLOAD_SUB' | translate"
|
||||
[accept]="acceptedFormats"
|
||||
[multiple]="true"
|
||||
(filesDropped)="onFilesDropped($event)">
|
||||
</app-dropzone>
|
||||
}
|
||||
|
||||
<!-- New File List with Details -->
|
||||
@if (items().length > 0) {
|
||||
<div class="items-grid">
|
||||
@for (item of items(); track item.file.name; let i = $index) {
|
||||
<div class="file-card" [class.active]="item.file === selectedFile()" (click)="selectFile(item.file)">
|
||||
<div class="card-header">
|
||||
<span class="file-name" [title]="item.file.name">{{ item.file.name }}</span>
|
||||
</div>
|
||||
|
||||
<div class="card-body">
|
||||
<div class="card-controls">
|
||||
<div class="qty-group">
|
||||
<label>QTÀ</label>
|
||||
<input
|
||||
type="number"
|
||||
min="1"
|
||||
[value]="item.quantity"
|
||||
(change)="updateItemQuantity(i, $event)"
|
||||
class="qty-input"
|
||||
(click)="$event.stopPropagation()">
|
||||
</div>
|
||||
|
||||
<div class="color-group">
|
||||
<label>COLORE</label>
|
||||
<app-color-selector
|
||||
[selectedColor]="item.color"
|
||||
[variants]="currentMaterialVariants()"
|
||||
(colorSelected)="updateItemColor(i, $event)">
|
||||
</app-color-selector>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button type="button" class="btn-remove" (click)="removeItem(i); $event.stopPropagation()" title="Remove file">
|
||||
X
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<!-- "Add Files" Button (Visible only when files exist) -->
|
||||
<div class="add-more-container">
|
||||
<input #additionalInput type="file" [accept]="acceptedFormats" multiple hidden (change)="onAdditionalFilesSelected($event)">
|
||||
|
||||
<button type="button" class="btn-add-more" (click)="additionalInput.click()">
|
||||
+ {{ 'CALC.ADD_FILES' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (items().length === 0 && form.get('itemsTouched')?.value) {
|
||||
<div class="error-msg">{{ 'CALC.ERR_FILE_REQUIRED' | translate }}</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="grid">
|
||||
<app-select
|
||||
formControlName="material"
|
||||
[label]="'CALC.MATERIAL' | translate"
|
||||
[options]="materials()"
|
||||
></app-select>
|
||||
|
||||
@if (mode() === 'easy') {
|
||||
<app-select
|
||||
formControlName="quality"
|
||||
[label]="'CALC.QUALITY' | translate"
|
||||
[options]="qualities()"
|
||||
></app-select>
|
||||
} @else {
|
||||
<app-select
|
||||
formControlName="nozzleDiameter"
|
||||
[label]="'CALC.NOZZLE' | translate"
|
||||
[options]="nozzleDiameters()"
|
||||
></app-select>
|
||||
}
|
||||
</div>
|
||||
|
||||
<!-- Global quantity removed, now per item -->
|
||||
|
||||
@if (mode() === 'advanced') {
|
||||
<div class="grid">
|
||||
<app-select
|
||||
formControlName="infillPattern"
|
||||
[label]="'CALC.PATTERN' | translate"
|
||||
[options]="infillPatterns()"
|
||||
></app-select>
|
||||
|
||||
<app-select
|
||||
formControlName="layerHeight"
|
||||
[label]="'CALC.LAYER_HEIGHT' | translate"
|
||||
[options]="layerHeights()"
|
||||
></app-select>
|
||||
</div>
|
||||
|
||||
<div class="grid">
|
||||
<app-input
|
||||
formControlName="infillDensity"
|
||||
type="number"
|
||||
[label]="'CALC.INFILL' | translate"
|
||||
></app-input>
|
||||
|
||||
<div class="checkbox-row">
|
||||
<input type="checkbox" formControlName="supportEnabled" id="support">
|
||||
<label for="support">{{ 'CALC.SUPPORT' | translate }}</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
}
|
||||
|
||||
<app-input
|
||||
formControlName="notes"
|
||||
[label]="'CALC.NOTES' | translate"
|
||||
placeholder="Istruzioni specifiche..."
|
||||
></app-input>
|
||||
|
||||
<div class="actions">
|
||||
<!-- Progress Bar (Only when uploading i.e. progress < 100) -->
|
||||
@if (loading() && uploadProgress() < 100) {
|
||||
<div class="progress-container">
|
||||
<div class="progress-bar">
|
||||
<div class="progress-fill" [style.width.%]="uploadProgress()"></div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
<app-button
|
||||
type="submit"
|
||||
[disabled]="items().length === 0 || loading()"
|
||||
[fullWidth]="true">
|
||||
{{ loading() ? (uploadProgress() < 100 ? 'Uploading...' : 'Processing...') : ('CALC.CALCULATE' | translate) }}
|
||||
</app-button>
|
||||
</div>
|
||||
</form>
|
||||
@@ -0,0 +1,207 @@
|
||||
.section { margin-bottom: var(--space-6); }
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr;
|
||||
gap: var(--space-4);
|
||||
|
||||
@media(min-width: 640px) {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
}
|
||||
}
|
||||
.actions { margin-top: var(--space-6); }
|
||||
.error-msg { color: var(--color-danger-500); font-size: 0.875rem; margin-top: var(--space-2); text-align: center; }
|
||||
|
||||
.viewer-wrapper { position: relative; margin-bottom: var(--space-4); }
|
||||
|
||||
/* Grid Layout for Files */
|
||||
.items-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr; /* Force 2 columns on mobile */
|
||||
gap: var(--space-2); /* Tighten gap for mobile */
|
||||
margin-top: var(--space-4);
|
||||
margin-bottom: var(--space-4);
|
||||
|
||||
@media(min-width: 640px) {
|
||||
gap: var(--space-3);
|
||||
}
|
||||
}
|
||||
|
||||
.file-card {
|
||||
padding: var(--space-2); /* Reduced from space-3 */
|
||||
background: var(--color-neutral-100);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius-md);
|
||||
transition: all 0.2s;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px; /* Reduced gap */
|
||||
position: relative; /* For absolute positioning of remove btn */
|
||||
min-width: 0; /* Allow flex item to shrink below content size if needed */
|
||||
|
||||
&:hover { border-color: var(--color-neutral-300); }
|
||||
&.active {
|
||||
border-color: var(--color-brand);
|
||||
background: rgba(250, 207, 10, 0.05);
|
||||
box-shadow: 0 0 0 1px var(--color-brand);
|
||||
}
|
||||
}
|
||||
|
||||
.card-header {
|
||||
overflow: hidden;
|
||||
padding-right: 25px; /* Adjusted */
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.file-name {
|
||||
font-weight: 500;
|
||||
font-size: 0.8rem; /* Smaller font */
|
||||
color: var(--color-text);
|
||||
display: block;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.card-body {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding-top: 0;
|
||||
}
|
||||
|
||||
.card-controls {
|
||||
display: flex;
|
||||
align-items: flex-end; /* Align bottom of input and color circle */
|
||||
gap: 16px; /* Space between Qty and Color */
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.qty-group, .color-group {
|
||||
display: flex;
|
||||
flex-direction: column; /* Stack label and input */
|
||||
align-items: flex-start;
|
||||
gap: 0px;
|
||||
|
||||
label {
|
||||
font-size: 0.6rem;
|
||||
color: var(--color-text-muted);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
font-weight: 600;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
.color-group {
|
||||
align-items: flex-start; /* Align label left */
|
||||
/* margin-right removed */
|
||||
|
||||
/* Override margin in selector for this context */
|
||||
::ng-deep .color-selector-container {
|
||||
margin-left: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.qty-input {
|
||||
width: 36px; /* Slightly smaller */
|
||||
padding: 1px 2px;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius-sm);
|
||||
text-align: center;
|
||||
font-size: 0.85rem;
|
||||
background: white;
|
||||
height: 24px; /* Explicit height to match color circle somewhat */
|
||||
&:focus { outline: none; border-color: var(--color-brand); }
|
||||
}
|
||||
|
||||
.btn-remove {
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
right: 4px;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
border-radius: 4px;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--color-text-muted);
|
||||
font-weight: bold;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: all 0.2s;
|
||||
font-size: 0.8rem;
|
||||
|
||||
&:hover {
|
||||
background: var(--color-danger-100);
|
||||
color: var(--color-danger-500);
|
||||
}
|
||||
}
|
||||
|
||||
/* Prominent Add Button */
|
||||
.add-more-container {
|
||||
margin-top: var(--space-2);
|
||||
}
|
||||
|
||||
.btn-add-more {
|
||||
width: 100%;
|
||||
padding: var(--space-3);
|
||||
background: var(--color-neutral-800);
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: var(--radius-md);
|
||||
font-weight: 600;
|
||||
font-size: 0.9rem;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: var(--space-2);
|
||||
|
||||
&:hover {
|
||||
background: var(--color-neutral-900);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
&:active { transform: translateY(0); }
|
||||
}
|
||||
|
||||
.checkbox-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-3);
|
||||
height: 100%;
|
||||
padding-top: var(--space-4);
|
||||
|
||||
input[type="checkbox"] {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
accent-color: var(--color-brand);
|
||||
}
|
||||
label {
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
|
||||
/* Progress Bar */
|
||||
.progress-container {
|
||||
margin-bottom: var(--space-3);
|
||||
text-align: center;
|
||||
width: 100%;
|
||||
}
|
||||
.progress-bar {
|
||||
height: 4px;
|
||||
background: var(--color-border);
|
||||
border-radius: 2px;
|
||||
overflow: hidden;
|
||||
margin-bottom: 0;
|
||||
position: relative;
|
||||
width: 100%;
|
||||
}
|
||||
.progress-fill {
|
||||
height: 100%;
|
||||
background: var(--color-brand);
|
||||
width: 0%;
|
||||
transition: width 0.2s ease-out;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, input, output, signal } from '@angular/core';
|
||||
import { Component, input, output, signal, effect, OnInit, inject } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||
import { TranslateModule } from '@ngx-translate/core';
|
||||
@@ -7,190 +7,253 @@ import { AppSelectComponent } from '../../../../shared/components/app-select/app
|
||||
import { AppDropzoneComponent } from '../../../../shared/components/app-dropzone/app-dropzone.component';
|
||||
import { AppButtonComponent } from '../../../../shared/components/app-button/app-button.component';
|
||||
import { StlViewerComponent } from '../../../../shared/components/stl-viewer/stl-viewer.component';
|
||||
import { QuoteRequest } from '../../services/quote-estimator.service';
|
||||
import { ColorSelectorComponent } from '../../../../shared/components/color-selector/color-selector.component';
|
||||
import { QuoteRequest, QuoteEstimatorService, OptionsResponse, SimpleOption, MaterialOption, VariantOption } from '../../services/quote-estimator.service';
|
||||
import { getColorHex } from '../../../../core/constants/colors.const';
|
||||
|
||||
interface FormItem {
|
||||
file: File;
|
||||
quantity: number;
|
||||
color: string;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-upload-form',
|
||||
standalone: true,
|
||||
imports: [CommonModule, ReactiveFormsModule, TranslateModule, AppInputComponent, AppSelectComponent, AppDropzoneComponent, AppButtonComponent, StlViewerComponent],
|
||||
template: `
|
||||
<form [formGroup]="form" (ngSubmit)="onSubmit()">
|
||||
|
||||
<div class="section">
|
||||
@if (selectedFile()) {
|
||||
<div class="viewer-wrapper">
|
||||
<app-stl-viewer [file]="selectedFile()"></app-stl-viewer>
|
||||
<button type="button" class="btn-clear" (click)="clearFiles()">
|
||||
X
|
||||
</button>
|
||||
</div>
|
||||
<div class="file-list">
|
||||
@for (f of files(); track f.name) {
|
||||
<div class="file-item" [class.active]="f === selectedFile()" (click)="selectFile(f)">
|
||||
{{ f.name }}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
} @else {
|
||||
<app-dropzone
|
||||
[label]="'CALC.UPLOAD_LABEL' | translate"
|
||||
[subtext]="'CALC.UPLOAD_SUB' | translate"
|
||||
[accept]="acceptedFormats"
|
||||
[multiple]="true"
|
||||
(filesDropped)="onFilesDropped($event)">
|
||||
</app-dropzone>
|
||||
}
|
||||
|
||||
@if (form.get('files')?.invalid && form.get('files')?.touched) {
|
||||
<div class="error-msg">{{ 'CALC.ERR_FILE_REQUIRED' | translate }}</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="grid">
|
||||
<app-select
|
||||
formControlName="material"
|
||||
[label]="'CALC.MATERIAL' | translate"
|
||||
[options]="materials"
|
||||
></app-select>
|
||||
|
||||
<app-select
|
||||
formControlName="quality"
|
||||
[label]="'CALC.QUALITY' | translate"
|
||||
[options]="qualities"
|
||||
></app-select>
|
||||
</div>
|
||||
|
||||
<app-input
|
||||
formControlName="quantity"
|
||||
type="number"
|
||||
[label]="'CALC.QUANTITY' | translate"
|
||||
></app-input>
|
||||
|
||||
@if (mode() === 'advanced') {
|
||||
<app-input
|
||||
formControlName="notes"
|
||||
[label]="'CALC.NOTES' | translate"
|
||||
placeholder="Istruzioni specifiche..."
|
||||
></app-input>
|
||||
}
|
||||
|
||||
<div class="actions">
|
||||
<app-button
|
||||
type="submit"
|
||||
[disabled]="form.invalid || loading()"
|
||||
[fullWidth]="true">
|
||||
{{ loading() ? '...' : ('CALC.CALCULATE' | translate) }}
|
||||
</app-button>
|
||||
</div>
|
||||
</form>
|
||||
`,
|
||||
styles: [`
|
||||
.section { margin-bottom: var(--space-6); }
|
||||
.grid { display: grid; grid-template-columns: 1fr 1fr; gap: var(--space-4); }
|
||||
.actions { margin-top: var(--space-6); }
|
||||
.error-msg { color: var(--color-danger-500); font-size: 0.875rem; margin-top: var(--space-2); text-align: center; }
|
||||
|
||||
.viewer-wrapper { position: relative; margin-bottom: var(--space-4); }
|
||||
.btn-clear {
|
||||
position: absolute;
|
||||
top: 10px;
|
||||
right: 10px;
|
||||
background: rgba(0,0,0,0.5);
|
||||
color: white;
|
||||
border: none;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 50%;
|
||||
cursor: pointer;
|
||||
z-index: 10;
|
||||
&:hover { background: rgba(0,0,0,0.7); }
|
||||
}
|
||||
|
||||
.file-list {
|
||||
display: flex;
|
||||
gap: var(--space-2);
|
||||
overflow-x: auto;
|
||||
padding-bottom: var(--space-2);
|
||||
}
|
||||
.file-item {
|
||||
padding: 0.5rem 1rem;
|
||||
background: var(--color-neutral-100);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius-md);
|
||||
font-size: 0.85rem;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
&:hover { background: var(--color-neutral-200); }
|
||||
&.active {
|
||||
border-color: var(--color-brand);
|
||||
background: rgba(250, 207, 10, 0.1);
|
||||
font-weight: 600;
|
||||
}
|
||||
}
|
||||
`]
|
||||
imports: [CommonModule, ReactiveFormsModule, TranslateModule, AppInputComponent, AppSelectComponent, AppDropzoneComponent, AppButtonComponent, StlViewerComponent, ColorSelectorComponent],
|
||||
templateUrl: './upload-form.component.html',
|
||||
styleUrl: './upload-form.component.scss'
|
||||
})
|
||||
export class UploadFormComponent {
|
||||
export class UploadFormComponent implements OnInit {
|
||||
mode = input<'easy' | 'advanced'>('easy');
|
||||
loading = input<boolean>(false);
|
||||
uploadProgress = input<number>(0);
|
||||
submitRequest = output<QuoteRequest>();
|
||||
|
||||
private estimator = inject(QuoteEstimatorService);
|
||||
private fb = inject(FormBuilder);
|
||||
|
||||
form: FormGroup;
|
||||
|
||||
files = signal<File[]>([]);
|
||||
items = signal<FormItem[]>([]);
|
||||
selectedFile = signal<File | null>(null);
|
||||
|
||||
materials = [
|
||||
{ label: 'PLA (Standard)', value: 'PLA' },
|
||||
{ label: 'PETG (Resistente)', value: 'PETG' },
|
||||
{ label: 'TPU (Flessibile)', value: 'TPU' }
|
||||
];
|
||||
// Dynamic Options
|
||||
materials = signal<SimpleOption[]>([]);
|
||||
qualities = signal<SimpleOption[]>([]);
|
||||
nozzleDiameters = signal<SimpleOption[]>([]);
|
||||
infillPatterns = signal<SimpleOption[]>([]);
|
||||
layerHeights = signal<SimpleOption[]>([]);
|
||||
|
||||
// Store full material options to lookup variants/colors if needed later
|
||||
private fullMaterialOptions: MaterialOption[] = [];
|
||||
|
||||
// Computed variants for valid material
|
||||
currentMaterialVariants = signal<VariantOption[]>([]);
|
||||
|
||||
private updateVariants() {
|
||||
const matCode = this.form.get('material')?.value;
|
||||
if (matCode && this.fullMaterialOptions.length > 0) {
|
||||
const found = this.fullMaterialOptions.find(m => m.code === matCode);
|
||||
this.currentMaterialVariants.set(found ? found.variants : []);
|
||||
} else {
|
||||
this.currentMaterialVariants.set([]);
|
||||
}
|
||||
}
|
||||
|
||||
qualities = [
|
||||
{ label: 'Bozza (Veloce)', value: 'Draft' },
|
||||
{ label: 'Standard', value: 'Standard' },
|
||||
{ label: 'Alta definizione', value: 'High' }
|
||||
];
|
||||
acceptedFormats = '.stl,.3mf,.step,.stp,.obj,.amf,.ply,.igs,.iges';
|
||||
|
||||
constructor(private fb: FormBuilder) {
|
||||
constructor() {
|
||||
this.form = this.fb.group({
|
||||
files: [[], Validators.required],
|
||||
material: ['PLA', Validators.required],
|
||||
quality: ['Standard', Validators.required],
|
||||
quantity: [1, [Validators.required, Validators.min(1)]],
|
||||
notes: ['']
|
||||
itemsTouched: [false], // Hack to track touched state for custom items list
|
||||
material: ['', Validators.required],
|
||||
quality: ['', Validators.required],
|
||||
items: [[]], // Track items in form for validation if needed
|
||||
notes: [''],
|
||||
// Advanced fields
|
||||
infillDensity: [20, [Validators.min(0), Validators.max(100)]],
|
||||
layerHeight: [0.2, [Validators.min(0.05), Validators.max(1.0)]],
|
||||
nozzleDiameter: [0.4, Validators.required],
|
||||
infillPattern: ['grid'],
|
||||
supportEnabled: [false]
|
||||
});
|
||||
|
||||
// Listen to material changes to update variants
|
||||
this.form.get('material')?.valueChanges.subscribe(() => {
|
||||
this.updateVariants();
|
||||
});
|
||||
}
|
||||
|
||||
ngOnInit() {
|
||||
this.estimator.getOptions().subscribe({
|
||||
next: (options: OptionsResponse) => {
|
||||
this.fullMaterialOptions = options.materials;
|
||||
this.updateVariants(); // Trigger initial update
|
||||
|
||||
this.materials.set(options.materials.map(m => ({ label: m.label, value: m.code })));
|
||||
this.qualities.set(options.qualities.map(q => ({ label: q.label, value: q.id })));
|
||||
this.infillPatterns.set(options.infillPatterns.map(p => ({ label: p.label, value: p.id })));
|
||||
this.layerHeights.set(options.layerHeights.map(l => ({ label: l.label, value: l.value })));
|
||||
this.nozzleDiameters.set(options.nozzleDiameters.map(n => ({ label: n.label, value: n.value })));
|
||||
|
||||
this.setDefaults();
|
||||
},
|
||||
error: (err) => {
|
||||
console.error('Failed to load options', err);
|
||||
// Fallback for debugging/offline dev
|
||||
this.materials.set([{ label: 'PLA (Fallback)', value: 'PLA' }]);
|
||||
this.qualities.set([{ label: 'Standard', value: 'standard' }]);
|
||||
this.nozzleDiameters.set([{ label: '0.4 mm', value: 0.4 }]);
|
||||
this.setDefaults();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private setDefaults() {
|
||||
// Set Defaults if available
|
||||
if (this.materials().length > 0 && !this.form.get('material')?.value) {
|
||||
this.form.get('material')?.setValue(this.materials()[0].value);
|
||||
}
|
||||
if (this.qualities().length > 0 && !this.form.get('quality')?.value) {
|
||||
// Try to find 'standard' or use first
|
||||
const std = this.qualities().find(q => q.value === 'standard');
|
||||
this.form.get('quality')?.setValue(std ? std.value : this.qualities()[0].value);
|
||||
}
|
||||
if (this.nozzleDiameters().length > 0 && !this.form.get('nozzleDiameter')?.value) {
|
||||
this.form.get('nozzleDiameter')?.setValue(0.4); // Prefer 0.4
|
||||
}
|
||||
if (this.layerHeights().length > 0 && !this.form.get('layerHeight')?.value) {
|
||||
this.form.get('layerHeight')?.setValue(0.2); // Prefer 0.2
|
||||
}
|
||||
if (this.infillPatterns().length > 0 && !this.form.get('infillPattern')?.value) {
|
||||
this.form.get('infillPattern')?.setValue(this.infillPatterns()[0].value);
|
||||
}
|
||||
}
|
||||
|
||||
onFilesDropped(newFiles: File[]) {
|
||||
this.files.update(current => [...current, ...newFiles]);
|
||||
this.form.patchValue({ files: this.files() });
|
||||
this.form.get('files')?.markAsTouched();
|
||||
|
||||
// Select the last added file by default if none selected
|
||||
if (newFiles.length > 0) {
|
||||
this.selectedFile.set(newFiles[newFiles.length - 1]);
|
||||
const MAX_SIZE = 200 * 1024 * 1024; // 200MB
|
||||
const validItems: FormItem[] = [];
|
||||
let hasError = false;
|
||||
|
||||
for (const file of newFiles) {
|
||||
if (file.size > MAX_SIZE) {
|
||||
hasError = true;
|
||||
} else {
|
||||
// Default color is Black
|
||||
validItems.push({ file, quantity: 1, color: 'Black' });
|
||||
}
|
||||
}
|
||||
|
||||
if (hasError) {
|
||||
alert("Alcuni file superano il limite di 200MB e non sono stati aggiunti.");
|
||||
}
|
||||
|
||||
if (validItems.length > 0) {
|
||||
this.items.update(current => [...current, ...validItems]);
|
||||
this.form.get('itemsTouched')?.setValue(true);
|
||||
// Auto select last added
|
||||
this.selectedFile.set(validItems[validItems.length - 1].file);
|
||||
}
|
||||
}
|
||||
|
||||
onAdditionalFilesSelected(event: Event) {
|
||||
const input = event.target as HTMLInputElement;
|
||||
if (input.files && input.files.length > 0) {
|
||||
this.onFilesDropped(Array.from(input.files));
|
||||
// Reset input so same files can be selected again if needed
|
||||
input.value = '';
|
||||
}
|
||||
}
|
||||
|
||||
updateItemQuantityByName(fileName: string, quantity: number) {
|
||||
this.items.update(current => {
|
||||
return current.map(item => {
|
||||
if (item.file.name === fileName) {
|
||||
return { ...item, quantity };
|
||||
}
|
||||
return item;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
selectFile(file: File) {
|
||||
this.selectedFile.set(file);
|
||||
if (this.selectedFile() === file) {
|
||||
// toggle off? no, keep active
|
||||
} else {
|
||||
this.selectedFile.set(file);
|
||||
}
|
||||
}
|
||||
|
||||
clearFiles() {
|
||||
this.files.set([]);
|
||||
this.selectedFile.set(null);
|
||||
this.form.patchValue({ files: [] });
|
||||
// Helper to get color of currently selected file
|
||||
getSelectedFileColor(): string {
|
||||
const file = this.selectedFile();
|
||||
if (!file) return '#facf0a'; // Default
|
||||
|
||||
const item = this.items().find(i => i.file === file);
|
||||
if (item) {
|
||||
const vars = this.currentMaterialVariants();
|
||||
if (vars && vars.length > 0) {
|
||||
const found = vars.find(v => v.colorName === item.color);
|
||||
if (found) return found.hexColor;
|
||||
}
|
||||
return getColorHex(item.color);
|
||||
}
|
||||
return '#facf0a';
|
||||
}
|
||||
|
||||
updateItemQuantity(index: number, event: Event) {
|
||||
const input = event.target as HTMLInputElement;
|
||||
let val = parseInt(input.value, 10);
|
||||
if (isNaN(val) || val < 1) val = 1;
|
||||
|
||||
this.items.update(current => {
|
||||
const updated = [...current];
|
||||
updated[index] = { ...updated[index], quantity: val };
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
|
||||
updateItemColor(index: number, newColor: string) {
|
||||
this.items.update(current => {
|
||||
const updated = [...current];
|
||||
updated[index] = { ...updated[index], color: newColor };
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
|
||||
removeItem(index: number) {
|
||||
this.items.update(current => {
|
||||
const updated = [...current];
|
||||
const removed = updated.splice(index, 1)[0];
|
||||
if (this.selectedFile() === removed.file) {
|
||||
this.selectedFile.set(null);
|
||||
}
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
|
||||
onSubmit() {
|
||||
if (this.form.valid) {
|
||||
console.log('UploadFormComponent: onSubmit triggered');
|
||||
console.log('Form Valid:', this.form.valid, 'Items:', this.items().length);
|
||||
|
||||
if (this.form.valid && this.items().length > 0) {
|
||||
console.log('UploadFormComponent: Emitting submitRequest', this.form.value);
|
||||
this.submitRequest.emit({
|
||||
...this.form.value,
|
||||
items: this.items(), // Pass the items array explicitly AFTER form value to prevent overwrite
|
||||
mode: this.mode()
|
||||
});
|
||||
} else {
|
||||
console.warn('UploadFormComponent: Form Invalid or No Items');
|
||||
console.log('Form Errors:', this.form.errors);
|
||||
Object.keys(this.form.controls).forEach(key => {
|
||||
const control = this.form.get(key);
|
||||
if (control?.invalid) {
|
||||
console.log('Invalid Control:', key, control.errors, 'Value:', control.value);
|
||||
}
|
||||
});
|
||||
this.form.markAllAsTouched();
|
||||
this.form.get('itemsTouched')?.setValue(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
<div class="user-details-container">
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<app-card [title]="'USER_DETAILS.TITLE' | translate">
|
||||
<form [formGroup]="form" (ngSubmit)="onSubmit()">
|
||||
|
||||
<!-- Name & Surname -->
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<app-input
|
||||
formControlName="name"
|
||||
label="USER_DETAILS.NAME"
|
||||
placeholder="USER_DETAILS.NAME_PLACEHOLDER"
|
||||
[required]="true"
|
||||
[error]="form.get('name')?.invalid && form.get('name')?.touched ? ('COMMON.REQUIRED' | translate) : null">
|
||||
</app-input>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<app-input
|
||||
formControlName="surname"
|
||||
label="USER_DETAILS.SURNAME"
|
||||
placeholder="USER_DETAILS.SURNAME_PLACEHOLDER"
|
||||
[required]="true"
|
||||
[error]="form.get('surname')?.invalid && form.get('surname')?.touched ? ('COMMON.REQUIRED' | translate) : null">
|
||||
</app-input>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Email & Phone -->
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<app-input
|
||||
formControlName="email"
|
||||
label="USER_DETAILS.EMAIL"
|
||||
type="email"
|
||||
placeholder="USER_DETAILS.EMAIL_PLACEHOLDER"
|
||||
[required]="true"
|
||||
[error]="form.get('email')?.invalid && form.get('email')?.touched ? ('COMMON.INVALID_EMAIL' | translate) : null">
|
||||
</app-input>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<app-input
|
||||
formControlName="phone"
|
||||
label="USER_DETAILS.PHONE"
|
||||
type="tel"
|
||||
placeholder="USER_DETAILS.PHONE_PLACEHOLDER"
|
||||
[required]="true"
|
||||
[error]="form.get('phone')?.invalid && form.get('phone')?.touched ? ('COMMON.REQUIRED' | translate) : null">
|
||||
</app-input>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Address -->
|
||||
<app-input
|
||||
formControlName="address"
|
||||
label="USER_DETAILS.ADDRESS"
|
||||
placeholder="USER_DETAILS.ADDRESS_PLACEHOLDER"
|
||||
[required]="true"
|
||||
[error]="form.get('address')?.invalid && form.get('address')?.touched ? ('COMMON.REQUIRED' | translate) : null">
|
||||
</app-input>
|
||||
|
||||
<!-- Zip & City -->
|
||||
<div class="row">
|
||||
<div class="col-md-4">
|
||||
<app-input
|
||||
formControlName="zip"
|
||||
label="USER_DETAILS.ZIP"
|
||||
placeholder="USER_DETAILS.ZIP_PLACEHOLDER"
|
||||
[required]="true"
|
||||
[error]="form.get('zip')?.invalid && form.get('zip')?.touched ? ('COMMON.REQUIRED' | translate) : null">
|
||||
</app-input>
|
||||
</div>
|
||||
<div class="col-md-8">
|
||||
<app-input
|
||||
formControlName="city"
|
||||
label="USER_DETAILS.CITY"
|
||||
placeholder="USER_DETAILS.CITY_PLACEHOLDER"
|
||||
[required]="true"
|
||||
[error]="form.get('city')?.invalid && form.get('city')?.touched ? ('COMMON.REQUIRED' | translate) : null">
|
||||
</app-input>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="actions">
|
||||
<app-button
|
||||
type="button"
|
||||
variant="outline"
|
||||
(click)="onCancel()">
|
||||
{{ 'COMMON.BACK' | translate }}
|
||||
</app-button>
|
||||
<app-button
|
||||
type="submit"
|
||||
[disabled]="form.invalid || submitting()">
|
||||
{{ 'USER_DETAILS.SUBMIT' | translate }}
|
||||
</app-button>
|
||||
</div>
|
||||
|
||||
</form>
|
||||
</app-card>
|
||||
</div>
|
||||
|
||||
<!-- Order Summary Column -->
|
||||
<div class="col-md-6">
|
||||
<app-card [title]="'USER_DETAILS.SUMMARY_TITLE' | translate">
|
||||
|
||||
<div class="summary-content" *ngIf="quote()">
|
||||
<div class="summary-item" *ngFor="let item of quote()!.items">
|
||||
<div class="item-info">
|
||||
<span class="item-name">{{ item.fileName }}</span>
|
||||
<span class="item-meta">{{ item.material }} - {{ item.color || 'Default' }}</span>
|
||||
</div>
|
||||
<div class="item-qty">x{{ item.quantity }}</div>
|
||||
<div class="item-price">{{ (item.unitPrice * item.quantity) | currency:'CHF' }}</div>
|
||||
</div>
|
||||
|
||||
<hr>
|
||||
|
||||
<div class="total-row">
|
||||
<span>{{ 'QUOTE.TOTAL' | translate }}</span>
|
||||
<span class="total-price">{{ quote()!.totalPrice | currency:'CHF' }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</app-card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,102 @@
|
||||
.user-details-container {
|
||||
padding: 1rem 0;
|
||||
}
|
||||
|
||||
.row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
margin: 0 -0.5rem;
|
||||
|
||||
> [class*='col-'] {
|
||||
padding: 0 0.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
.col-md-6 {
|
||||
width: 100%;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
width: 50%;
|
||||
}
|
||||
}
|
||||
|
||||
.col-md-4 {
|
||||
width: 100%;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
width: 33.333%;
|
||||
}
|
||||
}
|
||||
|
||||
.col-md-8 {
|
||||
width: 100%;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
width: 66.666%;
|
||||
}
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 1rem;
|
||||
margin-top: 1.5rem;
|
||||
}
|
||||
|
||||
// Summary Styles
|
||||
.summary-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.summary-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 0.5rem 0;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
|
||||
|
||||
&:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
}
|
||||
|
||||
.item-info {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.item-name {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.item-meta {
|
||||
font-size: 0.85rem;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.item-qty {
|
||||
margin: 0 1rem;
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.item-price {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.total-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
font-size: 1.2rem;
|
||||
font-weight: 700;
|
||||
margin-top: 1rem;
|
||||
padding-top: 1rem;
|
||||
border-top: 2px solid rgba(255, 255, 255, 0.2);
|
||||
|
||||
.total-price {
|
||||
color: var(--primary-color, #00C853); // Fallback color
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { Component, input, output, signal } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||
import { TranslateModule } from '@ngx-translate/core';
|
||||
import { AppCardComponent } from '../../../../shared/components/app-card/app-card.component';
|
||||
import { AppInputComponent } from '../../../../shared/components/app-input/app-input.component';
|
||||
import { AppButtonComponent } from '../../../../shared/components/app-button/app-button.component';
|
||||
import { QuoteResult } from '../../services/quote-estimator.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-user-details',
|
||||
standalone: true,
|
||||
imports: [CommonModule, ReactiveFormsModule, TranslateModule, AppCardComponent, AppInputComponent, AppButtonComponent],
|
||||
templateUrl: './user-details.component.html',
|
||||
styleUrl: './user-details.component.scss'
|
||||
})
|
||||
export class UserDetailsComponent {
|
||||
quote = input<QuoteResult>();
|
||||
submitOrder = output<any>();
|
||||
cancel = output<void>();
|
||||
|
||||
form: FormGroup;
|
||||
submitting = signal(false);
|
||||
|
||||
constructor(private fb: FormBuilder) {
|
||||
this.form = this.fb.group({
|
||||
name: ['', Validators.required],
|
||||
surname: ['', Validators.required],
|
||||
email: ['', [Validators.required, Validators.email]],
|
||||
phone: ['', Validators.required],
|
||||
address: ['', Validators.required],
|
||||
zip: ['', Validators.required],
|
||||
city: ['', Validators.required]
|
||||
});
|
||||
}
|
||||
|
||||
onSubmit() {
|
||||
if (this.form.valid) {
|
||||
this.submitting.set(true);
|
||||
|
||||
const orderData = {
|
||||
customer: this.form.value,
|
||||
quote: this.quote()
|
||||
};
|
||||
|
||||
// Simulate API delay
|
||||
setTimeout(() => {
|
||||
this.submitOrder.emit(orderData);
|
||||
this.submitting.set(false);
|
||||
}, 1000);
|
||||
} else {
|
||||
this.form.markAllAsTouched();
|
||||
}
|
||||
}
|
||||
|
||||
onCancel() {
|
||||
this.cancel.emit();
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user