Lims api working version with comments

This commit is contained in:
Lasha Kapanadze 2025-09-22 20:16:56 +04:00
parent 412dce8941
commit 0a6fb98476
2 changed files with 85 additions and 132 deletions

View File

@ -187,4 +187,9 @@ class VisualLimsApiClient
return json_decode($response, true); return json_decode($response, true);
} }
public function getBaseUrl()
{
return $this->baseUrl;
}
} }

View File

@ -13,8 +13,7 @@ try {
throw new Exception("Missing iddatadb"); throw new Exception("Missing iddatadb");
} }
// ⚠️ Simulation ON (change it to false to enable real API calls) echo "✅ START Export for iddatadb={$iddatadb}\n";
$simulate = true;
// 🔹 STEP 1+2: Fetch Cliente ID + Schema ID // 🔹 STEP 1+2: Fetch Cliente ID + Schema ID
$stmt = $pdo->prepare(" $stmt = $pdo->prepare("
@ -34,15 +33,19 @@ try {
$clienteId = (int) $result['clienteId']; $clienteId = (int) $result['clienteId'];
$schemaId = (int) $result['schemaId']; $schemaId = (int) $result['schemaId'];
// 🔹 STEP 3: Fetch Parts echo "✅ Cliente={$clienteId}, Schema={$schemaId}\n";
// 🔹 STEP 3: Fetch Parts (including idmatrice)
$stmt = $pdo->prepare(" $stmt = $pdo->prepare("
SELECT part_number, part_description, material, color, mix SELECT part_number, part_description, material, color, mix, idmatrice
FROM identification_parts FROM identification_parts
WHERE iddatadb = :iddatadb WHERE iddatadb = :iddatadb
"); ");
$stmt->execute(['iddatadb' => $iddatadb]); $stmt->execute(['iddatadb' => $iddatadb]);
$parts = $stmt->fetchAll(PDO::FETCH_ASSOC); $parts = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "✅ Parts found: " . count($parts) . "\n";
// 🔹 STEP 4: Fetch Field Values with Labels // 🔹 STEP 4: Fetch Field Values with Labels
$stmt = $pdo->prepare(" $stmt = $pdo->prepare("
SELECT SELECT
@ -58,169 +61,114 @@ try {
$stmt->execute(['iddatadb' => $iddatadb]); $stmt->execute(['iddatadb' => $iddatadb]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "✅ Field rows found: " . count($rows) . "\n";
$fieldValues = []; $fieldValues = [];
foreach ($rows as $row) { foreach ($rows as $row) {
$fieldValues[] = [ $fieldValues[] = [
"FieldLabel" => $row['field_label'], "IdCommesseCustomFields" => (int) $row['field_id'],
"FieldValue" => $row['field_value'], "Valore" => $row['field_value']
"SchemaId" => (int) $row['schema_id'],
"FieldId" => (int) $row['field_id']
]; ];
} }
// 🔹 Initialize API client (even in simulation mode for consistency) // 🔹 Initialize API client
$api = null; $api = VisualLimsApiClient::getInstance();
if (!$simulate) {
$api = VisualLimsApiClient::getInstance();
}
// 🔹 STEP 5: Create WebOrder // 🔹 STEP 5: Create CommessaWeb (NOT WebOrder)
$webOrderPayload = [ $commessaWebPayload = [
"Customer" => $clienteId "Cliente" => $clienteId,
"SchemaCustomField" => $schemaId,
"Richiedente" => "Test Web Import",
"Descrizione" => "TEST CommessaWeb",
]; ];
if ($simulate) { echo "➡️ Creating CommessaWeb...\n";
// Simulate WebOrder creation $commessaWeb = $api->post("CommessaWeb", $commessaWebPayload);
$webOrder = [
"Id" => 999999,
"Code" => "TEST-WO-001",
"Customer" => $clienteId,
"CreatedDate" => date('c'),
"Status" => "Draft"
];
} else {
// Real API call
$webOrder = $api->post("odata/WebOrder", $webOrderPayload);
}
$webOrderId = $webOrder["Id"]; $commessaId = $commessaWeb["IdCommessa"];
echo "✅ CommessaWeb created: ID={$commessaId}\n";
// 🔹 STEP 6: Create Samples for each part // 🔹 STEP 6: Create Campioni (Samples) for each part
$samples = []; $campioni = [];
foreach ($parts as $index => $part) { foreach ($parts as $index => $part) {
$samplePayload = [ $matriceId = (int) ($part["idmatrice"] ?? 0);
"OrderId" => $webOrderId,
"Description" => $part["part_description"] ?? "",
"SampleCode" => $part["part_number"] ?? "",
"Material" => $part["material"] ?? "",
"Color" => $part["color"] ?? "",
"Mix" => $part["mix"] ?? ""
];
if ($simulate) { if ($matriceId <= 0) {
// Simulate Sample creation throw new Exception("Invalid or missing idmatrice for part: " . ($part["part_number"] ?? "Unknown"));
$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; $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 // 🔹 STEP 7: Update Custom Fields for CommessaWeb
$samplesWithCustomFields = []; if (!empty($fieldValues)) {
foreach ($samples as $sample) { echo "➡️ Updating CommessaWeb Custom Fields...\n";
$sampleId = $sample["Id"]; $commessaWithFields = $api->get("CommessaWeb(" . $commessaId . ")?\$expand=CommesseCustomFields");
$commessaCustomFields = [];
if ($simulate) { foreach ($commessaWithFields["CommesseCustomFields"] as $customField) {
// 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) { foreach ($fieldValues as $fieldValue) {
// This might need to be adjusted based on the actual Custom Fields API structure if ($customField["IdCommesseCustomFields"] == $fieldValue["IdCommesseCustomFields"]) {
$customFieldPayload = [ $commessaCustomFields[] = [
"SampleId" => $sampleId, "IdCommesseCustomFields" => $customField["IdCommesseCustomFields"],
"FieldLabel" => $fieldValue["FieldLabel"], "Valore" => $fieldValue["Valore"]
"FieldValue" => $fieldValue["FieldValue"] ];
]; break;
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; if (!empty($commessaCustomFields)) {
} $updatePayload = ["CommesseCustomFields" => $commessaCustomFields];
$api->patch("CommessaWeb({$commessaId})", $updatePayload);
// 🔹 STEP 8: Optionally send the order to laboratory echo "✅ CommessaWeb Custom Fields updated\n";
$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 // 🔹 STEP 9: Send CommessaWeb to laboratory
$finalWebOrder = [ echo "➡️ Sending CommessaWeb...\n";
"IdCommessa" => $webOrderId, $sendResult = $api->post("CommessaWeb({$commessaId})/InviaCommessa", []);
"CodiceCommessa" => $webOrder["Code"] ?? "N/A", echo "✅ CommessaWeb sent to Lab\n";
"IdCliente" => $clienteId,
"IdSchema" => $schemaId, // 🔹 STEP 10: Prepare final response
"Customer" => $webOrder["Customer"] ?? $clienteId, $finalCommessa = [
"Status" => $webOrder["Status"] ?? "Draft", "Cliente" => $clienteId,
"CreatedDate" => $webOrder["CreatedDate"] ?? date('c'), "SchemaCustomField" => $schemaId,
"Fields" => $fieldValues, "Richiedente" => $commessaWeb["Richiedente"] ?? "Web Import",
"Samples" => $samplesWithCustomFields, "Descrizione" => $commessaWeb["Descrizione"] ?? "",
"Inviato" => $orderSent ? 1 : 0 "CommesseCustomFields" => $fieldValues,
"Campioni" => $campioni,
"Inviata" => 1
]; ];
// 🔹 Final Response
echo json_encode([ echo json_encode([
"success" => true, "success" => true,
"webOrder" => $finalWebOrder, "commessaWeb" => $finalCommessa,
"totalSamples" => count($samplesWithCustomFields), "totalCampioni" => count($campioni),
"totalCustomFields" => count($fieldValues), "totalCustomFields" => count($fieldValues)
"simulation" => $simulate,
"orderSent" => $orderSent
]); ]);
} catch (Exception $e) { } catch (Exception $e) {
// Log the error for debugging
error_log("LIMS Export Error: " . $e->getMessage() . "\nTrace: " . $e->getTraceAsString()); error_log("LIMS Export Error: " . $e->getMessage() . "\nTrace: " . $e->getTraceAsString());
echo json_encode([ echo json_encode([
"success" => false, "success" => false,
"message" => "Export failed: " . $e->getMessage(), "message" => "Export failed: " . $e->getMessage()
"simulation" => $simulate ?? true
]); ]);
} }