Added automatic Rollwidth and Area Weigth selection by Article

This commit is contained in:
2026-07-01 07:58:49 +00:00
parent 71d49c6f28
commit 637d000bc2
11 changed files with 6271 additions and 808 deletions
+4941 -754
View File
File diff suppressed because it is too large Load Diff
+284
View File
@@ -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();
});
+197 -54
View File
@@ -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 ASSETS_TO_CACHE = [
'./',
'./roll_calculator_v9.html',
'./article-data.json',
'./config.json',
'./service-worker.js'
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
// ===================================================================
// INSTALL EVENT - Cache static assets
// ===================================================================
self.addEventListener('install', event => {
console.log('[ServiceWorker] Installing...');
event.waitUntil(
caches.open(CACHE_NAME).then(cache => {
console.log('[ServiceWorker] Caching assets:', ASSETS_TO_CACHE);
return cache.addAll(ASSETS_TO_CACHE);
}).catch(err => {
console.error('[ServiceWorker] Cache failed:', err);
})
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())
);
self.skipWaiting();
});
// Activate Event: Cleanup alte Caches
// ===================================================================
// 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 !== CACHE_NAME) {
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())
);
self.clients.claim();
});
// Fetch Event: Cache First Strategy
// ===================================================================
// FETCH EVENT - Intelligent caching strategy
// ===================================================================
self.addEventListener('fetch', event => {
const url = event.request.url;
if (event.request.method !== 'GET') return;
event.respondWith(
caches.match(event.request)
.then(response => {
if (response) {
console.log('[ServiceWorker] Cache HIT:', url);
return response;
}
console.log('[ServiceWorker] Cache MISS, fetching:', url);
return fetch(event.request)
.then(response => {
if (!response || response.status !== 200 || response.type === 'error') {
return response;
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());
}
const responseClone = response.clone();
caches.open(CACHE_NAME).then(cache => {
cache.put(event.request, responseClone);
});
return response;
})
.catch(() => {
return caches.match(event.request).then(response => {
if (response) return response;
return new Response('Offline - resource not available', {
status: 503,
statusText: 'Service Unavailable'
});
});
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;
}
});
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');
+226
View File
@@ -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');