Lokasi:
/
home
/
u847703118
/
domains
/
alphamed.cloud
/
public_html
/
Ubah: test_imports.php
<?php require('includes/auth_session.php'); if (!userHasModule('system_import_tests') && !userCanAccess('tests', ['admin', 'chief_med_tech'])) { header("Location: dashboard.php"); exit(); } if (isset($_GET['download']) && $_GET['download'] === 'sample') { $sample = "Test Name,Category,Price,Gender,Min_Age,Max_Age,Test_Type,Result_Unit,Result_Normal_Range,Component_Name,Component_Unit,Component_Normal_Range,Component_Order\n"; $sample .= "Fasting Blood Sugar (FBS),Clinical Chemistry,150.00,Any,,,Lab,mg/dL,70-100,,,\n"; header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment; filename="lab_tests_template.csv"'); header('Content-Length: ' . strlen($sample)); echo $sample; exit(); } $message = ''; $error = ''; $details = []; $previewRows = []; $previewSummary = null; if (isset($_SESSION['test_import_preview']) && is_array($_SESSION['test_import_preview'])) { $previewSummary = $_SESSION['test_import_preview']; if (isset($previewSummary['rows']) && is_array($previewSummary['rows'])) { $previewRows = $previewSummary['rows']; } } if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (isset($_POST['confirm_import'])) { if (!$previewSummary || empty($previewRows)) { $error = 'No scanned data found. Please upload a CSV file first.'; } else { $inserted = 0; $updated = 0; $skipped = 0; try { $pdo->beginTransaction(); $selectStmt = $pdo->prepare('SELECT id FROM lab_tests WHERE test_name = ? LIMIT 1'); $insertStmt = $pdo->prepare('INSERT INTO lab_tests (test_name, test_type, category, price, gender_applicability, min_age_years, max_age_years) VALUES (?, ?, ?, ?, ?, ?, ?)'); $updateStmt = $pdo->prepare('UPDATE lab_tests SET test_type = ?, category = ?, price = ?, gender_applicability = ?, min_age_years = ?, max_age_years = ? WHERE id = ?'); $updateUnitStmt = $pdo->prepare('UPDATE lab_tests SET unit = ? WHERE id = ?'); $updateRangeStmt = $pdo->prepare('UPDATE lab_tests SET normal_range = ? WHERE id = ?'); $deleteComponentsStmt = $pdo->prepare('DELETE FROM test_components WHERE test_id = ?'); $insertComponentStmt = $pdo->prepare('INSERT INTO test_components (test_id, name, unit, normal_range, order_index) VALUES (?, ?, ?, ?, ?)'); $seenTests = []; $componentCounters = []; foreach ($previewRows as $r) { $testName = $r['test_name']; $category = $r['category']; $price = $r['price']; $gender = $r['gender']; $minAge = $r['min_age']; $maxAge = $r['max_age']; $testType = $r['test_type']; $resultUnit = $r['result_unit']; $resultRange = $r['result_range']; $componentName = $r['component_name']; $componentUnit = $r['component_unit']; $componentRange = $r['component_range']; $componentOrder = $r['component_order']; $status = $r['status']; if ($status === 'skip') { $skipped++; continue; } $selectStmt->execute([$testName]); $existingId = $selectStmt->fetchColumn(); if ($existingId) { $testId = (int)$existingId; $updateStmt->execute([$testType, $category, $price, $gender, $minAge, $maxAge, $testId]); $updated++; } else { $insertStmt->execute([$testName, $testType, $category, $price, $gender, $minAge, $maxAge]); $testId = (int)$pdo->lastInsertId(); $inserted++; } if ($resultUnit !== '') { $updateUnitStmt->execute([$resultUnit, $testId]); } if ($resultRange !== '') { $updateRangeStmt->execute([$resultRange, $testId]); } if (!array_key_exists($testId, $seenTests)) { $deleteComponentsStmt->execute([$testId]); $seenTests[$testId] = true; $componentCounters[$testId] = 0; } if ($componentName !== '') { $orderIndex = is_int($componentOrder) ? $componentOrder : $componentCounters[$testId]; $insertComponentStmt->execute([$testId, $componentName, $componentUnit, $componentRange, $orderIndex]); $componentCounters[$testId]++; } } $pdo->commit(); unset($_SESSION['test_import_preview']); $previewRows = []; $previewSummary = null; if (function_exists('logAction')) { $summary = "Imported tests via CSV: inserted={$inserted}, updated={$updated}, skipped={$skipped}"; logAction($pdo, $_SESSION['user_id'], 'Import Tests', $summary); } $message = "Import completed. Inserted: {$inserted}, Updated: {$updated}, Skipped: {$skipped}."; } catch (Exception $e) { $pdo->rollBack(); $error = 'Error during import: ' . $e->getMessage(); } } } else { $inserted = 0; $updated = 0; $skipped = 0; $details = []; $previewRows = []; if (!isset($_FILES['csv_file']) || $_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) { $error = 'Please select a valid CSV file.'; } else { $tmpPath = $_FILES['csv_file']['tmp_name']; $fh = fopen($tmpPath, 'r'); if ($fh === false) { $error = 'Unable to read uploaded file.'; } else { $header = fgetcsv($fh); if ($header === false) { $error = 'CSV file is empty.'; } else { $map = []; foreach ($header as $idx => $col) { $key = strtolower(trim($col)); if ($key === 'test name' || $key === 'test_name' || $key === 'name') { $map['test_name'] = $idx; } elseif ($key === 'category' || $key === 'test type' || $key === 'type') { $map['category'] = $idx; } elseif ($key === 'price' || $key === 'amount' || $key === 'rate') { $map['price'] = $idx; } elseif ($key === 'gender' || $key === 'sex' || $key === 'gender_applicability') { $map['gender'] = $idx; } elseif ($key === 'min_age' || $key === 'min_age_years' || $key === 'min age') { $map['min_age'] = $idx; } elseif ($key === 'max_age' || $key === 'max_age_years' || $key === 'max age') { $map['max_age'] = $idx; } elseif ($key === 'test_type' || $key === 'result_type') { $map['test_type'] = $idx; } elseif ($key === 'result_unit' || $key === 'result unit' || $key === 'unit') { $map['result_unit'] = $idx; } elseif ($key === 'result_normal_range' || $key === 'result normal range' || $key === 'normal_range' || $key === 'normal range') { $map['result_range'] = $idx; } elseif ($key === 'component_name' || $key === 'component name' || $key === 'comp_name') { $map['component_name'] = $idx; } elseif ($key === 'component_unit' || $key === 'component unit' || $key === 'comp_unit') { $map['component_unit'] = $idx; } elseif ($key === 'component_normal_range' || $key === 'component normal range' || $key === 'comp_range') { $map['component_range'] = $idx; } elseif ($key === 'component_order' || $key === 'component order' || $key === 'comp_order') { $map['component_order'] = $idx; } } if (!isset($map['test_name']) || !isset($map['price']) || !isset($map['category'])) { $error = 'CSV must contain at least Test Name, Category, and Price columns.'; } else { $selectStmt = $pdo->prepare('SELECT id FROM lab_tests WHERE test_name = ? LIMIT 1'); $categoryMap = [ 'hematology' => 'Hematology', 'clinical microscopy' => 'Clinical Microscopy', 'clin microscopy' => 'Clinical Microscopy', 'clin. microscopy' => 'Clinical Microscopy', 'chemistry' => 'Clinical Chemistry', 'clinical chemistry' => 'Clinical Chemistry', 'serology' => 'Serology', 'sero' => 'Serology', 'x-ray' => 'X-Ray', 'xray' => 'X-Ray', 'x ray' => 'X-Ray', 'ultrasound' => 'Ultrasound', 'u/s' => 'Ultrasound', 'u/sound' => 'Ultrasound', 'ecg' => 'ECG', '2d echo' => '2D Echo' ]; while (($row = fgetcsv($fh)) !== false) { $nameIdx = $map['test_name']; $priceIdx = $map['price']; $catIdx = $map['category']; $testName = isset($row[$nameIdx]) ? trim($row[$nameIdx]) : ''; $categoryRaw = isset($row[$catIdx]) ? trim($row[$catIdx]) : ''; $categoryKey = strtolower($categoryRaw); if (isset($categoryMap[$categoryKey])) { $category = $categoryMap[$categoryKey]; } else { $category = $categoryRaw; } $priceRaw = isset($row[$priceIdx]) ? trim($row[$priceIdx]) : ''; $status = 'ok'; $reason = ''; if ($testName === '' || $category === '' || $priceRaw === '') { $status = 'skip'; $reason = 'Missing required fields'; } $price = 0; if ($status !== 'skip') { $priceSanitized = str_replace([',', '₱', ' '], '', $priceRaw); if (!is_numeric($priceSanitized)) { $status = 'skip'; $reason = 'Invalid price'; } else { $price = (float)$priceSanitized; } } $gender = 'Any'; if (isset($map['gender'])) { $genderIdx = $map['gender']; $gRaw = isset($row[$genderIdx]) ? strtolower(trim($row[$genderIdx])) : ''; if ($gRaw === 'male' || $gRaw === 'm') { $gender = 'Male'; } elseif ($gRaw === 'female' || $gRaw === 'f') { $gender = 'Female'; } } $minAge = null; $maxAge = null; if (isset($map['min_age'])) { $minIdx = $map['min_age']; $minRaw = isset($row[$minIdx]) ? trim($row[$minIdx]) : ''; if ($minRaw !== '' && is_numeric($minRaw)) { $minAge = (int)$minRaw; } } if (isset($map['max_age'])) { $maxIdx = $map['max_age']; $maxRaw = isset($row[$maxIdx]) ? trim($row[$maxIdx]) : ''; if ($maxRaw !== '' && is_numeric($maxRaw)) { $maxAge = (int)$maxRaw; } } $testType = 'Lab'; if (isset($map['test_type'])) { $typeIdx = $map['test_type']; $tRaw = isset($row[$typeIdx]) ? strtolower(trim($row[$typeIdx])) : ''; if ($tRaw === 'imaging' || $tRaw === 'x-ray' || $tRaw === 'ultrasound') { $testType = 'Imaging'; } } $resultUnit = ''; if (isset($map['result_unit'])) { $uIdx = $map['result_unit']; $uRaw = isset($row[$uIdx]) ? trim($row[$uIdx]) : ''; if ($uRaw !== '') { $resultUnit = $uRaw; } } $resultRange = ''; if (isset($map['result_range'])) { $rIdx = $map['result_range']; $rRaw = isset($row[$rIdx]) ? trim($row[$rIdx]) : ''; if ($rRaw !== '') { $resultRange = $rRaw; } } $componentName = ''; if (isset($map['component_name'])) { $cIdx = $map['component_name']; $componentName = isset($row[$cIdx]) ? trim($row[$cIdx]) : ''; } $componentUnit = ''; if (isset($map['component_unit'])) { $cuIdx = $map['component_unit']; $componentUnit = isset($row[$cuIdx]) ? trim($row[$cuIdx]) : ''; } $componentRange = ''; if (isset($map['component_range'])) { $crIdx = $map['component_range']; $componentRange = isset($row[$crIdx]) ? trim($row[$crIdx]) : ''; } $componentOrder = null; if (isset($map['component_order'])) { $coIdx = $map['component_order']; $coRaw = isset($row[$coIdx]) ? trim($row[$coIdx]) : ''; if ($coRaw !== '' && is_numeric($coRaw)) { $componentOrder = (int)$coRaw; } } $action = ''; if ($status === 'skip') { $skipped++; $details[] = 'Row for "' . $testName . '" skipped: ' . $reason; } else { $selectStmt->execute([$testName]); $existingId = $selectStmt->fetchColumn(); if ($existingId) { $action = 'Update'; $updated++; } else { $action = 'Insert'; $inserted++; } } $previewRows[] = [ 'test_name' => $testName, 'category' => $category, 'price' => $price, 'gender' => $gender, 'min_age' => $minAge, 'max_age' => $maxAge, 'test_type' => $testType, 'result_unit' => $resultUnit, 'result_range' => $resultRange, 'component_name' => $componentName, 'component_unit' => $componentUnit, 'component_range' => $componentRange, 'component_order' => $componentOrder, 'status' => $status === 'skip' ? 'skip' : strtolower($action), 'reason' => $status === 'skip' ? $reason : $action ]; } $_SESSION['test_import_preview'] = [ 'rows' => $previewRows, 'insert_count' => $inserted, 'update_count' => $updated, 'skip_count' => $skipped ]; $previewSummary = $_SESSION['test_import_preview']; $message = "Scan completed. Will insert {$inserted}, update {$updated}, skip {$skipped} rows."; } } fclose($fh); } } } } include('includes/header.php'); ?> <div class="d-flex justify-content-between align-items-center mb-4"> <h2>Import Lab Tests</h2> <a href="test_imports.php?download=sample" class="btn btn-outline-secondary"> Download Sample CSV </a> </div> <?php if (isset($_GET['msg']) && $_GET['msg'] === 'sample'): ?> <div class="alert alert-info"> You can prepare a CSV file with columns: Test Name, Category, Price, Gender (optional), Min_Age (optional), Max_Age (optional). </div> <?php endif; ?> <?php if ($message): ?> <div class="alert alert-success"> <?php echo htmlspecialchars($message); ?> </div> <?php endif; ?> <?php if ($error): ?> <div class="alert alert-danger"> <?php echo htmlspecialchars($error); ?> </div> <?php endif; ?> <div class="card mb-4"> <div class="card-header">Upload CSV</div> <div class="card-body"> <form method="POST" enctype="multipart/form-data"> <div class="mb-3"> <label class="form-label">CSV File</label> <input type="file" name="csv_file" class="form-control" accept=".csv,text/csv" required> </div> <p class="text-muted mb-2"> Expected columns (header row): <strong>Test Name</strong>, <strong>Category</strong>, <strong>Price</strong>. Optional: <strong>Gender</strong>, <strong>Min_Age</strong>, <strong>Max_Age</strong>, <strong>Test_Type</strong>, <strong>Result_Unit</strong>, <strong>Result_Normal_Range</strong>, <strong>Component_Name</strong>, <strong>Component_Unit</strong>, <strong>Component_Normal_Range</strong>, <strong>Component_Order</strong>. </p> <button type="submit" class="btn btn-primary">Scan CSV</button> </form> </div> </div> <?php if ($previewSummary && !empty($previewRows)): ?> <div class="card"> <div class="card-header">Scan Result</div> <div class="card-body"> <p class="mb-3"> Will insert <strong><?php echo (int)($previewSummary['insert_count'] ?? 0); ?></strong>, update <strong><?php echo (int)($previewSummary['update_count'] ?? 0); ?></strong>, skip <strong><?php echo (int)($previewSummary['skip_count'] ?? 0); ?></strong> rows. </p> <form method="POST" class="mb-3"> <input type="hidden" name="confirm_import" value="1"> <button type="submit" class="btn btn-success">Proceed with Import</button> </form> <div class="table-responsive"> <table class="table table-sm table-bordered"> <thead> <tr> <th>Test Name</th> <th>Category</th> <th>Price</th> <th>Gender</th> <th>Type</th> <th>Result Unit</th> <th>Result Range</th> <th>Component Name</th> <th>Component Unit</th> <th>Component Range</th> <th>Component Order</th> <th>Status</th> </tr> </thead> <tbody> <?php foreach ($previewRows as $r): ?> <tr> <td><?php echo htmlspecialchars($r['test_name']); ?></td> <td><?php echo htmlspecialchars($r['category']); ?></td> <td><?php echo htmlspecialchars((string)$r['price']); ?></td> <td><?php echo htmlspecialchars($r['gender']); ?></td> <td><?php echo htmlspecialchars($r['test_type']); ?></td> <td><?php echo htmlspecialchars($r['result_unit']); ?></td> <td><?php echo htmlspecialchars($r['result_range']); ?></td> <td><?php echo htmlspecialchars($r['component_name']); ?></td> <td><?php echo htmlspecialchars($r['component_unit']); ?></td> <td><?php echo htmlspecialchars($r['component_range']); ?></td> <td><?php echo htmlspecialchars($r['component_order'] === null ? '' : (string)$r['component_order']); ?></td> <td><?php echo htmlspecialchars($r['reason']); ?></td> </tr> <?php endforeach; ?> </tbody> </table> </div> </div> </div> <?php endif; ?> <?php include('includes/footer.php'); ?>
Batal