refactor: corrige duplicações e código morto

- Remove Toast Manager duplicado (core/toast-manager.js)
- Unifica loadPreferences/savePreferences de app.js para state.js
- Unifica adminConfig de app.js para state.js
- Remove código morto (if false block)
- Adiciona checkStorage para validar localStorage
This commit is contained in:
2026-04-03 21:35:36 +00:00
parent 084dc7a155
commit 85c053ff30
3 changed files with 59 additions and 442 deletions

View File

@@ -1,116 +1,19 @@
// ========================================
// SteelBase v6.5 - PROFESSIONAL EDITION
// SteelBase v7.5 - PROFESSIONAL EDITION
// Plataforma Técnica Completa com Base de Materiais
// ========================================
// In-memory data storage WITH localStorage for preferences
// Import state from modules (userPreferences only - appState is still global for legacy)
import { userPreferences, loadPreferences, savePreferences, adminConfig } from './js/core/state.js';
// Make available globally for legacy code
window.userPreferences = userPreferences;
window.loadPreferences = loadPreferences;
window.savePreferences = savePreferences;
window.adminConfig = adminConfig;
// In-memory data storage (legacy - still global for compatibility)
const appState = {
history: [],
favorites: [],
budgetItems: [],
currentSection: 'cev',
currentTheme: 'dark', // 'dark' or 'light'
expertMode: false,
currentSidebarTab: 0
};
// User preferences (saved to localStorage)
let userPreferences = {
theme: 'dark',
colorScheme: 'default', // default, blue, green, purple, orange
fontSize: 'medium', // small, medium, large, xlarge
fontFamily: 'default' // default, modern, classic, mono
};
// Load preferences from localStorage
function loadPreferences() {
try {
const saved = localStorage.getItem('acoCalcPreferences');
if (saved) {
userPreferences = { ...userPreferences, ...JSON.parse(saved) };
}
} catch (e) {
console.warn('Não foi possível carregar preferências:', e);
}
}
// Save preferences to localStorage
function savePreferences() {
try {
localStorage.setItem('acoCalcPreferences', JSON.stringify(userPreferences));
} catch (e) {
console.warn('Não foi possível salvar preferências:', e);
}
}
// Admin configuration (in-memory)
const adminConfig = {
appName: 'SteelBase',
appSubtitle: 'Plataforma Técnica com Base de Dados de Materiais Brasileiros',
footerText: '© 2025 SteelBase v6.5 PROFESSIONAL EDITION - Plataforma Técnica com Base de Dados de Materiais Brasileiros',
themeDefault: 'escuro',
modeDefault: 'simples',
toolsVisibility: {
// Aços Estruturais
'cev': true,
'seletor': true,
'equivalencias': false,
'comparativo': false,
'assistente-inteligente': true,
// Consumíveis de Soldagem
'eletrodos': false,
'arames': false,
'fluxos': false,
'gases': false,
// Fixadores
'parafusos-catalogo': false,
'porcas': false,
'arruelas': false,
'chumbadores': false,
// Tintas e Revestimentos
'tintas-catalogo': false,
'sistemas-pintura': false,
'abrasivos': false,
'granalha': false,
// Elementos Complementares
'telhas': false,
'paineis': false,
'steel-deck': false,
'perfis-formados': false,
// Catálogo de Perfis
'cantoneiras': true,
'barras-redondas': true,
'tubos-circulares': true,
'perfis-i': true,
'perfis-w': true,
'tubos-rhs': true,
'chapas': true,
'perfis-hp': true,
'barras-roscadas': true,
'barras-chatas': true,
// Conexões
'parafusos': true,
'layout': true,
'parafuso-vs-solda': false,
// Soldagem
'preaquecimento': true,
'dureza': true,
'charpy': true,
'certificado': false,
'ultrassom': false,
// Pintura
'area-pintura': true,
'consumo-tinta': true,
'galvanizacao': false,
'custo-pintura': true,
'secagem': false,
'inspecao-pintura': false,
// Orçamento
'orcamento': true,
'peso-rigging': false,
'referencia': false
}
};
// ========================================
// CSV MAPPING AND LOADING FUNCTIONS v6.6
@@ -431,108 +334,6 @@ function showSection(sectionId) {
}, 500);
}
// CÓDIGO ANTIGO REMOVIDO - mantido apenas para referência
if (false && sectionId === 'cantoneiras') {
console.log('🔧 Seção cantoneiras detectada - iniciando carregamento forçado');
// Tentar múltiplas vezes até conseguir
let tentativas = 0;
const maxTentativas = 10;
const tentarCarregar = async () => {
tentativas++;
console.log(`🔄 Tentativa ${tentativas}/${maxTentativas} de carregar cantoneiras`);
const tbody = document.getElementById('cantoneiras-tbody');
if (tbody) {
console.log('✅ Elemento tbody encontrado! Carregando dados...');
try {
// Carregar CSV diretamente
const response = await fetch('BD/perfis/cantoneiras_brasil_completo.csv');
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const csvText = await response.text();
const linhas = csvText.trim().split('\n');
console.log(`📊 CSV carregado: ${linhas.length} linhas`);
const dados = [];
for (let i = 1; i < linhas.length; i++) {
const linha = linhas[i].trim();
if (!linha) continue;
const colunas = linha.split(',');
if (colunas.length >= 9) {
dados.push({
id: colunas[0].trim(),
nome: colunas[1].trim(),
lado_mm: parseFloat(colunas[2]),
espessura_mm: parseFloat(colunas[3]),
peso_kg_m: parseFloat(colunas[4]),
area_cm2: parseFloat(colunas[5]),
momento_inercia_cm4: parseFloat(colunas[6]),
raio_giracao_cm: parseFloat(colunas[7]),
tipo: colunas[8].trim()
});
}
}
console.log(`✅ Processados: ${dados.length} cantoneiras`);
// Exibir na tabela
tbody.innerHTML = dados.map(item => `
<tr>
<td><strong>${item.nome}</strong></td>
<td>${item.lado_mm}</td>
<td>${item.espessura_mm}</td>
<td>${item.peso_kg_m.toFixed(2)}</td>
<td>${item.area_cm2.toFixed(2)}</td>
<td>${item.momento_inercia_cm4.toFixed(2)}</td>
<td>${item.raio_giracao_cm.toFixed(2)}</td>
<td><span class="badge badge-info">${item.tipo}</span></td>
<td><button class="btn btn-sm btn-primary">👁️ Ver</button></td>
</tr>
`).join('');
console.log('🎉 Tabela preenchida com sucesso!');
// Atualizar contador
const totalEl = document.getElementById('cant-total');
if (totalEl) {
totalEl.textContent = dados.length;
}
} catch (error) {
console.error('❌ Erro ao carregar CSV:', error);
tbody.innerHTML = `
<tr>
<td colspan="9" style="text-align: center; padding: 20px; color: #ef4444;">
❌ Erro ao carregar dados: ${error.message}
<br><br>
<button class="btn btn-primary" onclick="location.reload()">🔄 Recarregar</button>
</td>
</tr>
`;
}
} else {
console.warn(`⚠️ Elemento tbody não encontrado (tentativa ${tentativas})`);
if (tentativas < maxTentativas) {
setTimeout(tentarCarregar, 300);
} else {
console.error('❌ Falha após todas as tentativas');
}
}
};
// Iniciar tentativas após um pequeno delay
setTimeout(tentarCarregar, 200);
}
// Add help button after content loads
setTimeout(() => {
if (sectionId === 'preaquecimento') {