← back to depelo__bobine

Function bodies 262 total

All specs Real LLM only Function bodies
encrypt function · javascript · L20-L28 (9 LOC)
config/crypto.js
function encrypt(plaintext) {
    const key = getKey();
    const iv = crypto.randomBytes(IV_LENGTH);
    const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
    const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
    const authTag = cipher.getAuthTag();
    // Layout: [IV 16B][AuthTag 16B][Ciphertext NB]
    return Buffer.concat([iv, authTag, encrypted]);
}
decrypt function · javascript · L31-L40 (10 LOC)
config/crypto.js
function decrypt(buffer) {
    const key = getKey();
    if (!Buffer.isBuffer(buffer)) buffer = Buffer.from(buffer);
    const iv = buffer.subarray(0, IV_LENGTH);
    const authTag = buffer.subarray(IV_LENGTH, IV_LENGTH + AUTH_TAG_LENGTH);
    const ciphertext = buffer.subarray(IV_LENGTH + AUTH_TAG_LENGTH);
    const decipher = crypto.createDecipheriv(ALGORITHM, key, iv);
    decipher.setAuthTag(authTag);
    return decipher.update(ciphertext, null, 'utf8') + decipher.final('utf8');
}
buildPoolConfig function · javascript · L38-L55 (18 LOC)
config/db-gb2.js
function buildPoolConfig(server, database, user, password, maxConns) {
    return {
        server,
        database,
        user,
        password,
        options: {
            encrypt: false,
            trustServerCertificate: true,
            enableArithAbort: true
        },
        pool: {
            max: maxConns || POOL_MAX_TEST,
            min: 0,
            idleTimeoutMillis: POOL_IDLE_MS
        }
    };
}
getPoolProd function · javascript · L63-L72 (10 LOC)
config/db-gb2.js
async function getPoolProd() {
    if (!poolProd) {
        poolProd = await new sql.ConnectionPool(
            buildPoolConfig(PRODUCTION_PROFILE.server, PRODUCTION_PROFILE.database_mrp,
                PRODUCTION_PROFILE.user, PRODUCTION_PROFILE.password, POOL_MAX_PROD)
        ).connect();
        console.log('[DB] Pool PRODUZIONE connesso — ' + PRODUCTION_PROFILE.server + '/' + PRODUCTION_PROFILE.database_mrp + ' (max ' + POOL_MAX_PROD + ')');
    }
    return poolProd;
}
getUserState function · javascript · L92-L105 (14 LOC)
config/db-gb2.js
function getUserState(userId) {
    if (!userStates.has(userId)) {
        userStates.set(userId, {
            pool: null,
            profile: null,
            hasRiep: false,
            lastActive: Date.now(),
            switching: false
        });
    }
    const state = userStates.get(userId);
    state.lastActive = Date.now();
    return state;
}
getPoolMRP function · javascript · L118-L123 (6 LOC)
config/db-gb2.js
async function getPoolMRP(userId) {
    const state = getUserState(userId || 0);
    if (state.switching) throw new Error('Switch profilo in corso, riprova tra un momento');
    if (state.pool) return state.pool;
    return getPoolProd();
}
getActiveProfile function · javascript · L129-L134 (6 LOC)
config/db-gb2.js
function getActiveProfile(userId) {
    const state = getUserState(userId || 0);
    if (state.profile) return state.profile;
    const { password, ...safe } = PRODUCTION_PROFILE;
    return safe;
}
About: code-quality intelligence by Repobility · https://repobility.com
isProduction function · javascript · L136-L139 (4 LOC)
config/db-gb2.js
function isProduction(userId) {
    const state = getUserState(userId || 0);
    return !state.profile;
}
setTestHasRiep function · javascript · L141-L144 (4 LOC)
config/db-gb2.js
function setTestHasRiep(userId, val) {
    const state = getUserState(userId || 0);
    state.hasRiep = !!val;
}
getTestHasRiep function · javascript · L146-L149 (4 LOC)
config/db-gb2.js
function getTestHasRiep(userId) {
    const state = getUserState(userId || 0);
    return state.hasRiep;
}
switchToTest function · javascript · L155-L182 (28 LOC)
config/db-gb2.js
async function switchToTest(userId, testProfile) {
    const state = getUserState(userId || 0);
    if (state.switching) throw new Error('Switch gia in corso');
    state.switching = true;
    try {
        // Tenta connessione a UJET11 sul server di prova
        const newPool = await new sql.ConnectionPool(
            buildPoolConfig(testProfile.server, testProfile.database_ujet11 || 'UJET11',
                testProfile.user, testProfile.password, POOL_MAX_TEST)
        ).connect();

        // Connessione riuscita — chiudi pool precedente di questo utente
        if (state.pool) { try { await state.pool.close(); } catch(e) {} }
        state.pool = newPool;
        state.hasRiep = false;

        // Salva profilo attivo senza password
        const { password, DbPassword, ...safe } = testProfile;
        state.profile = { ...safe, ambiente: 'prova' };

        console.log('[DB] User ' + userId + ' switch a PROVA:', testProfile.label, '—', testProfile.server);
        return state.
switchToProduction function · javascript · L188-L206 (19 LOC)
config/db-gb2.js
async function switchToProduction(userId) {
    const state = getUserState(userId || 0);
    if (state.switching) throw new Error('Switch gia in corso');
    state.switching = true;
    try {
        if (state.pool) { try { await state.pool.close(); } catch(e) {} }
        state.pool = null;
        state.profile = null;
        state.hasRiep = false;

        await getPoolProd();

        console.log('[DB] User ' + userId + ' switch a PRODUZIONE');
        const { password, ...safe } = PRODUCTION_PROFILE;
        return safe;
    } finally {
        state.switching = false;
    }
}
closeAll function · javascript · L229-L234 (6 LOC)
config/db-gb2.js
async function closeAll() {
    if (poolProd) { try { await poolProd.close(); } catch(e) {} }
    for (const [, state] of userStates.entries()) {
        if (state.pool) { try { await state.pool.close(); } catch(e) {} }
    }
}
getSmtpConfigForUser function · javascript · L16-L39 (24 LOC)
config/smtp-gb2.js
async function getSmtpConfigForUser(userId) {
    const pool = await getPoolProd();
    const result = await pool.request()
        .input('userId', sql.Int, userId)
        .query(`SELECT SmtpHost, SmtpPort, SmtpSecure, SmtpUser, SmtpPassword,
                       SmtpFromAddress, SmtpFromName
                FROM [GB2].[dbo].[UserPreferences]
                WHERE IDUser = @userId`);

    if (!result.recordset.length) return null;

    const row = result.recordset[0];
    if (!row.SmtpHost) return null;

    return {
        host: row.SmtpHost,
        port: row.SmtpPort || 587,
        secure: !!row.SmtpSecure,
        user: row.SmtpUser || '',
        password: row.SmtpPassword ? decrypt(row.SmtpPassword) : '',
        from_address: row.SmtpFromAddress || '',
        from_name: row.SmtpFromName || 'U.Jet s.r.l.'
    };
}
createTransporterFromConfig function · javascript · L45-L61 (17 LOC)
config/smtp-gb2.js
function createTransporterFromConfig(config) {
    if (!config || !config.host) {
        throw new Error('Host SMTP non configurato');
    }

    const opts = {
        host: config.host,
        port: config.port || 587,
        secure: config.secure || false
    };

    if (config.user && config.password) {
        opts.auth = { user: config.user, pass: config.password };
    }

    return nodemailer.createTransport(opts);
}
All rows scored by the Repobility analyzer (https://repobility.com)
init function · javascript · L28-L56 (29 LOC)
gb2/js/gb2-app.js
    function init() {
        // Init tema colori (prima di tutto per prevenire FOUC)
        MrpTheme.init();

        // Init configurazione DB (badge + modale profili)
        MrpDbConfig.init();

        // Navigazione tra view via nav buttons
        document.querySelectorAll('.mrp-nav-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                switchView(btn.dataset.view);
            });
        });

        // Health check iniziale
        fetch(`${API_BASE}/health`, { credentials: 'include' })
            .then(r => r.json())
            .then(data => {
                if (data.status === 'ok') {
                    console.log('[MRP] Connessione DB OK — UJET11:', data.ujet11, '| MRP:', data.mrp);
                } else {
                    console.error('[MRP] DB non raggiungibile:', data);
                }
            })
            .catch(err => console.error('[MRP] Health check fallito:', err));

        // Init moduli
        MrpParametri.in
switchView function · javascript · L58-L67 (10 LOC)
gb2/js/gb2-app.js
    function switchView(viewName) {
        document.querySelectorAll('.mrp-view').forEach(v => v.classList.remove('active'));
        document.querySelectorAll('.mrp-nav-btn').forEach(b => b.classList.remove('active'));

        const targetView = document.getElementById('view-' + viewName);
        const targetBtn = document.querySelector(`.mrp-nav-btn[data-view="${viewName}"]`);

        if (targetView) targetView.classList.add('active');
        if (targetBtn) targetBtn.classList.add('active');
    }
confermaOrdine function · javascript · L69-L71 (3 LOC)
gb2/js/gb2-app.js
    function confermaOrdine(key, datiOrdine) {
        state.ordiniConfermati.set(key, datiOrdine);
    }
rimuoviOrdine function · javascript · L73-L75 (3 LOC)
gb2/js/gb2-app.js
    function rimuoviOrdine(key) {
        state.ordiniConfermati.delete(key);
    }
getOrdiniConfermati function · javascript · L77-L79 (3 LOC)
gb2/js/gb2-app.js
    function getOrdiniConfermati() {
        return state.ordiniConfermati;
    }
isArticoloConfermato function · javascript · L81-L83 (3 LOC)
gb2/js/gb2-app.js
    function isArticoloConfermato(key) {
        return state.ordiniConfermati.has(key);
    }
getKeyOrdine function · javascript · L85-L87 (3 LOC)
gb2/js/gb2-app.js
    function getKeyOrdine(fornitore_codice, ol_codart, ol_fase, ol_magaz) {
        return `${fornitore_codice}|${ol_codart}|${ol_fase}|${ol_magaz}`;
    }
openMenuDrawer function · javascript · L9-L14 (6 LOC)
gb2/js/gb2-bootstrap.js
    function openMenuDrawer() {
        const drawer = document.getElementById('menuDrawer');
        const backdrop = document.getElementById('menuDrawerBackdrop');
        if (drawer) { drawer.classList.add('is-open'); drawer.setAttribute('aria-hidden', 'false'); }
        if (backdrop) { backdrop.classList.add('is-open'); backdrop.setAttribute('aria-hidden', 'false'); }
    }
Repobility · code-quality intelligence platform · https://repobility.com
closeMenuDrawer function · javascript · L16-L21 (6 LOC)
gb2/js/gb2-bootstrap.js
    function closeMenuDrawer() {
        const drawer = document.getElementById('menuDrawer');
        const backdrop = document.getElementById('menuDrawerBackdrop');
        if (drawer) { drawer.classList.remove('is-open'); drawer.setAttribute('aria-hidden', 'true'); }
        if (backdrop) { backdrop.classList.remove('is-open'); backdrop.setAttribute('aria-hidden', 'true'); }
    }
buildDynamicMenu function · javascript · L23-L51 (29 LOC)
gb2/js/gb2-bootstrap.js
    function buildDynamicMenu() {
        const apps = window.SecurityData?.user?.authorizedApps;
        if (!Array.isArray(apps)) return;

        const container = document.getElementById('dynamicMenuApps');
        if (!container) return;
        container.innerHTML = '';

        const urlMap = { 1: '/bobine.html', 3: '/ET.html' };

        apps.forEach((app) => {
            const aid = Number(app.id);
            if (aid === 4 || aid === 2) return;
            const url = urlMap[aid];
            if (!url) return;

            const btn = document.createElement('button');
            btn.type = 'button';
            btn.className = 'menu-drawer-btn';
            btn.textContent = app.name || 'App';
            btn.addEventListener('click', () => { closeMenuDrawer(); window.location.href = url; });
            container.appendChild(btn);
        });

        const captainBtn = document.getElementById('menuOpenCaptain');
        if (captainBtn && window.SecurityData?.user?.isSuper
init function · javascript · L9-L12 (4 LOC)
gb2/js/gb2-dbconfig.js
    async function init() {
        await refreshBadge();
        bindEvents();
    }
refreshBadge function · javascript · L18-L39 (22 LOC)
gb2/js/gb2-dbconfig.js
    async function refreshBadge() {
        try {
            const res = await fetch(API + '/active-profile');
            if (!res.ok) throw new Error('HTTP ' + res.status);
            const profile = await res.json();

            document.getElementById('dbBadgeDot').style.background = profile.color || '#16a34a';
            document.getElementById('dbBadgeLabel').textContent = profile.label || profile.id;
            document.getElementById('dbBadgeServer').textContent = profile.server + ' / ' + (profile.database_mrp || 'MRP');

            const header = document.querySelector('.mrp-header');
            header.style.borderBottomColor = profile.color || 'var(--border)';
            header.style.borderBottomWidth = '3px';

            aggiornaAmbienteBanner(profile);
        } catch (err) {
            console.error('[DbConfig] Errore refresh badge:', err);
            document.getElementById('dbBadgeDot').style.background = '#e11d48';
            document.getElementById('dbBadge
aggiornaAmbienteBanner function · javascript · L41-L79 (39 LOC)
gb2/js/gb2-dbconfig.js
    function aggiornaAmbienteBanner(profile) {
        const banner = document.getElementById('ambienteBanner');
        if (!banner) return;

        const ambiente = profile.ambiente || 'produzione';

        window.MrpAmbiente = {
            ambiente: ambiente,
            email_prova: profile.email_prova || ''
        };

        if (ambiente === 'prova') {
            const email = profile.email_prova || '';
            banner.style.display = 'block';
            banner.style.background = 'linear-gradient(135deg, #f59e0b, #d97706)';
            banner.style.color = 'white';
            banner.style.textAlign = 'center';
            banner.style.padding = '8px 16px';
            banner.style.fontWeight = '700';
            banner.style.fontSize = '0.85rem';
            banner.style.letterSpacing = '0.5px';
            banner.style.zIndex = '100';
            if (email) {
                banner.innerHTML = '\uD83D\uDD27 AMBIENTE DI PROVA \u2014 Le email vengono inviate a <strong>' 
openModal function · javascript · L85-L90 (6 LOC)
gb2/js/gb2-dbconfig.js
    function openModal() {
        document.getElementById('modalDbOverlay').classList.add('open');
        loadProfilesList();
        resetForm();
        loadSmtpForm();
    }
closeModal function · javascript · L92-L94 (3 LOC)
gb2/js/gb2-dbconfig.js
    function closeModal() {
        document.getElementById('modalDbOverlay').classList.remove('open');
    }
loadProfilesList function · javascript · L99-L141 (43 LOC)
gb2/js/gb2-dbconfig.js
    async function loadProfilesList() {
        try {
            const [profilesRes, activeRes] = await Promise.all([
                fetch(API + '/profiles'),
                fetch(API + '/active-profile')
            ]);
            const profiles = await profilesRes.json();
            const active = await activeRes.json();
            _cachedProfiles = profiles;

            const container = document.getElementById('dbProfilesList');

            container.innerHTML = profiles.map(p => {
                const isProd = p.id === 'produzione';
                const isActive = p.id === active.id;
                return `
                <div style="display:flex; align-items:center; gap:12px; padding:10px 14px;
                    border:1px solid ${isActive ? (p.color || 'var(--primary)') : 'var(--border)'};
                    border-left:4px solid ${p.color || '#999'};
                    border-radius:var(--radius-sm); margin-bottom:8px;
                    background:${isActive ?
Generated by Repobility's multi-pass static-analysis pipeline (https://repobility.com)
switchTo function · javascript · L143-L196 (54 LOC)
gb2/js/gb2-dbconfig.js
    async function switchTo(profileId) {
        const isProd = profileId === 'produzione';
        const profile = _cachedProfiles.find(p => p.id === profileId);

        if (isProd) {
            if (!confirm('\u26A0\uFE0F Stai per passare all\'ambiente di PRODUZIONE.\nGli ordini emessi saranno REALI e le email arriveranno ai FORNITORI.\n\nContinuare?')) return;
            if (!confirm('\u26A1 CONFERMA DEFINITIVA:\nSei SICURO di voler operare in PRODUZIONE?')) return;
        } else {
            const label = profile ? profile.label : profileId;
            if (!confirm('Switchare al profilo "' + label + '"?\nI dati attualmente visualizzati verranno cancellati.')) return;
        }

        try {
            let res;
            if (isProd) {
                res = await fetch(API + '/switch-production', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: '{}'
                });
            } else {
  
editProfile function · javascript · L198-L212 (15 LOC)
gb2/js/gb2-dbconfig.js
    async function editProfile(profileId) {
        const p = _cachedProfiles.find(x => x.id === profileId);
        if (!p || p.id === 'produzione') return;

        document.getElementById('dbFormEditId').value = p._dbId || '';
        document.getElementById('dbFormLabel').value = p.label;
        document.getElementById('dbFormServer').value = p.server;
        document.getElementById('dbFormUjet11').value = p.database_ujet11 || 'UJET11';
        document.getElementById('dbFormUser').value = p.user || '';
        document.getElementById('dbFormPassword').value = '';
        document.getElementById('dbFormColor').value = p.color || '#16a34a';
        document.getElementById('dbFormEmailProva').value = p.email_prova || '';
        document.getElementById('dbFormTitle').textContent = 'Modifica profilo: ' + p.label;
        document.getElementById('btnDbCancelEdit').style.display = '';
    }
resetForm function · javascript · L214-L226 (13 LOC)
gb2/js/gb2-dbconfig.js
    function resetForm() {
        document.getElementById('dbFormEditId').value = '';
        document.getElementById('dbFormLabel').value = '';
        document.getElementById('dbFormServer').value = '';
        document.getElementById('dbFormUjet11').value = 'UJET11';
        document.getElementById('dbFormUser').value = '';
        document.getElementById('dbFormPassword').value = '';
        document.getElementById('dbFormColor').value = '#16a34a';
        document.getElementById('dbFormEmailProva').value = '';
        document.getElementById('dbFormTitle').textContent = 'Nuovo profilo di prova';
        document.getElementById('btnDbCancelEdit').style.display = 'none';
        document.getElementById('dbFormStatus').textContent = '';
    }
saveProfile function · javascript · L228-L276 (49 LOC)
gb2/js/gb2-dbconfig.js
    async function saveProfile() {
        const editId = document.getElementById('dbFormEditId').value;
        const profileData = {
            label: document.getElementById('dbFormLabel').value.trim().toUpperCase(),
            server: document.getElementById('dbFormServer').value.trim(),
            database_ujet11: document.getElementById('dbFormUjet11').value.trim() || 'UJET11',
            user: document.getElementById('dbFormUser').value.trim(),
            password: document.getElementById('dbFormPassword').value,
            color: document.getElementById('dbFormColor').value,
            email_prova: document.getElementById('dbFormEmailProva').value.trim()
        };

        if (!profileData.label || !profileData.server || !profileData.user) {
            showFormStatus('Compila almeno Etichetta, Server e Utente DB', 'var(--warning)');
            return;
        }

        try {
            let res;
            if (editId) {
                if (!profileData.password) del
removeProfile function · javascript · L278-L291 (14 LOC)
gb2/js/gb2-dbconfig.js
    async function removeProfile(dbId) {
        if (!confirm('Eliminare questo profilo di prova?')) return;
        try {
            const res = await fetch(API + '/profiles/' + dbId, { method: 'DELETE' });
            const data = await res.json();
            if (data.success) {
                await loadProfilesList();
            } else {
                alert('Errore: ' + (data.error || 'sconosciuto'));
            }
        } catch (err) {
            alert('Errore: ' + err.message);
        }
    }
testConnection function · javascript · L293-L318 (26 LOC)
gb2/js/gb2-dbconfig.js
    async function testConnection() {
        showFormStatus('Test connessione in corso...', 'var(--warning)');
        try {
            const payload = {
                server: document.getElementById('dbFormServer').value.trim(),
                database_mrp: 'MRP',
                user: document.getElementById('dbFormUser').value.trim(),
                password: document.getElementById('dbFormPassword').value
            };

            if (!payload.server || !payload.user || !payload.password) {
                showFormStatus('Server, utente e password richiesti per il test', 'var(--warning)');
                return;
            }

            const res = await fetch(API + '/test-connection', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });
            const data = await res.json();
            showFormStatus(data.message, data.success ? 'var(--success)' : 'var(--dang
showWarningModal function · javascript · L320-L331 (12 LOC)
gb2/js/gb2-dbconfig.js
    function showWarningModal(warnings) {
        const overlay = document.getElementById('modalGenericOverlay');
        const titolo = document.getElementById('modalGenericTitolo');
        const icona = document.getElementById('modalGenericIcona');
        const corpo = document.getElementById('modalGenericCorpo');
        if (!overlay || !corpo) return;

        titolo.textContent = 'Avviso ambiente di prova';
        icona.textContent = '\u26A0\uFE0F';
        corpo.innerHTML = warnings.map(w => '<p style="margin:8px 0; font-size:0.9rem;">' + esc(w) + '</p>').join('');
        overlay.classList.add('open');
    }
showFormStatus function · javascript · L333-L337 (5 LOC)
gb2/js/gb2-dbconfig.js
    function showFormStatus(msg, color) {
        const el = document.getElementById('dbFormStatus');
        el.innerHTML = msg;
        el.style.color = color || 'var(--text)';
    }
About: code-quality intelligence by Repobility · https://repobility.com
esc function · javascript · L339-L343 (5 LOC)
gb2/js/gb2-dbconfig.js
    function esc(s) {
        const d = document.createElement('div');
        d.textContent = s || '';
        return d.innerHTML;
    }
loadSmtpForm function · javascript · L350-L367 (18 LOC)
gb2/js/gb2-dbconfig.js
    async function loadSmtpForm() {
        try {
            const res = await fetch('/api/mrp/smtp/config');
            if (!res.ok) throw new Error('HTTP ' + res.status);
            const data = await res.json();
            const c = data.config || {};

            document.getElementById('smtpFormHost').value = c.host || '';
            document.getElementById('smtpFormPort').value = c.port || 587;
            document.getElementById('smtpFormSecure').checked = c.secure === true;
            document.getElementById('smtpFormUser').value = c.user || '';
            document.getElementById('smtpFormPassword').value = '';
            document.getElementById('smtpFormFromAddress').value = c.from_address || '';
            document.getElementById('smtpFormFromName').value = c.from_name || 'U.Jet s.r.l.';
        } catch (err) {
            console.error('[SMTP] Errore caricamento:', err);
        }
    }
saveSmtp function · javascript · L369-L408 (40 LOC)
gb2/js/gb2-dbconfig.js
    async function saveSmtp() {
        const statusEl = document.getElementById('smtpFormStatus');
        try {
            const smtpData = {
                host: document.getElementById('smtpFormHost').value.trim(),
                port: parseInt(document.getElementById('smtpFormPort').value, 10) || 587,
                secure: document.getElementById('smtpFormSecure').checked,
                user: document.getElementById('smtpFormUser').value.trim(),
                from_address: document.getElementById('smtpFormFromAddress').value.trim(),
                from_name: document.getElementById('smtpFormFromName').value.trim() || 'U.Jet s.r.l.'
            };

            const pwd = document.getElementById('smtpFormPassword').value;
            if (pwd) smtpData.password = pwd;

            if (!smtpData.host || !smtpData.from_address) {
                statusEl.textContent = 'Host SMTP e email mittente sono obbligatori';
                statusEl.style.color = 'var(--warning)';
    
testSmtp function · javascript · L410-L428 (19 LOC)
gb2/js/gb2-dbconfig.js
    async function testSmtp() {
        const statusEl = document.getElementById('smtpFormStatus');
        statusEl.textContent = 'Test connessione SMTP in corso...';
        statusEl.style.color = 'var(--warning)';
        try {
            const res = await fetch('/api/mrp/smtp/test', { method: 'POST' });
            const data = await res.json();
            if (data.success) {
                statusEl.textContent = '\u2713 ' + data.message;
                statusEl.style.color = 'var(--success)';
            } else {
                statusEl.textContent = '\u2717 ' + (data.error || 'Errore');
                statusEl.style.color = 'var(--danger)';
            }
        } catch (err) {
            statusEl.textContent = '\u2717 ' + err.message;
            statusEl.style.color = 'var(--danger)';
        }
    }
bindEvents function · javascript · L430-L443 (14 LOC)
gb2/js/gb2-dbconfig.js
    function bindEvents() {
        document.getElementById('btnDbProfile').addEventListener('click', openModal);
        document.getElementById('modalDbClose').addEventListener('click', closeModal);
        document.getElementById('modalDbOverlay').addEventListener('click', e => {
            if (e.target === e.currentTarget) closeModal();
        });
        document.getElementById('btnDbSave').addEventListener('click', saveProfile);
        document.getElementById('btnDbTestConn').addEventListener('click', testConnection);
        document.getElementById('btnDbCancelEdit').addEventListener('click', resetForm);
        const btnSmtpSave = document.getElementById('btnSmtpSave');
        if (btnSmtpSave) btnSmtpSave.addEventListener('click', saveSmtp);
        const btnSmtpTest = document.getElementById('btnSmtpTest');
        if (btnSmtpTest) btnSmtpTest.addEventListener('click', testSmtp);
    }
init function · javascript · L14-L27 (14 LOC)
gb2/js/gb2-parametri.js
    function init() {
        setupCombo('paramCodart', 'paramCodartDropdown', 'codart');
        setupCombo('paramCodalt', 'paramCodaltDropdown', 'codalt');
        setupCombo('paramDescr', 'paramDescrDropdown', 'descr');

        document.getElementById('btnEsegui').addEventListener('click', esegui);

        // Chiudi dropdown quando si clicca fuori
        document.addEventListener('click', (e) => {
            if (!e.target.closest('.mrp-field-input')) {
                document.querySelectorAll('.mrp-dropdown').forEach(d => d.classList.remove('open'));
            }
        });
    }
setupCombo function · javascript · L29-L48 (20 LOC)
gb2/js/gb2-parametri.js
    function setupCombo(inputId, dropdownId, field) {
        const input = document.getElementById(inputId);
        const dropdown = document.getElementById(dropdownId);

        input.addEventListener('input', () => {
            clearTimeout(debounceTimer);
            debounceTimer = setTimeout(() => {
                const q = input.value.trim();
                if (q.length < 2) { dropdown.classList.remove('open'); return; }
                searchArticoli(q, field, dropdown);
            }, 250);
        });

        input.addEventListener('focus', () => {
            const q = input.value.trim();
            if (q.length >= 2) {
                searchArticoli(q, field, dropdown);
            }
        });
    }
searchArticoli function · javascript · L50-L78 (29 LOC)
gb2/js/gb2-parametri.js
    async function searchArticoli(q, field, dropdown) {
        try {
            const res = await fetch(`${MrpApp.API_BASE}/articoli/search?q=${encodeURIComponent(q)}&field=${field}`, { credentials: 'include' });
            const data = await res.json();

            dropdown.innerHTML = '';
            if (data.length === 0) {
                dropdown.innerHTML = '<div class="mrp-dropdown-item" style="color:var(--text-muted)">Nessun risultato</div>';
                dropdown.classList.add('open');
                return;
            }

            data.forEach(art => {
                const item = document.createElement('div');
                item.className = 'mrp-dropdown-item';
                item.innerHTML = `
                    <span class="dd-code">${art.ar_codart}</span>
                    <span class="dd-descr">${art.ar_descr || ''}</span>
                    <span class="dd-alt">${art.ar_codalt || ''}</span>
                `;
                item.addEventListener('clic
All rows scored by the Repobility analyzer (https://repobility.com)
selezionaArticolo function · javascript · L80-L98 (19 LOC)
gb2/js/gb2-parametri.js
    async function selezionaArticolo(art, dropdown) {
        // Popola tutte e 3 le combo
        document.getElementById('paramCodart').value = art.ar_codart;
        document.getElementById('paramCodalt').value = art.ar_codalt || '';
        document.getElementById('paramDescr').value = art.ar_descr || '';

        // Chiudi tutti i dropdown
        document.querySelectorAll('.mrp-dropdown').forEach(d => d.classList.remove('open'));

        // Salva nello stato
        MrpApp.state.articoloSelezionato = art;
        MrpApp.state.parametri.codart = art.ar_codart;

        // Carica le fasi
        await caricaFasi(art.ar_codart);

        // Status
        setStatus(`Articolo selezionato: ${art.ar_codart} — ${art.ar_descr}`);
    }
caricaFasi function · javascript · L100-L117 (18 LOC)
gb2/js/gb2-parametri.js
    async function caricaFasi(codart) {
        const select = document.getElementById('paramFase');
        select.innerHTML = '<option value="">Tutte</option>';

        try {
            const res = await fetch(`${MrpApp.API_BASE}/articoli/${encodeURIComponent(codart)}/fasi`, { credentials: 'include' });
            const fasi = await res.json();

            fasi.forEach(f => {
                const opt = document.createElement('option');
                opt.value = f.af_fase;
                opt.textContent = `${f.af_fase} — ${f.af_descr || ''}`;
                select.appendChild(opt);
            });
        } catch (err) {
            console.error('[Parametri] Errore caricamento fasi:', err);
        }
    }
esegui function · javascript · L119-L157 (39 LOC)
gb2/js/gb2-parametri.js
    async function esegui() {
        const codart = MrpApp.state.parametri.codart;
        if (!codart) {
            setStatus('Seleziona prima un articolo', true);
            return;
        }

        const magaz = document.getElementById('paramMagaz').value.trim();
        const fase = document.getElementById('paramFase').value;
        const modo = document.querySelector('input[name="paramModo"]:checked')?.value || '2';
        const sintetico = document.getElementById('paramSintetico').checked ? '1' : '0';

        // Aggiorna stato
        MrpApp.state.parametri = { codart, magaz, fase, modo, sintetico };

        setStatus('Caricamento in corso...');
        document.getElementById('btnEsegui').disabled = true;

        try {
            const params = new URLSearchParams({ codart, magaz, fase, modo, sintetico });
            const res = await fetch(`${MrpApp.API_BASE}/progressivi?${params}`, { credentials: 'include' });
            const data = await res.json();

           
‹ prevpage 2 / 6next ›