« Back to History
import_mesr_month_end_snapshot.php
|
20260722_120325.php
Initial Domain Snapshot
Copy Code
<?php error_reporting(E_ALL); ini_set('display_errors', 1); /* ========= ERP AUTH ========= */ require_once __DIR__ . '/../modules/auth/page_acl.php'; $ctx = page_require_access('import_mesr_month_end_snapshot'); /* IMPORTANT: define $pdo BEFORE header */ $pdo = $ctx['pdo']; $company_id = (int)$ctx['company_id']; function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); } $msg = ''; /* ========= HANDLE UPLOAD ========= */ if ($_SERVER['REQUEST_METHOD'] === 'POST') { if ( !isset($_FILES['csv_file']) || $_FILES['csv_file']['error'] !== UPLOAD_ERR_OK ) { $msg = 'CSV upload failed.'; } else { $fh = fopen($_FILES['csv_file']['tmp_name'], 'r'); if (!$fh) { $msg = 'Unable to read uploaded CSV file.'; } else { // clean previous snapshot $pdo->prepare(" DELETE FROM mesr_month_end_snapshot WHERE company_id = ? ")->execute([$company_id]); $ins = $pdo->prepare(" INSERT INTO mesr_month_end_snapshot ( company_id, machine_no, machine_type, slot, beam_no, source ) VALUES ( :company_id, :machine_no, :machine_type, :slot, :beam_no, 'csv-upload' ) "); fgetcsv($fh); // skip header $count = 0; while (($row = fgetcsv($fh)) !== false) { [ $id, $csv_company_id, $machine_no, $machine_type, $p_run, $p_adv, $p_fin, $s_run, $s_adv, $s_fin, $updated_at ] = array_pad($row, 11, null); if (!$machine_no || !$machine_type) continue; if ($p_run) { $ins->execute([ ':company_id' => $company_id, ':machine_no' => (int)$machine_no, ':machine_type' => $machine_type, ':slot' => 'primary', ':beam_no' => (int)$p_run, ]); $count++; } if ($s_run) { $ins->execute([ ':company_id' => $company_id, ':machine_no' => (int)$machine_no, ':machine_type' => $machine_type, ':slot' => 'secondary', ':beam_no' => (int)$s_run, ]); $count++; } } fclose($fh); $msg = "Import successful. {$count} rows inserted."; } } } require_once __DIR__ . '/../partials/header.php'; ?> <div class="wrap"> <div class="card"> <h3>Import MESR Month-End Snapshot</h3> <?php if ($msg): ?> <div class="notice"><?= h($msg) ?></div> <?php endif; ?> <form method="post" enctype="multipart/form-data"> <div class="form-group"> <label>Upload CSV file</label> <input type="file" name="csv_file" accept=".csv" required> </div> <button class="btn btn-primary">Import Snapshot</button> </form> <p class="muted" style="margin-top:10px;"> CSV must be exported from <code>machine_beam_status</code> </p> </div> </div> <?php require_once __DIR__ . '/../partials/footer.php'; ?>