water-uploadsubmit.php 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. <?php
  2. /**
  3. * dashboard/crop-analysis/water-test-data/water-uploadsubmit.php
  4. *
  5. * Spreadsheet bulk-upload handler for water test records.
  6. * Requires the SpreadsheetReader library.
  7. *
  8. * NOTE: Column index → DB field mapping below must match the actual
  9. * spreadsheet format provided by the lab. Update $colMap as needed.
  10. */
  11. if (session_status() === PHP_SESSION_NONE) {
  12. session_start();
  13. }
  14. require_once __DIR__ . '/../../../config/database.php';
  15. require_once __DIR__ . '/../../../lib/auth.php';
  16. requireLogin();
  17. $readerBase = __DIR__ . '/../../../client-assets/php/spreadsheet';
  18. $readerFile = $readerBase . '/php-excel-reader/excel_reader2.php';
  19. $spreadFile = $readerBase . '/SpreadsheetReader.php';
  20. if (!file_exists($readerFile) || !file_exists($spreadFile)) {
  21. http_response_code(500);
  22. exit('<p class="text-danger">Spreadsheet reader library not found.</p>');
  23. }
  24. require_once $readerFile;
  25. require_once $spreadFile;
  26. if (!isset($_POST['Submit'])) {
  27. exit;
  28. }
  29. $allowedMimes = [
  30. 'application/vnd.ms-excel',
  31. 'text/xls', 'text/xlsx', 'text/csv',
  32. 'application/vnd.oasis.opendocument.spreadsheet',
  33. 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  34. ];
  35. if (!in_array($_FILES['file']['type'] ?? '', $allowedMimes, true)) {
  36. exit('<p class="text-danger">Invalid file type. Please upload an Excel or CSV file.</p>');
  37. }
  38. $uploadDir = __DIR__ . '/../../../client-assets/uploads/';
  39. $uploadPath = $uploadDir . basename($_FILES['file']['name']);
  40. if (!move_uploaded_file($_FILES['file']['tmp_name'], $uploadPath)) {
  41. exit('<p class="text-danger">Failed to upload file.</p>');
  42. }
  43. $reader = new SpreadsheetReader($uploadPath);
  44. $totalSheet = count($reader->sheets());
  45. echo '<p>File uploaded — ' . (int) $totalSheet . ' sheet(s) found.</p>';
  46. $pdo = getDBConnection();
  47. $userId = getCurrentUserId();
  48. /**
  49. * Map spreadsheet column indices to soil_records column names.
  50. * Water test data is stored in soil_records pending a dedicated water_records table.
  51. * Adjust indices to match the lab's spreadsheet layout.
  52. */
  53. $colMap = [
  54. 0 => 'analysis_type',
  55. 1 => 'lab_no',
  56. 2 => 'batch_no',
  57. 3 => 'sample_id',
  58. 4 => 'site_id',
  59. 5 => 'crop',
  60. 6 => 'date_sampled',
  61. 7 => 'tec',
  62. 8 => 'cec',
  63. 9 => 'texture',
  64. 10 => 'gravel',
  65. 11 => 'colour',
  66. 12 => 'NO3_N',
  67. 13 => 'NH3_N',
  68. 14 => 'p_mehlick',
  69. 15 => 'p_bray2',
  70. 16 => 'p_morgan',
  71. 17 => 'k_morgan',
  72. 18 => 'ca_morgan',
  73. 19 => 'mg_morgan',
  74. 20 => 'na_morgan',
  75. 21 => 'ch_h2o',
  76. 22 => 'ocarbon',
  77. 23 => 'omatter',
  78. 24 => 'fe',
  79. 25 => 'ec',
  80. 26 => 'ph_cacl2',
  81. 27 => 'ph_h2o',
  82. 28 => 'paramag',
  83. 29 => 's_morgan',
  84. 30 => 'b_cacl2',
  85. 31 => 'mn_dtpa',
  86. 32 => 'zn_dtpa',
  87. 33 => 'fe_dtpa',
  88. 34 => 'cu_dtpa',
  89. 35 => 'al',
  90. 36 => 'sl_cacl2',
  91. 37 => 'm_dtpa',
  92. 38 => 'co_dtpa',
  93. 39 => 'se',
  94. 40 => 'ca_mehlick3',
  95. 41 => 'mg_mehlick3',
  96. 42 => 'k_mehlick3',
  97. 43 => 'na_mehlick3',
  98. 44 => 'al_mehlick3',
  99. ];
  100. $columns = array_values($colMap);
  101. $placeholders = implode(', ', array_fill(0, count($columns) + 2, '?'));
  102. $colList = 'modx_user_id, rand, ' . implode(', ', array_map(fn($c) => "`$c`", $columns));
  103. $stmt = $pdo->prepare(
  104. "INSERT INTO soil_records ($colList) VALUES ($placeholders)"
  105. );
  106. $inserted = 0;
  107. $skipped = 0;
  108. for ($i = 0; $i < $totalSheet; $i++) {
  109. $reader->ChangeSheet($i);
  110. $firstRow = true;
  111. foreach ($reader as $row) {
  112. if ($firstRow) { $firstRow = false; continue; } // skip header row
  113. $rand = mt_rand(10000, 99999);
  114. $values = [$userId, $rand];
  115. foreach ($colMap as $idx => $colName) {
  116. $val = isset($row[$idx]) ? trim((string) $row[$idx]) : null;
  117. $values[] = ($val === '') ? null : $val;
  118. }
  119. try {
  120. $stmt->execute($values);
  121. $inserted++;
  122. } catch (\PDOException $e) {
  123. $skipped++;
  124. }
  125. }
  126. }
  127. @unlink($uploadPath);
  128. echo '<p class="text-success">Import complete: '
  129. . (int) $inserted . ' record(s) inserted, '
  130. . (int) $skipped . ' skipped.</p>';