| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- <?php
- namespace App\Module\UrsPromotion\AdminControllers\Metrics;
- use App\Module\UrsPromotion\Models\UrsUserMapping;
- use Carbon\Carbon;
- use Dcat\Admin\Widgets\Metrics\Line;
- use Illuminate\Http\Request;
- /**
- * URS新用户折线图
- * 显示每日新用户数量趋势
- */
- class UrsNewUsersChart extends Line
- {
- /**
- * 初始化卡片内容
- *
- * @return void
- */
- protected function init()
- {
- parent::init();
-
- $this->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,
- ],
- ],
- ]);
- }
- }
|