getConnection(); header("Content-Type: application/json"); try { $iddatadb = $_POST['iddatadb'] ?? null; if (!$iddatadb) { throw new Exception("Missing iddatadb"); } echo "✅ START Export for iddatadb={$iddatadb}\n"; // 🔹 STEP 1+2: Fetch Cliente ID + Schema ID $stmt = $pdo->prepare(" SELECT et.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']; echo "✅ Cliente={$clienteId}, Schema={$schemaId}\n"; // 🔹 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); echo "✅ Parts found: " . count($parts) . "\n"; // 🔹 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); echo "✅ Field rows found: " . count($rows) . "\n"; $fieldValues = []; foreach ($rows as $row) { $fieldValues[] = [ "IdCommesseCustomFields" => (int) $row['field_id'], "Valore" => $row['field_value'] ]; } // 🔹 Initialize API client $api = VisualLimsApiClient::getInstance(); // 🔹 STEP 5: Create CommessaWeb (NOT WebOrder) $commessaWebPayload = [ "Cliente" => $clienteId, "SchemaCustomField" => $schemaId, "Richiedente" => "Test Web Import", "Descrizione" => "TEST CommessaWeb", ]; echo "➡️ Creating CommessaWeb...\n"; $commessaWeb = $api->post("CommessaWeb", $commessaWebPayload); $commessaId = $commessaWeb["IdCommessa"]; echo "✅ CommessaWeb created: ID={$commessaId}\n"; // 🔹 STEP 6: Create Campioni (Samples) for each part $campioni = []; 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"] ?? "" ]; echo "➡️ Creating Campione {$index} with Matrice={$matriceId}\n"; $campione = $api->post("Campione", $campionePayload); $campione["PartNumber"] = $part["part_number"] ?? ""; $campione["Material"] = $part["material"] ?? ""; $campione["Color"] = $part["color"] ?? ""; $campione["Mix"] = $part["mix"] ?? ""; $campioni[] = $campione; echo "✅ Campione {$index} created: ID=" . ($campione["IdCampione"] ?? "N/A") . "\n"; } // 🔹 STEP 7: Update Custom Fields for CommessaWeb if (!empty($fieldValues)) { echo "➡️ Updating CommessaWeb Custom Fields...\n"; $commessaWithFields = $api->get("CommessaWeb(" . $commessaId . ")?\$expand=CommesseCustomFields"); $commessaCustomFields = []; foreach ($commessaWithFields["CommesseCustomFields"] as $customField) { foreach ($fieldValues as $fieldValue) { if ($customField["IdCommesseCustomFields"] == $fieldValue["IdCommesseCustomFields"]) { $commessaCustomFields[] = [ "IdCommesseCustomFields" => $customField["IdCommesseCustomFields"], "Valore" => $fieldValue["Valore"] ]; break; } } } if (!empty($commessaCustomFields)) { $updatePayload = ["CommesseCustomFields" => $commessaCustomFields]; $api->patch("CommessaWeb({$commessaId})", $updatePayload); echo "✅ CommessaWeb Custom Fields updated\n"; } } // 🔹 STEP 9: Send CommessaWeb to laboratory echo "➡️ Sending CommessaWeb...\n"; $sendResult = $api->post("CommessaWeb({$commessaId})/InviaCommessa", []); echo "✅ CommessaWeb sent to Lab\n"; // 🔹 STEP 10: Prepare final response $finalCommessa = [ "Cliente" => $clienteId, "SchemaCustomField" => $schemaId, "Richiedente" => $commessaWeb["Richiedente"] ?? "Web Import", "Descrizione" => $commessaWeb["Descrizione"] ?? "", "CommesseCustomFields" => $fieldValues, "Campioni" => $campioni, "Inviata" => 1 ]; echo json_encode([ "success" => true, "commessaWeb" => $finalCommessa, "totalCampioni" => count($campioni), "totalCustomFields" => count($fieldValues) ]); } catch (Exception $e) { error_log("LIMS Export Error: " . $e->getMessage() . "\nTrace: " . $e->getTraceAsString()); echo json_encode([ "success" => false, "message" => "Export failed: " . $e->getMessage() ]); }