| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- <?php
- namespace App\Console\Commands;
- use App\Services\PointsStatsService;
- use Illuminate\Console\Command;
- class PointsDailyStatsCommand extends Command
- {
- protected $signature = 'stats:points-daily
- {--date= : 统计指定日期 Y-m-d,默认昨天}
- {--from= : 批量补跑起始日期 Y-m-d}
- {--to= : 批量补跑结束日期 Y-m-d,需与 --from 同用}';
- protected $description = '按日聚合积分消耗与token用量统计';
- public function handle(PointsStatsService $service)
- {
- $from = $this->option('from');
- $to = $this->option('to');
- $date = $this->option('date');
- dLog('command')->info('开始统计积分消耗与token用量', [
- 'date' => $date ?: null,
- 'from' => $from ?: null,
- 'to' => $to ?: null,
- ]);
- if ($from && $to) {
- $dates = $this->dateRange($from, $to);
- } elseif ($date) {
- $dates = [$date];
- } elseif ($from || $to) {
- dLog('command')->warning('--from 与 --to 必须同时提供', ['from' => $from, 'to' => $to]);
- $this->error('--from 与 --to 必须同时提供');
- return 1;
- } else {
- $dates = [date('Y-m-d', strtotime('-1 day'))];
- }
- $total = 0;
- try {
- foreach ($dates as $d) {
- if (!$this->validDate($d)) {
- dLog('command')->error('无效日期,终止统计', ['date' => $d]);
- $this->error("无效日期: {$d}");
- return 1;
- }
- $count = $service->statsForDate($d);
- $total += $count;
- dLog('command')->info('日期统计完成', ['date' => $d, 'rows' => $count]);
- $this->info("{$d} 写入 {$count} 行");
- }
- } catch (\Throwable $e) {
- dLog('command')->error('积分token日统计失败', [
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString(),
- ]);
- $this->error('统计失败: ' . $e->getMessage());
- return 1;
- }
- dLog('command')->info('积分token日统计完成', ['dates' => count($dates), 'total_rows' => $total]);
- $this->info("完成,共写入 {$total} 行");
- return 0;
- }
- private function validDate(string $date): bool
- {
- $parts = explode('-', $date);
- if (count($parts) !== 3) {
- return false;
- }
- [$year, $month, $day] = array_map('intval', $parts);
- return checkdate($month, $day, $year);
- }
- private function dateRange(string $from, string $to): array
- {
- $dates = [];
- $cursor = strtotime($from);
- $end = strtotime($to);
- while ($cursor <= $end) {
- $dates[] = date('Y-m-d', $cursor);
- $cursor = strtotime('+1 day', $cursor);
- }
- return $dates;
- }
- }
|