Added automatic Rollwidth and Area Weigth selection by Article
This commit is contained in:
@@ -0,0 +1,284 @@
|
|||||||
|
|
||||||
|
/**
|
||||||
|
* ROLLCALC V14 - ENHANCED ARTICLE SELECTION & AUTO-WEIGHT
|
||||||
|
* =========================================================
|
||||||
|
* Improvements:
|
||||||
|
* 1. Auto-fill thickness + area_weight from article-data.json
|
||||||
|
* 2. Auto-extract roll width from product name
|
||||||
|
* 3. Auto-calculate weight when article is selected
|
||||||
|
* 4. Better error handling and logging
|
||||||
|
*/
|
||||||
|
|
||||||
|
// ===================================================================
|
||||||
|
// AUTO-WEIGHT CALCULATION FUNCTION
|
||||||
|
// ===================================================================
|
||||||
|
function triggerAutoWeightCalculation() {
|
||||||
|
console.log('[AutoCalc] Attempting automatic weight calculation...');
|
||||||
|
|
||||||
|
const wiEl = document.getElementById('de-wi');
|
||||||
|
const awEl = document.getElementById('d-aw');
|
||||||
|
const LEL = document.getElementById('d-le');
|
||||||
|
const resultEl = document.getElementById('d-wo');
|
||||||
|
|
||||||
|
if (!wiEl || !awEl || !LEL || !resultEl) {
|
||||||
|
console.warn('[AutoCalc] Missing weight calculation elements');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const wi = parseFloat(wiEl.value) || 0;
|
||||||
|
const aw = parseFloat(awEl.value) || 0;
|
||||||
|
const L = parseFloat(LEL.value) || 0;
|
||||||
|
|
||||||
|
console.log('[AutoCalc] Values: Width=', wi, 'AreaWeight=', aw, 'Length=', L);
|
||||||
|
|
||||||
|
if (wi > 0 && aw > 0 && L > 0) {
|
||||||
|
const weight = (aw * L * wi / 1000).toFixed(1);
|
||||||
|
resultEl.value = weight;
|
||||||
|
console.log('[AutoCalc] ✓ Weight calculated:', weight, 'kg');
|
||||||
|
return true;
|
||||||
|
} else {
|
||||||
|
console.log('[AutoCalc] Cannot calculate - missing values');
|
||||||
|
resultEl.value = '';
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===================================================================
|
||||||
|
// IMPROVED ARTICLE DROPDOWN POPULATION
|
||||||
|
// ===================================================================
|
||||||
|
function populateArticleDropdowns_v14() {
|
||||||
|
const data = window.ARTICLE_DATA || [];
|
||||||
|
|
||||||
|
if (!data || data.length === 0) {
|
||||||
|
console.warn('[ArticleDropdown] No article data available');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('[ArticleDropdown] Populating with', data.length, 'articles');
|
||||||
|
|
||||||
|
// Populate both datalists
|
||||||
|
['d-art', 'e-art'].forEach(function(inputId) {
|
||||||
|
const dl = document.getElementById(inputId + '-list');
|
||||||
|
if (!dl) {
|
||||||
|
console.warn('[ArticleDropdown] Datalist not found:', inputId + '-list');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
data.forEach(function(article) {
|
||||||
|
const displayText = article.nr + ' – ' + article.name;
|
||||||
|
const opt = document.createElement('option');
|
||||||
|
opt.value = displayText;
|
||||||
|
opt.dataset.articleNr = article.nr;
|
||||||
|
opt.dataset.thickness = article.thickness || 0;
|
||||||
|
opt.dataset.areaWeight = article.area_weight || 0;
|
||||||
|
opt.dataset.width = extractWidthFromName(article.name) || 0;
|
||||||
|
opt.dataset.fullData = JSON.stringify(article);
|
||||||
|
|
||||||
|
dl.appendChild(opt);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('[ArticleDropdown] ✓ Datalists populated');
|
||||||
|
|
||||||
|
// ===================================================================
|
||||||
|
// DIRECT CALCULATION TAB - Article Selection Handler
|
||||||
|
// ===================================================================
|
||||||
|
const dArt = document.getElementById('d-art');
|
||||||
|
if (dArt) {
|
||||||
|
dArt.addEventListener('input', function() {
|
||||||
|
const inputVal = dArt.value.trim();
|
||||||
|
|
||||||
|
// Try to find matching article
|
||||||
|
const match = data.find(function(a) {
|
||||||
|
const displayText = a.nr + ' – ' + a.name;
|
||||||
|
return displayText === inputVal ||
|
||||||
|
inputVal.startsWith(a.nr + ' –') ||
|
||||||
|
inputVal === a.nr;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (match) {
|
||||||
|
console.log('[DirectCalc-Article] ✓ Article found:', match.nr);
|
||||||
|
|
||||||
|
// 1. AUTO-FILL THICKNESS
|
||||||
|
document.getElementById('d-th').value = match.thickness || 0;
|
||||||
|
console.log(' └─ Thickness:', match.thickness);
|
||||||
|
|
||||||
|
// 2. AUTO-FILL AREA WEIGHT (if available)
|
||||||
|
if (match.area_weight && match.area_weight > 0) {
|
||||||
|
document.getElementById('d-aw').value = match.area_weight;
|
||||||
|
console.log(' └─ Area Weight:', match.area_weight, 'g/m²');
|
||||||
|
} else {
|
||||||
|
console.log(' └─ Area Weight: not available (0)');
|
||||||
|
document.getElementById('d-aw').value = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. AUTO-EXTRACT ROLL WIDTH from product name (e.g., "5,00 x 30 m" → 5.00)
|
||||||
|
const extractedWidth = extractWidthFromName(match.name);
|
||||||
|
if (extractedWidth > 0) {
|
||||||
|
document.getElementById('de-wi').value = extractedWidth;
|
||||||
|
console.log(' └─ Roll Width extracted:', extractedWidth, 'm');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. TRIGGER automatic weight calculation (async)
|
||||||
|
setTimeout(function() {
|
||||||
|
triggerAutoWeightCalculation();
|
||||||
|
}, 100);
|
||||||
|
|
||||||
|
} else if (inputVal.length > 0) {
|
||||||
|
console.log('[DirectCalc-Article] No match found for:', inputVal);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===================================================================
|
||||||
|
// EXTRAPOLATION TAB - Article Selection Handler
|
||||||
|
// ===================================================================
|
||||||
|
const eArt = document.getElementById('e-art');
|
||||||
|
if (eArt) {
|
||||||
|
eArt.addEventListener('input', function() {
|
||||||
|
const inputVal = eArt.value.trim();
|
||||||
|
|
||||||
|
const match = data.find(function(a) {
|
||||||
|
const displayText = a.nr + ' – ' + a.name;
|
||||||
|
return displayText === inputVal ||
|
||||||
|
inputVal.startsWith(a.nr + ' –') ||
|
||||||
|
inputVal === a.nr;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (match) {
|
||||||
|
console.log('[Extrap-Article] ✓ Article found:', match.nr);
|
||||||
|
|
||||||
|
// Set core diameter (default 150 if not specified)
|
||||||
|
const coreVal = match.core_type && match.core_type > 0 ? match.core_type : 150;
|
||||||
|
document.getElementById('e-co').value = coreVal;
|
||||||
|
console.log(' └─ Core Diameter:', coreVal, 'mm');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===================================================================
|
||||||
|
// CORE PRESET BUTTONS
|
||||||
|
// ===================================================================
|
||||||
|
document.querySelectorAll('.core-preset-btn').forEach(function(btn) {
|
||||||
|
btn.addEventListener('click', function(e) {
|
||||||
|
e.preventDefault();
|
||||||
|
const coreVal = btn.dataset.core;
|
||||||
|
const pane = btn.closest('.tab-pane');
|
||||||
|
|
||||||
|
if (pane) {
|
||||||
|
const inp = pane.querySelector('input[id$="-co"]');
|
||||||
|
if (inp) {
|
||||||
|
inp.value = coreVal;
|
||||||
|
|
||||||
|
// Visual feedback
|
||||||
|
pane.querySelectorAll('.core-preset-btn').forEach(function(b) {
|
||||||
|
b.classList.remove('active');
|
||||||
|
});
|
||||||
|
btn.classList.add('active');
|
||||||
|
|
||||||
|
console.log('[CorePreset] Set to:', coreVal, 'mm');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('[ArticleDropdown] ✓ All event listeners attached');
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===================================================================
|
||||||
|
// HELPER: Extract width from product name
|
||||||
|
// ===================================================================
|
||||||
|
function extractWidthFromName(productName) {
|
||||||
|
if (!productName) return 0;
|
||||||
|
|
||||||
|
// Regex: Match patterns like "5,00 x 30 m" or "5.00 x 30 m" or "4,85 x 40 m"
|
||||||
|
const match = productName.match(/(\d+[,\.]\d+)\s*x\s*\d+\s*m/i);
|
||||||
|
|
||||||
|
if (match && match[1]) {
|
||||||
|
// Convert German decimal (comma) to English decimal (dot)
|
||||||
|
const widthStr = match[1].replace(',', '.');
|
||||||
|
const width = parseFloat(widthStr);
|
||||||
|
|
||||||
|
if (width > 0 && width < 100) { // Sanity check
|
||||||
|
return width;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===================================================================
|
||||||
|
// ENHANCED WEIGHT CALCULATION - Listen to all relevant inputs
|
||||||
|
// ===================================================================
|
||||||
|
function setupWeightCalculationListeners() {
|
||||||
|
console.log('[WeightCalc] Setting up automatic calculation listeners...');
|
||||||
|
|
||||||
|
const inputIds = ['de-wi', 'd-aw', 'd-le'];
|
||||||
|
|
||||||
|
inputIds.forEach(function(id) {
|
||||||
|
const el = document.getElementById(id);
|
||||||
|
if (el) {
|
||||||
|
el.addEventListener('change', function() {
|
||||||
|
console.log('[WeightCalc] Input changed:', id);
|
||||||
|
triggerAutoWeightCalculation();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Also trigger on blur for better UX
|
||||||
|
el.addEventListener('blur', function() {
|
||||||
|
triggerAutoWeightCalculation();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('[WeightCalc] ✓ Listeners attached to:', inputIds.join(', '));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===================================================================
|
||||||
|
// INITIALIZATION HOOK
|
||||||
|
// ===================================================================
|
||||||
|
function initRollCalcV14() {
|
||||||
|
console.log('[RollCalcV14] Initializing enhanced features...');
|
||||||
|
|
||||||
|
// Wait for article data to be loaded
|
||||||
|
const checkDataInterval = setInterval(function() {
|
||||||
|
if (window.ARTICLE_DATA && window.ARTICLE_DATA.length > 0) {
|
||||||
|
clearInterval(checkDataInterval);
|
||||||
|
console.log('[RollCalcV14] ✓ Article data ready, populating dropdowns...');
|
||||||
|
|
||||||
|
// Use improved version
|
||||||
|
populateArticleDropdowns_v14();
|
||||||
|
setupWeightCalculationListeners();
|
||||||
|
|
||||||
|
console.log('[RollCalcV14] ✓ Initialization complete');
|
||||||
|
}
|
||||||
|
}, 100);
|
||||||
|
|
||||||
|
// Failsafe: timeout after 5 seconds
|
||||||
|
setTimeout(function() {
|
||||||
|
if (window.ARTICLE_DATA && window.ARTICLE_DATA.length > 0) {
|
||||||
|
clearInterval(checkDataInterval);
|
||||||
|
} else {
|
||||||
|
console.warn('[RollCalcV14] Article data not loaded within 5s - using fallback');
|
||||||
|
clearInterval(checkDataInterval);
|
||||||
|
}
|
||||||
|
}, 5000);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===================================================================
|
||||||
|
// EXPORT & ATTACH TO WINDOW
|
||||||
|
// ===================================================================
|
||||||
|
window.RollCalcV14 = {
|
||||||
|
initRollCalcV14: initRollCalcV14,
|
||||||
|
triggerAutoWeightCalculation: triggerAutoWeightCalculation,
|
||||||
|
populateArticleDropdowns_v14: populateArticleDropdowns_v14,
|
||||||
|
extractWidthFromName: extractWidthFromName,
|
||||||
|
setupWeightCalculationListeners: setupWeightCalculationListeners
|
||||||
|
};
|
||||||
|
|
||||||
|
console.log('[RollCalcV14] Module loaded and ready');
|
||||||
|
|
||||||
|
// Auto-init when DOM is ready
|
||||||
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
|
console.log('[RollCalcV14] DOM ready - starting initialization');
|
||||||
|
window.RollCalcV14.initRollCalcV14();
|
||||||
|
});
|
||||||
+34
@@ -0,0 +1,34 @@
|
|||||||
|
# Python
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*.pyo
|
||||||
|
.venv/
|
||||||
|
venv/
|
||||||
|
|
||||||
|
# Flask
|
||||||
|
instance/
|
||||||
|
|
||||||
|
# VS Code
|
||||||
|
.vscode/
|
||||||
|
|
||||||
|
# JetBrains
|
||||||
|
.idea/
|
||||||
|
|
||||||
|
# macOS
|
||||||
|
.DS_Store
|
||||||
|
|
||||||
|
# Linux
|
||||||
|
*~
|
||||||
|
|
||||||
|
# Logs
|
||||||
|
*.log
|
||||||
|
|
||||||
|
# Environment
|
||||||
|
.env
|
||||||
|
|
||||||
|
# Node (falls später Frontend hinzukommt)
|
||||||
|
node_modules/
|
||||||
|
|
||||||
|
# Backup files
|
||||||
|
.bak
|
||||||
|
.backup
|
||||||
@@ -145,5 +145,68 @@
|
|||||||
"endpoint": "/",
|
"endpoint": "/",
|
||||||
"method": "GET",
|
"method": "GET",
|
||||||
"status": 200
|
"status": 200
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"timestamp": "2026-07-01T07:31:48.451519",
|
||||||
|
"username": "mtazl",
|
||||||
|
"endpoint": "/",
|
||||||
|
"method": "GET",
|
||||||
|
"status": 200
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"timestamp": "2026-07-01T07:31:48.676701",
|
||||||
|
"username": "mtazl",
|
||||||
|
"endpoint": "/",
|
||||||
|
"method": "GET",
|
||||||
|
"status": 200
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"timestamp": "2026-07-01T07:31:54.481445",
|
||||||
|
"username": "mtazl",
|
||||||
|
"endpoint": "/",
|
||||||
|
"method": "GET",
|
||||||
|
"status": 200
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"timestamp": "2026-07-01T07:31:58.011356",
|
||||||
|
"username": "mtazl",
|
||||||
|
"endpoint": "/",
|
||||||
|
"method": "GET",
|
||||||
|
"status": 200
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"timestamp": "2026-07-01T07:32:48.747837",
|
||||||
|
"username": "mtazl",
|
||||||
|
"endpoint": "/",
|
||||||
|
"method": "GET",
|
||||||
|
"status": 200
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"timestamp": "2026-07-01T07:33:07.753648",
|
||||||
|
"username": "mtazl",
|
||||||
|
"endpoint": "/",
|
||||||
|
"method": "GET",
|
||||||
|
"status": 200
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"timestamp": "2026-07-01T07:42:11.820817",
|
||||||
|
"username": "mtazl",
|
||||||
|
"endpoint": "/",
|
||||||
|
"method": "GET",
|
||||||
|
"status": 200
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"timestamp": "2026-07-01T07:43:37.598978",
|
||||||
|
"username": "mtazl",
|
||||||
|
"endpoint": "/",
|
||||||
|
"method": "GET",
|
||||||
|
"status": 200
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"timestamp": "2026-07-01T07:47:39.689201",
|
||||||
|
"username": "mtazl",
|
||||||
|
"endpoint": "/",
|
||||||
|
"method": "GET",
|
||||||
|
"status": 200
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
+241
@@ -0,0 +1,241 @@
|
|||||||
|
"""
|
||||||
|
Naue Roll Calculator - Beta
|
||||||
|
Flask app with HTTP Basic Authentication
|
||||||
|
"""
|
||||||
|
|
||||||
|
from flask import Flask, render_template, request, send_file, send_from_directory, jsonify
|
||||||
|
from flask_httpauth import HTTPBasicAuth
|
||||||
|
from functools import wraps
|
||||||
|
import os
|
||||||
|
from datetime import datetime
|
||||||
|
import json
|
||||||
|
|
||||||
|
app = Flask(__name__)
|
||||||
|
auth = HTTPBasicAuth()
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# CONFIGURATION
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
# Benutzer für Beta-Phase (in Produktion aus env-Variablen laden!)
|
||||||
|
BETA_USERS = {
|
||||||
|
"beta": "rollcalc_beta_2026", # Ändere das Passwort!
|
||||||
|
"naue": "naue_access_2026", # Zweiter User optional
|
||||||
|
"cniehues": "beta_test_2026", # Christian Niehues EDD
|
||||||
|
"lvollmert": "Geheim!", # Lars Vollmert EDD
|
||||||
|
"mtazl": "rollcalc", # Martin Tazl EDD
|
||||||
|
"controlling": "beta2026" # Lars Krückemeier und Lea-Marie
|
||||||
|
}
|
||||||
|
|
||||||
|
# Optional: Admin-Features (z.B. Logs, Stats)
|
||||||
|
ADMIN_USERS = {
|
||||||
|
"admin": "admin_secure_pwd_2026"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Logging für Auditing
|
||||||
|
LOG_FILE = "access_log.json"
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# AUTHENTICATION
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
@auth.verify_password
|
||||||
|
def verify_password(username, password):
|
||||||
|
"""Verify HTTP Basic Auth credentials"""
|
||||||
|
all_users = {**BETA_USERS, **ADMIN_USERS}
|
||||||
|
if username in all_users and all_users[username] == password:
|
||||||
|
return username
|
||||||
|
return None
|
||||||
|
|
||||||
|
def log_access(username, endpoint, method, status=200):
|
||||||
|
"""Log all access attempts for audit trail"""
|
||||||
|
log_entry = {
|
||||||
|
"timestamp": datetime.now().isoformat(),
|
||||||
|
"username": username,
|
||||||
|
"endpoint": endpoint,
|
||||||
|
"method": method,
|
||||||
|
"status": status
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
logs = []
|
||||||
|
if os.path.exists(LOG_FILE):
|
||||||
|
with open(LOG_FILE, "r") as f:
|
||||||
|
logs = json.load(f)
|
||||||
|
logs.append(log_entry)
|
||||||
|
with open(LOG_FILE, "w") as f:
|
||||||
|
json.dump(logs, f, indent=2)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[Logging Error] {e}")
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# ROUTES
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
@app.route("/", methods=["GET"])
|
||||||
|
@auth.login_required
|
||||||
|
def index():
|
||||||
|
"""Main calculator page - requires authentication"""
|
||||||
|
log_access(auth.current_user(), "/", "GET")
|
||||||
|
return render_template("roll_calculator.html")
|
||||||
|
|
||||||
|
@app.route("/static/<path:filename>", methods=["GET"])
|
||||||
|
@auth.login_required
|
||||||
|
def serve_static(filename):
|
||||||
|
"""Serve static files (CSS, JS, JSON) - protected"""
|
||||||
|
log_access(auth.current_user(), f"/static/{filename}", "GET")
|
||||||
|
return send_from_directory("static", filename)
|
||||||
|
|
||||||
|
@app.route("/api/health", methods=["GET"])
|
||||||
|
@auth.login_required
|
||||||
|
def health_check():
|
||||||
|
"""Simple health check endpoint"""
|
||||||
|
return jsonify({"status": "ok", "version": "1.0.0-beta"}), 200
|
||||||
|
|
||||||
|
@app.route("/api/user", methods=["GET"])
|
||||||
|
@auth.login_required
|
||||||
|
def get_user():
|
||||||
|
"""Get current authenticated user info"""
|
||||||
|
user = auth.current_user()
|
||||||
|
is_admin = user in ADMIN_USERS
|
||||||
|
return jsonify({
|
||||||
|
"username": user,
|
||||||
|
"authenticated": True,
|
||||||
|
"is_admin": is_admin,
|
||||||
|
"timestamp": datetime.now().isoformat()
|
||||||
|
}), 200
|
||||||
|
|
||||||
|
# Admin-only endpoint (optional)
|
||||||
|
@app.route("/admin/logs", methods=["GET"])
|
||||||
|
@auth.login_required
|
||||||
|
def get_logs():
|
||||||
|
"""View access logs - admin only"""
|
||||||
|
user = auth.current_user()
|
||||||
|
if user not in ADMIN_USERS:
|
||||||
|
log_access(user, "/admin/logs", "GET", 403)
|
||||||
|
return jsonify({"error": "Unauthorized"}), 403
|
||||||
|
|
||||||
|
log_access(user, "/admin/logs", "GET")
|
||||||
|
logs = []
|
||||||
|
if os.path.exists(LOG_FILE):
|
||||||
|
with open(LOG_FILE, "r") as f:
|
||||||
|
logs = json.load(f)
|
||||||
|
return jsonify({"logs": logs}), 200
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# ERROR HANDLERS
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
@app.errorhandler(401)
|
||||||
|
def unauthorized(e):
|
||||||
|
"""Handle 401 Unauthorized - browser will prompt for credentials"""
|
||||||
|
return jsonify({"error": "Unauthorized - please provide valid credentials"}), 401
|
||||||
|
|
||||||
|
@app.errorhandler(404)
|
||||||
|
def not_found(e):
|
||||||
|
"""Handle 404 Not Found"""
|
||||||
|
return jsonify({"error": "Not found"}), 404
|
||||||
|
|
||||||
|
@app.errorhandler(500)
|
||||||
|
def internal_error(e):
|
||||||
|
"""Handle 500 Internal Server Error"""
|
||||||
|
return jsonify({"error": "Internal server error"}), 500
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# ADMIN ROUTES
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
@app.route("/admin", methods=["GET"])
|
||||||
|
@auth.login_required
|
||||||
|
def admin_dashboard():
|
||||||
|
"""Admin Dashboard - nur für Admin-Benutzer"""
|
||||||
|
user = auth.current_user()
|
||||||
|
if user not in ADMIN_USERS:
|
||||||
|
log_access(user, "/admin", "GET", 403)
|
||||||
|
return jsonify({"error": "Unauthorized - Admin access required"}), 403
|
||||||
|
|
||||||
|
log_access(user, "/admin", "GET")
|
||||||
|
return render_template("admin.html")
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/api/admin/stats", methods=["GET"])
|
||||||
|
@auth.login_required
|
||||||
|
def get_admin_stats():
|
||||||
|
"""Statistiken für Admin Dashboard"""
|
||||||
|
user = auth.current_user()
|
||||||
|
if user not in ADMIN_USERS:
|
||||||
|
log_access(user, "/api/admin/stats", "GET", 403)
|
||||||
|
return jsonify({"error": "Unauthorized"}), 403
|
||||||
|
|
||||||
|
log_access(user, "/api/admin/stats", "GET")
|
||||||
|
|
||||||
|
logs = []
|
||||||
|
if os.path.exists(LOG_FILE):
|
||||||
|
try:
|
||||||
|
with open(LOG_FILE, "r") as f:
|
||||||
|
logs = json.load(f)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
logs = []
|
||||||
|
|
||||||
|
total_requests = len(logs)
|
||||||
|
unique_users = len(set(log.get("username", "unknown") for log in logs))
|
||||||
|
failed_logins = len([l for l in logs if l.get("status") == 401])
|
||||||
|
|
||||||
|
return jsonify({
|
||||||
|
"total_requests": total_requests,
|
||||||
|
"unique_users": unique_users,
|
||||||
|
"failed_logins": failed_logins,
|
||||||
|
"timestamp": datetime.now().isoformat()
|
||||||
|
}), 200
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/api/admin/logs", methods=["GET"])
|
||||||
|
@auth.login_required
|
||||||
|
def get_admin_logs():
|
||||||
|
"""Access Logs für Admin Dashboard"""
|
||||||
|
user = auth.current_user()
|
||||||
|
if user not in ADMIN_USERS:
|
||||||
|
log_access(user, "/api/admin/logs", "GET", 403)
|
||||||
|
return jsonify({"error": "Unauthorized"}), 403
|
||||||
|
|
||||||
|
log_access(user, "/api/admin/logs", "GET")
|
||||||
|
|
||||||
|
logs = []
|
||||||
|
if os.path.exists(LOG_FILE):
|
||||||
|
try:
|
||||||
|
with open(LOG_FILE, "r") as f:
|
||||||
|
logs = json.load(f)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
logs = []
|
||||||
|
|
||||||
|
logs_sorted = sorted(logs, key=lambda x: x.get("timestamp", ""), reverse=True)
|
||||||
|
return jsonify({"logs": logs_sorted[-500:]}), 200
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# STARTUP
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
# Erstelle templates-Verzeichnis falls nicht vorhanden
|
||||||
|
os.makedirs("templates", exist_ok=True)
|
||||||
|
os.makedirs("static", exist_ok=True)
|
||||||
|
|
||||||
|
print("""
|
||||||
|
╔═══════════════════════════════════════════════════════════╗
|
||||||
|
║ Naue Roll Calculator - Beta ║
|
||||||
|
║ HTTP Basic Auth Enabled ║
|
||||||
|
║ ║
|
||||||
|
║ Test credentials: ║
|
||||||
|
║ User: beta / Password: rollcalc_beta_2026 ║
|
||||||
|
║ User: admin / Password: admin_secure_pwd_2026 ║
|
||||||
|
║ ║
|
||||||
|
║ Starten auf: http://localhost:5000 ║
|
||||||
|
║ ⚠️ ÄNDERE DIE PASSWÖRTER VOR PRODUKTIVBEREITSTELLUNG! ║
|
||||||
|
╚═══════════════════════════════════════════════════════════╝
|
||||||
|
""")
|
||||||
|
|
||||||
|
app.run(
|
||||||
|
host="0.0.0.0",
|
||||||
|
port=5000,
|
||||||
|
debug=False, # In Produktion: False
|
||||||
|
use_reloader=True
|
||||||
|
)
|
||||||
+4909
-722
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,284 @@
|
|||||||
|
|
||||||
|
/**
|
||||||
|
* ROLLCALC V14 - ENHANCED ARTICLE SELECTION & AUTO-WEIGHT
|
||||||
|
* =========================================================
|
||||||
|
* Improvements:
|
||||||
|
* 1. Auto-fill thickness + area_weight from article-data.json
|
||||||
|
* 2. Auto-extract roll width from product name
|
||||||
|
* 3. Auto-calculate weight when article is selected
|
||||||
|
* 4. Better error handling and logging
|
||||||
|
*/
|
||||||
|
|
||||||
|
// ===================================================================
|
||||||
|
// AUTO-WEIGHT CALCULATION FUNCTION
|
||||||
|
// ===================================================================
|
||||||
|
function triggerAutoWeightCalculation() {
|
||||||
|
console.log('[AutoCalc] Attempting automatic weight calculation...');
|
||||||
|
|
||||||
|
const wiEl = document.getElementById('de-wi');
|
||||||
|
const awEl = document.getElementById('d-aw');
|
||||||
|
const LEL = document.getElementById('d-le');
|
||||||
|
const resultEl = document.getElementById('d-wo');
|
||||||
|
|
||||||
|
if (!wiEl || !awEl || !LEL || !resultEl) {
|
||||||
|
console.warn('[AutoCalc] Missing weight calculation elements');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const wi = parseFloat(wiEl.value) || 0;
|
||||||
|
const aw = parseFloat(awEl.value) || 0;
|
||||||
|
const L = parseFloat(LEL.value) || 0;
|
||||||
|
|
||||||
|
console.log('[AutoCalc] Values: Width=', wi, 'AreaWeight=', aw, 'Length=', L);
|
||||||
|
|
||||||
|
if (wi > 0 && aw > 0 && L > 0) {
|
||||||
|
const weight = (aw * L * wi / 1000).toFixed(1);
|
||||||
|
resultEl.value = weight;
|
||||||
|
console.log('[AutoCalc] ✓ Weight calculated:', weight, 'kg');
|
||||||
|
return true;
|
||||||
|
} else {
|
||||||
|
console.log('[AutoCalc] Cannot calculate - missing values');
|
||||||
|
resultEl.value = '';
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===================================================================
|
||||||
|
// IMPROVED ARTICLE DROPDOWN POPULATION
|
||||||
|
// ===================================================================
|
||||||
|
function populateArticleDropdowns_v14() {
|
||||||
|
const data = window.ARTICLE_DATA || [];
|
||||||
|
|
||||||
|
if (!data || data.length === 0) {
|
||||||
|
console.warn('[ArticleDropdown] No article data available');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('[ArticleDropdown] Populating with', data.length, 'articles');
|
||||||
|
|
||||||
|
// Populate both datalists
|
||||||
|
['d-art', 'e-art'].forEach(function(inputId) {
|
||||||
|
const dl = document.getElementById(inputId + '-list');
|
||||||
|
if (!dl) {
|
||||||
|
console.warn('[ArticleDropdown] Datalist not found:', inputId + '-list');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
data.forEach(function(article) {
|
||||||
|
const displayText = article.nr + ' – ' + article.name;
|
||||||
|
const opt = document.createElement('option');
|
||||||
|
opt.value = displayText;
|
||||||
|
opt.dataset.articleNr = article.nr;
|
||||||
|
opt.dataset.thickness = article.thickness || 0;
|
||||||
|
opt.dataset.areaWeight = article.area_weight || 0;
|
||||||
|
opt.dataset.width = extractWidthFromName(article.name) || 0;
|
||||||
|
opt.dataset.fullData = JSON.stringify(article);
|
||||||
|
|
||||||
|
dl.appendChild(opt);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('[ArticleDropdown] ✓ Datalists populated');
|
||||||
|
|
||||||
|
// ===================================================================
|
||||||
|
// DIRECT CALCULATION TAB - Article Selection Handler
|
||||||
|
// ===================================================================
|
||||||
|
const dArt = document.getElementById('d-art');
|
||||||
|
if (dArt) {
|
||||||
|
dArt.addEventListener('input', function() {
|
||||||
|
const inputVal = dArt.value.trim();
|
||||||
|
|
||||||
|
// Try to find matching article
|
||||||
|
const match = data.find(function(a) {
|
||||||
|
const displayText = a.nr + ' – ' + a.name;
|
||||||
|
return displayText === inputVal ||
|
||||||
|
inputVal.startsWith(a.nr + ' –') ||
|
||||||
|
inputVal === a.nr;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (match) {
|
||||||
|
console.log('[DirectCalc-Article] ✓ Article found:', match.nr);
|
||||||
|
|
||||||
|
// 1. AUTO-FILL THICKNESS
|
||||||
|
document.getElementById('d-th').value = match.thickness || 0;
|
||||||
|
console.log(' └─ Thickness:', match.thickness);
|
||||||
|
|
||||||
|
// 2. AUTO-FILL AREA WEIGHT (if available)
|
||||||
|
if (match.area_weight && match.area_weight > 0) {
|
||||||
|
document.getElementById('d-aw').value = match.area_weight;
|
||||||
|
console.log(' └─ Area Weight:', match.area_weight, 'g/m²');
|
||||||
|
} else {
|
||||||
|
console.log(' └─ Area Weight: not available (0)');
|
||||||
|
document.getElementById('d-aw').value = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. AUTO-EXTRACT ROLL WIDTH from product name (e.g., "5,00 x 30 m" → 5.00)
|
||||||
|
const extractedWidth = extractWidthFromName(match.name);
|
||||||
|
if (extractedWidth > 0) {
|
||||||
|
document.getElementById('de-wi').value = extractedWidth;
|
||||||
|
console.log(' └─ Roll Width extracted:', extractedWidth, 'm');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. TRIGGER automatic weight calculation (async)
|
||||||
|
setTimeout(function() {
|
||||||
|
triggerAutoWeightCalculation();
|
||||||
|
}, 100);
|
||||||
|
|
||||||
|
} else if (inputVal.length > 0) {
|
||||||
|
console.log('[DirectCalc-Article] No match found for:', inputVal);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===================================================================
|
||||||
|
// EXTRAPOLATION TAB - Article Selection Handler
|
||||||
|
// ===================================================================
|
||||||
|
const eArt = document.getElementById('e-art');
|
||||||
|
if (eArt) {
|
||||||
|
eArt.addEventListener('input', function() {
|
||||||
|
const inputVal = eArt.value.trim();
|
||||||
|
|
||||||
|
const match = data.find(function(a) {
|
||||||
|
const displayText = a.nr + ' – ' + a.name;
|
||||||
|
return displayText === inputVal ||
|
||||||
|
inputVal.startsWith(a.nr + ' –') ||
|
||||||
|
inputVal === a.nr;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (match) {
|
||||||
|
console.log('[Extrap-Article] ✓ Article found:', match.nr);
|
||||||
|
|
||||||
|
// Set core diameter (default 150 if not specified)
|
||||||
|
const coreVal = match.core_type && match.core_type > 0 ? match.core_type : 150;
|
||||||
|
document.getElementById('e-co').value = coreVal;
|
||||||
|
console.log(' └─ Core Diameter:', coreVal, 'mm');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===================================================================
|
||||||
|
// CORE PRESET BUTTONS
|
||||||
|
// ===================================================================
|
||||||
|
document.querySelectorAll('.core-preset-btn').forEach(function(btn) {
|
||||||
|
btn.addEventListener('click', function(e) {
|
||||||
|
e.preventDefault();
|
||||||
|
const coreVal = btn.dataset.core;
|
||||||
|
const pane = btn.closest('.tab-pane');
|
||||||
|
|
||||||
|
if (pane) {
|
||||||
|
const inp = pane.querySelector('input[id$="-co"]');
|
||||||
|
if (inp) {
|
||||||
|
inp.value = coreVal;
|
||||||
|
|
||||||
|
// Visual feedback
|
||||||
|
pane.querySelectorAll('.core-preset-btn').forEach(function(b) {
|
||||||
|
b.classList.remove('active');
|
||||||
|
});
|
||||||
|
btn.classList.add('active');
|
||||||
|
|
||||||
|
console.log('[CorePreset] Set to:', coreVal, 'mm');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('[ArticleDropdown] ✓ All event listeners attached');
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===================================================================
|
||||||
|
// HELPER: Extract width from product name
|
||||||
|
// ===================================================================
|
||||||
|
function extractWidthFromName(productName) {
|
||||||
|
if (!productName) return 0;
|
||||||
|
|
||||||
|
// Regex: Match patterns like "5,00 x 30 m" or "5.00 x 30 m" or "4,85 x 40 m"
|
||||||
|
const match = productName.match(/(\d+[,\.]\d+)\s*x\s*\d+\s*m/i);
|
||||||
|
|
||||||
|
if (match && match[1]) {
|
||||||
|
// Convert German decimal (comma) to English decimal (dot)
|
||||||
|
const widthStr = match[1].replace(',', '.');
|
||||||
|
const width = parseFloat(widthStr);
|
||||||
|
|
||||||
|
if (width > 0 && width < 100) { // Sanity check
|
||||||
|
return width;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===================================================================
|
||||||
|
// ENHANCED WEIGHT CALCULATION - Listen to all relevant inputs
|
||||||
|
// ===================================================================
|
||||||
|
function setupWeightCalculationListeners() {
|
||||||
|
console.log('[WeightCalc] Setting up automatic calculation listeners...');
|
||||||
|
|
||||||
|
const inputIds = ['de-wi', 'd-aw', 'd-le'];
|
||||||
|
|
||||||
|
inputIds.forEach(function(id) {
|
||||||
|
const el = document.getElementById(id);
|
||||||
|
if (el) {
|
||||||
|
el.addEventListener('change', function() {
|
||||||
|
console.log('[WeightCalc] Input changed:', id);
|
||||||
|
triggerAutoWeightCalculation();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Also trigger on blur for better UX
|
||||||
|
el.addEventListener('blur', function() {
|
||||||
|
triggerAutoWeightCalculation();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('[WeightCalc] ✓ Listeners attached to:', inputIds.join(', '));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===================================================================
|
||||||
|
// INITIALIZATION HOOK
|
||||||
|
// ===================================================================
|
||||||
|
function initRollCalcV14() {
|
||||||
|
console.log('[RollCalcV14] Initializing enhanced features...');
|
||||||
|
|
||||||
|
// Wait for article data to be loaded
|
||||||
|
const checkDataInterval = setInterval(function() {
|
||||||
|
if (window.ARTICLE_DATA && window.ARTICLE_DATA.length > 0) {
|
||||||
|
clearInterval(checkDataInterval);
|
||||||
|
console.log('[RollCalcV14] ✓ Article data ready, populating dropdowns...');
|
||||||
|
|
||||||
|
// Use improved version
|
||||||
|
populateArticleDropdowns_v14();
|
||||||
|
setupWeightCalculationListeners();
|
||||||
|
|
||||||
|
console.log('[RollCalcV14] ✓ Initialization complete');
|
||||||
|
}
|
||||||
|
}, 100);
|
||||||
|
|
||||||
|
// Failsafe: timeout after 5 seconds
|
||||||
|
setTimeout(function() {
|
||||||
|
if (window.ARTICLE_DATA && window.ARTICLE_DATA.length > 0) {
|
||||||
|
clearInterval(checkDataInterval);
|
||||||
|
} else {
|
||||||
|
console.warn('[RollCalcV14] Article data not loaded within 5s - using fallback');
|
||||||
|
clearInterval(checkDataInterval);
|
||||||
|
}
|
||||||
|
}, 5000);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===================================================================
|
||||||
|
// EXPORT & ATTACH TO WINDOW
|
||||||
|
// ===================================================================
|
||||||
|
window.RollCalcV14 = {
|
||||||
|
initRollCalcV14: initRollCalcV14,
|
||||||
|
triggerAutoWeightCalculation: triggerAutoWeightCalculation,
|
||||||
|
populateArticleDropdowns_v14: populateArticleDropdowns_v14,
|
||||||
|
extractWidthFromName: extractWidthFromName,
|
||||||
|
setupWeightCalculationListeners: setupWeightCalculationListeners
|
||||||
|
};
|
||||||
|
|
||||||
|
console.log('[RollCalcV14] Module loaded and ready');
|
||||||
|
|
||||||
|
// Auto-init when DOM is ready
|
||||||
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
|
console.log('[RollCalcV14] DOM ready - starting initialization');
|
||||||
|
window.RollCalcV14.initRollCalcV14();
|
||||||
|
});
|
||||||
+190
-47
@@ -1,83 +1,226 @@
|
|||||||
// service-worker.js
|
/**
|
||||||
// Cache-Strategie: Cache First (offline works, then network)
|
* SERVICE WORKER FOR NAUE ROLL CALCULATOR
|
||||||
|
* ========================================
|
||||||
|
* Caching strategy:
|
||||||
|
* 1. CACHE_FIRST for static assets (CSS, JS, images)
|
||||||
|
* 2. NETWORK_FIRST for API/data (with fallback to cache)
|
||||||
|
* 3. STALE_WHILE_REVALIDATE for article data
|
||||||
|
*/
|
||||||
|
|
||||||
const CACHE_NAME = 'roll-calculator-v3'; // bumped to v2 for new clearance settings
|
const CACHE_NAME = 'rollcalc-v14-' + new Date().getTime();
|
||||||
const ASSETS_TO_CACHE = [
|
const STATIC_CACHE = 'rollcalc-static-v14';
|
||||||
'./',
|
const DATA_CACHE = 'rollcalc-data-v14';
|
||||||
'./roll_calculator_v9.html',
|
|
||||||
'./article-data.json',
|
// Assets to cache on install
|
||||||
'./config.json',
|
const STATIC_ASSETS = [
|
||||||
'./service-worker.js'
|
'/',
|
||||||
|
'/index.html',
|
||||||
|
'/static/article-data.json',
|
||||||
|
'/static/config.json'
|
||||||
];
|
];
|
||||||
|
|
||||||
// Install Event
|
// ===================================================================
|
||||||
|
// INSTALL EVENT - Cache static assets
|
||||||
|
// ===================================================================
|
||||||
self.addEventListener('install', event => {
|
self.addEventListener('install', event => {
|
||||||
console.log('[ServiceWorker] Installing...');
|
console.log('[ServiceWorker] Installing...');
|
||||||
|
|
||||||
event.waitUntil(
|
event.waitUntil(
|
||||||
caches.open(CACHE_NAME).then(cache => {
|
caches.open(STATIC_CACHE)
|
||||||
console.log('[ServiceWorker] Caching assets:', ASSETS_TO_CACHE);
|
.then(cache => {
|
||||||
return cache.addAll(ASSETS_TO_CACHE);
|
console.log('[ServiceWorker] Caching static assets');
|
||||||
}).catch(err => {
|
return cache.addAll(STATIC_ASSETS).catch(err => {
|
||||||
console.error('[ServiceWorker] Cache failed:', err);
|
console.warn('[ServiceWorker] Some assets failed to cache:', err);
|
||||||
|
// Don't fail installation if some assets can't be cached
|
||||||
|
return Promise.resolve();
|
||||||
|
});
|
||||||
})
|
})
|
||||||
|
.then(() => self.skipWaiting())
|
||||||
);
|
);
|
||||||
self.skipWaiting();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Activate Event: Cleanup alte Caches
|
// ===================================================================
|
||||||
|
// ACTIVATE EVENT - Clean up old caches
|
||||||
|
// ===================================================================
|
||||||
self.addEventListener('activate', event => {
|
self.addEventListener('activate', event => {
|
||||||
console.log('[ServiceWorker] Activating...');
|
console.log('[ServiceWorker] Activating...');
|
||||||
|
|
||||||
event.waitUntil(
|
event.waitUntil(
|
||||||
caches.keys().then(cacheNames => {
|
caches.keys().then(cacheNames => {
|
||||||
return Promise.all(
|
return Promise.all(
|
||||||
cacheNames.map(cacheName => {
|
cacheNames.map(cacheName => {
|
||||||
if (cacheName !== CACHE_NAME) {
|
if (cacheName !== STATIC_CACHE &&
|
||||||
|
cacheName !== DATA_CACHE &&
|
||||||
|
cacheName !== CACHE_NAME) {
|
||||||
console.log('[ServiceWorker] Deleting old cache:', cacheName);
|
console.log('[ServiceWorker] Deleting old cache:', cacheName);
|
||||||
return caches.delete(cacheName);
|
return caches.delete(cacheName);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
}).then(() => self.clients.claim())
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ===================================================================
|
||||||
|
// FETCH EVENT - Intelligent caching strategy
|
||||||
|
// ===================================================================
|
||||||
|
self.addEventListener('fetch', event => {
|
||||||
|
const { request } = event;
|
||||||
|
const url = new URL(request.url);
|
||||||
|
|
||||||
|
// Skip cross-origin requests
|
||||||
|
if (url.origin !== location.origin) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------
|
||||||
|
// 1. JSON DATA (article-data.json, config.json)
|
||||||
|
// STALE_WHILE_REVALIDATE: Use cache first, update in background
|
||||||
|
// ---------------------------------------------------------------
|
||||||
|
if (url.pathname.includes('.json')) {
|
||||||
|
event.respondWith(
|
||||||
|
caches.open(DATA_CACHE).then(cache => {
|
||||||
|
return cache.match(request).then(response => {
|
||||||
|
const fetchPromise = fetch(request).then(networkResponse => {
|
||||||
|
// Update cache with fresh version
|
||||||
|
if (networkResponse && networkResponse.status === 200) {
|
||||||
|
cache.put(request, networkResponse.clone());
|
||||||
|
}
|
||||||
|
return networkResponse;
|
||||||
|
}).catch(() => {
|
||||||
|
// Network failed, return cached version
|
||||||
|
return response || cacheNotFound('JSON data not found');
|
||||||
|
});
|
||||||
|
|
||||||
|
// Return cached response immediately, update in background
|
||||||
|
return response || fetchPromise;
|
||||||
|
});
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
self.clients.claim();
|
return;
|
||||||
});
|
}
|
||||||
|
|
||||||
// Fetch Event: Cache First Strategy
|
|
||||||
self.addEventListener('fetch', event => {
|
|
||||||
const url = event.request.url;
|
|
||||||
|
|
||||||
if (event.request.method !== 'GET') return;
|
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------
|
||||||
|
// 2. HTML PAGES
|
||||||
|
// NETWORK_FIRST: Try network, fall back to cache
|
||||||
|
// ---------------------------------------------------------------
|
||||||
|
if (request.method === 'GET' &&
|
||||||
|
(url.pathname === '/' || url.pathname.endsWith('.html'))) {
|
||||||
event.respondWith(
|
event.respondWith(
|
||||||
caches.match(event.request)
|
fetch(request)
|
||||||
.then(response => {
|
.then(response => {
|
||||||
if (response) {
|
if (response && response.status === 200) {
|
||||||
console.log('[ServiceWorker] Cache HIT:', url);
|
const cache_copy = response.clone();
|
||||||
return response;
|
caches.open(STATIC_CACHE).then(cache => {
|
||||||
}
|
cache.put(request, cache_copy);
|
||||||
console.log('[ServiceWorker] Cache MISS, fetching:', url);
|
|
||||||
return fetch(event.request)
|
|
||||||
.then(response => {
|
|
||||||
if (!response || response.status !== 200 || response.type === 'error') {
|
|
||||||
return response;
|
|
||||||
}
|
|
||||||
const responseClone = response.clone();
|
|
||||||
caches.open(CACHE_NAME).then(cache => {
|
|
||||||
cache.put(event.request, responseClone);
|
|
||||||
});
|
});
|
||||||
|
}
|
||||||
return response;
|
return response;
|
||||||
})
|
})
|
||||||
.catch(() => {
|
.catch(() => {
|
||||||
return caches.match(event.request).then(response => {
|
return caches.match(request)
|
||||||
if (response) return response;
|
.then(response => response || cacheNotFound('Page not found'));
|
||||||
return new Response('Offline - resource not available', {
|
})
|
||||||
status: 503,
|
);
|
||||||
statusText: 'Service Unavailable'
|
return;
|
||||||
});
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------
|
||||||
|
// 3. STATIC ASSETS (CSS, JS, images)
|
||||||
|
// CACHE_FIRST: Use cache if available, fall back to network
|
||||||
|
// ---------------------------------------------------------------
|
||||||
|
if (request.method === 'GET') {
|
||||||
|
event.respondWith(
|
||||||
|
caches.open(STATIC_CACHE).then(cache => {
|
||||||
|
return cache.match(request).then(response => {
|
||||||
|
if (response) {
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
return fetch(request).then(networkResponse => {
|
||||||
|
// Only cache successful responses
|
||||||
|
if (networkResponse && networkResponse.status === 200) {
|
||||||
|
cache.put(request, networkResponse.clone());
|
||||||
|
}
|
||||||
|
return networkResponse;
|
||||||
|
}).catch(() => {
|
||||||
|
// Return offline placeholder
|
||||||
|
if (request.destination === 'image') {
|
||||||
|
return createPlaceholderImage();
|
||||||
|
}
|
||||||
|
return cacheNotFound('Asset not found');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------
|
||||||
|
// 4. POST/PUT/DELETE (API calls)
|
||||||
|
// NETWORK_ONLY: Do not cache, but handle errors gracefully
|
||||||
|
// ---------------------------------------------------------------
|
||||||
|
if (['POST', 'PUT', 'DELETE'].includes(request.method)) {
|
||||||
|
event.respondWith(
|
||||||
|
fetch(request)
|
||||||
|
.catch(() => {
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
error: 'You are offline. API calls are not available.',
|
||||||
|
status: 'offline'
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
status: 503,
|
||||||
|
statusText: 'Service Unavailable',
|
||||||
|
headers: new Headers({
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
})
|
||||||
|
}
|
||||||
|
);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log('[ServiceWorker] Script loaded (v2)');
|
// ===================================================================
|
||||||
|
// HELPER FUNCTIONS
|
||||||
|
// ===================================================================
|
||||||
|
|
||||||
|
function cacheNotFound(message) {
|
||||||
|
return new Response(
|
||||||
|
`<html><body style="font-family: sans-serif; padding: 20px; color: #666;">
|
||||||
|
<h2>Offline</h2>
|
||||||
|
<p>${message}</p>
|
||||||
|
<p style="font-size: 12px; color: #999;">Roll Calculator is offline or the resource is not cached.</p>
|
||||||
|
</body></html>`,
|
||||||
|
{
|
||||||
|
status: 404,
|
||||||
|
statusText: 'Not Found',
|
||||||
|
headers: new Headers({
|
||||||
|
'Content-Type': 'text/html'
|
||||||
|
})
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function createPlaceholderImage() {
|
||||||
|
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
|
||||||
|
<rect fill="#f0f0f0" width="100" height="100"/>
|
||||||
|
<text x="50" y="50" text-anchor="middle" dy=".3em" fill="#999" font-size="12">
|
||||||
|
Image offline
|
||||||
|
</text>
|
||||||
|
</svg>`;
|
||||||
|
|
||||||
|
return new Response(svg, {
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'image/svg+xml',
|
||||||
|
'Cache-Control': 'public, max-age=86400'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===================================================================
|
||||||
|
// LOG SERVICE WORKER STATUS
|
||||||
|
// ===================================================================
|
||||||
|
console.log('[ServiceWorker] Naue Roll Calculator Service Worker loaded');
|
||||||
|
|||||||
@@ -0,0 +1,226 @@
|
|||||||
|
/**
|
||||||
|
* SERVICE WORKER FOR NAUE ROLL CALCULATOR
|
||||||
|
* ========================================
|
||||||
|
* Caching strategy:
|
||||||
|
* 1. CACHE_FIRST for static assets (CSS, JS, images)
|
||||||
|
* 2. NETWORK_FIRST for API/data (with fallback to cache)
|
||||||
|
* 3. STALE_WHILE_REVALIDATE for article data
|
||||||
|
*/
|
||||||
|
|
||||||
|
const CACHE_NAME = 'rollcalc-v14-' + new Date().getTime();
|
||||||
|
const STATIC_CACHE = 'rollcalc-static-v14';
|
||||||
|
const DATA_CACHE = 'rollcalc-data-v14';
|
||||||
|
|
||||||
|
// Assets to cache on install
|
||||||
|
const STATIC_ASSETS = [
|
||||||
|
'/',
|
||||||
|
'/index.html',
|
||||||
|
'/static/article-data.json',
|
||||||
|
'/static/config.json'
|
||||||
|
];
|
||||||
|
|
||||||
|
// ===================================================================
|
||||||
|
// INSTALL EVENT - Cache static assets
|
||||||
|
// ===================================================================
|
||||||
|
self.addEventListener('install', event => {
|
||||||
|
console.log('[ServiceWorker] Installing...');
|
||||||
|
|
||||||
|
event.waitUntil(
|
||||||
|
caches.open(STATIC_CACHE)
|
||||||
|
.then(cache => {
|
||||||
|
console.log('[ServiceWorker] Caching static assets');
|
||||||
|
return cache.addAll(STATIC_ASSETS).catch(err => {
|
||||||
|
console.warn('[ServiceWorker] Some assets failed to cache:', err);
|
||||||
|
// Don't fail installation if some assets can't be cached
|
||||||
|
return Promise.resolve();
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.then(() => self.skipWaiting())
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ===================================================================
|
||||||
|
// ACTIVATE EVENT - Clean up old caches
|
||||||
|
// ===================================================================
|
||||||
|
self.addEventListener('activate', event => {
|
||||||
|
console.log('[ServiceWorker] Activating...');
|
||||||
|
|
||||||
|
event.waitUntil(
|
||||||
|
caches.keys().then(cacheNames => {
|
||||||
|
return Promise.all(
|
||||||
|
cacheNames.map(cacheName => {
|
||||||
|
if (cacheName !== STATIC_CACHE &&
|
||||||
|
cacheName !== DATA_CACHE &&
|
||||||
|
cacheName !== CACHE_NAME) {
|
||||||
|
console.log('[ServiceWorker] Deleting old cache:', cacheName);
|
||||||
|
return caches.delete(cacheName);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}).then(() => self.clients.claim())
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ===================================================================
|
||||||
|
// FETCH EVENT - Intelligent caching strategy
|
||||||
|
// ===================================================================
|
||||||
|
self.addEventListener('fetch', event => {
|
||||||
|
const { request } = event;
|
||||||
|
const url = new URL(request.url);
|
||||||
|
|
||||||
|
// Skip cross-origin requests
|
||||||
|
if (url.origin !== location.origin) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------
|
||||||
|
// 1. JSON DATA (article-data.json, config.json)
|
||||||
|
// STALE_WHILE_REVALIDATE: Use cache first, update in background
|
||||||
|
// ---------------------------------------------------------------
|
||||||
|
if (url.pathname.includes('.json')) {
|
||||||
|
event.respondWith(
|
||||||
|
caches.open(DATA_CACHE).then(cache => {
|
||||||
|
return cache.match(request).then(response => {
|
||||||
|
const fetchPromise = fetch(request).then(networkResponse => {
|
||||||
|
// Update cache with fresh version
|
||||||
|
if (networkResponse && networkResponse.status === 200) {
|
||||||
|
cache.put(request, networkResponse.clone());
|
||||||
|
}
|
||||||
|
return networkResponse;
|
||||||
|
}).catch(() => {
|
||||||
|
// Network failed, return cached version
|
||||||
|
return response || cacheNotFound('JSON data not found');
|
||||||
|
});
|
||||||
|
|
||||||
|
// Return cached response immediately, update in background
|
||||||
|
return response || fetchPromise;
|
||||||
|
});
|
||||||
|
})
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------
|
||||||
|
// 2. HTML PAGES
|
||||||
|
// NETWORK_FIRST: Try network, fall back to cache
|
||||||
|
// ---------------------------------------------------------------
|
||||||
|
if (request.method === 'GET' &&
|
||||||
|
(url.pathname === '/' || url.pathname.endsWith('.html'))) {
|
||||||
|
event.respondWith(
|
||||||
|
fetch(request)
|
||||||
|
.then(response => {
|
||||||
|
if (response && response.status === 200) {
|
||||||
|
const cache_copy = response.clone();
|
||||||
|
caches.open(STATIC_CACHE).then(cache => {
|
||||||
|
cache.put(request, cache_copy);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return response;
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
return caches.match(request)
|
||||||
|
.then(response => response || cacheNotFound('Page not found'));
|
||||||
|
})
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------
|
||||||
|
// 3. STATIC ASSETS (CSS, JS, images)
|
||||||
|
// CACHE_FIRST: Use cache if available, fall back to network
|
||||||
|
// ---------------------------------------------------------------
|
||||||
|
if (request.method === 'GET') {
|
||||||
|
event.respondWith(
|
||||||
|
caches.open(STATIC_CACHE).then(cache => {
|
||||||
|
return cache.match(request).then(response => {
|
||||||
|
if (response) {
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
return fetch(request).then(networkResponse => {
|
||||||
|
// Only cache successful responses
|
||||||
|
if (networkResponse && networkResponse.status === 200) {
|
||||||
|
cache.put(request, networkResponse.clone());
|
||||||
|
}
|
||||||
|
return networkResponse;
|
||||||
|
}).catch(() => {
|
||||||
|
// Return offline placeholder
|
||||||
|
if (request.destination === 'image') {
|
||||||
|
return createPlaceholderImage();
|
||||||
|
}
|
||||||
|
return cacheNotFound('Asset not found');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
})
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------
|
||||||
|
// 4. POST/PUT/DELETE (API calls)
|
||||||
|
// NETWORK_ONLY: Do not cache, but handle errors gracefully
|
||||||
|
// ---------------------------------------------------------------
|
||||||
|
if (['POST', 'PUT', 'DELETE'].includes(request.method)) {
|
||||||
|
event.respondWith(
|
||||||
|
fetch(request)
|
||||||
|
.catch(() => {
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
error: 'You are offline. API calls are not available.',
|
||||||
|
status: 'offline'
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
status: 503,
|
||||||
|
statusText: 'Service Unavailable',
|
||||||
|
headers: new Headers({
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
})
|
||||||
|
}
|
||||||
|
);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// ===================================================================
|
||||||
|
// HELPER FUNCTIONS
|
||||||
|
// ===================================================================
|
||||||
|
|
||||||
|
function cacheNotFound(message) {
|
||||||
|
return new Response(
|
||||||
|
`<html><body style="font-family: sans-serif; padding: 20px; color: #666;">
|
||||||
|
<h2>Offline</h2>
|
||||||
|
<p>${message}</p>
|
||||||
|
<p style="font-size: 12px; color: #999;">Roll Calculator is offline or the resource is not cached.</p>
|
||||||
|
</body></html>`,
|
||||||
|
{
|
||||||
|
status: 404,
|
||||||
|
statusText: 'Not Found',
|
||||||
|
headers: new Headers({
|
||||||
|
'Content-Type': 'text/html'
|
||||||
|
})
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function createPlaceholderImage() {
|
||||||
|
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
|
||||||
|
<rect fill="#f0f0f0" width="100" height="100"/>
|
||||||
|
<text x="50" y="50" text-anchor="middle" dy=".3em" fill="#999" font-size="12">
|
||||||
|
Image offline
|
||||||
|
</text>
|
||||||
|
</svg>`;
|
||||||
|
|
||||||
|
return new Response(svg, {
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'image/svg+xml',
|
||||||
|
'Cache-Control': 'public, max-age=86400'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===================================================================
|
||||||
|
// LOG SERVICE WORKER STATUS
|
||||||
|
// ===================================================================
|
||||||
|
console.log('[ServiceWorker] Naue Roll Calculator Service Worker loaded');
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
|
<script src="/static/rollcalc-improvements.js"></script>
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="theme-color" content="#0066cc">
|
<meta name="theme-color" content="#0066cc">
|
||||||
<meta name="description" content="Roll Diameter Calculator - Internal Naue Tool">
|
<meta name="description" content="Roll Diameter Calculator - Internal Naue Tool">
|
||||||
|
|||||||
Reference in New Issue
Block a user