prepare("INSERT INTO questionnaire_sessions (created_by) VALUES (?)"); $stmt->execute([$userId]); $sessionId = $pdo->lastInsertId(); header("Location: questionnaire.php?id=$sessionId"); exit; } $sessId = (int)($_GET['id'] ?? 0); $sess = null; if ($sessId) { $stmt = $pdo->prepare("SELECT * FROM questionnaire_sessions WHERE id=?"); $stmt->execute([$sessId]); $sess = $stmt->fetch(); if (!$sess) { $sessId = 0; } } // Handle manual step navigation via GET if ($sessId && isset($_GET['step']) && $sess && $sess['status'] !== 'completed') { $goStep = (int)$_GET['step']; if ($goStep >= 1 && $goStep <= 5 && $goStep <= (int)$sess['current_step']) { $pdo->prepare("UPDATE questionnaire_sessions SET current_step=? WHERE id=?")->execute([$goStep, $sessId]); header("Location: questionnaire.php?id=$sessId"); exit; } } // Save answers if ($_SERVER['REQUEST_METHOD'] === 'POST' && $sess) { $csrf = $_POST['csrf_token'] ?? ''; if (!auth_csrf_verify($csrf)) { $message = 'Ошибка безопасности.'; } else { $step = (int)($_POST['step'] ?? 1); $goNext = isset($_POST['next']); $answers = []; // Collect all answers from POST (skip meta fields) foreach ($_POST as $key => $val) { if (strpos($key, '_') === 0 || $key === 'csrf_token' || $key === 'step' || $key === 'next' || $key === 'save') continue; if (is_array($val)) { $answers[$key] = implode(',', $val); } else { $answers[$key] = $val; } } // Save answers $stmt = $pdo->prepare("INSERT INTO questionnaire_answers (session_id, step, question_key, answer_value) VALUES ($1,$2,$3,$4) ON CONFLICT (session_id, question_key) DO UPDATE SET answer_value=EXCLUDED.answer_value"); foreach ($answers as $qk => $qv) { $stmt->execute([$sessId, $step, $qk, $qv]); } if ($goNext && $step < 5) { $pdo->prepare("UPDATE questionnaire_sessions SET current_step=? WHERE id=?")->execute([$step + 1, $sessId]); header("Location: questionnaire.php?id=$sessId"); exit; } // Step 5 = final calculation if ($step === 5 || isset($_POST['save'])) { // Calculate everything from all answers $allAnswers = $pdo->prepare("SELECT question_key, answer_value FROM questionnaire_answers WHERE session_id=?"); $allAnswers->execute([$sessId]); $qa = []; foreach ($allAnswers as $row) { $qa[$row['question_key']] = $row['answer_value']; } $riskScore = calc_risk_score( ($qa['no_archive'] ?? '') === 'on', ($qa['no_power'] ?? '') === 'on', ($qa['no_regulations'] ?? '') === 'on', ($qa['frequent_failures'] ?? '') === 'on', ($qa['no_documentation'] ?? '') === 'on' ); $complexity = calc_complexity( (int)($qa['camera_count'] ?? 0), (int)($qa['access_points'] ?? 0), $qa['fire_type'] ?? 'simple', isset($qa['has_it']) && $qa['has_it'] === 'on' ); $infraLoad = calc_infrastructure_load( $qa['server_state'] ?? 'ok', $qa['network_state'] ?? 'stable', $qa['power_state'] ?? 'ok' ); $serviceHist = calc_service_history($qa['service_state'] ?? 'none'); $objIndex = calc_object_index($riskScore, $complexity, $infraLoad, $serviceHist); // Region factor $regionFactor = (float)($qa['region_factor'] ?? 1.0); $baseCost = 15000; $riskMult = risk_multiplier($riskScore); $slaPrice = calc_sla_price($baseCost, $objIndex, $regionFactor, $riskMult); // Update session with results $pdo->prepare("UPDATE questionnaire_sessions SET status='completed', current_step=5, risk_score=?, complexity_index=?, infrastructure_load=?, service_history=?, object_index=?, sla_price_monthly=? WHERE id=?")->execute([$riskScore, $complexity, $infraLoad, $serviceHist, $objIndex, $slaPrice, $sessId]); // Create/update object if we have name if (!empty($qa['object_name'])) { $stmtObj = $pdo->prepare("INSERT INTO objects (name, object_type, address, contact_person, contact_phone, status, risk_score, complexity_index, infrastructure_load, service_history, object_index, sla_price_monthly, region_factor, created_by, notes) VALUES ($1,$2,$3,$4,$5,'active',$6,$7,$8,$9,$10,$11,$12,$13,'Из опросника #' || $14) ON CONFLICT DO NOTHING"); $stmtObj->execute([ $qa['object_name'], $qa['object_type'] ?? '', $qa['address'] ?? '', $qa['contact_person'] ?? '', $qa['contact_phone'] ?? '', $riskScore, $complexity, $infraLoad, $serviceHist, $objIndex, $slaPrice, $regionFactor, $userId, $sessId ]); $objId = $pdo->lastInsertId(); } else { $objId = null; } // Passport $passportData = json_encode([ 'answers' => $qa, 'risk_score' => $riskScore, 'complexity' => $complexity, 'infra_load' => $infraLoad, 'service_history' => $serviceHist, 'object_index' => $objIndex, 'sla_price' => $slaPrice, ]); $pdo->prepare("INSERT INTO object_passports (session_id, object_id, object_index, risk_score, complexity_index, sla_price_monthly, passport_data, created_by) VALUES (?,?,?,?,?,?,?,?)") ->execute([$sessId, $objId, $objIndex, $riskScore, $complexity, $slaPrice, $passportData, $userId]); $message = '✅ Расчёт выполнен! Паспорт объекта сформирован.'; $sess = $pdo->prepare("SELECT * FROM questionnaire_sessions WHERE id=?"); $sess->execute([$sessId]); $sess = $sess->fetch(); } if (!isset($_POST['save']) && $step < 5) { $message = 'Шаг сохранён.'; } if (isset($_POST['save'])) { $message = 'Данные сохранены.'; } } } // Load existing answers for editing $answers = []; if ($sessId) { $stmt = $pdo->prepare("SELECT question_key, answer_value FROM questionnaire_answers WHERE session_id=?"); $stmt->execute([$sessId]); foreach ($stmt as $row) { $answers[$row['question_key']] = $row['answer_value']; } } // Load questionnaire items from DB $qItems = []; $qSections = []; if ($sessId) { $stmt = $pdo->prepare("SELECT * FROM questionnaire_items WHERE is_active=1 AND step=? ORDER BY sort_order, id"); $stmt->execute([$step]); $qItems = $stmt->fetchAll(); // Group by section foreach ($qItems as $qi) { if ($qi['section'] && !isset($qSections[$qi['section']])) { $qSections[$qi['section']] = []; } if ($qi['section']) { $qSections[$qi['section']][] = $qi; } else { $qSections[''][] = $qi; } } } $csrf = auth_csrf_token(); // Sessions list $sessions = $pdo->query("SELECT qs.*, u.full_name as author_name FROM questionnaire_sessions qs LEFT JOIN users u ON u.id=qs.created_by ORDER BY qs.created_at DESC LIMIT 20")->fetchAll(); require __DIR__ . '/../../inc/header.php'; ?>
| ID | Автор | Статус | Risk Score | Object Index | SLA / мес | Дата | |
|---|---|---|---|---|---|---|---|
| #= $s['id'] ?> | = htmlspecialchars($s['author_name'] ?: '—') ?> | = $s['status'] ?> | = $s['risk_score'] ?: '—' ?> | = $s['object_index'] ?: '—' ?> | = $s['sla_price_monthly'] ? fmt_money($s['sla_price_monthly']) : '—' ?> | = date('d.m.Y', strtotime($s['created_at'])) ?> | 👁️ |