getConnection(); header("Content-Type: application/json"); // 🔹 Configura directory log (creala se non esiste) $logDir = __DIR__ . '/logs/api/'; if (!is_dir($logDir)) { mkdir($logDir, 0755, true); } // 🔹 Base URL API $apiBaseUrl = 'https://93.43.5.102/limsapi/api/odata/'; // 🔹 Funzione per validare e convertire date function validateDate($value) { // Prova a validare come data (accetta formati comuni) $date = DateTime::createFromFormat('Y-m-d', $value) ?: DateTime::createFromFormat('Y-m-d H:i:s', $value); if ($date) { return $date->format('Y-m-d\TH:i:sP'); // Formato ISO 8601 } return null; // Imposta null se non è una data valida } try { $iddatadb = $_POST['iddatadb'] ?? null; if (!$iddatadb) { throw new Exception("Missing iddatadb"); } // 🔹 STEP 1+2: Fetch Cliente ID from datadb and Schema ID from excel_templates $stmt = $pdo->prepare(" SELECT d.idclient AS clienteId, et.idschema AS schemaId FROM datadb as d INNER JOIN excel_templates as et ON d.templateid = et.id WHERE d.iddatadb = :iddatadb LIMIT 1 "); $stmt->execute(['iddatadb' => $iddatadb]); $result = $stmt->fetch(PDO::FETCH_ASSOC); if (!$result) { throw new Exception("No Cliente/Schema found for iddatadb {$iddatadb}"); } $clienteId = (int) $result['clienteId']; $schemaId = (int) $result['schemaId']; // 🔹 STEP 3: Fetch Parts (including idmatrice) $stmt = $pdo->prepare(" SELECT part_number, part_description, material, color, mix, idmatrice FROM identification_parts WHERE iddatadb = :iddatadb "); $stmt->execute(['iddatadb' => $iddatadb]); $parts = $stmt->fetchAll(PDO::FETCH_ASSOC); // 🔹 STEP 4: Fetch Field Values with Labels $stmt = $pdo->prepare(" SELECT idd.field_value, m.field_label, m.schema_id, m.field_id FROM import_data_details as idd JOIN template_mapping m ON idd.mapping_id = m.id WHERE idd.id = :iddatadb "); $stmt->execute(['iddatadb' => $iddatadb]); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); $fieldValues = []; $valueMap = []; foreach ($rows as $row) { $fieldValues[] = [ "IdCommesseCustomFields" => (int) $row['field_id'], "Valore" => $row['field_value'], "FieldLabel" => $row['field_label'] ]; $valueMap[(int) $row['field_id']] = $row['field_value']; } // Logga i fieldValues in error_log $logFieldValues = "FieldValues dal DB (iddatadb={$iddatadb}):\n" . json_encode($fieldValues, JSON_PRETTY_PRINT); error_log($logFieldValues); // 🔹 Initialize API client $api = VisualLimsApiClient::getInstance(); // 🔹 STEP 5: Create CommessaWeb (NOT WebOrder) $commessaWebPayload = [ "Cliente" => $clienteId, "SchemaCustomField" => $schemaId, "Richiedente" => "Test Web Import", "Descrizione" => "TEST CommessaWeb", ]; // Costruisci log curl-like per STEP 5 $jsonPayload = json_encode($commessaWebPayload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); $logContentStep5 = "curl --location --request POST '{$apiBaseUrl}CommessaWeb' \\\n" . "--header 'Content-Type: application/json' \\\n" . "--header 'Authorization: Bearer ••••••' \\\n" . "--data '{$jsonPayload}'"; $commessaWeb = $api->post("CommessaWeb", $commessaWebPayload); $logContentStep5 .= "\n\nRESPONSE:\n" . json_encode($commessaWeb, JSON_PRETTY_PRINT); // Salva log $logFileStep5 = $logDir . "commessa_create_step5_" . $iddatadb . "_" . time() . ".txt"; file_put_contents($logFileStep5, $logContentStep5); $commessaId = $commessaWeb["IdCommessa"]; $commessaWebCode = substr($commessaWeb["CodiceCommessa"] ?? "TEST CommessaWeb", 0, 30); // Limite a 30 caratteri // 🔹 STEP 6: Create Campioni (Samples) for each part $campioni = []; $logContentStep6 = ""; foreach ($parts as $index => $part) { $matriceId = (int) ($part["idmatrice"] ?? 0); if ($matriceId <= 0) { throw new Exception("Invalid or missing idmatrice for part: " . ($part["part_number"] ?? "Unknown")); } $campionePayload = [ "Commessa" => $commessaId, "Matrice" => $matriceId, "SottoMatrice" => null, "SchemaCustomField" => $schemaId, "NoteWeb" => $part["part_description"] ?? "" ]; // Costruisci curl-like per questo campione $jsonPayload = json_encode($campionePayload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); $logContentStep6 .= "CAMPIONE #{$index}\n" . "curl --location --request POST '{$apiBaseUrl}Campione' \\\n" . "--header 'Content-Type: application/json' \\\n" . "--header 'Authorization: Bearer ••••••' \\\n" . "--data '{$jsonPayload}'\n\n"; $campione = $api->post("Campione", $campionePayload); $logContentStep6 .= "RESPONSE:\n" . json_encode($campione, JSON_PRETTY_PRINT) . "\n\n---\n"; $campione["PartNumber"] = $part["part_number"] ?? ""; $campione["Material"] = $part["material"] ?? ""; $campione["Color"] = $part["color"] ?? ""; $campione["Mix"] = $part["mix"] ?? ""; $campioni[] = $campione; } // Salva log per STEP 6 $logFileStep6 = $logDir . "commessa_{$commessaId}_campioni_step6_" . time() . ".txt"; file_put_contents($logFileStep6, $logContentStep6); // 🔹 STEP 7: Update Custom Fields for CommessaWeb if (!empty($fieldValues)) { // GET con espansione per CustomField $expand = "CommesseCustomFields(\$expand=CustomField)"; $commessaWithFields = $api->get("CommessaWeb(" . $commessaId . ")?\$expand=" . $expand); // Logga il GET $logContentGet = "curl --location --request GET '{$apiBaseUrl}CommessaWeb({$commessaId})?\$expand=CommesseCustomFields(\$expand=CustomField)' \\\n" . "--header 'Authorization: Bearer ••••••'\n\n" . "RESPONSE:\n" . json_encode($commessaWithFields, JSON_PRETTY_PRINT); $logFileGet = $logDir . "commessa_{$commessaId}_get_step7_" . time() . ".txt"; file_put_contents($logFileGet, $logContentGet); // Prepara payload PATCH $commessaCustomFields = []; foreach ($commessaWithFields["CommesseCustomFields"] as $customField) { $definitionId = (int) ($customField["CustomField"]["IdCustomField"] ?? 0); $fieldId = (int) $customField["IdCommesseCustomFields"]; $currentValue = $customField["Valore"] ?? ''; $fieldType = $customField["CustomField"]["Tipo"] ?? ''; $newValue = isset($valueMap[$definitionId]) ? $valueMap[$definitionId] : $currentValue; // Valida se il campo è di tipo Data if ($fieldType === 'Data' && $newValue !== $currentValue) { $newValue = validateDate($newValue); } $commessaCustomFields[] = [ "IdCommesseCustomFields" => $fieldId, "Valore" => $newValue ]; } if (!empty($commessaCustomFields)) { $updatePayload = ["CommesseCustomFields" => $commessaCustomFields]; // Logga payload e response $jsonPayload = json_encode($updatePayload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); $logContentStep7 = "curl --location --request PATCH '{$apiBaseUrl}CommessaWeb({$commessaId})' \\\n" . "--header 'Content-Type: application/json' \\\n" . "--header 'Authorization: Bearer ••••••' \\\n" . "--data '{$jsonPayload}'"; $patchResponse = $api->patch("CommessaWeb({$commessaId})", $updatePayload); $logContentStep7 .= "\n\nRESPONSE:\n" . json_encode($patchResponse, JSON_PRETTY_PRINT); $logFileStep7 = $logDir . "commessa_{$commessaId}_update_step7_" . time() . ".txt"; file_put_contents($logFileStep7, $logContentStep7); } } // 🔹 STEP 8: Update datadb with idcommessaweb, commessaweb, and status $stmt = $pdo->prepare(" UPDATE datadb SET idcommessaweb = :idcommessaweb, commessaweb = :commessaweb, status = 'l' WHERE iddatadb = :iddatadb "); $stmt->execute([ 'idcommessaweb' => $commessaId, 'commessaweb' => $commessaWebCode, 'iddatadb' => $iddatadb ]); // 🔹 STEP 9: Send CommessaWeb to laboratory (commentato come richiesto) /* $sendResult = $api->post("CommessaWeb({$commessaId})/InviaCommessa", []); // Logga il POST $logContentStep9 = "curl --location --request POST '{$apiBaseUrl}CommessaWeb({$commessaId})/InviaCommessa' \\\n" . "--header 'Content-Type: application/json' \\\n" . "--header 'Authorization: Bearer ••••••' \\\n" . "--data '{}'\n\n" . "RESPONSE:\n" . json_encode($sendResult, JSON_PRETTY_PRINT); $logFileStep9 = $logDir . "commessa_{$commessaId}_send_step9_" . time() . ".txt"; file_put_contents($logFileStep9, $logContentStep9); */ // 🔹 STEP 10: GET di controllo post-PATCH $expand = "CommesseCustomFields(\$expand=CustomField)"; $commessaAfterPatch = $api->get("CommessaWeb(" . $commessaId . ")?\$expand=" . $expand); // Logga il GET di controllo $logContentStep10 = "curl --location --request GET '{$apiBaseUrl}CommessaWeb({$commessaId})?\$expand=CommesseCustomFields(\$expand=CustomField)' \\\n" . "--header 'Authorization: Bearer ••••••'\n\n" . "RESPONSE:\n" . json_encode($commessaAfterPatch, JSON_PRETTY_PRINT); $logFileStep10 = $logDir . "commessa_{$commessaId}_get_step10_" . time() . ".txt"; file_put_contents($logFileStep10, $logContentStep10); // 🔹 STEP 11: Prepare final response $finalCommessa = [ "Cliente" => $clienteId, "SchemaCustomField" => $schemaId, "Richiedente" => $commessaWeb["Richiedente"] ?? "Web Import", "Descrizione" => $commessaWeb["Descrizione"] ?? "", "CommesseCustomFields" => $commessaAfterPatch["CommesseCustomFields"] ?? [], "Campioni" => $campioni, "Inviata" => 0 // Non inviato, come richiesto ]; echo json_encode([ "success" => true, "commessaWeb" => $finalCommessa, "commessaWebApiResponse" => $commessaWeb, // Incluso per debug "totalCampioni" => count($campioni), "totalCustomFields" => count($commessaAfterPatch["CommesseCustomFields"] ?? []), "message" => "Export successful", "logFiles" => [ "step5_create" => $logFileStep5, "step6_campioni" => $logFileStep6, "step7_patch" => $logFileStep7, "step10_get" => $logFileStep10 ] ]); } catch (Exception $e) { error_log("LIMS Export Error: " . $e->getMessage() . "\nTrace: " . $e->getTraceAsString()); echo json_encode([ "success" => false, "message" => "Export failed: " . $e->getMessage(), "logFiles" => [ "step5_create" => $logFileStep5 ?? null, "step6_campioni" => $logFileStep6 ?? null, "step7_patch" => $logFileStep7 ?? null, "step10_get" => $logFileStep10 ?? null ] ]); }