report_teacher_weekly_stats.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. <?php
  2. /**
  3. * 近 7 天老师组卷 + 学情分析套数(exam_analysis_results 按 paper_id 去重,一套卷计 1)。
  4. * 按老师:学案/分析/学生数为「本 / 上」并列(仅本侧数字在本大于上时绿色);保留学案·环比、学情·环比。
  5. * 用法:
  6. * php scripts/report_teacher_weekly_stats.php
  7. * php scripts/report_teacher_weekly_stats.php > storage/app/reports/teacher-weekly-stats-$(date +%Y-%m-%d)_$(date +%H%M%S).md
  8. * (shell 里 %H%M%S 会展开为当前时分秒;PDF 见 scripts/report_teacher_weekly_stats_pdf.php)
  9. */
  10. require __DIR__ . '/../vendor/autoload.php';
  11. $app = require_once __DIR__ . '/../bootstrap/app.php';
  12. $app->make(\Illuminate\Contracts\Console\Kernel::class)->bootstrap();
  13. $endCurrent = now();
  14. $startCurrent = now()->subDays(7);
  15. $startPrev = now()->subDays(14);
  16. $endPrev = $startCurrent;
  17. $db = \Illuminate\Support\Facades\DB::class;
  18. $sumPapers = static function ($from, $toExclusive) use ($db) {
  19. $q = $db::table('papers')
  20. ->whereNotNull('teacher_id')
  21. ->where('teacher_id', '!=', '')
  22. ->where('created_at', '>=', $from);
  23. if ($toExclusive !== null) {
  24. $q->where('created_at', '<', $toExclusive);
  25. }
  26. return (int) $q->count();
  27. };
  28. /** 学情分析:以卷子为单位,同一 paper_id 在区间内多条记录只计 1 */
  29. $countDistinctAnalysisPapers = static function ($from, $toExclusive) use ($db) {
  30. $q = $db::table('exam_analysis_results as ear')
  31. ->join('papers as p', 'p.paper_id', '=', 'ear.paper_id')
  32. ->whereNotNull('p.teacher_id')
  33. ->where('p.teacher_id', '!=', '')
  34. ->where('ear.created_at', '>=', $from);
  35. if ($toExclusive !== null) {
  36. $q->where('ear.created_at', '<', $toExclusive);
  37. }
  38. return (int) $q->distinct()->count('ear.paper_id');
  39. };
  40. $countActiveTeachers = static function ($from, $toExclusive) use ($db) {
  41. $q = $db::table('papers')
  42. ->whereNotNull('teacher_id')
  43. ->where('teacher_id', '!=', '')
  44. ->where('created_at', '>=', $from);
  45. if ($toExclusive !== null) {
  46. $q->where('created_at', '<', $toExclusive);
  47. }
  48. return (int) $q->distinct()->count('teacher_id');
  49. };
  50. $totalPapersCur = $sumPapers($startCurrent, null);
  51. $totalPapersPrev = $sumPapers($startPrev, $endPrev);
  52. $totalAnalysisCur = $countDistinctAnalysisPapers($startCurrent, null);
  53. $totalAnalysisPrev = $countDistinctAnalysisPapers($startPrev, $endPrev);
  54. $teachersCur = $countActiveTeachers($startCurrent, null);
  55. $teachersPrev = $countActiveTeachers($startPrev, $endPrev);
  56. $wowLine = static function (int $cur, int $prev): string {
  57. $delta = $cur - $prev;
  58. if ($prev === 0) {
  59. if ($cur === 0) {
  60. return '0';
  61. }
  62. return sprintf('+%d(上周期0)', $delta);
  63. }
  64. $pct = round(($delta / $prev) * 100, 2);
  65. $sign = $delta >= 0 ? '+' : '';
  66. $dir = match (true) {
  67. $delta > 0 => '↑',
  68. $delta < 0 => '↓',
  69. default => '→',
  70. };
  71. return sprintf('%s%d(%s%.2f%%)%s', $sign, $delta, $sign, $pct, $dir);
  72. };
  73. /** 总量表环比列:仅增长标绿 */
  74. $wowLineHtml = static function (int $cur, int $prev) use ($wowLine): string {
  75. $plain = $wowLine($cur, $prev);
  76. if ($cur > $prev) {
  77. return '<span style="color:#16a34a;font-weight:600;">'.$plain.'</span>';
  78. }
  79. return $plain;
  80. };
  81. /** 明细环比列:仅增长标绿 */
  82. $compareCellHtml = static function (int $cur, int $prev): string {
  83. $d = $cur - $prev;
  84. if ($d === 0) {
  85. return '0';
  86. }
  87. if ($prev === 0) {
  88. if ($cur === 0) {
  89. return '0';
  90. }
  91. return '<span style="color:#16a34a;font-weight:600;">+'.$d.'(上0)</span>';
  92. }
  93. $pct = round(($d / $prev) * 100, 1);
  94. $sign = $d > 0 ? '+' : '';
  95. $text = sprintf('%s%d(%s%.1f%%)', $sign, $d, $sign, $pct);
  96. if ($d > 0) {
  97. return '<span style="color:#16a34a;font-weight:600;">'.$text.'</span>';
  98. }
  99. return $text;
  100. };
  101. /** 「本 / 上」并列显示;仅当本 > 上时将本侧数字标绿(上分保持默认色) */
  102. $slashPairGreenHtml = static function (int $cur, int $prev): string {
  103. if ($cur > $prev) {
  104. return '<span style="color:#16a34a;font-weight:600;">'.$cur.'</span> / '.$prev;
  105. }
  106. return $cur.' / '.$prev;
  107. };
  108. $byTeacher = \Illuminate\Support\Facades\DB::table('papers')
  109. ->whereNotNull('teacher_id')
  110. ->where('teacher_id', '!=', '')
  111. ->where('created_at', '>=', $startCurrent)
  112. ->selectRaw('teacher_id, COUNT(*) as paper_count')
  113. ->groupBy('teacher_id')
  114. ->get();
  115. // 近 7 天产生学情分析的试卷套数:按 ear.paper_id 去重后归到 papers.teacher_id
  116. $analysisByTeacher = \Illuminate\Support\Facades\DB::table('exam_analysis_results as ear')
  117. ->join('papers as p', 'p.paper_id', '=', 'ear.paper_id')
  118. ->whereNotNull('p.teacher_id')
  119. ->where('p.teacher_id', '!=', '')
  120. ->where('ear.created_at', '>=', $startCurrent)
  121. ->selectRaw('p.teacher_id, COUNT(DISTINCT ear.paper_id) AS paper_set_count')
  122. ->groupBy('p.teacher_id')
  123. ->get();
  124. $analysisMap = [];
  125. foreach ($analysisByTeacher as $r) {
  126. $analysisMap[(string) $r->teacher_id] = (int) $r->paper_set_count;
  127. }
  128. $paperMap = [];
  129. foreach ($byTeacher as $r) {
  130. $paperMap[(string) $r->teacher_id] = (int) $r->paper_count;
  131. }
  132. $byTeacherPrev = $db::table('papers')
  133. ->whereNotNull('teacher_id')
  134. ->where('teacher_id', '!=', '')
  135. ->where('created_at', '>=', $startPrev)
  136. ->where('created_at', '<', $endPrev)
  137. ->selectRaw('teacher_id, COUNT(*) as paper_count')
  138. ->groupBy('teacher_id')
  139. ->get();
  140. $analysisByTeacherPrev = $db::table('exam_analysis_results as ear')
  141. ->join('papers as p', 'p.paper_id', '=', 'ear.paper_id')
  142. ->whereNotNull('p.teacher_id')
  143. ->where('p.teacher_id', '!=', '')
  144. ->where('ear.created_at', '>=', $startPrev)
  145. ->where('ear.created_at', '<', $endPrev)
  146. ->selectRaw('p.teacher_id, COUNT(DISTINCT ear.paper_id) AS paper_set_count')
  147. ->groupBy('p.teacher_id')
  148. ->get();
  149. $paperMapPrev = [];
  150. foreach ($byTeacherPrev as $r) {
  151. $paperMapPrev[(string) $r->teacher_id] = (int) $r->paper_count;
  152. }
  153. $analysisMapPrev = [];
  154. foreach ($analysisByTeacherPrev as $r) {
  155. $analysisMapPrev[(string) $r->teacher_id] = (int) $r->paper_set_count;
  156. }
  157. /** 学生数:组卷 ∪ 学情,student_id 合并去重(按老师、时间窗) */
  158. $studentUnionSql = <<<'SQL'
  159. SELECT u.teacher_id, COUNT(DISTINCT u.student_id) AS c
  160. FROM (
  161. SELECT teacher_id, student_id FROM papers
  162. WHERE teacher_id IS NOT NULL AND teacher_id != ''
  163. AND student_id IS NOT NULL AND student_id != ''
  164. AND created_at >= ? AND created_at < ?
  165. UNION
  166. SELECT p.teacher_id, ear.student_id
  167. FROM exam_analysis_results ear
  168. INNER JOIN papers p ON p.paper_id = ear.paper_id
  169. WHERE p.teacher_id IS NOT NULL AND p.teacher_id != ''
  170. AND ear.student_id IS NOT NULL AND ear.student_id != ''
  171. AND ear.created_at >= ? AND ear.created_at < ?
  172. ) u
  173. GROUP BY u.teacher_id
  174. SQL;
  175. $studentUnionCurRows = $db::select($studentUnionSql, [$startCurrent, $endCurrent, $startCurrent, $endCurrent]);
  176. $studentUnionPrevRows = $db::select($studentUnionSql, [$startPrev, $endPrev, $startPrev, $endPrev]);
  177. $studentUnionCurMap = [];
  178. foreach ($studentUnionCurRows as $row) {
  179. $studentUnionCurMap[(string) $row->teacher_id] = (int) $row->c;
  180. }
  181. $studentUnionPrevMap = [];
  182. foreach ($studentUnionPrevRows as $row) {
  183. $studentUnionPrevMap[(string) $row->teacher_id] = (int) $row->c;
  184. }
  185. $names = \Illuminate\Support\Facades\DB::table('teachers')->pluck('name', 'teacher_id');
  186. $nameStrMap = [];
  187. foreach ($names as $tid => $nm) {
  188. $nameStrMap[(string) $tid] = $nm;
  189. }
  190. $rows = [];
  191. foreach ($paperMap as $tid => $paperCount) {
  192. $rows[] = [
  193. 'teacher_id' => $tid,
  194. 'name' => (string) ($nameStrMap[$tid] ?? $tid),
  195. 'papers' => $paperCount,
  196. 'analysis_sets' => (int) ($analysisMap[$tid] ?? 0),
  197. 'papers_prev' => (int) ($paperMapPrev[$tid] ?? 0),
  198. 'analysis_sets_prev' => (int) ($analysisMapPrev[$tid] ?? 0),
  199. ];
  200. }
  201. usort($rows, static fn ($a, $b) => $b['papers'] <=> $a['papers']);
  202. $windowCur = sprintf(
  203. '%s ~ %s',
  204. $startCurrent->format('Y-m-d H:i:s'),
  205. $endCurrent->format('Y-m-d H:i:s')
  206. );
  207. $windowPrev = sprintf(
  208. '%s ~ %s',
  209. $startPrev->format('Y-m-d H:i:s'),
  210. $endPrev->format('Y-m-d H:i:s')
  211. );
  212. $generatedAt = $endCurrent->format('Y-m-d H:i:s');
  213. $tz = (string) config('app.timezone', 'UTC');
  214. /**
  215. * 将 [from, to) 均分为 7 段,返回每段内组卷数、学情去重套数。
  216. *
  217. * @return array{labels: list<string>, papers: list<int>, analysis: list<int>}
  218. */
  219. $dailySlices = static function (\Carbon\Carbon $from, \Carbon\Carbon $toExclusive) use ($db): array {
  220. $totalSec = max(1, $toExclusive->getTimestamp() - $from->getTimestamp());
  221. $sliceSec = $totalSec / 7;
  222. $labels = [];
  223. $papers = [];
  224. $analysis = [];
  225. for ($i = 0; $i < 7; $i++) {
  226. $sliceFrom = $from->copy()->addSeconds((int) floor($sliceSec * $i));
  227. $sliceTo = $i < 6
  228. ? $from->copy()->addSeconds((int) floor($sliceSec * ($i + 1)))
  229. : $toExclusive;
  230. $labels[] = $sliceFrom->format('n/j');
  231. $papers[] = (int) $db::table('papers')
  232. ->whereNotNull('teacher_id')
  233. ->where('teacher_id', '!=', '')
  234. ->where('created_at', '>=', $sliceFrom)
  235. ->where('created_at', '<', $sliceTo)
  236. ->count();
  237. $analysis[] = (int) $db::table('exam_analysis_results as ear')
  238. ->join('papers as p', 'p.paper_id', '=', 'ear.paper_id')
  239. ->whereNotNull('p.teacher_id')
  240. ->where('p.teacher_id', '!=', '')
  241. ->where('ear.created_at', '>=', $sliceFrom)
  242. ->where('ear.created_at', '<', $sliceTo)
  243. ->distinct()
  244. ->count('ear.paper_id');
  245. }
  246. return ['labels' => $labels, 'papers' => $papers, 'analysis' => $analysis];
  247. };
  248. $curDaily = $dailySlices($startCurrent, $endCurrent);
  249. $prevDaily = $dailySlices($startPrev, $endPrev);
  250. $buildChartSvg = static function (array $curDaily, array $prevDaily): string {
  251. $labels = $curDaily['labels'];
  252. $pc = $curDaily['papers'];
  253. $ac = $curDaily['analysis'];
  254. $pp = $prevDaily['papers'];
  255. $ap = $prevDaily['analysis'];
  256. $maxY = max(1, ...$pc, ...$ac, ...$pp, ...$ap);
  257. $W = 480;
  258. $H = 200;
  259. $padL = 44;
  260. $padR = 12;
  261. $padT = 16;
  262. $padB = 36;
  263. $gw = $W - $padL - $padR;
  264. $gh = $H - $padT - $padB;
  265. $n = 7;
  266. $xAt = static function (int $i) use ($padL, $gw, $n): float {
  267. return $padL + ($n <= 1 ? $gw / 2 : $gw * $i / ($n - 1));
  268. };
  269. $yAt = static function (int $v) use ($padT, $gh, $maxY): float {
  270. return $padT + $gh - ($v / $maxY) * $gh;
  271. };
  272. $lineWithDots = static function (array $vals, string $stroke, string $dash, float $sw = 1.6) use ($xAt, $yAt, $n): string {
  273. $pts = [];
  274. $circles = '';
  275. for ($i = 0; $i < $n; $i++) {
  276. $x = $xAt($i);
  277. $y = $yAt((int) $vals[$i]);
  278. $pts[] = round($x, 1).','.round($y, 1);
  279. $circles .= sprintf(
  280. '<circle cx="%.1f" cy="%.1f" r="3.2" fill="%s" stroke="#fff" stroke-width="1"/>',
  281. $x,
  282. $y,
  283. $stroke
  284. );
  285. }
  286. $poly = implode(' ', $pts);
  287. $dashAttr = $dash !== '' ? ' stroke-dasharray="'.$dash.'"' : '';
  288. return '<polyline fill="none" stroke="'.$stroke.'" stroke-width="'.$sw.'"'.$dashAttr.' points="'.$poly.'" />'.$circles;
  289. };
  290. $xAxisY = $padT + $gh;
  291. $tickTxt = '';
  292. for ($i = 0; $i < $n; $i++) {
  293. $x = $xAt($i);
  294. $lab = htmlspecialchars((string) ($labels[$i] ?? ''), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
  295. $tickTxt .= sprintf(
  296. '<text x="%.1f" y="%d" text-anchor="middle" font-size="9" fill="#374151" font-family="sun-exta,sans-serif">%s</text>',
  297. $x,
  298. $H - 10,
  299. $lab
  300. );
  301. }
  302. $yTick = '';
  303. for ($k = 0; $k <= 4; $k++) {
  304. $v = (int) round($maxY * $k / 4);
  305. $y = $yAt($v);
  306. $yTick .= sprintf(
  307. '<line x1="%d" y1="%.1f" x2="%d" y2="%.1f" stroke="#e5e7eb" stroke-width="1"/>',
  308. $padL,
  309. $y,
  310. $padL + $gw,
  311. $y
  312. );
  313. $yTick .= sprintf(
  314. '<text x="%d" y="%.1f" font-size="8" fill="#6b7280" font-family="sun-exta,sans-serif">%d</text>',
  315. 4,
  316. $y + 3,
  317. $v
  318. );
  319. }
  320. $legend = '<g font-family="sun-exta,sans-serif" font-size="9">';
  321. $lx = $padL + $gw - 168;
  322. $ly = $padT + 4;
  323. $items = [
  324. ['#2563eb', '学案·本周期', ''],
  325. ['#ea580c', '学情·本周期', ''],
  326. ['#93c5fd', '学案·上周期', '6,4'],
  327. ['#fdba74', '学情·上周期', '6,4'],
  328. ];
  329. foreach ($items as $idx => $it) {
  330. $yy = $ly + $idx * 13;
  331. $legend .= sprintf(
  332. '<line x1="%d" y1="%d" x2="%d" y2="%d" stroke="%s" stroke-width="2" %s/>',
  333. $lx,
  334. $yy,
  335. $lx + 18,
  336. $yy,
  337. $it[0],
  338. $it[2] !== '' ? 'stroke-dasharray="'.$it[2].'"' : ''
  339. );
  340. $legend .= sprintf(
  341. '<text x="%d" y="%d" fill="#111">%s</text>',
  342. $lx + 24,
  343. $yy + 4,
  344. htmlspecialchars($it[1], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8')
  345. );
  346. }
  347. $legend .= '</g>';
  348. $svg = sprintf(
  349. '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 %d %d" width="100%%" height="auto" style="max-width:520px;">',
  350. $W,
  351. $H
  352. );
  353. $svg .= sprintf('<rect x="0" y="0" width="%d" height="%d" fill="#fafafa"/>', $W, $H);
  354. $svg .= $yTick;
  355. $svg .= sprintf('<line x1="%d" y1="%.1f" x2="%.1f" y2="%.1f" stroke="#9ca3af" stroke-width="1"/>', $padL, $xAxisY, $padL + $gw, $xAxisY);
  356. $svg .= $lineWithDots($pp, '#93c5fd', '6,4', 1.4);
  357. $svg .= $lineWithDots($ap, '#fdba74', '6,4', 1.4);
  358. $svg .= $lineWithDots($pc, '#2563eb', '', 1.8);
  359. $svg .= $lineWithDots($ac, '#ea580c', '', 1.8);
  360. $svg .= $tickTxt;
  361. $svg .= $legend;
  362. $svg .= '</svg>';
  363. return $svg;
  364. };
  365. $chartSvg = $buildChartSvg($curDaily, $prevDaily);
  366. echo "## 老师组卷与学情分析(近7天)\n\n";
  367. echo "> 生成 {$generatedAt} · {$tz} · 本 {$windowCur} · 上 {$windowPrev}\n\n";
  368. echo "### 总量\n\n";
  369. echo "| 指标 | 本周期 | 上周期 | 环比 |\n";
  370. echo "| --- | ---: | ---: | --- |\n";
  371. echo sprintf("| 组卷总套数 | %d | %d | %s |\n", $totalPapersCur, $totalPapersPrev, $wowLineHtml($totalPapersCur, $totalPapersPrev));
  372. echo sprintf("| 学情分析套数(卷去重) | %d | %d | %s |\n", $totalAnalysisCur, $totalAnalysisPrev, $wowLineHtml($totalAnalysisCur, $totalAnalysisPrev));
  373. echo sprintf("| 有组卷老师数 | %d | %d | %s |\n", $teachersCur, $teachersPrev, $wowLineHtml($teachersCur, $teachersPrev));
  374. echo "\n### 近7段每日对比(本周期与上周期时间轴对齐)\n\n";
  375. echo '<div class="weekly-chart">';
  376. echo $chartSvg;
  377. echo "</div>\n\n";
  378. echo "### 按老师\n\n";
  379. echo '<table class="weekly-teacher-table">';
  380. echo '<colgroup>';
  381. echo '<col style="width:4%" /><col style="width:12%" />';
  382. echo '<col class="col-slash" style="width:10%" /><col style="width:13%" />';
  383. echo '<col class="col-slash" style="width:10%" /><col style="width:13%" />';
  384. echo '<col class="col-slash" style="width:10%" />';
  385. echo '</colgroup>';
  386. echo '<thead><tr>';
  387. echo '<th>排名</th><th>老师</th><th>学案数量</th><th>学案·环比</th><th>分析数量</th><th>学情·环比</th><th>学生数</th>';
  388. echo "</tr></thead>\n<tbody>\n";
  389. $i = 1;
  390. foreach ($rows as $r) {
  391. $tidKey = (string) $r['teacher_id'];
  392. $nmRaw = (string) $r['name'];
  393. $nmEsc = htmlspecialchars($nmRaw, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
  394. $tidEsc = htmlspecialchars($tidKey, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
  395. $nameWithId = $nmEsc.' <span class="teacher-id">('.$tidEsc.')</span>';
  396. $pc = $r['papers'];
  397. $pp = $r['papers_prev'];
  398. $ac = $r['analysis_sets'];
  399. $ap = $r['analysis_sets_prev'];
  400. $stuC = (int) ($studentUnionCurMap[$tidKey] ?? 0);
  401. $stuP = (int) ($studentUnionPrevMap[$tidKey] ?? 0);
  402. echo '<tr>';
  403. echo '<td style="text-align:right">'.((string) $i++).'</td>';
  404. echo '<td class="td-name">'.$nameWithId.'</td>';
  405. echo '<td style="text-align:right" class="td-slash" title="本周期 / 上周期:组卷套数">'.$slashPairGreenHtml($pc, $pp).'</td>';
  406. echo '<td>'.$compareCellHtml($pc, $pp).'</td>';
  407. echo '<td style="text-align:right" class="td-slash" title="本周期 / 上周期:学情分析套数(卷去重)">'.$slashPairGreenHtml($ac, $ap).'</td>';
  408. echo '<td>'.$compareCellHtml($ac, $ap).'</td>';
  409. echo '<td style="text-align:right" class="td-slash td-stu" title="本周期 / 上周期:组卷∪学情学生合并去重">'.$slashPairGreenHtml($stuC, $stuP).'</td>';
  410. echo "</tr>\n";
  411. }
  412. echo "</tbody></table>\n";
  413. echo sprintf("\n本周期有组卷 **%d** 人。\n", count($rows));