update schema
This commit is contained in:
parent
b38f3e1240
commit
aa355905d7
@ -2,7 +2,6 @@
|
||||
header('Content-Type: application/json');
|
||||
require_once 'class/db-functions.php';
|
||||
|
||||
// Disabilita l'output di errori HTML
|
||||
ini_set('display_errors', '0');
|
||||
error_reporting(E_ALL);
|
||||
|
||||
@ -13,108 +12,235 @@ try {
|
||||
throw new Exception("Invalid request method.");
|
||||
}
|
||||
|
||||
// Recupera i dati dal body JSON
|
||||
$input = json_decode(file_get_contents('php://input'), true);
|
||||
$template_id = isset($input['template_id']) ? intval($input['template_id']) : null;
|
||||
$schemajson = isset($input['schemajson']) ? trim($input['schemajson']) : '';
|
||||
|
||||
// Controllo sui campi obbligatori
|
||||
$template_id = isset($input['template_id']) ? intval($input['template_id']) : null;
|
||||
$schemajson = isset($input['schemajson']) ? trim($input['schemajson']) : '';
|
||||
|
||||
if (empty($template_id) || empty($schemajson)) {
|
||||
throw new Exception("All fields marked with * are required, including schemajson.");
|
||||
}
|
||||
|
||||
// Validazione del JSON
|
||||
$decoded_json = json_decode($schemajson, true);
|
||||
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
throw new Exception("Invalid JSON format for schemajson.");
|
||||
}
|
||||
|
||||
// Connessione al database
|
||||
$db = DBHandlerSelect::getInstance();
|
||||
$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->execute([$template_id]);
|
||||
$template = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
if (!$template) {
|
||||
throw new Exception("Template not found.");
|
||||
}
|
||||
|
||||
$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_fields = $decoded_json['SchemiCustomFieldsDettagli'] ?? [];
|
||||
|
||||
if (empty($schema_id)) {
|
||||
throw new Exception("Schema ID not found in schemajson.");
|
||||
}
|
||||
|
||||
if (empty($schema_fields)) {
|
||||
throw new Exception("No fields found in schema.");
|
||||
}
|
||||
|
||||
// Prepara la query per l'inserimento condizionato in template_mapping
|
||||
$insert_stmt = $pdo->prepare("
|
||||
$pdo->beginTransaction();
|
||||
|
||||
/*
|
||||
* 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 (
|
||||
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
|
||||
)
|
||||
SELECT :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
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM template_mapping
|
||||
WHERE template_id = :template_id_check AND field_id = :field_id_check
|
||||
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
|
||||
) 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) {
|
||||
$custom_field = $field['CustomField'] ?? [];
|
||||
|
||||
if (empty($custom_field['IdCustomField'])) {
|
||||
continue; // Salta se manca l'ID del campo
|
||||
continue;
|
||||
}
|
||||
|
||||
$insert_stmt->execute([
|
||||
':template_id' => $template_id,
|
||||
':schema_id' => $schema_id,
|
||||
':field_id' => $custom_field['IdCustomField'],
|
||||
':data_type' => $custom_field['Tipo'] ?? 'Testo',
|
||||
':is_required' => $custom_field['ObbligatorioWeb'] ? 1 : 0,
|
||||
':default_value' => $custom_field['ValoreDefault'] ?? null,
|
||||
':has_list' => $custom_field['Elenco'] ? 1 : 0,
|
||||
':length' => $custom_field['Lunghezza'] ?? 0,
|
||||
':decimals' => $custom_field['Decimali'] ?? 0,
|
||||
':min_value' => $custom_field['Minimo'] ?? null,
|
||||
':max_value' => $custom_field['Massimo'] ?? null,
|
||||
':default_curr_date' => $custom_field['DefaultCurrDate'] ? 1 : 0,
|
||||
':tablename' => $target_table,
|
||||
':field_label' => $custom_field['TitoloTraduzione'] ?? '',
|
||||
':template_id_check' => $template_id,
|
||||
':field_id_check' => $custom_field['IdCustomField']
|
||||
]);
|
||||
$fieldId = (int)$custom_field['IdCustomField'];
|
||||
$currentFieldIds[] = $fieldId;
|
||||
|
||||
$newDataType = $custom_field['Tipo'] ?? 'Testo';
|
||||
|
||||
$data = [
|
||||
':schema_id' => $schema_id,
|
||||
':data_type' => $newDataType,
|
||||
':is_required' => !empty($custom_field['ObbligatorioWeb']) ? 1 : 0,
|
||||
':default_value' => $custom_field['ValoreDefault'] ?? null,
|
||||
':has_list' => !empty($custom_field['Elenco']) ? 1 : 0,
|
||||
':length' => $custom_field['Lunghezza'] ?? 0,
|
||||
':decimals' => $custom_field['Decimali'] ?? 0,
|
||||
':min_value' => $custom_field['Minimo'] ?? null,
|
||||
':max_value' => $custom_field['Massimo'] ?? null,
|
||||
':default_curr_date' => !empty($custom_field['DefaultCurrDate']) ? 1 : 0,
|
||||
':tablename' => $target_table,
|
||||
':field_label' => $custom_field['TitoloTraduzione'] ?? ''
|
||||
];
|
||||
|
||||
$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();
|
||||
|
||||
$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) {
|
||||
if (isset($pdo) && $pdo->inTransaction()) {
|
||||
$pdo->rollback();
|
||||
}
|
||||
|
||||
$response["message"] = $e->getMessage();
|
||||
}
|
||||
|
||||
// Restituisce un JSON per il fetch
|
||||
echo json_encode($response);
|
||||
Loading…
x
Reference in New Issue
Block a user