Browse Source

付费用户送金统计

laowu 7 hours ago
parent
commit
f1b40fd0fd

+ 176 - 0
app/Console/Commands/RecordPaidRewardDailyStatistics.php

@@ -0,0 +1,176 @@
+<?php
+
+namespace App\Console\Commands;
+
+use App\Facade\TableName;
+use App\Models\RecordScoreInfo;
+use Carbon\Carbon;
+use Illuminate\Console\Command;
+use Illuminate\Support\Facades\DB;
+
+class RecordPaidRewardDailyStatistics extends Command
+{
+    protected $signature = 'RecordPaidRewardDailyStatistics {day?}';
+
+    protected $description = '统计付费用户各奖励类型每日送出金额';
+
+    public function handle()
+    {
+        $day = $this->argument('day') ?: Carbon::yesterday()->format('Y-m-d');
+
+        $dateId = date('Ymd', strtotime($day));
+
+        $stats = $this->buildStats($day);
+
+        foreach ($stats as $item) {
+            DB::table(TableName::QPRecordDB() . 'RecordPaidRewardDailyStatistics')->updateOrInsert(
+                [
+                    'DateID' => $dateId,
+                    'StatType' => $item['StatType'],
+                ],
+                [
+                    'TotalAmount' => $item['TotalAmount'],
+                    'CreatedAt' => now()->format('Y-m-d H:i:s'),
+                    'UpdatedAt' => now()->format('Y-m-d H:i:s'),
+                ]
+            );
+        }
+
+        $this->info("RecordPaidRewardDailyStatistics done: {$day}");
+
+        return true;
+    }
+
+    private function buildStats(string $day): array
+    {
+        $stats = [];
+        $signIn = $this->signInState($day);
+        $stats[] = $signIn;
+        $bankruptHelp = $this->bankruptHelp($day);
+        $stats[] = $bankruptHelp;
+        $stats[] = $this->fromSuperballPrize($day, 'superball');
+        $stats[] = $this->fromChristmasWheel($day, 'christmas_gift_wheel');
+        $stats[] = $this->fromScoreReason($day, 'bound_phone', 21);
+        $dbStats = DB::table(TableName::QPRecordDB() . 'RecordPaidRewardDailyStatistics')
+            ->lock('with(nolock)')
+            ->where('DateID', date('Ymd', strtotime($day)))
+            ->select('StatType', 'TotalAmount')
+            ->get()->map(function ($item) {
+                return json_decode(json_encode($item), true);
+            })->toArray();
+        $stats[] = $this->sumAll(array_merge($dbStats, $stats), 'total_send');
+
+        return $stats;
+    }
+
+    private function sumAll(array $stats, string $type): array
+    {
+        $totalAmount = 0;
+
+        foreach ($stats as $item) {
+            $totalAmount += (int)($item['TotalAmount'] ?? 0);
+        }
+
+        return [
+            'StatType' => $type,
+            'TotalAmount' => $totalAmount,
+        ];
+    }
+
+    private function fromScoreReason(string $day, string $type, int $reason): array
+    {
+        $start = $day . ' 00:00:00';
+        $end = date('Y-m-d H:i:s', strtotime($day . ' +1 day'));
+
+        $row = DB::connection('sqlsrv')
+            ->table(TableName::QPRecordDB() . 'RecordUserScoreChange as r')
+            ->join(TableName::QPAccountsDB() . 'YN_VIPAccount as va', 'va.UserID', '=', 'r.UserID')
+            ->where('va.Recharge', '>', 0)
+            ->where('r.Reason', $reason)
+            ->where('r.UpdateTime', '>=', $start)
+            ->where('r.UpdateTime', '<', $end)
+            ->selectRaw('
+                ISNULL(CAST(SUM(r.ChangeScore) AS BIGINT), 0) as TotalAmount
+            ')
+            ->first();
+
+        return [
+            'StatType' => $type,
+            'TotalAmount' => (int)($row->TotalAmount ?? 0),
+        ];
+    }
+
+    private function fromSuperballPrize(string $day, string $type): array
+    {
+        $row = DB::connection('sqlsrv')
+            ->table(TableName::agent() . 'superball_prize_log as p')
+            ->join(TableName::QPAccountsDB() . 'YN_VIPAccount as va', 'va.UserID', '=', 'p.user_id')
+            ->where('va.Recharge', '>', 0)
+            ->whereDate('p.created_at', $day)
+            ->selectRaw('
+                ISNULL(CAST(SUM(p.total_amount) AS BIGINT), 0) as TotalAmount
+            ')
+            ->first();
+
+        return [
+            'StatType' => $type,
+            'TotalAmount' => (int)($row->TotalAmount ?? 0),
+        ];
+    }
+
+    private function fromChristmasWheel(string $day, string $type): array
+    {
+        $start = $day . ' 00:00:00';
+        $end = date('Y-m-d H:i:s', strtotime($day . ' +1 day'));
+
+        $row = DB::connection('sqlsrv')
+            ->table(TableName::agent() . 'christmas_wheel_history as h')
+            ->join(TableName::QPAccountsDB() . 'YN_VIPAccount as va', 'va.UserID', '=', 'h.UserID')
+            ->where('va.Recharge', '>', 0)
+            ->where('h.created_at', '>=', $start)
+            ->where('h.created_at', '<', $end)
+            ->selectRaw('
+                ISNULL(CAST(SUM(h.reward * 100) AS BIGINT), 0) as TotalAmount
+            ')
+            ->first();
+
+        return [
+            'StatType' => $type,
+            'TotalAmount' => (int)($row->TotalAmount ?? 0),
+        ];
+    }
+
+    private function signInState(string $day)
+    {
+        $res = DB::table('QPRecordDB.dbo.RecordSignIn as h')
+            ->lock('with(nolock)')
+            ->whereDate('SignInDate', $day)
+            ->leftJoin(DB::raw('QPAccountsDB.dbo.YN_VIPAccount as va with(nolock)'),
+                'va.UserID', '=', 'h.UserID')
+            ->where('va.Recharge', '>', 0)
+            ->selectRaw('sum(RewardScore) as TotalAmount')
+            ->first();
+        return [
+            'StatType' => 'sign_in',
+            'TotalAmount' => (int)($res->TotalAmount ?? 0),
+        ];
+    }
+
+    private function bankruptHelp(string $day)
+    {
+        $res = DB::table('QPRecordDB.dbo.RecordUserScoreChange as rus')
+            ->lock('with(nolock)')
+            ->leftJoin(DB::raw('QPAccountsDB.dbo.YN_VIPAccount as va with(nolock)'),
+                'va.UserID', '=', 'rus.UserID')
+            ->whereDate('UpdateTime', $day)
+            ->where('va.Recharge', '>', 0)
+            ->where('rus.Reason', 13)
+            ->selectRaw('sum(ChangeScore) as TotalAmount')
+            ->first();
+        return [
+            'StatType' => 'bankrupt_help',
+            'TotalAmount' => (int)($res->TotalAmount ?? 0),
+        ];
+    }
+}
+

+ 3 - 0
app/Console/Kernel.php

@@ -14,6 +14,7 @@ use App\Console\Commands\RecordPlatformData;
 use App\Console\Commands\RecordServerGameCount;
 use App\Console\Commands\RecordServerGameCountYesterday;
 use App\Console\Commands\RecordThreeGameYesterday;
+use App\Console\Commands\RecordPaidRewardDailyStatistics;
 use App\Console\Commands\RecordUserScoreChangeStatistics;
 use App\Console\Commands\SuperballUpdatePoolAndStats;
 use Illuminate\Console\Scheduling\Schedule;
@@ -34,6 +35,7 @@ class Kernel extends ConsoleKernel
         RecordPlatformData::class,
         RecordServerGameCount::class,
         RecordServerGameCountYesterday::class,
+        RecordPaidRewardDailyStatistics::class,
         RecordUserScoreChangeStatistics::class,
         DecStock::class,
         CheckIosAppStore::class,
@@ -59,6 +61,7 @@ class Kernel extends ConsoleKernel
         $schedule->command('online_max')->cron('*/8 * * * * ')->description('最高在线人数统计');
         $schedule->command('record_server_game_count_yesterday')->cron('05 0 * * * ')->description('按天统计游戏人数--今日执行昨日');
         $schedule->command('RecordPlatformData')->cron('10 0 * * * ')->description('数据统计');
+        $schedule->command('RecordPaidRewardDailyStatistics')->cron('15 0 * * * ')->description('付费用户奖励日统计');
         $schedule->command('RecordUserScoreChangeStatistics')->cron('03 0 * * * ')->description('用户金额变化明细按天按用户汇总');
         $schedule->command('superball:update-pool-stats')->everyMinute()->description('Superball 每分钟刷新奖池及展示统计');
         $schedule->command('online_report')->everyMinute()->description('每分钟统计曲线');

+ 26 - 2
app/Http/Controllers/Game/PayRechargeController.php

@@ -11,6 +11,7 @@ use App\Http\Controllers\Controller;
 use App\Http\helper\NumConfig;
 use App\Models\Order;
 use App\Services\OrderServices;
+use App\Services\PaidRewardStatisticsService;
 use App\Utility\SetNXLock;
 use App\Util;
 use Illuminate\Http\Request;
@@ -670,7 +671,15 @@ class PayRechargeController extends Controller
             // 添加奖励到用户账户
             if ($rewardAmount > 0) {
                 OuroGameService::AddScore($userId, $rewardAmount * NumConfig::NUM_VALUE, 52, true);  // 52=首充礼包奖励
-                
+                $userRecharge = DB::table('QPAccountsDB.dbo.YN_VIPAccount')->lock('with(nolock)')
+                    ->where('UserID', $userId)
+                    ->value('Recharge') ?: 0;
+                if ($userRecharge > 0) {
+                    app(PaidRewardStatisticsService::class)
+                        ->incrementRecordByDateIDAndType(date('Ymd'), 'first_recharge_claim',
+                            $rewardAmount * NumConfig::NUM_VALUE);
+                }
+
                 \Log::info('首充礼包奖励领取', [
                     'user_id' => $userId,
                     'reward_type' => $rewardType,
@@ -1074,7 +1083,15 @@ class PayRechargeController extends Controller
         try {
             // 发放奖励
             OuroGameService::AddScore($userId, $rewardAmount * NumConfig::NUM_VALUE, 52, true); // 52=礼包奖励
-            
+            $userRecharge = DB::table('QPAccountsDB.dbo.YN_VIPAccount')->lock('with(nolock)')
+                ->where('UserID', $userId)
+                ->value('Recharge') ?: 0;
+            if ($userRecharge > 0) {
+                app(PaidRewardStatisticsService::class)
+                    ->incrementRecordByDateIDAndType(date('Ymd'), 'daily_gift_claim',
+                        $rewardAmount * NumConfig::NUM_VALUE);
+            }
+
             // 标记已领取
             Redis::setex($redisKey, 86400, 1); // 24小时过期
             
@@ -1568,6 +1585,13 @@ class PayRechargeController extends Controller
         try {
             // 发放奖励
             OuroGameService::AddScore($userId, $amount * NumConfig::NUM_VALUE, 52, true); // 52=礼包奖励
+            $userRecharge = DB::table('QPAccountsDB.dbo.YN_VIPAccount')->lock('with(nolock)')
+                ->where('UserID', $userId)
+                ->value('Recharge') ?: 0;
+            if ($userRecharge > 0) {
+                app(PaidRewardStatisticsService::class)
+                    ->incrementRecordByDateIDAndType(date('Ymd'), 'vip_inactive_claim', $amount * NumConfig::NUM_VALUE);
+            }
 
             // 更新位标记
             $newMask = $claimedMask | (1 << $dayIndex);

+ 19 - 0
app/Services/OrderServices.php

@@ -358,9 +358,26 @@ class  OrderServices
                     $vipSendChips = floor($Recharge * NumConfig::NUM_VALUE * ($level->RechargeExtraSendRate/100));
                     if ($vipSendChips > 0) {
                         RecordScoreInfo::addScore($user_id, $vipSendChips, RecordScoreInfo::REASON_VIP_SEND_CHIPS, $AfterScore);
+                        app(PaidRewardStatisticsService::class)
+                            ->incrementRecordByDateIDAndType(date('Ymd'), 'vip_recharge', $vipSendChips);
                     }
                 }
             }
+
+            if (in_array($GiftsID, [0, 301, 302, 304, 305, 402]) && $give > 0) {
+                $typeMap= [
+                    0 => 'normal_recharge',
+                    301 => 'first_recharge_gift',
+                    302 => 'bankrupt_gift',
+                    304 => 'daily_gift',
+                    305 => 'vip_inactive_gift',
+                    402 => 'christmas_gift',
+                ];
+                $type = $typeMap[$GiftsID] ?? 'unknown';
+                app(PaidRewardStatisticsService::class)
+                    ->incrementRecordByDateIDAndType(date('Ymd'), $type, $give);
+            }
+
         }
         // free bonus 礼包:充值后赠送 InsureScore(单位为分)
         if (in_array($GiftsID, [306]) && $payAmt > 0) {
@@ -373,6 +390,8 @@ class  OrderServices
                     DB::table('QPTreasureDB.dbo.GameScoreInfo')
                         ->where('UserID', $user_id)
                         ->increment('InsureScore', $bonus);
+                    app(PaidRewardStatisticsService::class)
+                        ->incrementRecordByDateIDAndType(date('Ymd'), 'free_bonus_gift', $give);
                 }
             }
         }

+ 43 - 0
app/Services/PaidRewardStatisticsService.php

@@ -0,0 +1,43 @@
+<?php
+
+namespace App\Services;
+
+use Illuminate\Database\QueryException;
+use Illuminate\Support\Facades\DB;
+
+class PaidRewardStatisticsService
+{
+    /**
+     * @param $DateID
+     * @param $type
+     * @param mixed $amount 单位:分
+     * @return mixed
+     */
+    public function incrementRecordByDateIDAndType($DateID, $type, $amount)
+    {
+        $this->createIfNotExist($DateID, $type);
+        return DB::table('QPRecordDB.dbo.RecordPaidRewardDailyStatistics')
+            ->where(['DateID' => $DateID, 'StatType' => $type])
+            ->increment('TotalAmount', $amount);
+    }
+
+    private function createIfNotExist($DateID, $type)
+    {
+        $exist = DB::table('QPRecordDB.dbo.RecordPaidRewardDailyStatistics')
+            ->where(['DateID' => $DateID, 'StatType' => $type])->first();
+        if (!$exist) {
+            try {
+                DB::table('QPRecordDB.dbo.RecordPaidRewardDailyStatistics')->insert([
+                    'DateID' => $DateID,
+                    'StatType' => $type,
+                ]);
+            } catch (QueryException $e) {
+                if (stripos($e->getMessage(), 'duplicate key') === false) {
+                    throw $e;
+                }
+            }
+
+        }
+        return true;
+    }
+}