get(); $rows = []; foreach ($surveys as $survey) { $rows[] = $this->buildSurveyRow($survey); } return $this->view() ->assign('surveys', $rows) ->display('admin/survey/index.tpl'); } public function create($request, $response, $args) { return $this->view() ->assign('survey', null) ->assign('survey_questions', []) ->display('admin/survey/form.tpl'); } public function add($request, $response, $args) { return $this->saveSurvey($request, $response, null); } public function edit($request, $response, $args) { $survey = UserSurvey::find((int) $args['id']); if ($survey === null) { return $response->withStatus(302)->withHeader('Location', '/admin/survey'); } return $this->view() ->assign('survey', $survey) ->assign('survey_questions', $this->buildQuestionRows($survey, false, false)) ->display('admin/survey/form.tpl'); } public function update($request, $response, $args) { $survey = UserSurvey::find((int) $args['id']); if ($survey === null) { return $this->json($response, 0, '调查不存在'); } return $this->saveSurvey($request, $response, $survey); } public function delete($request, $response, $args) { $id = (int) $request->getParam('id', 0); $survey = $id > 0 ? UserSurvey::find($id) : null; if ($survey === null) { return $this->json($response, 0, '调查不存在'); } UserSurveyResponse::where('survey_id', $id)->delete(); UserSurveyOption::where('survey_id', $id)->delete(); UserSurveyQuestion::where('survey_id', $id)->delete(); $survey->delete(); return $this->json($response, 1, '删除成功'); } private function saveSurvey($request, $response, $survey) { $payload = $request->getParams(); $targetType = trim((string) ($payload['target_type'] ?? 'all')); if (!in_array($targetType, ['all', 'paid'], true)) { return $this->json($response->withStatus(422), 0, '调查对象仅支持全部用户或付费用户。'); } $title = $this->limitText($this->cleanText(isset($payload['title']) ? $payload['title'] : ''), 255); if ($title === '') { return $this->json($response, 0, '请填写调查名称'); } $questions = $this->normalizeQuestions(isset($payload['questions']) ? $payload['questions'] : []); if (count($questions) < 1) { return $this->json($response, 0, '至少需要填写一个调查题目'); } foreach ($questions as $index => $question) { if ($question['title'] === '') { return $this->json($response, 0, '第 ' . ($index + 1) . ' 个题目标题不能为空'); } if (count($question['options']) < 2) { return $this->json($response, 0, '第 ' . ($index + 1) . ' 个题目至少需要两个选项'); } } $now = time(); if ($survey === null) { $survey = new UserSurvey(); $survey->created_at = $now; } $survey->title = $title; $survey->description = $this->limitText($this->cleanText(isset($payload['description']) ? $payload['description'] : ''), 5000); $survey->status = $this->normalizeStatus(isset($payload['status']) ? $payload['status'] : 0); $survey->display_mode = $this->normalizeDisplayMode(isset($payload['display_mode']) ? $payload['display_mode'] : 'card'); $survey->target_type = $targetType; $survey->target_value = ''; $survey->allow_skip = isset($payload['allow_skip']) ? 1 : 0; $survey->priority = $this->clampInt(isset($payload['priority']) ? $payload['priority'] : 0, 0, 1000000); $survey->start_at = $this->parseDateTime(isset($payload['start_at']) ? $payload['start_at'] : '', $now); $survey->end_at = $this->parseDateTime(isset($payload['end_at']) ? $payload['end_at'] : '', 0); if ((int) $survey->end_at > 0 && (int) $survey->end_at < (int) $survey->start_at) { return $this->json($response, 0, '结束时间不能早于开始时间'); } $survey->updated_at = $now; $survey->save(); $this->saveQuestions($survey, $questions); return $this->json($response, 1, '保存成功', [ 'redirect' => '/admin/survey', ]); } private function saveQuestions($survey, array $questions) { $existing = UserSurveyQuestion::where('survey_id', (int) $survey->id)->get()->keyBy('id'); $keptQuestionIds = []; $now = time(); foreach ($questions as $index => $questionRow) { $id = (int) $questionRow['id']; $question = $id > 0 && isset($existing[$id]) ? $existing[$id] : new UserSurveyQuestion(); if ((int) $question->id <= 0) { $question->survey_id = (int) $survey->id; $question->created_at = $now; } $question->title = $questionRow['title']; $question->description = $questionRow['description']; $question->status = 1; $question->sort = $index; $question->updated_at = $now; $question->save(); $keptQuestionIds[] = (int) $question->id; $this->saveOptions($survey, $question, $questionRow['options']); } foreach ($existing as $oldQuestion) { if (in_array((int) $oldQuestion->id, $keptQuestionIds, true)) { continue; } $oldQuestion->status = 0; $oldQuestion->updated_at = $now; $oldQuestion->save(); UserSurveyOption::where('survey_id', (int) $survey->id) ->where('question_id', (int) $oldQuestion->id) ->update(['status' => 0, 'updated_at' => $now]); } UserSurveyOption::where('survey_id', (int) $survey->id) ->whereNotIn('question_id', $keptQuestionIds) ->update(['status' => 0, 'updated_at' => $now]); } private function saveOptions($survey, $question, array $options) { $existing = UserSurveyOption::where('survey_id', (int) $survey->id) ->where('question_id', (int) $question->id) ->get() ->keyBy('id'); $keptIds = []; $now = time(); foreach ($options as $index => $optionRow) { $id = (int) $optionRow['id']; $option = $id > 0 && isset($existing[$id]) ? $existing[$id] : new UserSurveyOption(); if ((int) $option->id <= 0) { $option->survey_id = (int) $survey->id; $option->question_id = (int) $question->id; $option->created_at = $now; } $option->question_id = (int) $question->id; $option->label = $this->optionLabel($index); $option->content = $optionRow['content']; $option->status = 1; $option->sort = $index; $option->updated_at = $now; $option->save(); $keptIds[] = (int) $option->id; } foreach ($existing as $oldOption) { if (in_array((int) $oldOption->id, $keptIds, true)) { continue; } $oldOption->status = 0; $oldOption->updated_at = $now; $oldOption->save(); } } private function buildSurveyRow($survey) { $questions = $this->buildQuestionRows($survey, true, true); $totalUsers = UserSurveyResponse::where('survey_id', (int) $survey->id)->distinct()->count('user_id'); $totalResponses = UserSurveyResponse::where('survey_id', (int) $survey->id)->count(); $topPercent = '0'; foreach ($questions as &$question) { $questionTotal = 0; foreach ($question['options'] as $option) { $questionTotal += (int) $option['count']; } $question['total'] = $questionTotal; foreach ($question['options'] as &$option) { $percent = $questionTotal > 0 ? round((int) $option['count'] * 100 / $questionTotal, 2) : 0; $option['percent'] = $this->formatPercent($percent); if ($percent > (float) $topPercent) { $topPercent = $this->formatPercent($percent); } } unset($option); } unset($question); return [ 'id' => (int) $survey->id, 'title' => (string) $survey->title, 'description' => (string) $survey->description, 'status' => (int) $survey->status, 'status_label' => $this->statusLabel((int) $survey->status), 'status_class' => $this->statusClass((int) $survey->status), 'display_mode' => (string) $survey->display_mode, 'display_mode_label' => $this->displayModeLabel((string) $survey->display_mode), 'target_label' => $this->targetLabel((string) $survey->target_type, (string) $survey->target_value), 'start_at' => (int) $survey->start_at > 0 ? date('Y-m-d H:i', (int) $survey->start_at) : '-', 'end_at' => (int) $survey->end_at > 0 ? date('Y-m-d H:i', (int) $survey->end_at) : '长期', 'total' => $totalUsers, 'total_responses' => $totalResponses, 'top_percent' => $topPercent, 'questions' => $questions, ]; } private function buildQuestionRows($survey, $includeInactive, $includeStats) { $query = UserSurveyQuestion::where('survey_id', (int) $survey->id); if (!$includeInactive) { $query->where('status', 1); } $questionModels = $query->orderBy('sort', 'asc')->orderBy('id', 'asc')->get(); $rows = []; foreach ($questionModels as $question) { $rows[] = $this->buildQuestionRow($survey, $question, $includeInactive, $includeStats); } if (count($rows) === 0) { $legacyOptions = $this->buildOptionRows($survey, 0, $includeInactive, $includeStats); if (count($legacyOptions) > 0) { $rows[] = [ 'id' => 0, 'title' => (string) $survey->title, 'description' => (string) $survey->description, 'status' => 1, 'options' => $legacyOptions, 'total' => 0, ]; } } return $rows; } private function buildQuestionRow($survey, $question, $includeInactive, $includeStats) { return [ 'id' => (int) $question->id, 'title' => (string) $question->title, 'description' => (string) $question->description, 'status' => (int) $question->status, 'options' => $this->buildOptionRows($survey, (int) $question->id, $includeInactive, $includeStats), 'total' => 0, ]; } private function buildOptionRows($survey, $questionId, $includeInactive, $includeStats) { $query = UserSurveyOption::where('survey_id', (int) $survey->id) ->where('question_id', (int) $questionId); if (!$includeInactive) { $query->where('status', 1); } $rows = []; $options = $query->orderBy('sort', 'asc')->orderBy('id', 'asc')->get(); foreach ($options as $option) { $count = 0; if ($includeStats) { $count = UserSurveyResponse::where('survey_id', (int) $survey->id) ->where('question_id', (int) $questionId) ->where('option_id', (int) $option->id) ->count(); } $rows[] = [ 'id' => (int) $option->id, 'label' => (string) $option->label, 'content' => (string) $option->content, 'status' => (int) $option->status, 'count' => $count, 'percent' => '0', ]; } return $rows; } private function normalizeQuestions($questions) { if (!is_array($questions)) { return []; } $rows = []; foreach ($questions as $question) { if (!is_array($question)) { continue; } $options = $this->normalizeOptions( isset($question['options']) ? $question['options'] : [], isset($question['option_ids']) ? $question['option_ids'] : [] ); $title = $this->limitText($this->cleanText(isset($question['title']) ? $question['title'] : ''), 255); $description = $this->limitText($this->cleanText(isset($question['description']) ? $question['description'] : ''), 2000); if ($title === '' && count($options) === 0) { continue; } $rows[] = [ 'id' => isset($question['id']) ? (int) $question['id'] : 0, 'title' => $title, 'description' => $description, 'options' => $options, ]; } return $rows; } private function normalizeOptions($optionValues, $optionIds) { if (!is_array($optionValues)) { $optionValues = []; } if (!is_array($optionIds)) { $optionIds = []; } $rows = []; foreach ($optionValues as $index => $value) { $content = $this->limitText($this->cleanText($value), 500); if ($content === '') { continue; } $rows[] = [ 'id' => isset($optionIds[$index]) ? (int) $optionIds[$index] : 0, 'content' => $content, ]; } return $rows; } private function optionLabel($index) { $index = (int) $index; $label = ''; do { $label = chr(65 + ($index % 26)) . $label; $index = (int) floor($index / 26) - 1; } while ($index >= 0); return $label; } private function normalizeStatus($value) { $value = (int) $value; return in_array($value, [0, 1, 2], true) ? $value : 0; } private function normalizeDisplayMode($value) { $value = trim((string) $value); return in_array($value, ['card', 'modal', 'required'], true) ? $value : 'card'; } private function normalizeTargetType($value) { $value = trim((string) $value); return in_array($value, ['all', 'paid'], true) ? $value : 'all'; } private function parseDateTime($value, $default) { $value = trim((string) $value); if ($value === '') { return (int) $default; } $timestamp = strtotime($value); return $timestamp === false ? (int) $default : (int) $timestamp; } private function statusLabel($status) { if ((int) $status === 1) { return '进行中'; } if ((int) $status === 2) { return '已关闭'; } return '草稿'; } private function statusClass($status) { if ((int) $status === 1) { return 'text-bg-success'; } if ((int) $status === 2) { return 'text-bg-secondary'; } return 'text-bg-light'; } private function displayModeLabel($mode) { $labels = [ 'card' => '首页卡片', 'modal' => '弹窗提醒', 'required' => '必须选择', ]; return isset($labels[$mode]) ? $labels[$mode] : '首页卡片'; } private function targetLabel($type, $value) { if ($type === 'paid') { return '付费用户'; } return '全部用户'; } private function cleanText($value) { return trim(strip_tags((string) $value)); } private function limitText($text, $length) { $text = (string) $text; if (function_exists('mb_substr')) { return mb_substr($text, 0, $length, 'UTF-8'); } return substr($text, 0, $length); } private function clampInt($value, $min, $max) { return max($min, min($max, (int) $value)); } private function formatPercent($value) { return rtrim(rtrim(number_format((float) $value, 2, '.', ''), '0'), '.'); } private function json($response, $ret, $msg, array $extra = []) { $payload = array_merge([ 'ret' => $ret, 'msg' => $msg, ], $extra); $response->getBody()->write(json_encode($payload)); return $response->withHeader('Content-Type', 'application/json; charset=utf-8'); } }