report_teacher_weekly_stats.php 17 KB

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