From 33e3ae059d777eec0164d26abb165c555eb4a61a Mon Sep 17 00:00:00 2001 From: kapsona777 Date: Tue, 9 Sep 2025 17:28:48 +0400 Subject: [PATCH 1/8] this commit is uploaded for testing only, no api calls are made --- .../class/VisualLimsApiClient.class.php | 67 +++++++++++++ public/userarea/export_to_lims.php | 96 +++++++++++++++++++ public/userarea/import_edit2.php | 28 +++++- 3 files changed, 190 insertions(+), 1 deletion(-) create mode 100644 public/userarea/export_to_lims.php diff --git a/public/userarea/class/VisualLimsApiClient.class.php b/public/userarea/class/VisualLimsApiClient.class.php index e9b4a80..48e600e 100644 --- a/public/userarea/class/VisualLimsApiClient.class.php +++ b/public/userarea/class/VisualLimsApiClient.class.php @@ -120,4 +120,71 @@ class VisualLimsApiClient return $data; } + + public function post($endpoint, $payload) + { + $token = $this->getToken(); + $url = "{$this->baseUrl}/api/odata/{$endpoint}"; + + $ch = curl_init($url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload)); + curl_setopt($ch, CURLOPT_HTTPHEADER, [ + "Authorization: Bearer {$token}", + "Content-Type: application/json", + "Accept: application/json" + ]); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); + + $response = curl_exec($ch); + $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); + $curl_error = curl_error($ch); + curl_close($ch); + + if ($response === false) { + throw new Exception("Errore nella richiesta POST: {$curl_error}"); + } + + if ($http_code < 200 || $http_code >= 300) { + throw new Exception("POST fallito: HTTP {$http_code}, Risposta: " . substr($response, 0, 1000)); + } + + return json_decode($response, true); + } + + public function patch($endpoint, $payload) + { + $token = $this->getToken(); + $url = "{$this->baseUrl}/api/odata/{$endpoint}"; + + $ch = curl_init($url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH"); + curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload)); + curl_setopt($ch, CURLOPT_HTTPHEADER, [ + "Authorization: Bearer {$token}", + "Content-Type: application/json", + "Accept: application/json" + ]); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); + + $response = curl_exec($ch); + $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); + $curl_error = curl_error($ch); + curl_close($ch); + + if ($response === false) { + throw new Exception("Errore nella richiesta PATCH: {$curl_error}"); + } + + if ($http_code < 200 || $http_code >= 300) { + throw new Exception("PATCH fallito: HTTP {$http_code}, Risposta: " . substr($response, 0, 1000)); + } + + return json_decode($response, true); + } + } diff --git a/public/userarea/export_to_lims.php b/public/userarea/export_to_lims.php new file mode 100644 index 0000000..2a09ebf --- /dev/null +++ b/public/userarea/export_to_lims.php @@ -0,0 +1,96 @@ +getConnection(); + +header("Content-Type: application/json"); + +try { + $iddatadb = $_POST['iddatadb'] ?? null; + if (!$iddatadb) { + throw new Exception("Missing iddatadb"); + } + + // ⚠️ IMPORTANT: Disable API calls, keep only DB real + $simulate = true; + + // 🔹 STEP 1: Fetch Cliente ID from your DB + // get client id here + + $clienteId = 12345; // Replace with actual client ID fetching logic + + // 🔹 STEP 2: Fetch Parts (Campioni) for this record + $stmt = $pdo->prepare(" + SELECT part_number, part_description, material, color, mix + FROM identification_parts + WHERE iddatadb = :iddatadb + "); + $stmt->execute(['iddatadb' => $iddatadb]); + $parts = $stmt->fetchAll(PDO::FETCH_ASSOC); + + // 🔹 STEP 3: Fetch Field Values from import_data_details + $stmt = $pdo->prepare(" + SELECT mapping_id, field_value + FROM import_data_details + WHERE id = :iddatadb + "); + $stmt->execute(['iddatadb' => $iddatadb]); + $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); + + $fieldValues = []; + foreach ($rows as $row) { + $fieldValues[] = [ + "MappingId" => (int) $row['mapping_id'], + "FieldValue" => $row['field_value'] + ]; + } + + if ($simulate) { + // Simulated CommessaWeb + $commessaId = 999999; + $commessa = [ + "IdCommessa" => $commessaId, + "CodiceCommessa" => "TEST001", + "StatoCommessaWeb" => "Nuova", + "Cliente" => $clienteId + ]; + + // Use REAL parts fetched from DB + $createdParts = []; + foreach ($parts as $p) { + $createdParts[] = array_merge($p, [ + "Commessa" => $commessaId, + // optional: give each part a fake Campione ID just for simulation + "IdCampione" => rand(1000, 9999) + ]); + } + + // Simulated CommessaField values + $createdFields = []; + foreach ($fieldValues as $f) { + $createdFields[] = [ + "Commessa" => $commessaId, + "MappingId" => $f["MappingId"], + "FieldValue" => $f["FieldValue"], + "IdCommessaField" => rand(2000, 9999) + ]; + } + } + + echo json_encode([ + "success" => true, + "commessaId" => $commessaId, + "commessa" => $commessa, + "parts" => $createdParts, // now comes from DB + "fields" => $createdFields, // simulated push + "simulation" => $simulate + ]); + +} catch (Exception $e) { + echo json_encode([ + "success" => false, + "message" => $e->getMessage() + ]); +} diff --git a/public/userarea/import_edit2.php b/public/userarea/import_edit2.php index e23039d..7c48046 100644 --- a/public/userarea/import_edit2.php +++ b/public/userarea/import_edit2.php @@ -709,6 +709,32 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) { - \ No newline at end of file + From ac09d8d0eb43e2c81ac6600c43a33f1e3c1b69c3 Mon Sep 17 00:00:00 2001 From: kapsona777 Date: Wed, 10 Sep 2025 20:30:02 +0400 Subject: [PATCH 2/8] =?UTF-8?q?fixed=20issue,=20now=20works=20great.=20//?= =?UTF-8?q?=20=E2=9A=A0=EF=B8=8F=20Simulation=20ON=20(change=20it=20to=20f?= =?UTF-8?q?alse=20to=20enable=20real=20API=20calls)=20=20=20=20=20=20=20?= =?UTF-8?q?=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20?= =?UTF-8?q?=20=20=20=20=20=20=20$simulate=20=3D=20true;?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- public/userarea/export_to_lims.php | 92 ++++++++++++++++++------------ public/userarea/import_edit2.php | 4 +- 2 files changed, 59 insertions(+), 37 deletions(-) diff --git a/public/userarea/export_to_lims.php b/public/userarea/export_to_lims.php index 2a09ebf..110ef21 100644 --- a/public/userarea/export_to_lims.php +++ b/public/userarea/export_to_lims.php @@ -13,15 +13,28 @@ try { throw new Exception("Missing iddatadb"); } - // ⚠️ IMPORTANT: Disable API calls, keep only DB real + // ⚠️ Simulation ON (change it to false to enable real API calls) $simulate = true; - // 🔹 STEP 1: Fetch Cliente ID from your DB - // get client id here + // 🔹 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); - $clienteId = 12345; // Replace with actual client ID fetching logic + if (!$result) { + throw new Exception("No Cliente/Schema found for iddatadb {$iddatadb}"); + } - // 🔹 STEP 2: Fetch Parts (Campioni) for this record + $clienteId = (int) $result['clienteId']; + $schemaId = (int) $result['schemaId']; + + // 🔹 STEP 3: Fetch Parts $stmt = $pdo->prepare(" SELECT part_number, part_description, material, color, mix FROM identification_parts @@ -30,61 +43,70 @@ try { $stmt->execute(['iddatadb' => $iddatadb]); $parts = $stmt->fetchAll(PDO::FETCH_ASSOC); - // 🔹 STEP 3: Fetch Field Values from import_data_details + // 🔹 STEP 4: Fetch Field Values with Labels $stmt = $pdo->prepare(" - SELECT mapping_id, field_value - FROM import_data_details - WHERE id = :iddatadb - "); - $stmt->execute(['iddatadb' => $iddatadb]); + SELECT + idd.field_value, + m.field_label + 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 = []; foreach ($rows as $row) { $fieldValues[] = [ - "MappingId" => (int) $row['mapping_id'], + "FieldLabel" => $row['field_label'], "FieldValue" => $row['field_value'] ]; } + // 🔹 Simulation Mode if ($simulate) { - // Simulated CommessaWeb $commessaId = 999999; $commessa = [ - "IdCommessa" => $commessaId, + "IdCommessa" => $commessaId, "CodiceCommessa" => "TEST001", - "StatoCommessaWeb" => "Nuova", - "Cliente" => $clienteId + "IdCliente" => $clienteId, + "Fields" => $fieldValues ]; + } else { + // 🔹 REAL API FLOW + $api = VisualLimsApiClient::getInstance(); - // Use REAL parts fetched from DB - $createdParts = []; - foreach ($parts as $p) { - $createdParts[] = array_merge($p, [ - "Commessa" => $commessaId, - // optional: give each part a fake Campione ID just for simulation - "IdCampione" => rand(1000, 9999) - ]); - } + // 1. Create CommessaWeb + $commessaPayload = [ + "IdCliente" => $clienteId, + "IdSchemaCustomFields" => $schemaId, + "Inviato" => 1 + ]; + $commessa = $api->post("CommessaWeb", $commessaPayload); + $commessaId = $commessa["IdCommessa"]; - // Simulated CommessaField values - $createdFields = []; + // 2. Push Fields + $fields = []; foreach ($fieldValues as $f) { - $createdFields[] = [ - "Commessa" => $commessaId, - "MappingId" => $f["MappingId"], - "FieldValue" => $f["FieldValue"], - "IdCommessaField" => rand(2000, 9999) + $fieldPayload = [ + "Commessa" => $commessaId, + "FieldLabel" => $f["FieldLabel"], + "FieldValue" => $f["FieldValue"] ]; + $res = $api->post("CommessaField", $fieldPayload); + $fields[] = $res; } + + $commessa["Fields"] = $fields; } echo json_encode([ "success" => true, - "commessaId" => $commessaId, "commessa" => $commessa, - "parts" => $createdParts, // now comes from DB - "fields" => $createdFields, // simulated push + "parts" => $parts, "simulation" => $simulate ]); diff --git a/public/userarea/import_edit2.php b/public/userarea/import_edit2.php index 7c48046..2956644 100644 --- a/public/userarea/import_edit2.php +++ b/public/userarea/import_edit2.php @@ -724,7 +724,7 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) { }, success: function (response) { if (response.success) { - alert("✅ CommessaWeb created. ID: " + response.commessaId); + alert("✅ CommessaWeb created. ID: " + response.comessa); } else { alert("❌ Error: " + response.message); } @@ -734,7 +734,7 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) { } }); }); - + document.addEventListener("DOMContentLoaded", function() { console.log("Page loaded, initializing event listeners"); From 586226ceaf1cbd02a0f0fa4177633f88e301ed6e Mon Sep 17 00:00:00 2001 From: kapsona777 Date: Wed, 10 Sep 2025 20:54:31 +0400 Subject: [PATCH 3/8] fixed alert issue --- public/userarea/export_to_lims.php | 5 ++++- public/userarea/import_edit2.php | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/public/userarea/export_to_lims.php b/public/userarea/export_to_lims.php index 110ef21..3d6f0f4 100644 --- a/public/userarea/export_to_lims.php +++ b/public/userarea/export_to_lims.php @@ -73,7 +73,9 @@ try { "IdCommessa" => $commessaId, "CodiceCommessa" => "TEST001", "IdCliente" => $clienteId, - "Fields" => $fieldValues + "IdSchema" => $schemaId, + "Fields" => $fieldValues, + "Inviato" => 1 ]; } else { // 🔹 REAL API FLOW @@ -82,6 +84,7 @@ try { // 1. Create CommessaWeb $commessaPayload = [ "IdCliente" => $clienteId, + "IdSchema" => $schemaId, "IdSchemaCustomFields" => $schemaId, "Inviato" => 1 ]; diff --git a/public/userarea/import_edit2.php b/public/userarea/import_edit2.php index 2956644..419f056 100644 --- a/public/userarea/import_edit2.php +++ b/public/userarea/import_edit2.php @@ -724,7 +724,7 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) { }, success: function (response) { if (response.success) { - alert("✅ CommessaWeb created. ID: " + response.comessa); + alert("✅ CommessaWeb created. ID: " + response.commessa.IdCommessa); } else { alert("❌ Error: " + response.message); } From 412dce8941563a8fc19d744169c7fa70c04ddb6c Mon Sep 17 00:00:00 2001 From: kapsona777 Date: Thu, 11 Sep 2025 18:46:47 +0400 Subject: [PATCH 4/8] refactored api code --- public/userarea/export_to_lims.php | 207 ++++++++++++++++++++++------- public/userarea/import_edit2.php | 2 +- 2 files changed, 157 insertions(+), 52 deletions(-) diff --git a/public/userarea/export_to_lims.php b/public/userarea/export_to_lims.php index 3d6f0f4..2c868ed 100644 --- a/public/userarea/export_to_lims.php +++ b/public/userarea/export_to_lims.php @@ -45,77 +45,182 @@ try { // 🔹 STEP 4: Fetch Field Values with Labels $stmt = $pdo->prepare(" - SELECT - idd.field_value, - m.field_label - FROM - import_data_details as idd - JOIN template_mapping m ON idd.mapping_id = m.id - WHERE idd.id = :iddatadb -"); - $stmt->execute([ - 'iddatadb' => $iddatadb - ]); + 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 = []; foreach ($rows as $row) { $fieldValues[] = [ "FieldLabel" => $row['field_label'], - "FieldValue" => $row['field_value'] + "FieldValue" => $row['field_value'], + "SchemaId" => (int) $row['schema_id'], + "FieldId" => (int) $row['field_id'] ]; } - // 🔹 Simulation Mode + // 🔹 Initialize API client (even in simulation mode for consistency) + $api = null; + if (!$simulate) { + $api = VisualLimsApiClient::getInstance(); + } + + // 🔹 STEP 5: Create WebOrder + $webOrderPayload = [ + "Customer" => $clienteId + ]; + if ($simulate) { - $commessaId = 999999; - $commessa = [ - "IdCommessa" => $commessaId, - "CodiceCommessa" => "TEST001", - "IdCliente" => $clienteId, - "IdSchema" => $schemaId, - "Fields" => $fieldValues, - "Inviato" => 1 + // Simulate WebOrder creation + $webOrder = [ + "Id" => 999999, + "Code" => "TEST-WO-001", + "Customer" => $clienteId, + "CreatedDate" => date('c'), + "Status" => "Draft" ]; } else { - // 🔹 REAL API FLOW - $api = VisualLimsApiClient::getInstance(); - - // 1. Create CommessaWeb - $commessaPayload = [ - "IdCliente" => $clienteId, - "IdSchema" => $schemaId, - "IdSchemaCustomFields" => $schemaId, - "Inviato" => 1 - ]; - $commessa = $api->post("CommessaWeb", $commessaPayload); - $commessaId = $commessa["IdCommessa"]; - - // 2. Push Fields - $fields = []; - foreach ($fieldValues as $f) { - $fieldPayload = [ - "Commessa" => $commessaId, - "FieldLabel" => $f["FieldLabel"], - "FieldValue" => $f["FieldValue"] - ]; - $res = $api->post("CommessaField", $fieldPayload); - $fields[] = $res; - } - - $commessa["Fields"] = $fields; + // Real API call + $webOrder = $api->post("odata/WebOrder", $webOrderPayload); } + $webOrderId = $webOrder["Id"]; + + // 🔹 STEP 6: Create Samples for each part + $samples = []; + foreach ($parts as $index => $part) { + $samplePayload = [ + "OrderId" => $webOrderId, + "Description" => $part["part_description"] ?? "", + "SampleCode" => $part["part_number"] ?? "", + "Material" => $part["material"] ?? "", + "Color" => $part["color"] ?? "", + "Mix" => $part["mix"] ?? "" + ]; + + if ($simulate) { + // Simulate Sample creation + $sample = [ + "Id" => 888000 + $index, + "OrderId" => $webOrderId, + "Description" => $part["part_description"] ?? "", + "SampleCode" => $part["part_number"] ?? "", + "Material" => $part["material"] ?? "", + "Color" => $part["color"] ?? "", + "Mix" => $part["mix"] ?? "", + "Status" => "Created", + "CreatedDate" => date('c') + ]; + } else { + // Real API call + $sample = $api->post("odata/Sample", $samplePayload); + } + + $samples[] = $sample; + } + + // 🔹 STEP 7: Handle Custom Fields for each sample + $samplesWithCustomFields = []; + foreach ($samples as $sample) { + $sampleId = $sample["Id"]; + + if ($simulate) { + // Simulate getting sample with custom fields + $sampleWithFields = $sample; + $sampleWithFields["CustomFieldSamples"] = []; + + // Simulate custom field updates + foreach ($fieldValues as $fieldIndex => $fieldValue) { + $customField = [ + "Id" => 777000 + $fieldIndex, + "SampleId" => $sampleId, + "FieldLabel" => $fieldValue["FieldLabel"], + "FieldValue" => $fieldValue["FieldValue"], + "UpdatedDate" => date('c') + ]; + $sampleWithFields["CustomFieldSamples"][] = $customField; + } + } else { + // Real API calls + // Get sample with custom fields expanded + $sampleWithFields = $api->get("odata/Sample({$sampleId})?$expand=CustomFieldSamples"); + + // Update custom fields (this depends on the actual API structure) + foreach ($fieldValues as $fieldValue) { + // This might need to be adjusted based on the actual Custom Fields API structure + $customFieldPayload = [ + "SampleId" => $sampleId, + "FieldLabel" => $fieldValue["FieldLabel"], + "FieldValue" => $fieldValue["FieldValue"] + ]; + + try { + $customFieldResult = $api->post("odata/CustomFieldSample", $customFieldPayload); + } catch (Exception $e) { + // Log custom field error but don't fail the entire process + error_log("Custom Field Error for Sample {$sampleId}: " . $e->getMessage()); + } + } + + // Re-fetch sample with updated custom fields + $sampleWithFields = $api->get("odata/Sample({$sampleId})?$expand=CustomFieldSamples"); + } + + $samplesWithCustomFields[] = $sampleWithFields; + } + + // 🔹 STEP 8: Optionally send the order to laboratory + $orderSent = false; + if (!$simulate) { + try { + $sendResult = $api->post("odata/WebOrder({$webOrderId})/SendOrder", []); + $orderSent = true; + } catch (Exception $e) { + // Log error but don't fail the process + error_log("Send Order Error: " . $e->getMessage()); + } + } + + // 🔹 STEP 9: Prepare final response + $finalWebOrder = [ + "IdCommessa" => $webOrderId, + "CodiceCommessa" => $webOrder["Code"] ?? "N/A", + "IdCliente" => $clienteId, + "IdSchema" => $schemaId, + "Customer" => $webOrder["Customer"] ?? $clienteId, + "Status" => $webOrder["Status"] ?? "Draft", + "CreatedDate" => $webOrder["CreatedDate"] ?? date('c'), + "Fields" => $fieldValues, + "Samples" => $samplesWithCustomFields, + "Inviato" => $orderSent ? 1 : 0 + ]; + + // 🔹 Final Response echo json_encode([ "success" => true, - "commessa" => $commessa, - "parts" => $parts, - "simulation" => $simulate + "webOrder" => $finalWebOrder, + "totalSamples" => count($samplesWithCustomFields), + "totalCustomFields" => count($fieldValues), + "simulation" => $simulate, + "orderSent" => $orderSent ]); } catch (Exception $e) { + // Log the error for debugging + error_log("LIMS Export Error: " . $e->getMessage() . "\nTrace: " . $e->getTraceAsString()); + echo json_encode([ "success" => false, - "message" => $e->getMessage() + "message" => "Export failed: " . $e->getMessage(), + "simulation" => $simulate ?? true ]); } diff --git a/public/userarea/import_edit2.php b/public/userarea/import_edit2.php index 419f056..8f85f47 100644 --- a/public/userarea/import_edit2.php +++ b/public/userarea/import_edit2.php @@ -724,7 +724,7 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) { }, success: function (response) { if (response.success) { - alert("✅ CommessaWeb created. ID: " + response.commessa.IdCommessa); + alert("✅ CommessaWeb created. ID: " + response.webOrder.IdCommessa); } else { alert("❌ Error: " + response.message); } From 0a6fb98476165009b262cfdffb0a7e9798ac1d0e Mon Sep 17 00:00:00 2001 From: kapsona777 Date: Mon, 22 Sep 2025 20:16:56 +0400 Subject: [PATCH 5/8] Lims api working version with comments --- .../class/VisualLimsApiClient.class.php | 5 + public/userarea/export_to_lims.php | 212 +++++++----------- 2 files changed, 85 insertions(+), 132 deletions(-) diff --git a/public/userarea/class/VisualLimsApiClient.class.php b/public/userarea/class/VisualLimsApiClient.class.php index 48e600e..f1df702 100644 --- a/public/userarea/class/VisualLimsApiClient.class.php +++ b/public/userarea/class/VisualLimsApiClient.class.php @@ -187,4 +187,9 @@ class VisualLimsApiClient return json_decode($response, true); } + public function getBaseUrl() + { + return $this->baseUrl; + } + } diff --git a/public/userarea/export_to_lims.php b/public/userarea/export_to_lims.php index 2c868ed..3331fae 100644 --- a/public/userarea/export_to_lims.php +++ b/public/userarea/export_to_lims.php @@ -13,8 +13,7 @@ try { throw new Exception("Missing iddatadb"); } - // ⚠️ Simulation ON (change it to false to enable real API calls) - $simulate = true; + echo "✅ START Export for iddatadb={$iddatadb}\n"; // 🔹 STEP 1+2: Fetch Cliente ID + Schema ID $stmt = $pdo->prepare(" @@ -34,15 +33,19 @@ try { $clienteId = (int) $result['clienteId']; $schemaId = (int) $result['schemaId']; - // 🔹 STEP 3: Fetch Parts + echo "✅ Cliente={$clienteId}, Schema={$schemaId}\n"; + + // 🔹 STEP 3: Fetch Parts (including idmatrice) $stmt = $pdo->prepare(" - SELECT part_number, part_description, material, color, mix + 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 @@ -58,169 +61,114 @@ try { $stmt->execute(['iddatadb' => $iddatadb]); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); + echo "✅ Field rows found: " . count($rows) . "\n"; + $fieldValues = []; foreach ($rows as $row) { $fieldValues[] = [ - "FieldLabel" => $row['field_label'], - "FieldValue" => $row['field_value'], - "SchemaId" => (int) $row['schema_id'], - "FieldId" => (int) $row['field_id'] + "IdCommesseCustomFields" => (int) $row['field_id'], + "Valore" => $row['field_value'] ]; } - // 🔹 Initialize API client (even in simulation mode for consistency) - $api = null; - if (!$simulate) { - $api = VisualLimsApiClient::getInstance(); - } + // 🔹 Initialize API client + $api = VisualLimsApiClient::getInstance(); - // 🔹 STEP 5: Create WebOrder - $webOrderPayload = [ - "Customer" => $clienteId + // 🔹 STEP 5: Create CommessaWeb (NOT WebOrder) + $commessaWebPayload = [ + "Cliente" => $clienteId, + "SchemaCustomField" => $schemaId, + "Richiedente" => "Test Web Import", + "Descrizione" => "TEST CommessaWeb", ]; - if ($simulate) { - // Simulate WebOrder creation - $webOrder = [ - "Id" => 999999, - "Code" => "TEST-WO-001", - "Customer" => $clienteId, - "CreatedDate" => date('c'), - "Status" => "Draft" - ]; - } else { - // Real API call - $webOrder = $api->post("odata/WebOrder", $webOrderPayload); - } + echo "➡️ Creating CommessaWeb...\n"; + $commessaWeb = $api->post("CommessaWeb", $commessaWebPayload); - $webOrderId = $webOrder["Id"]; + $commessaId = $commessaWeb["IdCommessa"]; + echo "✅ CommessaWeb created: ID={$commessaId}\n"; - // 🔹 STEP 6: Create Samples for each part - $samples = []; + // 🔹 STEP 6: Create Campioni (Samples) for each part + $campioni = []; foreach ($parts as $index => $part) { - $samplePayload = [ - "OrderId" => $webOrderId, - "Description" => $part["part_description"] ?? "", - "SampleCode" => $part["part_number"] ?? "", - "Material" => $part["material"] ?? "", - "Color" => $part["color"] ?? "", - "Mix" => $part["mix"] ?? "" - ]; + $matriceId = (int) ($part["idmatrice"] ?? 0); - if ($simulate) { - // Simulate Sample creation - $sample = [ - "Id" => 888000 + $index, - "OrderId" => $webOrderId, - "Description" => $part["part_description"] ?? "", - "SampleCode" => $part["part_number"] ?? "", - "Material" => $part["material"] ?? "", - "Color" => $part["color"] ?? "", - "Mix" => $part["mix"] ?? "", - "Status" => "Created", - "CreatedDate" => date('c') - ]; - } else { - // Real API call - $sample = $api->post("odata/Sample", $samplePayload); + if ($matriceId <= 0) { + throw new Exception("Invalid or missing idmatrice for part: " . ($part["part_number"] ?? "Unknown")); } - $samples[] = $sample; + $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: Handle Custom Fields for each sample - $samplesWithCustomFields = []; - foreach ($samples as $sample) { - $sampleId = $sample["Id"]; - - if ($simulate) { - // Simulate getting sample with custom fields - $sampleWithFields = $sample; - $sampleWithFields["CustomFieldSamples"] = []; - - // Simulate custom field updates - foreach ($fieldValues as $fieldIndex => $fieldValue) { - $customField = [ - "Id" => 777000 + $fieldIndex, - "SampleId" => $sampleId, - "FieldLabel" => $fieldValue["FieldLabel"], - "FieldValue" => $fieldValue["FieldValue"], - "UpdatedDate" => date('c') - ]; - $sampleWithFields["CustomFieldSamples"][] = $customField; - } - } else { - // Real API calls - // Get sample with custom fields expanded - $sampleWithFields = $api->get("odata/Sample({$sampleId})?$expand=CustomFieldSamples"); - - // Update custom fields (this depends on the actual API structure) + // 🔹 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) { - // This might need to be adjusted based on the actual Custom Fields API structure - $customFieldPayload = [ - "SampleId" => $sampleId, - "FieldLabel" => $fieldValue["FieldLabel"], - "FieldValue" => $fieldValue["FieldValue"] - ]; - - try { - $customFieldResult = $api->post("odata/CustomFieldSample", $customFieldPayload); - } catch (Exception $e) { - // Log custom field error but don't fail the entire process - error_log("Custom Field Error for Sample {$sampleId}: " . $e->getMessage()); + if ($customField["IdCommesseCustomFields"] == $fieldValue["IdCommesseCustomFields"]) { + $commessaCustomFields[] = [ + "IdCommesseCustomFields" => $customField["IdCommesseCustomFields"], + "Valore" => $fieldValue["Valore"] + ]; + break; } } - - // Re-fetch sample with updated custom fields - $sampleWithFields = $api->get("odata/Sample({$sampleId})?$expand=CustomFieldSamples"); } - $samplesWithCustomFields[] = $sampleWithFields; - } - - // 🔹 STEP 8: Optionally send the order to laboratory - $orderSent = false; - if (!$simulate) { - try { - $sendResult = $api->post("odata/WebOrder({$webOrderId})/SendOrder", []); - $orderSent = true; - } catch (Exception $e) { - // Log error but don't fail the process - error_log("Send Order Error: " . $e->getMessage()); + if (!empty($commessaCustomFields)) { + $updatePayload = ["CommesseCustomFields" => $commessaCustomFields]; + $api->patch("CommessaWeb({$commessaId})", $updatePayload); + echo "✅ CommessaWeb Custom Fields updated\n"; } } - // 🔹 STEP 9: Prepare final response - $finalWebOrder = [ - "IdCommessa" => $webOrderId, - "CodiceCommessa" => $webOrder["Code"] ?? "N/A", - "IdCliente" => $clienteId, - "IdSchema" => $schemaId, - "Customer" => $webOrder["Customer"] ?? $clienteId, - "Status" => $webOrder["Status"] ?? "Draft", - "CreatedDate" => $webOrder["CreatedDate"] ?? date('c'), - "Fields" => $fieldValues, - "Samples" => $samplesWithCustomFields, - "Inviato" => $orderSent ? 1 : 0 + // 🔹 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 ]; - // 🔹 Final Response echo json_encode([ "success" => true, - "webOrder" => $finalWebOrder, - "totalSamples" => count($samplesWithCustomFields), - "totalCustomFields" => count($fieldValues), - "simulation" => $simulate, - "orderSent" => $orderSent + "commessaWeb" => $finalCommessa, + "totalCampioni" => count($campioni), + "totalCustomFields" => count($fieldValues) ]); } catch (Exception $e) { - // Log the error for debugging error_log("LIMS Export Error: " . $e->getMessage() . "\nTrace: " . $e->getTraceAsString()); echo json_encode([ "success" => false, - "message" => "Export failed: " . $e->getMessage(), - "simulation" => $simulate ?? true + "message" => "Export failed: " . $e->getMessage() ]); } From a36dd0277185ca4b9c82dbbb803589b24bee1591 Mon Sep 17 00:00:00 2001 From: kapsona777 Date: Mon, 22 Sep 2025 20:24:53 +0400 Subject: [PATCH 6/8] Lims api working version without comment --- public/userarea/export_to_lims.php | 20 ++------------------ public/userarea/import_edit2.php | 2 +- 2 files changed, 3 insertions(+), 19 deletions(-) diff --git a/public/userarea/export_to_lims.php b/public/userarea/export_to_lims.php index 3331fae..7b01e66 100644 --- a/public/userarea/export_to_lims.php +++ b/public/userarea/export_to_lims.php @@ -13,8 +13,6 @@ try { 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 @@ -33,8 +31,6 @@ try { $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 @@ -44,8 +40,6 @@ try { $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 @@ -61,8 +55,6 @@ try { $stmt->execute(['iddatadb' => $iddatadb]); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); - echo "✅ Field rows found: " . count($rows) . "\n"; - $fieldValues = []; foreach ($rows as $row) { $fieldValues[] = [ @@ -81,12 +73,9 @@ try { "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 = []; @@ -105,7 +94,6 @@ try { "NoteWeb" => $part["part_description"] ?? "" ]; - echo "➡️ Creating Campione {$index} with Matrice={$matriceId}\n"; $campione = $api->post("Campione", $campionePayload); $campione["PartNumber"] = $part["part_number"] ?? ""; @@ -114,12 +102,10 @@ try { $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) { @@ -137,14 +123,11 @@ try { 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 = [ @@ -161,7 +144,8 @@ try { "success" => true, "commessaWeb" => $finalCommessa, "totalCampioni" => count($campioni), - "totalCustomFields" => count($fieldValues) + "totalCustomFields" => count($fieldValues), + "message" => "Export successful" ]); } catch (Exception $e) { diff --git a/public/userarea/import_edit2.php b/public/userarea/import_edit2.php index 8f85f47..a6bc337 100644 --- a/public/userarea/import_edit2.php +++ b/public/userarea/import_edit2.php @@ -724,7 +724,7 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) { }, success: function (response) { if (response.success) { - alert("✅ CommessaWeb created. ID: " + response.webOrder.IdCommessa); + alert(response.message); } else { alert("❌ Error: " + response.message); } From 3da8ff81c90e98bc91f341ae830bbd67720dddeb Mon Sep 17 00:00:00 2001 From: Claudio Date: Tue, 23 Sep 2025 09:44:58 +0200 Subject: [PATCH 7/8] added record idcommessaweb and commessaweb and update status to export to lims --- public/userarea/export_to_lims.php | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/public/userarea/export_to_lims.php b/public/userarea/export_to_lims.php index 7b01e66..392c32f 100644 --- a/public/userarea/export_to_lims.php +++ b/public/userarea/export_to_lims.php @@ -76,6 +76,8 @@ try { $commessaWeb = $api->post("CommessaWeb", $commessaWebPayload); $commessaId = $commessaWeb["IdCommessa"]; + // Estraiamo il numero della commessa usando CodiceCommessa + $commessaWebCode = substr($commessaWeb["CodiceCommessa"] ?? "TEST CommessaWeb", 0, 30); // Limite a 30 caratteri // 🔹 STEP 6: Create Campioni (Samples) for each part $campioni = []; @@ -126,6 +128,18 @@ try { } } + // 🔹 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 $sendResult = $api->post("CommessaWeb({$commessaId})/InviaCommessa", []); @@ -143,11 +157,11 @@ try { echo json_encode([ "success" => true, "commessaWeb" => $finalCommessa, + "commessaWebApiResponse" => $commessaWeb, // Incluso per debug "totalCampioni" => count($campioni), "totalCustomFields" => count($fieldValues), "message" => "Export successful" ]); - } catch (Exception $e) { error_log("LIMS Export Error: " . $e->getMessage() . "\nTrace: " . $e->getTraceAsString()); From 5d6302fa9cea2c9c0d21cef92d61c4d85ce19a8e Mon Sep 17 00:00:00 2001 From: Claudio Date: Tue, 23 Sep 2025 10:33:16 +0200 Subject: [PATCH 8/8] added admin role to button export --- public/userarea/import_edit2.php | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/public/userarea/import_edit2.php b/public/userarea/import_edit2.php index a6bc337..5068685 100644 --- a/public/userarea/import_edit2.php +++ b/public/userarea/import_edit2.php @@ -559,7 +559,11 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) { $row): ?>
- + + hasRole('Admin'))) : ?> + + + @@ -709,27 +713,28 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) { - + \ No newline at end of file