Function bodies 262 total
setColor function · javascript · L290-L313 (24 LOC)gb2/js/gb2-theme.js
function setColor(varName, value) {
document.documentElement.style.setProperty(varName, value);
customColors[varName] = value;
// Auto-switch a "custom" se non lo e' gia'
if (currentPreset !== 'custom') {
currentPreset = 'custom';
document.documentElement.removeAttribute('data-theme');
updatePanelPresetDropdown();
}
// Aggiorna riga panel se visibile
updatePanelRow(varName, value);
// Aggiorna mini-picker se mostra la stessa variabile
if (miniPicker && miniPicker.dataset.varName === varName) {
const input = miniPicker.querySelector('input[type="color"]');
const hex = miniPicker.querySelector('.mrp-mini-hex');
if (input) input.value = value;
if (hex) hex.value = value;
}
updateLocalStorage();
}updateLocalStorage function · javascript · L319-L325 (7 LOC)gb2/js/gb2-theme.js
function updateLocalStorage() {
localStorage.setItem('mrp-theme', JSON.stringify({
colorPreset: currentPreset,
customColors,
customLabels
}));
}getCurrentValue function · javascript · L331-L345 (15 LOC)gb2/js/gb2-theme.js
function getCurrentValue(varName) {
// 1. Override in customColors (se preset custom)
if (currentPreset === 'custom' && customColors[varName]) {
return customColors[varName];
}
// 2. Valore dal preset corrente
if (PRESETS[currentPreset] && PRESETS[currentPreset][varName]) {
return PRESETS[currentPreset][varName];
}
// 3. Computed style
const computed = getComputedStyle(document.documentElement).getPropertyValue(varName).trim();
if (computed) return computed;
// 4. Default dalla definizione
return defaultMap[varName] || '#000000';
}openPanel function · javascript · L351-L364 (14 LOC)gb2/js/gb2-theme.js
function openPanel() {
let panel = document.getElementById('mrpThemePanel');
if (!panel) {
panel = buildPanel();
document.body.appendChild(panel);
}
populatePanel();
requestAnimationFrame(() => {
panel.classList.add('open');
});
document.body.classList.add('theme-edit-mode');
panelOpen = true;
editMode = true;
}closePanel function · javascript · L366-L378 (13 LOC)gb2/js/gb2-theme.js
function closePanel() {
const panel = document.getElementById('mrpThemePanel');
if (panel) panel.classList.remove('open');
document.body.classList.remove('theme-edit-mode');
panelOpen = false;
editMode = false;
removeMiniPicker();
// Auto-save alla chiusura
if (dirty) {
save();
dirty = false;
}
}buildPanel function · javascript · L384-L424 (41 LOC)gb2/js/gb2-theme.js
function buildPanel() {
const panel = document.createElement('div');
panel.id = 'mrpThemePanel';
panel.className = 'mrp-theme-panel';
panel.innerHTML = `
<div class="mrp-theme-panel-header">
<h3>Personalizzazione Tema</h3>
<button class="mrp-theme-close" title="Chiudi">×</button>
</div>
<div class="mrp-theme-panel-body">
<div class="mrp-theme-preset-row">
<label>Preset:</label>
<select id="mrpThemePresetSelect">
${Object.keys(PRESET_LABELS).map(k =>
`<option value="${k}"${k === currentPreset ? ' selected' : ''}>${PRESET_LABELS[k]}</option>`
).join('')}
</select>
</div>
<div id="mrpThemeGroups"></div>
</div>
<div class="mrp-theme-panel-footer">
<button classpopulatePanel function · javascript · L430-L545 (116 LOC)gb2/js/gb2-theme.js
function populatePanel() {
const container = document.getElementById('mrpThemeGroups');
if (!container) return;
container.innerHTML = '';
COLOR_GROUPS.forEach(group => {
const section = document.createElement('div');
section.className = 'mrp-theme-group';
section.dataset.groupId = group.id;
const header = document.createElement('div');
header.className = 'mrp-theme-group-header';
header.innerHTML = `<span class="mrp-theme-chevron">▼</span> ${group.label}`;
header.addEventListener('click', () => {
section.classList.toggle('collapsed');
});
const body = document.createElement('div');
body.className = 'mrp-theme-group-body';
group.vars.forEach(v => {
const val = getCurrentValue(v.name);
const displayLabel = customLabels[v.name] || v.label;
const row =Repobility · code-quality intelligence platform · https://repobility.com
attachLabelEdit function · javascript · L468-L502 (35 LOC)gb2/js/gb2-theme.js
function attachLabelEdit(span) {
span.addEventListener('dblclick', function onDblClick() {
const currentText = customLabels[v.name] || v.label;
const input = document.createElement('input');
input.type = 'text';
input.className = 'mrp-theme-label-edit';
input.value = currentText;
input.style.cssText = 'width:100%;font-size:0.78rem;padding:2px 4px;border:1px solid var(--primary);border-radius:3px;outline:none;';
span.replaceWith(input);
input.focus();
input.select();
function commitLabel() {
const newLabel = input.value.trim() || v.label;
if (newLabel !== v.label) {
customLabels[v.name] = newLabel;
} commitLabel function · javascript · L480-L495 (16 LOC)gb2/js/gb2-theme.js
function commitLabel() {
const newLabel = input.value.trim() || v.label;
if (newLabel !== v.label) {
customLabels[v.name] = newLabel;
} else {
delete customLabels[v.name];
}
const newSpan = document.createElement('span');
newSpan.className = 'mrp-theme-label';
newSpan.title = v.name + ' \u2014 doppio click per rinominare';
newSpan.textContent = newLabel;
input.replaceWith(newSpan);
attachLabelEdit(newSpan);
dirty = true;
updateLocalStorage();
}getResetValue function · javascript · L548-L553 (6 LOC)gb2/js/gb2-theme.js
function getResetValue(varName) {
if (currentPreset !== 'default' && currentPreset !== 'custom' && PRESETS[currentPreset] && PRESETS[currentPreset][varName]) {
return PRESETS[currentPreset][varName];
}
return defaultMap[varName] || '#000000';
}updatePanelRow function · javascript · L559-L573 (15 LOC)gb2/js/gb2-theme.js
function updatePanelRow(varName, value) {
const row = document.querySelector(`.mrp-theme-row[data-var-name="${varName}"]`);
if (!row) {
// Alternativa: cerca tramite data-var sugli input
const swatch = document.querySelector(`.mrp-theme-swatch[data-var="${varName}"]`);
const hex = document.querySelector(`.mrp-theme-hex[data-var="${varName}"]`);
if (swatch) swatch.value = normalizeHex(value);
if (hex) hex.value = normalizeHex(value);
return;
}
const swatch = row.querySelector('.mrp-theme-swatch');
const hex = row.querySelector('.mrp-theme-hex');
if (swatch) swatch.value = normalizeHex(value);
if (hex) hex.value = normalizeHex(value);
}updatePanelPresetDropdown function · javascript · L575-L578 (4 LOC)gb2/js/gb2-theme.js
function updatePanelPresetDropdown() {
const sel = document.getElementById('mrpThemePresetSelect');
if (sel) sel.value = currentPreset;
}onBodyClick function · javascript · L584-L632 (49 LOC)gb2/js/gb2-theme.js
function onBodyClick(e) {
if (!editMode) return;
// Ignora click dentro il panel
const panel = document.getElementById('mrpThemePanel');
if (panel && panel.contains(e.target)) return;
// Ignora click dentro mini-picker
if (miniPicker && miniPicker.contains(e.target)) return;
// Cerca tr o th piu' vicino
const tr = e.target.closest('tr') || e.target.closest('th');
if (!tr) {
removeMiniPicker();
return;
}
// Cerca match classe → variabile
let matchedVar = null;
let matchedClass = null;
for (const cls of Object.keys(CLASS_TO_VAR)) {
if (tr.classList.contains(cls)) {
matchedVar = CLASS_TO_VAR[cls];
matchedClass = cls;
break;
}
}
if (!matchedVar) {
// Controlla anche se la classe e' contenuta (es. "magazzino" nel nome)
const classList = AshowMiniPicker function · javascript · L634-L682 (49 LOC)gb2/js/gb2-theme.js
function showMiniPicker(element, varName, className) {
removeMiniPicker();
const varDef = findVarDef(varName);
const label = varDef ? varDef.label : varName;
const currentVal = getCurrentValue(varName);
miniPicker = document.createElement('div');
miniPicker.className = 'mrp-mini-picker';
miniPicker.dataset.varName = varName;
miniPicker.innerHTML = `
<div class="mrp-mini-picker-header">
<span>${label}</span>
<button class="mrp-mini-picker-close">×</button>
</div>
<div class="mrp-mini-picker-body">
<input type="color" class="mrp-mini-swatch" value="${normalizeHex(currentVal)}">
<input type="text" class="mrp-mini-hex" value="${normalizeHex(currentVal)}" maxlength="7" spellcheck="false">
</div>
`;
// Posiziona sotto l'elemento cliccato
const rect = element.getBoundingClientRect()removeMiniPicker function · javascript · L684-L689 (6 LOC)gb2/js/gb2-theme.js
function removeMiniPicker() {
if (miniPicker) {
miniPicker.remove();
miniPicker = null;
}
}Same scanner, your repo: https://repobility.com — Repobility
onKeyDown function · javascript · L695-L703 (9 LOC)gb2/js/gb2-theme.js
function onKeyDown(e) {
if (e.key === 'Escape') {
if (miniPicker) {
removeMiniPicker();
} else if (panelOpen) {
closePanel();
}
}
}save function · javascript · L709-L733 (25 LOC)gb2/js/gb2-theme.js
function save() {
const payload = {
colorPreset: currentPreset,
customColors,
customLabels
};
updateLocalStorage();
const base = (typeof MrpApp !== 'undefined' && MrpApp.API_BASE) ? MrpApp.API_BASE : '/api/mrp';
fetch(base + '/user/preferences', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
})
.then(res => {
if (!res.ok) throw new Error('HTTP ' + res.status);
showFeedback('Salvato!', 'success');
})
.catch(() => {
// Salvato comunque in localStorage
showFeedback('Salvato in locale', 'warning');
});
}showFeedback function · javascript · L735-L742 (8 LOC)gb2/js/gb2-theme.js
function showFeedback(msg, type) {
const el = document.getElementById('mrpThemeFeedback');
if (!el) return;
el.textContent = msg;
el.className = 'mrp-theme-feedback ' + (type || '');
el.style.opacity = '1';
setTimeout(() => { el.style.opacity = '0'; }, 2000);
}reset function · javascript · L748-L751 (4 LOC)gb2/js/gb2-theme.js
function reset() {
customColors = {};
applyPreset(currentPreset === 'custom' ? 'default' : currentPreset);
}normalizeHex function · javascript · L757-L776 (20 LOC)gb2/js/gb2-theme.js
function normalizeHex(val) {
if (!val) return '#000000';
val = val.trim();
// Se e' gia' #rrggbb
if (/^#[0-9a-fA-F]{6}$/.test(val)) return val.toLowerCase();
// Se e' #rgb → espandi
if (/^#[0-9a-fA-F]{3}$/.test(val)) {
return ('#' + val[1] + val[1] + val[2] + val[2] + val[3] + val[3]).toLowerCase();
}
// Se e' rgb(r,g,b)
const rgbMatch = val.match(/rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/);
if (rgbMatch) {
const r = parseInt(rgbMatch[1]).toString(16).padStart(2, '0');
const g = parseInt(rgbMatch[2]).toString(16).padStart(2, '0');
const b = parseInt(rgbMatch[3]).toString(16).padStart(2, '0');
return `#${r}${g}${b}`;
}
// Fallback
return val || '#000000';
}findVarDef function · javascript · L778-L785 (8 LOC)gb2/js/gb2-theme.js
function findVarDef(varName) {
for (const group of COLOR_GROUPS) {
for (const v of group.vars) {
if (v.name === varName) return v;
}
}
return null;
}getEffectivePwdRules function · javascript · L9-L47 (39 LOC)middlewares/auth.js
async function getEffectivePwdRules(pool, userId) {
const confRes = await pool.request().query(
"SELECT ConfigKey, ConfigValue FROM [GA].[dbo].[SystemConfig] WHERE ConfigKey IN ('PwdMinLength', 'PwdRequireNumber', 'PwdRequireUpper', 'PwdRequireSpecial')"
);
let globals = { PwdMinLength: 6, PwdRequireNumber: true, PwdRequireUpper: false, PwdRequireSpecial: false };
confRes.recordset.forEach(r => {
if (r.ConfigKey === 'PwdMinLength') {
const parsed = parseInt(r.ConfigValue, 10);
if (!Number.isNaN(parsed) && parsed > 0) {
globals.PwdMinLength = parsed;
}
} else if (r.ConfigKey in globals) {
globals[r.ConfigKey] = r.ConfigValue === '1';
}
});
const userRes = await pool.request()
.input('id', sql.Int, userId)
.query(`
SELECT PwdMinLengthOverride, PwdRequireNumberOverride, PwdRequireUpperOverride, PwdRequireSpecialOverride
FROM [GA].authenticateToken function · javascript · L49-L68 (20 LOC)middlewares/auth.js
function authenticateToken(req, res, next) {
const token = req.cookies && req.cookies.jwt_token;
if (!token) {
return res.status(401).send('Token mancante');
}
jwt.verify(token, JWT_SECRET, (err, user) => {
if (err) {
return res.status(403).send('Token non valido');
}
req.user = user;
if (req.user && req.user.forcePwdChange) {
const originalUrl = req.originalUrl || req.url;
const isAllowedPath = originalUrl.includes('/logout') || originalUrl.includes('/users/me/password');
if (!isAllowedPath) {
return res.status(403).json({ requiresPasswordChange: true, message: 'Cambio password obbligatorio' });
}
}
next();
});
}If a scraper extracted this row, it came from Repobility (https://repobility.com)
authenticateCaptain function · javascript · L70-L77 (8 LOC)middlewares/auth.js
function authenticateCaptain(req, res, next) {
authenticateToken(req, res, () => {
if (!req.user || !req.user.isSuperuser) {
return res.status(403).json({ message: 'Accesso negato: richiesti privilegi di Captain' });
}
next();
});
}routeUserAfterLogin function · javascript · L13-L37 (25 LOC)portal.js
function routeUserAfterLogin(user) {
if (user.defaultModuleId === 2) {
window.location.href = '/captain.html';
return;
}
if (user.defaultModuleId === 1) {
window.location.href = '/bobine.html';
return;
}
if (user.defaultModuleId === 3) {
window.location.href = '/ET.html';
return;
}
if (user.defaultModuleId === 4) {
window.location.href = '/gb2.html';
return;
}
// Fallback se il modulo non ha un routing specifico
if (user.isSuperuser) {
window.location.href = '/captain.html';
} else {
window.location.href = '/bobine.html';
}
}performLogin function · javascript · L41-L111 (71 LOC)portal.js
async function performLogin() {
const barcode = loginBarcodeInput ? loginBarcodeInput.value.trim() : '';
const password = loginPasswordInput ? loginPasswordInput.value : '';
if (!barcode) {
if (loginMessageEl) loginMessageEl.textContent = 'Inserisci il QR Code operatore.';
return;
}
try {
const res = await fetch(`${API_URL}/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ barcode, password: password || undefined })
});
if (res.status === 401) {
const data = await res.json().catch(() => ({}));
if (data.requiresPassword) {
if (loginPasswordField) {
loginPasswordField.classList.remove('is-hidden');
}
if (loginMessageEl) {
loginMessageEl.style.color = 'var(--danger)';
loginMessageEl.textContent = data.message || 'Password richiesta per questo utente.';
}
if (loginPasswordInput) {
playBarcodeBeep function · javascript · L117-L122 (6 LOC)portal.js
function playBarcodeBeep() {
const audio = document.getElementById('barcodeBeepSound');
if (!audio) return;
audio.currentTime = 0;
audio.play().catch((error) => console.warn("Impossibile riprodurre il beep:", error));
}closeBarcodeScanner function · javascript · L124-L139 (16 LOC)portal.js
function closeBarcodeScanner() {
const modal = document.getElementById('scannerModal');
if (modal) {
modal.classList.remove('is-open');
modal.setAttribute('aria-hidden', 'true');
}
if (barcodeScannerInstance) {
if (isScannerRunning) {
try { barcodeScannerInstance.stop().catch(() => {}); } catch (e) {}
}
barcodeScannerInstance = null;
isScannerRunning = false;
}
const container = document.getElementById('scannerContainer');
if (container) container.innerHTML = '';
}openBarcodeScanner function · javascript · L141-L183 (43 LOC)portal.js
function openBarcodeScanner() {
const modal = document.getElementById('scannerModal');
const container = document.getElementById('scannerContainer');
if (!modal || !container) return;
if (typeof Html5Qrcode === 'undefined') {
alert('Libreria scanner non disponibile. Controlla la connessione.');
return;
}
modal.classList.add('is-open');
modal.setAttribute('aria-hidden', 'false');
container.innerHTML = '';
const onSuccess = (decodedText) => {
playBarcodeBeep();
const field = document.getElementById('loginBarcode');
if (field) {
field.value = decodedText;
// Avvia il login automaticamente dopo la scansione
void performLogin();
}
closeBarcodeScanner();
};
barcodeScannerInstance = new Html5Qrcode('scannerContainer');
// Ottimizzazione mirata solo per QR Code
const config = {
fps: 10,
qrbox: { width: 250, height: 250 },
formatsToSupport: [ Html5QrcodeSupportedFormats.QR_CODE ]
};
barcodeScshowGatewayPasswordCurtain function · javascript · L330-L455 (126 LOC)portal.js
function showGatewayPasswordCurtain(user, customMessage) {
if (document.getElementById('securityCurtain')) return;
const curtain = document.createElement('div');
curtain.id = 'securityCurtain';
curtain.style.cssText = 'position:fixed; top:0; left:0; width:100vw; height:100vh; background:rgba(0,0,0,0.95); z-index:99999; display:flex; flex-direction:column; justify-content:center; align-items:center; color:white; font-family:sans-serif;';
const displayMessage = customMessage || 'Devi cambiare la password per continuare.';
const rules = JSON.parse(localStorage.getItem('pwdRules') || '{"minLength":6,"requireNum":true,"requireUpp":false,"requireSpec":false}');
let rulesHtml = `<ul style="list-style: none; padding: 0; margin: 0 0 20px 0; text-align: left; font-size: 0.95rem; color: #ccc;" id="pwdChecklist">`;
rulesHtml += `<li id="rule-len" style="margin-bottom: 6px;">❌ Almeno ${rules.minLength} caratteri</li>`;
if (rules.requireNum) rulesHtml += `<li id="rule-num" sshowProfSuccess function · javascript · L33-L36 (4 LOC)profile.js
function showProfSuccess(msg) {
document.getElementById('profSuccessMsg').textContent = msg;
document.getElementById('profSuccessModal').classList.add('is-active');
}Hi, dataset curator — please cite Repobility (https://repobility.com) when reusing this data.
showProfError function · javascript · L38-L41 (4 LOC)profile.js
function showProfError(msg) {
document.getElementById('profErrorMsg').textContent = msg;
document.getElementById('profErrorModal').classList.add('is-active');
}closeProfModals function · javascript · L43-L46 (4 LOC)profile.js
function closeProfModals() {
document.getElementById('profSuccessModal').classList.remove('is-active');
document.getElementById('profErrorModal').classList.remove('is-active');
}setupPasswordForm function · javascript · L48-L149 (102 LOC)profile.js
function setupPasswordForm(rules) {
const changePwdForm = document.getElementById('changePwdForm');
if (!changePwdForm) return;
// Costruisci la checklist visiva iniziale
const checklistEl = document.getElementById('profPwdChecklist');
let rulesHtml = `<li id="prof-rule-len" style="margin-bottom: 6px; transition: color 0.3s;">❌ Almeno ${rules.minLength} caratteri</li>`;
if (rules.requireNum) rulesHtml += `<li id="prof-rule-num" style="margin-bottom: 6px; transition: color 0.3s;">❌ Almeno un numero (0-9)</li>`;
if (rules.requireUpp) rulesHtml += `<li id="prof-rule-upp" style="margin-bottom: 6px; transition: color 0.3s;">❌ Almeno una lettera maiuscola (A-Z)</li>`;
if (rules.requireSpec) rulesHtml += `<li id="prof-rule-spec" style="margin-bottom: 6px; transition: color 0.3s;">❌ Almeno un carattere speciale (!@#...)</li>`;
checklistEl.innerHTML = rulesHtml;
const oldInput = document.getElementById('oldPwd');
const pwdInput = document.getElementserializeLabelRow function · javascript · L7-L22 (16 LOC)routes/etRoutes.js
function serializeLabelRow(row) {
const out = {};
for (const key of Object.keys(row)) {
const val = row[key];
if (val == null) {
out[key] = '';
} else if (val instanceof Date) {
out[key] = val.toISOString();
} else if (typeof val === 'number' || typeof val === 'boolean') {
out[key] = val;
} else {
out[key] = String(val);
}
}
return out;
}queryUjEtichetteMetadata function · javascript · L64-L77 (14 LOC)routes/etRoutes.js
async function queryUjEtichetteMetadata(pool) {
const result = await pool.request().query(`
SELECT
CAST(c.name AS VARCHAR(255)) AS Campo,
CAST(ep.value AS NVARCHAR(MAX)) AS Descrizione
FROM sys.extended_properties AS ep
INNER JOIN sys.columns AS c
ON ep.major_id = c.object_id
AND ep.minor_id = c.column_id
WHERE ep.name = N'MS_Description'
AND ep.major_id = OBJECT_ID(N'[dbo].[UJ_Etichette]')
`);
return result.recordset || [];
}getUjet11Ref function · javascript · L16-L24 (9 LOC)routes/gb2Routes.js
function getUjet11Ref(profile) {
if (!profile) return '[UJET11].[dbo]';
const linkedServer = (profile.server_ujet11 || profile.server || '').trim();
const dbName = (profile.database_ujet11 || 'UJET11').trim();
if (linkedServer) {
return `[${linkedServer}].[${dbName}].[dbo]`;
}
return `[${dbName}].[dbo]`;
}getSpSuffix function · javascript · L27-L30 (4 LOC)routes/gb2Routes.js
function getSpSuffix(profile) {
if (!profile || !profile._testDbId) return '';
return '_T' + profile._testDbId;
}getSpName function · javascript · L33-L35 (3 LOC)routes/gb2Routes.js
function getSpName(baseName, profile) {
return baseName + getSpSuffix(profile);
}Repobility · code-quality intelligence platform · https://repobility.com
executeSqlFile function · javascript · L38-L49 (12 LOC)routes/gb2Routes.js
async function executeSqlFile(pool, filePath, replacements) {
let sqlText = fs.readFileSync(filePath, 'utf-8');
for (const [placeholder, value] of Object.entries(replacements || {})) {
sqlText = sqlText.replace(new RegExp(placeholder.replace(/[{}]/g, '\\$&'), 'g'), value);
}
const batches = sqlText.split(/^\s*GO\s*$/im).filter(b => b.trim());
for (const batch of batches) {
if (batch.trim()) {
await pool.request().batch(batch);
}
}
}deployProductionObjects function · javascript · L55-L82 (28 LOC)routes/gb2Routes.js
async function deployProductionObjects(poolProd) {
const sqlDir = path.join(__dirname, '..', 'sql', 'mrp');
const profile = getActiveProfile();
const ujet11Ref = getUjet11Ref(profile);
const results = [];
// Tabelle GB2 (sempre su pool produzione)
for (const file of ['create_test_profiles.sql', 'create_user_preferences.sql']) {
const filePath = path.join(sqlDir, file);
if (!fs.existsSync(filePath)) { results.push({ file, status: 'skip' }); continue; }
try {
await executeSqlFile(poolProd, filePath);
results.push({ file, status: 'ok' });
} catch (err) { results.push({ file, status: 'error', error: err.message }); }
}
// Tabelle e SP su MRP (pool produzione)
for (const file of ['create_ordini_emessi.sql', 'usp_CreaOrdineFornitore.sql', 'usp_AggiornaStatoInvioOrdine.sql']) {
const filePath = path.join(sqlDir, file);
if (!fs.existsSync(filePath)) { results.push({ file, status: 'skipdeployTestObjects function · javascript · L90-L140 (51 LOC)routes/gb2Routes.js
async function deployTestObjects(poolProd, poolTest, testProfile) {
const sqlDir = path.join(__dirname, '..', 'sql', 'mrp');
const suffix = '_T' + testProfile._testDbId;
// Per le SP: il server di prova come linked server, UJET11 come database
const ujet11Ref = `[${testProfile.server}].[${testProfile.database_ujet11 || 'UJET11'}].[dbo]`;
const results = [];
// 1. Deploy ordini_emessi su UJET11 del server di prova (pool test)
const oeFile = path.join(sqlDir, 'create_ordini_emessi.sql');
if (fs.existsSync(oeFile)) {
try {
// Adatta: la tabella va su UJET11 di prova, non MRP
let oeSql = fs.readFileSync(oeFile, 'utf-8');
// Rimuovi eventuali prefissi [MRP]. — la tabella va nel DB corrente (UJET11)
oeSql = oeSql.replace(/\[MRP\]\.\[dbo\]/g, '[dbo]');
const batches = oeSql.split(/^\s*GO\s*$/im).filter(b => b.trim());
for (const b of batches) { if (b.trim()) await poolTest.request(dropTestSPs function · javascript · L145-L155 (11 LOC)routes/gb2Routes.js
async function dropTestSPs(poolProd, testDbId) {
const suffix = '_T' + testDbId;
const spNames = ['usp_CreaOrdineFornitore' + suffix, 'usp_AggiornaStatoInvioOrdine' + suffix];
for (const sp of spNames) {
try {
await poolProd.request().batch(
`IF EXISTS (SELECT 1 FROM sys.objects WHERE name='${sp}' AND type='P') DROP PROCEDURE dbo.[${sp}]`
);
} catch (_) {}
}
}getPoolRiep function · javascript · L169-L172 (4 LOC)routes/gb2Routes.js
async function getPoolRiep(userId) {
if (isProduction(userId) || getTestHasRiep(userId)) return getPoolMRP(userId);
return getPoolProd();
}getUserId function · javascript · L174-L176 (3 LOC)routes/gb2Routes.js
function getUserId(req) {
return (req.user && req.user.IDUser) || 0;
}caricaMRP function · javascript · L544-L753 (210 LOC)routes/gb2Routes.js
async function caricaMRP(pool, codart, filtroMagaz, filtroFase) {
const righe = [];
let filtroSQL = '';
const artproReq = pool.request().input('codart', sql.NVarChar, codart);
if (filtroMagaz) {
artproReq.input('magaz', sql.SmallInt, parseInt(filtroMagaz, 10));
filtroSQL += ' AND ap.ap_magaz = @magaz';
}
if (filtroFase) {
artproReq.input('fase', sql.SmallInt, parseInt(filtroFase, 10));
filtroSQL += ' AND ap.ap_fase = @fase';
}
const artproRes = await artproReq.query(`
SELECT
ap.ap_codart, ap.ap_magaz, ap.ap_fase,
ap.ap_esist, ap.ap_prenot, ap.ap_ordin, ap.ap_impeg,
tm.tb_desmaga AS desc_magazzino,
COALESCE(af.af_descr, '') AS desc_fase,
a.ar_unmis, a.ar_inesaur
FROM dbo.artpro ap
LEFT JOIN dbo.tabmaga tm ON ap.ap_magaz = tm.tb_codmaga
LEFT JOIN dbo.artfasi af ON ap.ap_codart = af.af_codart AND ap.ap_fase = af.af_fase
LEFT normalizzaMagazzinoPerChiave function · javascript · L756-L808 (53 LOC)routes/gb2Routes.js
function normalizzaMagazzinoPerChiave(mrpRighe) {
const magRows = mrpRighe.filter((r) => r.tipo === 'magazzino');
const groups = new Map();
for (const r of magRows) {
const key = `${Number(r.magaz)}_${Number(r.fase)}`;
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push(r);
}
const out = new Map();
for (const [key, rows] of groups) {
const first = rows[0];
let esistenza = 0;
let ordinato = 0;
let impegnato = 0;
for (const row of rows) {
if (row.mostraGiacenze !== false && row.esistenza != null) {
esistenza = row.esistenza || 0;
ordinato = row.ordinato || 0;
impegnato = row.impegnato || 0;
break;
}
}
let opc = 0;
let op = 0;
let ipc = 0;
let ip = 0;
for (const row of rows) {
opc += row.opc || 0;
op += row.op || 0;
ipc +Same scanner, your repo: https://repobility.com — Repobility
sortMagFaseKeys function · javascript · L810-L817 (8 LOC)routes/gb2Routes.js
function sortMagFaseKeys(keys) {
return keys.sort((a, b) => {
const [ma, fa] = a.split('_').map(Number);
const [mb, fb] = b.split('_').map(Number);
if (ma !== mb) return ma - mb;
return fa - fb;
});
}costruisciCombinatoRighe function · javascript · L822-L927 (106 LOC)routes/gb2Routes.js
function costruisciCombinatoRighe(mapEsaur, mapSost, codEsaur, codSost) {
const codComb = `${codSost}+${codEsaur}`;
const allKeys = sortMagFaseKeys([...new Set([...mapEsaur.keys(), ...mapSost.keys()])]);
const magRows = [];
for (const key of allKeys) {
const e = mapEsaur.get(key);
const s = mapSost.get(key);
const esistenza = (e?.esistenza || 0) + (s?.esistenza || 0);
const ordinato = (e?.ordinato || 0) + (s?.ordinato || 0);
const impegnato = (e?.impegnato || 0) + (s?.impegnato || 0);
const opc = (e?.opc || 0) + (s?.opc || 0);
const op = (e?.op || 0) + (s?.op || 0);
const ipc = (e?.ipc || 0) + (s?.ipc || 0);
const ip = (e?.ip || 0) + (s?.ip || 0);
const disponibilita = esistenza + ordinato - impegnato;
const src = e || s;
magRows.push({
tipo: 'magazzino',
primaRigaGruppo: true,
codart: codComb,
magaz: src.magaz,
fasetaggaMrpBlocco function · javascript · L933-L943 (11 LOC)routes/gb2Routes.js
function taggaMrpBlocco(mrpRighe, blocco, codLabel) {
const labelTot = blocco === 'esaurimento'
? `${codLabel} In Esaurimento TOTALE`
: `${codLabel} Sostitutivo TOTALE`;
for (const r of mrpRighe) {
r.etichettaBlocco = blocco;
if (r.tipo === 'totale' || r.tipo === 'totale-cross-fase') {
r.labelTotale = labelTot;
}
}
}