update schema

This commit is contained in:
Claudio 2026-05-08 11:10:21 +02:00
parent b38f3e1240
commit aa355905d7

View File

@ -2,7 +2,6 @@
header('Content-Type: application/json'); header('Content-Type: application/json');
require_once 'class/db-functions.php'; require_once 'class/db-functions.php';
// Disabilita l'output di errori HTML
ini_set('display_errors', '0'); ini_set('display_errors', '0');
error_reporting(E_ALL); error_reporting(E_ALL);
@ -13,108 +12,235 @@ try {
throw new Exception("Invalid request method."); throw new Exception("Invalid request method.");
} }
// Recupera i dati dal body JSON
$input = json_decode(file_get_contents('php://input'), true); $input = json_decode(file_get_contents('php://input'), true);
$template_id = isset($input['template_id']) ? intval($input['template_id']) : null; $template_id = isset($input['template_id']) ? intval($input['template_id']) : null;
$schemajson = isset($input['schemajson']) ? trim($input['schemajson']) : ''; $schemajson = isset($input['schemajson']) ? trim($input['schemajson']) : '';
// Controllo sui campi obbligatori
if (empty($template_id) || empty($schemajson)) { if (empty($template_id) || empty($schemajson)) {
throw new Exception("All fields marked with * are required, including schemajson."); throw new Exception("All fields marked with * are required, including schemajson.");
} }
// Validazione del JSON
$decoded_json = json_decode($schemajson, true); $decoded_json = json_decode($schemajson, true);
if (json_last_error() !== JSON_ERROR_NONE) { if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception("Invalid JSON format for schemajson."); throw new Exception("Invalid JSON format for schemajson.");
} }
// Connessione al database
$db = DBHandlerSelect::getInstance(); $db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection(); $pdo = $db->getConnection();
// Recupera il target_table e verifica l'esistenza del template
$stmt = $pdo->prepare("SELECT target_table FROM excel_templates WHERE id = ?"); $stmt = $pdo->prepare("SELECT target_table FROM excel_templates WHERE id = ?");
$stmt->execute([$template_id]); $stmt->execute([$template_id]);
$template = $stmt->fetch(PDO::FETCH_ASSOC); $template = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$template) { if (!$template) {
throw new Exception("Template not found."); throw new Exception("Template not found.");
} }
$target_table = $template['target_table']; $target_table = $template['target_table'];
// Inizia una transazione
$pdo->beginTransaction();
// Aggiorna il schemajson in excel_templates
$stmt = $pdo->prepare("UPDATE excel_templates
SET schemajson = ?, updated_at = NOW()
WHERE id = ?");
$stmt->execute([$schemajson, $template_id]);
// Estrai i campi dallo schema
$schema_id = $decoded_json['IdSchemaCustomFields'] ?? null; $schema_id = $decoded_json['IdSchemaCustomFields'] ?? null;
$schema_fields = $decoded_json['SchemiCustomFieldsDettagli'] ?? []; $schema_fields = $decoded_json['SchemiCustomFieldsDettagli'] ?? [];
if (empty($schema_id)) { if (empty($schema_id)) {
throw new Exception("Schema ID not found in schemajson."); throw new Exception("Schema ID not found in schemajson.");
} }
if (empty($schema_fields)) { if (empty($schema_fields)) {
throw new Exception("No fields found in schema."); throw new Exception("No fields found in schema.");
} }
// Prepara la query per l'inserimento condizionato in template_mapping $pdo->beginTransaction();
$insert_stmt = $pdo->prepare("
/*
* 1) Update raw schema JSON in excel_templates
*/
$stmt = $pdo->prepare("
UPDATE excel_templates
SET schemajson = ?, updated_at = NOW()
WHERE id = ?
");
$stmt->execute([$schemajson, $template_id]);
/*
* Prepare reusable statements
*/
// Check if mapping already exists
$checkStmt = $pdo->prepare("
SELECT id, data_type
FROM template_mapping
WHERE template_id = ?
AND field_id = ?
LIMIT 1
");
// Insert new field
$insertStmt = $pdo->prepare("
INSERT INTO template_mapping ( INSERT INTO template_mapping (
template_id, schema_id, field_id, data_type, is_required, default_value, template_id,
has_list, length, decimals, min_value, max_value, default_curr_date, schema_id,
tablename, field_label field_id,
) data_type,
SELECT :template_id, :schema_id, :field_id, :data_type, :is_required, :default_value, is_required,
:has_list, :length, :decimals, :min_value, :max_value, :default_curr_date, default_value,
:tablename, :field_label has_list,
WHERE NOT EXISTS ( length,
SELECT 1 FROM template_mapping decimals,
WHERE template_id = :template_id_check AND field_id = :field_id_check min_value,
max_value,
default_curr_date,
tablename,
field_label
) VALUES (
:template_id,
:schema_id,
:field_id,
:data_type,
:is_required,
:default_value,
:has_list,
:length,
:decimals,
:min_value,
:max_value,
:default_curr_date,
:tablename,
:field_label
) )
"); ");
// Itera sui campi dello schema e inserisci quelli mancanti // Update existing field WITHOUT clearing manual_default
$updateSameTypeStmt = $pdo->prepare("
UPDATE template_mapping
SET
schema_id = :schema_id,
data_type = :data_type,
is_required = :is_required,
default_value = :default_value,
has_list = :has_list,
length = :length,
decimals = :decimals,
min_value = :min_value,
max_value = :max_value,
default_curr_date = :default_curr_date,
tablename = :tablename,
field_label = :field_label
WHERE id = :id
");
// Update existing field AND clear user-entered value if type changed
$updateChangedTypeStmt = $pdo->prepare("
UPDATE template_mapping
SET
schema_id = :schema_id,
data_type = :data_type,
is_required = :is_required,
default_value = :default_value,
has_list = :has_list,
length = :length,
decimals = :decimals,
min_value = :min_value,
max_value = :max_value,
default_curr_date = :default_curr_date,
tablename = :tablename,
field_label = :field_label,
manual_default = NULL,
auto_value = 'none'
WHERE id = :id
");
$currentFieldIds = [];
/*
* 2) Insert new fields and update existing fields
*/
foreach ($schema_fields as $field) { foreach ($schema_fields as $field) {
$custom_field = $field['CustomField'] ?? []; $custom_field = $field['CustomField'] ?? [];
if (empty($custom_field['IdCustomField'])) { if (empty($custom_field['IdCustomField'])) {
continue; // Salta se manca l'ID del campo continue;
} }
$insert_stmt->execute([ $fieldId = (int)$custom_field['IdCustomField'];
':template_id' => $template_id, $currentFieldIds[] = $fieldId;
$newDataType = $custom_field['Tipo'] ?? 'Testo';
$data = [
':schema_id' => $schema_id, ':schema_id' => $schema_id,
':field_id' => $custom_field['IdCustomField'], ':data_type' => $newDataType,
':data_type' => $custom_field['Tipo'] ?? 'Testo', ':is_required' => !empty($custom_field['ObbligatorioWeb']) ? 1 : 0,
':is_required' => $custom_field['ObbligatorioWeb'] ? 1 : 0,
':default_value' => $custom_field['ValoreDefault'] ?? null, ':default_value' => $custom_field['ValoreDefault'] ?? null,
':has_list' => $custom_field['Elenco'] ? 1 : 0, ':has_list' => !empty($custom_field['Elenco']) ? 1 : 0,
':length' => $custom_field['Lunghezza'] ?? 0, ':length' => $custom_field['Lunghezza'] ?? 0,
':decimals' => $custom_field['Decimali'] ?? 0, ':decimals' => $custom_field['Decimali'] ?? 0,
':min_value' => $custom_field['Minimo'] ?? null, ':min_value' => $custom_field['Minimo'] ?? null,
':max_value' => $custom_field['Massimo'] ?? null, ':max_value' => $custom_field['Massimo'] ?? null,
':default_curr_date' => $custom_field['DefaultCurrDate'] ? 1 : 0, ':default_curr_date' => !empty($custom_field['DefaultCurrDate']) ? 1 : 0,
':tablename' => $target_table, ':tablename' => $target_table,
':field_label' => $custom_field['TitoloTraduzione'] ?? '', ':field_label' => $custom_field['TitoloTraduzione'] ?? ''
':template_id_check' => $template_id, ];
':field_id_check' => $custom_field['IdCustomField']
]); $checkStmt->execute([$template_id, $fieldId]);
$existing = $checkStmt->fetch(PDO::FETCH_ASSOC);
if (!$existing) {
// New field: insert it
$insertData = $data;
$insertData[':template_id'] = $template_id;
$insertData[':field_id'] = $fieldId;
$insertStmt->execute($insertData);
} else {
// Existing field: update schema details
$oldDataType = $existing['data_type'] ?? '';
$updateData = $data;
$updateData[':id'] = (int)$existing['id'];
if ($oldDataType !== $newDataType) {
// Type changed: clear manual value because it may no longer be valid
$updateChangedTypeStmt->execute($updateData);
} else {
// Same type: keep manual_default, excel/json mapping, visibility, main field, etc.
$updateSameTypeStmt->execute($updateData);
}
}
}
/*
* 3) Remove fields no longer present in the schema
*/
$currentFieldIds = array_values(array_unique(array_filter($currentFieldIds)));
if (!empty($currentFieldIds)) {
$placeholders = implode(',', array_fill(0, count($currentFieldIds), '?'));
$deleteParams = array_merge([$template_id], $currentFieldIds);
$deleteStmt = $pdo->prepare("
DELETE FROM template_mapping
WHERE template_id = ?
AND field_id NOT IN ($placeholders)
");
$deleteStmt->execute($deleteParams);
} }
// Commit della transazione
$pdo->commit(); $pdo->commit();
$response["success"] = true; $response["success"] = true;
$response["message"] = "Schema JSON updated and template mappings created successfully!"; $response["message"] = "Schema JSON updated, mappings synchronized, removed fields deleted, and changed fields updated successfully.";
} catch (Exception $e) { } catch (Exception $e) {
if (isset($pdo) && $pdo->inTransaction()) { if (isset($pdo) && $pdo->inTransaction()) {
$pdo->rollback(); $pdo->rollback();
} }
$response["message"] = $e->getMessage(); $response["message"] = $e->getMessage();
} }
// Restituisce un JSON per il fetch
echo json_encode($response); echo json_encode($response);