report_teacher_weekly_stats.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. <?php
  2. /**
  3. * 近 7 天老师组卷 + 学情分析套数(exam_analysis_results 按 paper_id 去重,一套卷计 1)。
  4. * 按老师:学生数·本/上 = 组卷∪学情 student_id 合并去重,分列本周期与上周期;老师列含 teacher_id,如 龚 (433)。
  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. $byTeacher = \Illuminate\Support\Facades\DB::table('papers')
  102. ->whereNotNull('teacher_id')
  103. ->where('teacher_id', '!=', '')
  104. ->where('created_at', '>=', $startCurrent)
  105. ->selectRaw('teacher_id, COUNT(*) as paper_count')
  106. ->groupBy('teacher_id')
  107. ->get();
  108. // 近 7 天产生学情分析的试卷套数:按 ear.paper_id 去重后归到 papers.teacher_id
  109. $analysisByTeacher = \Illuminate\Support\Facades\DB::table('exam_analysis_results as ear')
  110. ->join('papers as p', 'p.paper_id', '=', 'ear.paper_id')
  111. ->whereNotNull('p.teacher_id')
  112. ->where('p.teacher_id', '!=', '')
  113. ->where('ear.created_at', '>=', $startCurrent)
  114. ->selectRaw('p.teacher_id, COUNT(DISTINCT ear.paper_id) AS paper_set_count')
  115. ->groupBy('p.teacher_id')
  116. ->get();
  117. $analysisMap = [];
  118. foreach ($analysisByTeacher as $r) {
  119. $analysisMap[(string) $r->teacher_id] = (int) $r->paper_set_count;
  120. }
  121. $paperMap = [];
  122. foreach ($byTeacher as $r) {
  123. $paperMap[(string) $r->teacher_id] = (int) $r->paper_count;
  124. }
  125. $byTeacherPrev = $db::table('papers')
  126. ->whereNotNull('teacher_id')
  127. ->where('teacher_id', '!=', '')
  128. ->where('created_at', '>=', $startPrev)
  129. ->where('created_at', '<', $endPrev)
  130. ->selectRaw('teacher_id, COUNT(*) as paper_count')
  131. ->groupBy('teacher_id')
  132. ->get();
  133. $analysisByTeacherPrev = $db::table('exam_analysis_results as ear')
  134. ->join('papers as p', 'p.paper_id', '=', 'ear.paper_id')
  135. ->whereNotNull('p.teacher_id')
  136. ->where('p.teacher_id', '!=', '')
  137. ->where('ear.created_at', '>=', $startPrev)
  138. ->where('ear.created_at', '<', $endPrev)
  139. ->selectRaw('p.teacher_id, COUNT(DISTINCT ear.paper_id) AS paper_set_count')
  140. ->groupBy('p.teacher_id')
  141. ->get();
  142. $paperMapPrev = [];
  143. foreach ($byTeacherPrev as $r) {
  144. $paperMapPrev[(string) $r->teacher_id] = (int) $r->paper_count;
  145. }
  146. $analysisMapPrev = [];
  147. foreach ($analysisByTeacherPrev as $r) {
  148. $analysisMapPrev[(string) $r->teacher_id] = (int) $r->paper_set_count;
  149. }
  150. /** 学生数:组卷 ∪ 学情,student_id 合并去重(按老师、时间窗) */
  151. $studentUnionSql = <<<'SQL'
  152. SELECT u.teacher_id, COUNT(DISTINCT u.student_id) AS c
  153. FROM (
  154. SELECT teacher_id, student_id FROM papers
  155. WHERE teacher_id IS NOT NULL AND teacher_id != ''
  156. AND student_id IS NOT NULL AND student_id != ''
  157. AND created_at >= ? AND created_at < ?
  158. UNION
  159. SELECT p.teacher_id, ear.student_id
  160. FROM exam_analysis_results ear
  161. INNER JOIN papers p ON p.paper_id = ear.paper_id
  162. WHERE p.teacher_id IS NOT NULL AND p.teacher_id != ''
  163. AND ear.student_id IS NOT NULL AND ear.student_id != ''
  164. AND ear.created_at >= ? AND ear.created_at < ?
  165. ) u
  166. GROUP BY u.teacher_id
  167. SQL;
  168. $studentUnionCurRows = $db::select($studentUnionSql, [$startCurrent, $endCurrent, $startCurrent, $endCurrent]);
  169. $studentUnionPrevRows = $db::select($studentUnionSql, [$startPrev, $endPrev, $startPrev, $endPrev]);
  170. $studentUnionCurMap = [];
  171. foreach ($studentUnionCurRows as $row) {
  172. $studentUnionCurMap[(string) $row->teacher_id] = (int) $row->c;
  173. }
  174. $studentUnionPrevMap = [];
  175. foreach ($studentUnionPrevRows as $row) {
  176. $studentUnionPrevMap[(string) $row->teacher_id] = (int) $row->c;
  177. }
  178. $names = \Illuminate\Support\Facades\DB::table('teachers')->pluck('name', 'teacher_id');
  179. $nameStrMap = [];
  180. foreach ($names as $tid => $nm) {
  181. $nameStrMap[(string) $tid] = $nm;
  182. }
  183. $rows = [];
  184. foreach ($paperMap as $tid => $paperCount) {
  185. $rows[] = [
  186. 'teacher_id' => $tid,
  187. 'name' => (string) ($nameStrMap[$tid] ?? $tid),
  188. 'papers' => $paperCount,
  189. 'analysis_sets' => (int) ($analysisMap[$tid] ?? 0),
  190. 'papers_prev' => (int) ($paperMapPrev[$tid] ?? 0),
  191. 'analysis_sets_prev' => (int) ($analysisMapPrev[$tid] ?? 0),
  192. ];
  193. }
  194. usort($rows, static fn ($a, $b) => $b['papers'] <=> $a['papers']);
  195. $windowCur = sprintf(
  196. '%s ~ %s',
  197. $startCurrent->format('Y-m-d H:i:s'),
  198. $endCurrent->format('Y-m-d H:i:s')
  199. );
  200. $windowPrev = sprintf(
  201. '%s ~ %s',
  202. $startPrev->format('Y-m-d H:i:s'),
  203. $endPrev->format('Y-m-d H:i:s')
  204. );
  205. $generatedAt = $endCurrent->format('Y-m-d H:i:s');
  206. $tz = (string) config('app.timezone', 'UTC');
  207. /**
  208. * 将 [from, to) 均分为 7 段,返回每段内组卷数、学情去重套数。
  209. *
  210. * @return array{labels: list<string>, papers: list<int>, analysis: list<int>}
  211. */
  212. $dailySlices = static function (\Carbon\Carbon $from, \Carbon\Carbon $toExclusive) use ($db): array {
  213. $totalSec = max(1, $toExclusive->getTimestamp() - $from->getTimestamp());
  214. $sliceSec = $totalSec / 7;
  215. $labels = [];
  216. $papers = [];
  217. $analysis = [];
  218. for ($i = 0; $i < 7; $i++) {
  219. $sliceFrom = $from->copy()->addSeconds((int) floor($sliceSec * $i));
  220. $sliceTo = $i < 6
  221. ? $from->copy()->addSeconds((int) floor($sliceSec * ($i + 1)))
  222. : $toExclusive;
  223. $labels[] = $sliceFrom->format('n/j');
  224. $papers[] = (int) $db::table('papers')
  225. ->whereNotNull('teacher_id')
  226. ->where('teacher_id', '!=', '')
  227. ->where('created_at', '>=', $sliceFrom)
  228. ->where('created_at', '<', $sliceTo)
  229. ->count();
  230. $analysis[] = (int) $db::table('exam_analysis_results as ear')
  231. ->join('papers as p', 'p.paper_id', '=', 'ear.paper_id')
  232. ->whereNotNull('p.teacher_id')
  233. ->where('p.teacher_id', '!=', '')
  234. ->where('ear.created_at', '>=', $sliceFrom)
  235. ->where('ear.created_at', '<', $sliceTo)
  236. ->distinct()
  237. ->count('ear.paper_id');
  238. }
  239. return ['labels' => $labels, 'papers' => $papers, 'analysis' => $analysis];
  240. };
  241. $curDaily = $dailySlices($startCurrent, $endCurrent);
  242. $prevDaily = $dailySlices($startPrev, $endPrev);
  243. $buildChartSvg = static function (array $curDaily, array $prevDaily): string {
  244. $labels = $curDaily['labels'];
  245. $pc = $curDaily['papers'];
  246. $ac = $curDaily['analysis'];
  247. $pp = $prevDaily['papers'];
  248. $ap = $prevDaily['analysis'];
  249. $maxY = max(1, ...$pc, ...$ac, ...$pp, ...$ap);
  250. $W = 480;
  251. $H = 200;
  252. $padL = 44;
  253. $padR = 12;
  254. $padT = 16;
  255. $padB = 36;
  256. $gw = $W - $padL - $padR;
  257. $gh = $H - $padT - $padB;
  258. $n = 7;
  259. $xAt = static function (int $i) use ($padL, $gw, $n): float {
  260. return $padL + ($n <= 1 ? $gw / 2 : $gw * $i / ($n - 1));
  261. };
  262. $yAt = static function (int $v) use ($padT, $gh, $maxY): float {
  263. return $padT + $gh - ($v / $maxY) * $gh;
  264. };
  265. $lineWithDots = static function (array $vals, string $stroke, string $dash, float $sw = 1.6) use ($xAt, $yAt, $n): string {
  266. $pts = [];
  267. $circles = '';
  268. for ($i = 0; $i < $n; $i++) {
  269. $x = $xAt($i);
  270. $y = $yAt((int) $vals[$i]);
  271. $pts[] = round($x, 1).','.round($y, 1);
  272. $circles .= sprintf(
  273. '<circle cx="%.1f" cy="%.1f" r="3.2" fill="%s" stroke="#fff" stroke-width="1"/>',
  274. $x,
  275. $y,
  276. $stroke
  277. );
  278. }
  279. $poly = implode(' ', $pts);
  280. $dashAttr = $dash !== '' ? ' stroke-dasharray="'.$dash.'"' : '';
  281. return '<polyline fill="none" stroke="'.$stroke.'" stroke-width="'.$sw.'"'.$dashAttr.' points="'.$poly.'" />'.$circles;
  282. };
  283. $xAxisY = $padT + $gh;
  284. $tickTxt = '';
  285. for ($i = 0; $i < $n; $i++) {
  286. $x = $xAt($i);
  287. $lab = htmlspecialchars((string) ($labels[$i] ?? ''), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
  288. $tickTxt .= sprintf(
  289. '<text x="%.1f" y="%d" text-anchor="middle" font-size="9" fill="#374151" font-family="sun-exta,sans-serif">%s</text>',
  290. $x,
  291. $H - 10,
  292. $lab
  293. );
  294. }
  295. $yTick = '';
  296. for ($k = 0; $k <= 4; $k++) {
  297. $v = (int) round($maxY * $k / 4);
  298. $y = $yAt($v);
  299. $yTick .= sprintf(
  300. '<line x1="%d" y1="%.1f" x2="%d" y2="%.1f" stroke="#e5e7eb" stroke-width="1"/>',
  301. $padL,
  302. $y,
  303. $padL + $gw,
  304. $y
  305. );
  306. $yTick .= sprintf(
  307. '<text x="%d" y="%.1f" font-size="8" fill="#6b7280" font-family="sun-exta,sans-serif">%d</text>',
  308. 4,
  309. $y + 3,
  310. $v
  311. );
  312. }
  313. $legend = '<g font-family="sun-exta,sans-serif" font-size="9">';
  314. $lx = $padL + $gw - 168;
  315. $ly = $padT + 4;
  316. $items = [
  317. ['#2563eb', '组卷·本周期', ''],
  318. ['#ea580c', '学情·本周期', ''],
  319. ['#93c5fd', '组卷·上周期', '6,4'],
  320. ['#fdba74', '学情·上周期', '6,4'],
  321. ];
  322. foreach ($items as $idx => $it) {
  323. $yy = $ly + $idx * 13;
  324. $legend .= sprintf(
  325. '<line x1="%d" y1="%d" x2="%d" y2="%d" stroke="%s" stroke-width="2" %s/>',
  326. $lx,
  327. $yy,
  328. $lx + 18,
  329. $yy,
  330. $it[0],
  331. $it[2] !== '' ? 'stroke-dasharray="'.$it[2].'"' : ''
  332. );
  333. $legend .= sprintf(
  334. '<text x="%d" y="%d" fill="#111">%s</text>',
  335. $lx + 24,
  336. $yy + 4,
  337. htmlspecialchars($it[1], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8')
  338. );
  339. }
  340. $legend .= '</g>';
  341. $svg = sprintf(
  342. '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 %d %d" width="100%%" height="auto" style="max-width:520px;">',
  343. $W,
  344. $H
  345. );
  346. $svg .= sprintf('<rect x="0" y="0" width="%d" height="%d" fill="#fafafa"/>', $W, $H);
  347. $svg .= $yTick;
  348. $svg .= sprintf('<line x1="%d" y1="%.1f" x2="%.1f" y2="%.1f" stroke="#9ca3af" stroke-width="1"/>', $padL, $xAxisY, $padL + $gw, $xAxisY);
  349. $svg .= $lineWithDots($pp, '#93c5fd', '6,4', 1.4);
  350. $svg .= $lineWithDots($ap, '#fdba74', '6,4', 1.4);
  351. $svg .= $lineWithDots($pc, '#2563eb', '', 1.8);
  352. $svg .= $lineWithDots($ac, '#ea580c', '', 1.8);
  353. $svg .= $tickTxt;
  354. $svg .= $legend;
  355. $svg .= '</svg>';
  356. return $svg;
  357. };
  358. $chartSvg = $buildChartSvg($curDaily, $prevDaily);
  359. echo "## 老师组卷与学情分析(近7天)\n\n";
  360. echo "> 生成 {$generatedAt} · {$tz} · 本 {$windowCur} · 上 {$windowPrev}\n\n";
  361. echo "### 总量\n\n";
  362. echo "| 指标 | 本周期 | 上周期 | 环比 |\n";
  363. echo "| --- | ---: | ---: | --- |\n";
  364. echo sprintf("| 组卷总套数 | %d | %d | %s |\n", $totalPapersCur, $totalPapersPrev, $wowLineHtml($totalPapersCur, $totalPapersPrev));
  365. echo sprintf("| 学情分析套数(卷去重) | %d | %d | %s |\n", $totalAnalysisCur, $totalAnalysisPrev, $wowLineHtml($totalAnalysisCur, $totalAnalysisPrev));
  366. echo sprintf("| 有组卷老师数 | %d | %d | %s |\n", $teachersCur, $teachersPrev, $wowLineHtml($teachersCur, $teachersPrev));
  367. echo "\n### 近7段每日对比(本周期与上周期时间轴对齐)\n\n";
  368. echo '<div class="weekly-chart">';
  369. echo '<p style="font-size:9pt;color:#4b5563;margin:0 0 6px 0;">横轴为统计窗口均分的 7 段,数字为每段「组卷套数 / 学情分析套数(卷去重)」;实线本周期,虚线上一同期。</p>';
  370. echo $chartSvg;
  371. echo "</div>\n\n";
  372. echo "### 按老师\n\n";
  373. echo '<table class="weekly-teacher-table">';
  374. echo '<colgroup>';
  375. echo '<col style="width:4%" /><col style="width:11%" />';
  376. echo '<col style="width:7%" /><col style="width:7%" /><col style="width:8%" />';
  377. echo '<col class="col-an" style="width:9%" /><col class="col-an" style="width:9%" /><col style="width:8%" />';
  378. echo '<col class="col-stu" style="width:8%" /><col class="col-stu" style="width:8%" />';
  379. echo '</colgroup>';
  380. echo '<thead><tr>';
  381. echo '<th>排名</th><th>老师</th><th>组卷·本</th><th>组卷·上</th><th>组卷·环比</th><th>学情·本</th><th>学情·上</th><th>学情·环比</th><th>学生数·本</th><th>学生数·上</th>';
  382. echo "</tr></thead>\n<tbody>\n";
  383. $i = 1;
  384. foreach ($rows as $r) {
  385. $tidKey = (string) $r['teacher_id'];
  386. $nmRaw = (string) $r['name'];
  387. $nmEsc = htmlspecialchars($nmRaw, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
  388. $tidEsc = htmlspecialchars($tidKey, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
  389. $nameWithId = $nmEsc.' <span class="teacher-id">('.$tidEsc.')</span>';
  390. $pc = $r['papers'];
  391. $pp = $r['papers_prev'];
  392. $ac = $r['analysis_sets'];
  393. $ap = $r['analysis_sets_prev'];
  394. $stuC = (int) ($studentUnionCurMap[$tidKey] ?? 0);
  395. $stuP = (int) ($studentUnionPrevMap[$tidKey] ?? 0);
  396. echo '<tr>';
  397. echo '<td style="text-align:right">'.((string) $i++).'</td>';
  398. echo '<td class="td-name">'.$nameWithId.'</td>';
  399. echo '<td style="text-align:right">'.((string) $pc).'</td>';
  400. echo '<td style="text-align:right">'.((string) $pp).'</td>';
  401. echo '<td>'.$compareCellHtml($pc, $pp).'</td>';
  402. echo '<td style="text-align:right" class="td-an">'.((string) $ac).'</td>';
  403. echo '<td style="text-align:right" class="td-an">'.((string) $ap).'</td>';
  404. echo '<td>'.$compareCellHtml($ac, $ap).'</td>';
  405. echo '<td style="text-align:right" class="td-stu" title="组卷∪学情,学生合并去重">'.$stuC.'</td>';
  406. echo '<td style="text-align:right" class="td-stu" title="组卷∪学情,学生合并去重">'.$stuP.'</td>';
  407. echo "</tr>\n";
  408. }
  409. echo "</tbody></table>\n";
  410. echo sprintf("\n本周期有组卷 **%d** 人。\n", count($rows));