added fixed field in json

This commit is contained in:
2026-06-09 09:46:21 +02:00
parent 25bd916221
commit 6e43a178af
3 changed files with 412 additions and 81 deletions
+334 -54
View File
@@ -87,10 +87,19 @@ $mappings = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Recupera i fixed fields dalla tabella template_fixed_mapping
$stmt = $pdo->prepare("
SELECT id, fixed_field_key, is_manual, data_type, is_required, default_value, is_visible_import
FROM template_fixed_mapping
WHERE template_id = ?
ORDER BY id ASC
SELECT
id,
fixed_field_key,
is_manual,
data_type,
is_required,
default_value,
default_source,
json_node,
is_visible_import
FROM template_fixed_mapping
WHERE template_id = ?
ORDER BY id ASC
");
$stmt->execute([$id]);
$fixedMappings = $stmt->fetchAll(PDO::FETCH_ASSOC);
@@ -447,19 +456,18 @@ $apiSampleJson = $template['api_sample_json'] ?? '';
<td>
<?php
$isSceltaMultipla = ($mapping['data_type'] === 'SceltaMultipla');
$isApiSceltaMultipla = ($sourceType === 'API' && $isSceltaMultipla);
$autoValue = $mapping['auto_value'] ?? 'none';
$hasAuto = ($autoValue && $autoValue !== 'none');
if ($isSceltaMultipla) {
$mappingValue = 'manual';
} elseif ($hasAuto) {
$mappingValue = 'auto';
} elseif ($sourceType === 'XLS' && !empty($mapping['excel_column'])) {
$mappingValue = 'xls';
} elseif ($sourceType === 'API' && !empty($mapping['json_node'])) {
if ($sourceType === 'API' && !empty($mapping['json_node'])) {
$mappingValue = 'json';
} elseif ((int)$mapping['is_manual'] === 1) {
} elseif ($sourceType === 'XLS' && !$isSceltaMultipla && !empty($mapping['excel_column'])) {
$mappingValue = 'xls';
} elseif (!$isSceltaMultipla && $hasAuto) {
$mappingValue = 'auto';
} elseif ((int)$mapping['is_manual'] === 1 || $isSceltaMultipla) {
$mappingValue = 'manual';
} else {
$mappingValue = '';
@@ -469,17 +477,18 @@ $apiSampleJson = $template['api_sample_json'] ?? '';
<select class="form-select mapping-select"
data-id="<?php echo (int)$mapping['id']; ?>"
data-field-id="<?php echo (int)$mapping['field_id']; ?>"
<?php echo $isSceltaMultipla ? 'disabled' : ''; ?>>
data-is-scelta-multipla="<?php echo $isSceltaMultipla ? '1' : '0'; ?>"
<?php echo ($isSceltaMultipla && $sourceType !== 'API') ? 'disabled' : ''; ?>>
<option value="">Select Option</option>
<?php if ($sourceType === 'XLS' && !$isSceltaMultipla): ?>
<option value="xls" <?php echo ($mappingValue === 'xls') ? 'selected' : ''; ?>>Map to XLS Column</option>
<?php elseif ($sourceType === 'API'): ?>
<option value="json" <?php echo ($mappingValue === 'json') ? 'selected' : ''; ?>>Map to JSON Node</option>
<?php endif; ?>
<?php if (!$isSceltaMultipla): ?>
<option value="">Select Option</option>
<?php if ($sourceType === 'XLS'): ?>
<option value="xls" <?php echo ($mappingValue === 'xls') ? 'selected' : ''; ?>>Map to XLS Column</option>
<?php elseif ($sourceType === 'API'): ?>
<option value="json" <?php echo ($mappingValue === 'json') ? 'selected' : ''; ?>>Map to JSON Node</option>
<?php endif; ?>
<option value="auto" <?php echo ($mappingValue === 'auto') ? 'selected' : ''; ?>>Auto value</option>
<?php endif; ?>
@@ -615,39 +624,68 @@ $apiSampleJson = $template['api_sample_json'] ?? '';
<td><?php echo htmlspecialchars($fm['data_type']); ?></td>
<td>
<?php
$fixedDefaultSource = $fm['default_source'] ?? 'manual';
$fixedJsonNode = $fm['json_node'] ?? '';
$showFixedManual = ($fixedDefaultSource !== 'json');
$showFixedJson = ($fixedDefaultSource === 'json');
?>
<?php if ($fm['data_type'] === 'DATE'): ?>
<input type="date"
class="form-control fixed-default-input"
<?php if ($sourceType === 'API'): ?>
<select class="form-select fixed-source-select"
data-fixed-id="<?php echo (int)$fm['id']; ?>"
value="<?php echo htmlspecialchars($fm['default_value'] ?? ''); ?>">
<?php elseif (in_array($fm['fixed_field_key'], [
'ClienteResponsabile',
'ClienteFornitore',
'ClienteAnalisi',
'MoltiplicatorePrezzo',
'AnagraficaCertestObject',
'AnagraficaCertestService'
])): ?>
<select class="form-select fixed-default-select"
data-fixed-id="<?php echo (int)$fm['id']; ?>"
data-fixed-key="<?php echo htmlspecialchars($fm['fixed_field_key']); ?>"
data-current-value="<?php echo htmlspecialchars($fm['default_value'] ?? ''); ?>">
<option value="">Loading...</option>
style="margin-bottom:6px;">
<option value="manual" <?php echo ($fixedDefaultSource === 'manual') ? 'selected' : ''; ?>>
Manual value
</option>
<option value="json" <?php echo ($fixedDefaultSource === 'json') ? 'selected' : ''; ?>>
Map to JSON Node
</option>
</select>
<?php else: ?>
<input type="text"
class="form-control fixed-default-input"
<select class="form-select fixed-json-node-select"
data-fixed-id="<?php echo (int)$fm['id']; ?>"
value="<?php echo htmlspecialchars($fm['default_value'] ?? ''); ?>">
data-current-json="<?php echo htmlspecialchars($fixedJsonNode, ENT_QUOTES, 'UTF-8'); ?>"
style="display:<?php echo $showFixedJson ? 'block' : 'none'; ?>; margin-bottom:6px;">
</select>
<?php endif; ?>
<div class="fixed-manual-wrapper"
style="display:<?php echo $showFixedManual ? 'block' : 'none'; ?>;">
<?php if ($fm['data_type'] === 'DATE'): ?>
<input type="date"
class="form-control fixed-default-input"
data-fixed-id="<?php echo (int)$fm['id']; ?>"
value="<?php echo htmlspecialchars($fm['default_value'] ?? ''); ?>">
<?php elseif (in_array($fm['fixed_field_key'], [
'ClienteResponsabile',
'ClienteFornitore',
'ClienteAnalisi',
'MoltiplicatorePrezzo',
'AnagraficaCertestObject',
'AnagraficaCertestService'
])): ?>
<select class="form-select fixed-default-select"
data-fixed-id="<?php echo (int)$fm['id']; ?>"
data-fixed-key="<?php echo htmlspecialchars($fm['fixed_field_key']); ?>"
data-current-value="<?php echo htmlspecialchars($fm['default_value'] ?? ''); ?>">
<option value="">Loading...</option>
</select>
<?php else: ?>
<input type="text"
class="form-control fixed-default-input"
data-fixed-id="<?php echo (int)$fm['id']; ?>"
value="<?php echo htmlspecialchars($fm['default_value'] ?? ''); ?>">
<?php endif; ?>
</div>
</td>
</tr>
@@ -1183,6 +1221,46 @@ $apiSampleJson = $template['api_sample_json'] ?? '';
initSelect2ForJsonDropdowns();
}
function updateFixedJsonDropdowns() {
document.querySelectorAll('select.fixed-json-node-select').forEach(select => {
let currentValue = select.value || select.dataset.currentJson || '';
let options = availableJsonNodes
.map(node => {
const clean = String(node || '').trim();
if (!clean) return '';
const info = jsonNodeLabels[clean] || {};
const shortName = info.shortName || getLastJsonNodeName(clean);
const sample = info.sample || '';
let label = shortName;
if (sample) {
label += ` — ${sample}`;
}
const isSelected = clean === currentValue ? 'selected' : '';
return `
<option
value="${escapeHtmlAttr(clean)}"
data-short-name="${escapeHtmlAttr(shortName)}"
data-sample="${escapeHtmlAttr(sample)}"
data-full-path="${escapeHtmlAttr(clean)}"
${isSelected}>
${escapeHtmlText(label)}
</option>
`;
})
.join('');
select.innerHTML = '<option value="">Select JSON Node</option>' + options;
select.dataset.currentJson = currentValue;
});
initSelect2ForFixedJsonDropdowns();
}
function initSelect2ForJsonDropdowns() {
if (!(window.jQuery && $.fn.select2)) return;
@@ -1266,7 +1344,81 @@ $apiSampleJson = $template['api_sample_json'] ?? '';
});
}
function initSelect2ForFixedJsonDropdowns() {
if (!(window.jQuery && $.fn.select2)) return;
$('.fixed-json-node-select').each(function() {
const $el = $(this);
if (this.style.display === 'none') {
return;
}
if ($el.hasClass('select2-hidden-accessible')) {
$el.select2('destroy');
}
$el.select2({
width: '100%',
placeholder: 'Select JSON Node',
allowClear: true,
templateResult: function(data) {
if (!data.id) return data.text;
const option = data.element;
const shortName = option.getAttribute('data-short-name') || data.text;
const sample = option.getAttribute('data-sample') || '';
const $row = $('<span class="select2-json-row"></span>');
$row.append(`<span class="select2-json-node">${escapeHtmlText(shortName)}</span>`);
if (sample) {
$row.append(`<span class="select2-json-value">${escapeHtmlText(sample)}</span>`);
}
return $row;
},
templateSelection: function(data) {
if (!data.id) return data.text;
const option = data.element;
const shortName = option.getAttribute('data-short-name') || data.text;
const sample = option.getAttribute('data-sample') || '';
if (sample) {
return `${shortName} — ${sample}`;
}
return shortName;
},
matcher: function(params, data) {
if ($.trim(params.term) === '') {
return data;
}
const term = params.term.toLowerCase();
const option = data.element;
const fullPath = option?.getAttribute('data-full-path')?.toLowerCase() || '';
const shortName = option?.getAttribute('data-short-name')?.toLowerCase() || '';
const sample = option?.getAttribute('data-sample')?.toLowerCase() || '';
if (
fullPath.includes(term) ||
shortName.includes(term) ||
sample.includes(term)
) {
return data;
}
return null;
}
});
});
}
function saveJsonNodes(sampleJson, nodes) {
return fetch('update_api_json_nodes.php', {
@@ -1411,6 +1563,7 @@ $apiSampleJson = $template['api_sample_json'] ?? '';
availableJsonNodes = nodes;
usedJsonNodesFromDB = [];
updateJsonDropdowns();
updateFixedJsonDropdowns();
try {
const data = await saveJsonNodes(rawJson, nodes);
@@ -1556,9 +1709,12 @@ $apiSampleJson = $template['api_sample_json'] ?? '';
return;
}
const mappingSelect = tr?.querySelector('.mapping-select');
const currentMappingType = mappingSelect ? mappingSelect.value : 'manual';
saveMapping(
mappingId,
'manual',
currentMappingType || 'manual',
el.value,
xlsSelect ? xlsSelect.value : null,
null,
@@ -1588,9 +1744,12 @@ $apiSampleJson = $template['api_sample_json'] ?? '';
return;
}
const mappingSelect = tr?.querySelector('.mapping-select');
const currentMappingType = mappingSelect ? mappingSelect.value : 'manual';
saveMapping(
mappingId,
'manual',
currentMappingType || 'manual',
el.value,
xlsSelect ? xlsSelect.value : null,
null,
@@ -1674,6 +1833,7 @@ $apiSampleJson = $template['api_sample_json'] ?? '';
const removeBtn = tr.querySelector('.remove-xls');
const removeJsonBtn = tr.querySelector('.remove-json');
const isSceltaMultipla = mappingSelect.dataset.isSceltaMultipla === '1';
function destroyJsonSelect2() {
if (jsonSelect && window.jQuery && $(jsonSelect).hasClass('select2-hidden-accessible')) {
@@ -1716,8 +1876,12 @@ $apiSampleJson = $template['api_sample_json'] ?? '';
if (autoSelect) autoSelect.style.display = 'none';
if (manualInput) {
manualInput.style.display = 'none';
manualInput.value = '';
if (isSceltaMultipla) {
manualInput.style.display = 'block';
} else {
manualInput.style.display = 'none';
manualInput.value = '';
}
}
if (mappedColumn) mappedColumn.style.display = 'none';
@@ -1958,13 +2122,19 @@ $apiSampleJson = $template['api_sample_json'] ?? '';
let mappingId = event.target.getAttribute('data-id');
let xlsSelect = tr.querySelector('.xls-columns');
let jsonSelect = tr.querySelector('.json-nodes');
let mappingSelect = tr.querySelector('.mapping-select');
let currentMappingType = mappingSelect ? mappingSelect.value : 'manual';
console.log("Manual default dropdown changed:", {
id: mappingId,
value: event.target.value
value: event.target.value,
mappingType: currentMappingType
});
saveMapping(
mappingId,
'manual',
currentMappingType || 'manual',
event.target.value,
xlsSelect ? xlsSelect.value : null,
null,
@@ -2063,7 +2233,7 @@ $apiSampleJson = $template['api_sample_json'] ?? '';
mapping_type: mappingType,
excel_column: mappingType === 'xls' ? excelColumn : null,
json_node: mappingType === 'json' ? jsonNode : null,
manual_default: mappingType === 'manual' ? defaultValue : null,
manual_default: defaultValue,
auto_value: mappingType === 'auto' ? (autoValue || 'none') : 'none',
tablename: "<?php echo $template['target_table']; ?>"
})
@@ -2092,6 +2262,115 @@ $apiSampleJson = $template['api_sample_json'] ?? '';
// FIXED FIELDS (DB autosave)
// =======================
// =======================
// FIXED FIELDS: source manual/json autosave
// Only used for API/JSON templates
// =======================
document.addEventListener('change', function(e) {
if (!e.target.classList.contains('fixed-source-select')) return;
const sourceSelect = e.target;
const fixedId = sourceSelect.dataset.fixedId;
const tr = sourceSelect.closest('tr');
const manualWrapper = tr.querySelector('.fixed-manual-wrapper');
const jsonSelect = tr.querySelector('.fixed-json-node-select');
if (sourceSelect.value === 'json') {
if (manualWrapper) {
manualWrapper.style.display = 'none';
}
if (jsonSelect) {
jsonSelect.style.display = 'block';
updateFixedJsonDropdowns();
}
} else {
if (jsonSelect) {
if (window.jQuery && $(jsonSelect).hasClass('select2-hidden-accessible')) {
$(jsonSelect).select2('destroy');
}
jsonSelect.value = '';
jsonSelect.dataset.currentJson = '';
jsonSelect.style.display = 'none';
}
if (manualWrapper) {
manualWrapper.style.display = 'block';
}
}
fetch('update_fixed_field.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
id: fixedId,
field: 'default_source',
value: sourceSelect.value
})
})
.then(response => response.json())
.then(data => {
if (!data.success) {
throw new Error(data.message || 'Update failed');
}
fixedStatus('✅ Saved');
})
.catch(error => {
console.error(error);
fixedStatus('❌ Save error', true);
});
});
// =======================
// FIXED FIELDS: JSON node autosave
// =======================
function saveFixedJsonNode(selectEl) {
const fixedId = selectEl.dataset.fixedId;
const jsonNode = selectEl.value || '';
fetch('update_fixed_field.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
id: fixedId,
field: 'json_node',
value: jsonNode
})
})
.then(response => response.json())
.then(data => {
if (!data.success) {
throw new Error(data.message || 'Update failed');
}
selectEl.dataset.currentJson = jsonNode;
fixedStatus('✅ Saved');
})
.catch(error => {
console.error(error);
fixedStatus('❌ Save error', true);
});
}
document.addEventListener('change', function(e) {
if (!e.target.classList.contains('fixed-json-node-select')) return;
saveFixedJsonNode(e.target);
});
if (window.jQuery) {
$(document).on('select2:select select2:clear', '.fixed-json-node-select', function() {
saveFixedJsonNode(this);
});
}
function escapeHtml(str) {
return String(str ?? '')
.replaceAll('&', '&amp;')
@@ -2328,6 +2607,7 @@ $apiSampleJson = $template['api_sample_json'] ?? '';
}
updateJsonDropdowns();
updateFixedJsonDropdowns();
}
fillFixedDropdowns().then(() => {