height(300); $this->chartHeight(180); $this->title('URS新用户趋势'); $this->dropdown([ '7' => '最近 7 天', '14' => '最近 14 天', '28' => '最近 28 天', '90' => '最近 90 天', ]); } /** * 处理请求 * * @param Request $request * * @return mixed|void */ public function handle(Request $request) { $days = (int) $request->get('option', 7); $data = $this->getNewUsersData($days); // 卡片内容 - 显示总数 $this->withContent($data['total']); // 图表数据 - 显示每日数量 $this->withChart($data['daily']); } /** * 获取新用户数据 * * @param int $days 天数 * @return array */ private function getNewUsersData(int $days): array { $endDate = Carbon::today(); $startDate = $endDate->copy()->subDays($days - 1); // 获取指定时间范围内的新用户数据 $newUsers = UrsUserMapping::where('created_at', '>=', $startDate) ->where('created_at', '<=', $endDate->endOfDay()) ->where('status', UrsUserMapping::STATUS_VALID) ->selectRaw('DATE(created_at) as date, COUNT(*) as count') ->groupBy('date') ->orderBy('date') ->get() ->keyBy('date'); // 构建每日数据数组 $dailyData = []; $totalCount = 0; for ($i = 0; $i < $days; $i++) { $date = $startDate->copy()->addDays($i)->format('Y-m-d'); $count = $newUsers->get($date)->count ?? 0; $dailyData[] = $count; $totalCount += $count; } return [ 'total' => number_format($totalCount), 'daily' => $dailyData, ]; } /** * 设置图表数据 * * @param array $data * @return $this */ public function withChart(array $data) { return $this->chart([ 'series' => [ [ 'name' => $this->title, 'data' => $data, ], ], ]); } }