month = $date; try { $this->initStart(); }catch (\Exception $e){ return json_encode(["status"=>"error", "msg"=>$e->getMessage()], 256); } } $this->reRun(); return json_encode(["status"=>"success", "msg"=>""], 256); } // 重跑 protected function reRun(): void { $day = date('d'); $hour = date('H'); $i = date('i'); // 重跑上个整月 if(($day==1 || $day==15) && $hour==4 && $i<10){ $this->month = date('Y-m', strtotime("-1 month")); $this->initStart(); } } protected function initStart(): void { // 重置数据 $this->data = []; $this->regPay(); $this->siteAuth(); $this->replaceData(); } protected function regPay(): void { $tb = "sdk_order_success"; $sDate = "{$this->month}-01 00:00:00"; $eDate = date('Y-m-t 23:59:59', strtotime($this->month)); $filed = "{$this->group}, DATE_FORMAT(reg_date,'%Y-%m') as reg_month, sum(money) as pay_total, sum(paid_amount) as pay_amount, count(distinct uid) as pay_num"; $where = [ ['pay_date', 'between', [$sDate, $eDate]], ]; $result = Db::connect('db_game_log')->table($tb)->field($filed)->where($where)->group("{$this->group}, DATE_FORMAT(reg_date,'%Y-%m')")->select()->toArray(); $this->pushData($result); $regMonthList = array_column($result, 'reg_month'); foreach ($regMonthList as $regMonth){ $res = $this->addupTotalMonth($regMonth); if($res) $this->pushData($res); } } protected function addupTotalMonth($regMonth) { $tb = "sdk_order_success"; $filed = "{$this->group},$regMonth as reg_month, sum(money) as addup_pay_total, sum(paid_amount) as addup_pay_amount, count(distinct uid) as addup_pay_num"; $srData = $regMonth."-01 00:00:00"; $erDate = date('Y-m-t 23:59:59', strtotime($srData)); $epDate = date('Y-m-t 23:59:59', strtotime($this->month)); $where = array( 'reg_date' => ['between', [$srData, $erDate]], 'pay_date' => ['between', [$srData, $epDate]], ); return Db::connect('db_game_log')->table($tb)->field($filed)->where($where)->group_by($this->group.", reg_month")->select(); } protected function siteAuth(): void { $agentList = Db::connect('db_advert')->table("agent")->column("id, media_id, auth_id"); $agentListMap = array_column($agentList, null, "id"); if($this->data){ foreach ($this->data as &$item){ $item['tdate'] = $this->month; $item['auth_id'] = $agentListMap[$item['agent_id']]['auth_id'] ?? 0; // 负责人 $item['media_id'] = $agentListMap[$item['agent_id']]['media_id'] ?? 0; // 媒体 } } } protected function replaceData(): bool { // 先删除,再写入 Db::connect('db_data_report')->table($this->table)->where(['reg_month' => $this->month, 'pay_month'=>$this->month])->delete(); return Db::connect('db_data_report')->table($this->table)->insertAll($this->data) !== false; } protected function pushData($rows): void { if ($rows) { foreach ($rows as $row) { $groupArr = explode(',', $this->group); $uniqueKey = ""; foreach ($groupArr as $groupKey){ $uniqueKey .= $row[$groupKey] . "-"; } foreach ($row as $k => $v) { $this->data[$uniqueKey][$k] = !empty($this->data[$uniqueKey][$k]) ? $this->data[$uniqueKey][$k] + $v :$v; } } } } }