<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 < zuojiazi @ vip . qq . com > < http: / / www . zjzit . cn >
// +----------------------------------------------------------------------
namespace Admin\Controller;
use User\Api\UserApi as UserApi;
use function GuzzleHttp\Psr7\str;
/**
* 后台首页控制器
* @author 麦当苗儿 < zuojiazi @ vip . qq . com >
*/
class TimingController extends AdminController {
public function _initialize(){
}
public function caculateDeviceInfo() {
$start = strtotime(date("Ymd",time()))-86400;
$end = $start+1;
// if (I('time')) {
// $start = strtotime(I('time'));
// $end = $start+1;
// }
if (I('start')& & I('end')) {
$start = strtotime(I('start'));
$end = strtotime(I('end'))+1;
} else if (I('start')& & !I('end')) {
$start = strtotime(I('start'));
$end = strtotime(I('start'))+1;
} else if (!I('start')& & I('end')) {
$start = strtotime(I('end'));
$end = strtotime(I('end'))+1;
}
if ($start>$end) {
echo '开始时间不能大于结束时间';
}
ini_set('memory_limit','1024M');
// $device = D('DeviceRecord');
// echo 1;
for($startTime = $start;$startTime< $end;$startTime=$startTime+86400) {
echo date("Y-m-d",$startTime).' 安卓 ';
//当日新增设备
$newSql = M('device_record','tab_')->field('min(create_time) as create_time,model,unique_code,id')->where(['version'=>1])->group('unique_code')->select(false);
$data['new_device'] = M('device_record','tab_')->table('(' . $newSql . ') as a')->where(['create_time'=>array('between',[$startTime,$startTime+86399])])->order('create_time')->count();
echo $data['new_device'].' ';
//当日活跃设备
$data['active_device'] = $this->active(['create_time'=>array('between',[$startTime,$startTime+86399]),'version'=>1]);
echo $data['active_device'].' ';
$data['time'] = $startTime;
$data['version'] = 1;
$data['today_new_device'] =json_encode($this->news_on_time(['create_time'=>['between',[$startTime,$startTime+86399]]],'news',5,'time,version','time',1));
// echo M('device_record','tab_')->_sql()."\n";
$data['today_active_device'] =json_encode($this->active_on_time(['create_time'=>['between',[$startTime,$startTime+86399]],'version'=>1],'active',5,'time,version'));
// echo M('device_record','tab_')->_sql()."\n";
$data['today_model_device'] = json_encode($this->model(['create_time'=>['between',[$startTime,$startTime+86399]],'version'=>1]));
$data['model'] = json_encode($this->modelDevice(['create_time'=>['between',[$startTime,$startTime+86399]],'version'=>1]));
$duration = $this->duration(['create_time'=>array('between',[$startTime-86400*7,$startTime-1])]);
$newSqls = M('device_record','tab_')->field('min(create_time) as create_time,model,unique_code,id')->group('unique_code')->select(false);
$data['duration7'] = ($duration/M('device_record','tab_')->table('(' . $newSqls . ') as a')->where(['create_time'=>array('between',[$startTime-86400*7,$startTime-1])])->order('create_time')->count())/7;
$getStatistics = M('device_statistics','tab_')->where(['time'=>$startTime,'version'=>1])->find();
echo "\n";
if (!$getStatistics) {
M('device_statistics','tab_')->add($data);
} else {
M('device_statistics','tab_')->where(['time'=>$startTime,'version'=>1])->save($data);
}
echo date("Y-m-d",$startTime).' 苹果 ';
//当日新增设备
$newSql = M('device_record','tab_')->field('min(create_time) as create_time,model,unique_code,id')->where(['version'=>2])->group('unique_code')->select(false);
$data['new_device'] = M('device_record','tab_')->table('(' . $newSql . ') as a')->where(['create_time'=>array('between',[$startTime,$startTime+86399])])->order('create_time')->count();
echo $data['new_device'].' ';
//当日活跃设备
$data['active_device'] = $this->active(['create_time'=>array('between',[$startTime,$startTime+86399]),'version'=>2]);
echo $data['active_device'].' ';
$data['time'] = $startTime;
$data['version'] = 2;
$data['today_new_device'] =json_encode($this->news_on_time(['create_time'=>['between',[$startTime,$startTime+86399]]],'news',5,'time,version','time',2));
// echo M('device_record','tab_')->_sql();die();
$data['today_active_device'] =json_encode($this->active_on_time(['create_time'=>['between',[$startTime,$startTime+86399]],'version'=>2],'active',5,'time,version'));
$data['today_model_device'] = json_encode($this->model(['create_time'=>['between',[$startTime,$startTime+86399]],'version'=>2]));
$data['model'] = json_encode($this->modelDevice(['create_time'=>['between',[$startTime,$startTime+86399]],'version'=>2]));
// $duration = $this->duration(['create_time'=>array('between',[$startTime-86400*7,$startTime-1]),'version'=>2]);
// $data['duration7'] = ($duration/M('device_record','tab_')->table('(' . $newSql . ') as a')->where(['create_time'=>array('between',[$startTime-86400*7,$startTime-1])])->order('create_time')->count())/7;
$data['duration7'] = 0;
$getStatistics = M('device_statistics','tab_')->where(['time'=>$startTime,'version'=>2])->find();
echo "\n";
if (!$getStatistics) {
M('device_statistics','tab_')->add($data);
} else {
M('device_statistics','tab_')->where(['time'=>$startTime,'version'=>2])->save($data);
}
}
}
public function caculateTodayDevice() {
$start = strtotime(date("Ymd",time()));
$end = $start+1;
if (I('start')& & I('end')) {
$start = strtotime(I('start'));
$end = strtotime(I('end'))+1;
} else if (I('start')& & !I('end')) {
$start = strtotime(I('start'));
$end = strtotime(I('start'))+1;
} else if (!I('start')& & I('end')) {
$start = strtotime(I('end'));
$end = strtotime(I('end'))+1;
}
if ($start>$end) {
echo '开始时间不能大于结束时间';
}
ini_set('memory_limit','1024M');
// $device = D('DeviceRecord');
// echo 1;
for($startTime = $start;$startTime< $end;$startTime=$startTime+86400) {
echo date("Y-m-d",$startTime).' 安卓 ';
//当日新增设备
$newSql = M('device_record','tab_')->field('min(create_time) as create_time,model,unique_code,id')->where(['version'=>1])->group('unique_code')->select(false);
$data['new_device'] = M('device_record','tab_')->table('(' . $newSql . ') as a')->where(['create_time'=>array('between',[$startTime,$startTime+86399])])->order('create_time')->count();
$data['time'] = $startTime;
echo $data['new_device'].' ';
$duration = $this->duration(['create_time'=>array('between',[$startTime-86400*7,$startTime-1])]);
$newSqls = M('device_record','tab_')->field('min(create_time) as create_time,model,unique_code,id')->group('unique_code')->select(false);
$data['duration7'] = ($duration/M('device_record','tab_')->table('(' . $newSqls . ') as a')->where(['create_time'=>array('between',[$startTime-86400*7,$startTime-1])])->order('create_time')->count())/7;
$data['version'] = 1;
$getStatistics = M('device_statistics','tab_')->where(['time'=>$startTime,'version'=>1])->find();
echo "\n";
if (!$getStatistics) {
M('device_statistics','tab_')->add($data);
} else {
M('device_statistics','tab_')->where(['time'=>$startTime,'version'=>1])->save($data);
}
$data['duration7'] = 0;
echo date("Y-m-d",$startTime).' 苹果 ';
//当日新增设备
$newSql = M('device_record','tab_')->field('min(create_time) as create_time,model,unique_code,id')->where(['version'=>2])->group('unique_code')->select(false);
$data['new_device'] = M('device_record','tab_')->table('(' . $newSql . ') as a')->where(['create_time'=>array('between',[$startTime,$startTime+86399])])->order('create_time')->count();
echo $data['new_device'].' ';
$data['version'] = 2;
$getStatistics = M('device_statistics','tab_')->where(['time'=>$startTime,'version'=>2])->find();
echo "\n";
if (!$getStatistics) {
M('device_statistics','tab_')->add($data);
} else {
M('device_statistics','tab_')->where(['time'=>$startTime,'version'=>2])->save($data);
}
}
}
public function duration($map=array()) {
return M('device_record','tab_')->where($map)->sum('duration');
}
public function active($map=array()) {
$sql = M('device_record','tab_')->field('create_time,model,unique_code')->where($map)->select(false);
$sql = M('device_record','tab_')->table('(' . $sql . ') as a')->group('unique_code')->order('create_time')->select(false);
$sql = "select count(*) as count from ({$sql})t";
$count = M('device_record','tab_')->query($sql);
return $count[0]['count'];
}
public function news_on_time($map=array(),$field='news',$flag=1,$group='time',$order='time',$version = 1) {
switch($flag) {
case 2:{$dateform = '%Y-%m';};break;
case 3:{$dateform = '%Y-%u';};break;
case 4:{$dateform = '%Y';};break;
case 5:{$dateform = '%Y-%m-%d %H';};break;
default:$dateform = '%Y-%m-%d';
}
$sql = M('device_record','tab_')->field('min(create_time) as create_time,version,unique_code,id')->where(['version'=>$version])->group('unique_code')->select(false);
$news = M('device_record','tab_')->table('(' . $sql . ') as a')
->field('FROM_UNIXTIME(a.create_time, "'.$dateform.'") as '.$group.',group_concat(a.id) as id,group_concat(a.unique_code) as unique_code ,COUNT(a.unique_code) AS '.$field)
->where($map)->group($group)->order($order)->select();
// echo M('device_record','tab_')->_sql();die();
return $news;
}
public function active_on_time($map=array(),$field='active',$flag=1,$group='time',$order='time') {
switch($flag) {
case 2:{$dateform = '%Y-%m';};break;
case 3:{$dateform = '%Y-%u';};break;
case 4:{$dateform = '%Y';};break;
case 5:{$dateform = '%Y-%m-%d %H';};break;
default:$dateform = '%Y-%m-%d';
}
$sql = M('device_record','tab_')->field('create_time,version,unique_code,id')->where($map)->select(false);
$mid = M('device_record','tab_')->table('(' . $sql . ') as m')->group('unique_code')->select(false);
$active = M('device_record','tab_')->table('(' . $mid . ') as a')
->field('FROM_UNIXTIME(a.create_time, "'.$dateform.'") as '.$group.',group_concat(a.id) as id,group_concat(a.unique_code) as unique_code ,COUNT(a.unique_code) AS '.$field)
->group($group)->order($order)->select();
// echo $this->_sql();die();
return $active;
}
public function model($map=array()) {
$sql = M('device_record','tab_')->field('create_time,model,version,unique_code')->where($map)->select(false);
$mid = M('device_record','tab_')->table('(' .$sql. ') as m')->group('unique_code')->select(false);
return M('device_record','tab_')->table('(' .$mid. ') as a')->field('a.model,version,count(a.unique_code) as count')->group('model,version')->order('count desc')->select();
}
public function modelDevice($map=array()) {
$sql = M('device_record','tab_')->field('model,version,unique_code')->where($map)->select(false);
$mid = M('device_record','tab_')->table('(' .$sql. ') as m')->group('unique_code')->select();
return $mid;
}
//格式 starttime 20200229 endtime 20200230
public function setAvailableBalance() {
if (strtotime($_GET['endtime'])< strtotime ( $ _GET [ ' starttime ' ] ) & & $ _GET [ ' endtime ' ] ) {
echo '错误,结束时间小于开始时间';
}
// $starttime = 1571587200;
$starttime = strtotime(date('Ymd',time()))-86400;
// var_dump($starttime);die();
if ($_GET['starttime']) {
$starttime = strtotime($_GET['starttime']);
}
$endtime = $starttime + 86399;
if ($_GET['endtime']) {
$endtime = strtotime($_GET['endtime']) + 86399;
}
for ($start = $starttime; $start< $endtime; $start=$start + 86400) {
// var_dump($starttime);die();
$data = M('spend','tab_')
->field("sum(`pay_amount`) as pay_amount,promote_id,promote_account,tab_spend.game_id,tab_spend.game_name,tab_spend.server_id,tab_spend.server_name,CASE WHEN old_value_ratio is NULL THEN 0 ELSE sum(`pay_amount`) * old_value_ratio END as available_balance")
->join('left join tab_resource_verify_config as config on tab_spend.game_id = config.game_id and config.status = 1')
->where(['pay_status'=>1,'pay_way'=>['egt',1],'pay_time'=>['between',[$start,$start+86399]]])
->group('promote_id,game_id,server_id')
->select();
// dump($data);die();
foreach ($data as $key => $value) {
$insert['promote_id'] = $value['promote_id'];
$insert['promote_account'] = $value['promote_account'];
$insert['game_id'] = $value['game_id'];
$insert['game_name'] = $value['game_name'];
$insert['available_balance'] = round($value['available_balance'],0);
$insert['server_id'] = $value['server_id'];
$insert['server_name'] = $value['server_name'];
$availableBalanceData = M('promote_game_available_balance','tab_')
->where(['promote_id'=>$value['promote_id'],'game_id'=>$value['game_id'],'server_id'=>$value['server_id']])
->find();
if (round($value['available_balance'],0) > 0 & & !$availableBalanceData) {
M('promote_game_available_balance','tab_')->add($insert);
} else if (round($value['available_balance'],0) > 0 & & $availableBalanceData) {
M('promote_game_available_balance','tab_')
->where(['promote_id'=>$value['promote_id'],'game_id'=>$value['game_id'],'server_id'=>$value['server_id']])
->setInc('available_balance',round($value['available_balance'],0));
}
// dump(round($value['available_balance'],0));
}
}
echo '执行成功';
}
public function getTogetherUserAccount() {
if (I('user_id','')) {
$user_id = I('user_id','');
} else {
return false;
}
$data = M('user','tab_')->field('account')->where(['id'=>$user_id])->find();
// var_dump($data);
if (!$data) {
return false;
}
$this->ajaxReturn($data);
}
public function getChannelConfig($pay_way = 0,$config=false) {
if(!$config) {
$payWayName = $this->pay_way_name[$pay_way];
$toolConfig = M('tool','tab_')->where(['name'=>$payWayName])->find();
$config = json_decode($toolConfig['config'],true);
if(empty($config['channel_rate'])){
$channel_rate = 0;
}else {
$channel_rate = $config['channel_rate'];
}
}else {
foreach($this->pay_way_name as $key => $value) {
$name = $value;
$toolConfig = M('tool','tab_')->where(['name'=>$name])->find();
$config = json_decode($toolConfig['config'],true);
if(empty($config['channel_rate'])){
$channel_rate[$key] = 0;
}else {
$channel_rate[$key] = $config['channel_rate'];
}
}
}
return $channel_rate;
}
public function setPromoteStatistics() {
echo "-------------------------------------------------------------\n";
$startTime = strtotime("20190829");
if (I("start_time")=="yesterday") {
$startTime = strtotime(date("Y-m-d",strtotime("-1 day")));
}
$endTime = time();
if (I("start_time")) {
$startTime = strtotime(I("start_time"));
}
if (I("end_time")) {
$endTime = strtotime(I("end_time"));
}
if ($endTime < $startTime) {
echo "错误,开始时间不得大于结束时间";die();
}
for($start = $startTime;$start< $endTime;$start=$start+86400) {
$map['pay_time'] = ['between', array($start, $start+86399)];
$map['tp1.chain'] = '/';
$map['pay_status'] = 1;
$map['promote_id'] = array('egt', 0);
$data = M('promote', 'tab_')->alias('tp1')
->field('tp1.account as promote_account,tp1.id as promote_id,floor(sum(pay_amount)*100) as count')
->join("tab_promote AS tp2 ON tp2.`chain` LIKE CONCAT('%/', tp1.id, '/%') OR tp2.id = tp1.id", 'left')
->join("tab_spend as s on tp2.id = s.promote_id", 'left')
->where($map)
->group('tp1.id')
->order('count desc')
->select();
foreach($data as $key => $value) {
$insert['promote_id'] = $value['promote_id'];
$insert['promote_account'] = $value['promote_account'];
$insert['count'] = $value['count']?$value['count']:0;
$insert['time'] = $start;
$statisticsData = M("promote_statistics","tab_")
->where(['promote_id'=>$value['promote_id'],'time'=>$start])
->find();
$date = date("Y-m-d",$start);
if ($statisticsData) {
M("promote_statistics","tab_")
->where(['promote_id'=>$value['promote_id'],'time'=>$start])
->save($insert);
echo "更新{$value['promote_account']}在{$date}充值:{$value['count']}\n";
} else {
M("promote_statistics","tab_")->add($insert);
echo "新增{$value['promote_account']}在{$date}充值:{$value['count']}\n";
}
}
}
echo "-------------------------------------------------------------\n";
}
public function shiftPromoteStatistics() {
$data = M("shift_task")->where(['change_status'=>0,'type'=>2])->select();
$promote_data = [];
$change_id = [];
foreach ($data as $key => $value) {
$promote_data[] = $value['from_promote_id'];
$promote_data[] = $value['to_promote_id'];
$change_id[] = $value['id'];
}
$promote_data=array_unique($promote_data);
sort($promote_data);
if(!$promote_data) {
echo "没有数据";
die();
}
$chain_data = M("promote","tab_")
->field("id")
->where(['chain'=>'/','id'=>['in',$promote_data]])
->select();
$chain_data = array_column($chain_data,'id');
$chain_data_secord = M("promote","tab_")
->field("substring_index(chain, '/', 2) as id")
->where(['id'=>['in',$promote_data]])
->select();
$chain_data_secord = array_column($chain_data_secord,'id');
foreach($chain_data_secord as $k=>$v){
if($v == '/'){
unset($chain_data_secord[$k]);
}
$chain_data_secord[$k] = substr($chain_data_secord[$k],1,strlen($v));
if ($chain_data_secord[$k] == false) {
unset($chain_data_secord[$k]);
}
// var_dump(strlen($chain_data_secord[$k]));
}
$data = [];
$data = array_merge(array_unique($chain_data),array_unique($chain_data_secord));
$this->PromoteStatistics($data);
M("shift_task")->where(['id'=>['in',$change_id]])->save(['change_status'=>1]);
// dump($data);
// dump(array_unique($chain_data_secord));
}
public function PromoteStatistics($promote) {
echo "-------------------------------------------------------------\n";
$startTime = strtotime("20190829");
$endTime = time();
if (I("start_time")) {
$startTime = strtotime(I("start_time"));
}
if ($promote) {
$map['tp2.id'] = ['in',$promote];
}
if (I("end_time")) {
$endTime = strtotime(I("end_time"));
}
if ($endTime < $startTime) {
echo "错误,开始时间不得大于结束时间";die();
}
for($start = $startTime;$start< $endTime;$start=$start+86400) {
$map['pay_time'] = ['between', array($start, $start+86399)];
$map['tp1.chain'] = '/';
$map['pay_status'] = 1;
$map['promote_id'] = array('egt', 0);
$data = M('promote', 'tab_')->alias('tp1')
->field('tp1.account as promote_account,tp1.id as promote_id,floor(sum(pay_amount)*100) as count')
->join("tab_promote AS tp2 ON tp2.`chain` LIKE CONCAT('%/', tp1.id, '/%') OR tp2.id = tp1.id", 'left')
->join("tab_spend as s on tp2.id = s.promote_id", 'left')
->where($map)
->group('tp1.id')
->order('count desc')
->select();
foreach($data as $key => $value) {
$insert['promote_id'] = $value['promote_id'];
$insert['promote_account'] = $value['promote_account'];
$insert['count'] = $value['count']?$value['count']:0;
$insert['time'] = $start;
$statisticsData = M("promote_statistics","tab_")
->where(['promote_id'=>$value['promote_id'],'time'=>$start])
->find();
$date = date("Y-m-d",$start);
if ($statisticsData) {
M("promote_statistics","tab_")
->where(['promote_id'=>$value['promote_id'],'time'=>$start])
->save($insert);
echo "更新{$value['promote_account']}在{$date}充值:{$value['count']}\n";
} else {
M("promote_statistics","tab_")->add($insert);
echo "新增{$value['promote_account']}在{$date}充值:{$value['count']}\n";
}
}
}
echo "-------------------------------------------------------------\n";
}
function getPayway($name) {
switch ($name){
case 'alipay': //支付宝 1
return 1;
case 'wei_xin': //微信支付 2 3
return 2;
case 'heepay': //汇付宝 6
return 6;
case 'sqpay': //双乾支付9,10,15
return 9;
case 'yeepay': //易宝支付17
return 17;
case 'ptb_pay':
return 0;
default:
return '';
}
}
/**
* 获取下游公司的特殊补点金额
* @param int $start_time
* @param int $end_time
* @return array
*/
public function getSpecialComplement($start_time=0,$end_time =0,$promote_id = 0) {
$data = SM("company_statement","tab_")
// ->where("statement_begin_time< ={$start_time} and statement_end_time< ={$end_time} and withdraw_type=3")
->where("(statement_begin_time < ={$end_time} AND ( statement_end_time = 0 OR statement_end_time >= {$start_time})) and withdraw_type=3")
->select();
$return = [];
foreach ($data as $key => $value) {
$info = [];
$pool_data = SM("company_statement_pool","tab_")
->field("id")
->where("(statement_begin_time < ={$end_time} AND ( statement_end_time = 0 OR statement_end_time >= {$start_time})) and withdraw_type=3 and statement_ids like '%{$value['id']}%'")
->select();
foreach ($pool_data as $pk => $pv) {
$info = SM("company_statement_info","tab_")
->field("statement_info")
->where("(statement_begin_time < ={$end_time} AND ( statement_end_time = 0 OR statement_end_time >= {$start_time})) and withdraw_type=3 and pool_id = {$pv['id']} and company_id = {$value['company_id']}")
->find()['statement_info'];
if ($info) {
break;
}
}
if ($info) {
$statement_info = json_decode($info,true);
} else {
$statement_info = json_decode($value['statement_info'],true);
}
$is_inside = M("PromoteCompany","tab_")->field("is_inside")->where("id='{$value['company_id']}'")->find()['is_inside'];
if ($value['company_type'] == 2) {
foreach ($statement_info as $skey => $sval) {
$info = $sval['game_list'];
foreach ($info as $k => $v) {
$statement_begin_time = strtotime(str_replace('.','-',$v['statement_begin_time']));
$statement_end_time = strtotime(str_replace('.','-',$v['statement_end_time']))+86399;
if (date("m",$statement_begin_time)!=date("m",$start_time) || date("m",$statement_end_time)!=date("m",$end_time)) {
continue;
}
//
if (isset($return[$value['company_id']."-".$sval['promote_id']."-".$v['relation_game_id']])) {
$return[$value['company_id']."-".$sval['promote_id']."-".$v['relation_game_id']] = !$is_inside?($v['sum_money']-($v['withhold']?$v['withhold']:0)):0;
} else {
$return[$value['company_id']."-".$sval['promote_id']."-".$v['relation_game_id']] += !$is_inside?($v['sum_money']-($v['withhold']?$v['withhold']:0)):0;
}
}
}
} else {
//判断公司比例是不是隶属于这个会长
$compamy_info = M("promote","tab_")->where(['id'=>$promote_id,'company_id'=>$value['company_id']])->find();
if ($compamy_info) {
foreach ($statement_info as $k => $v) {
$statement_begin_time = strtotime(str_replace('.','-',$v['statement_begin_time']));
$statement_end_time = strtotime(str_replace('.','-',$v['statement_end_time']))+86399;
if (date("m",$statement_begin_time)!=date("m",$start_time) || date("m",$statement_end_time)!=date("m",$end_time)) {
continue;
}
$amount_time['is_check'] = ['neq',2];
$amount_time['tab_spend.pay_status'] = 1;
$amount_time['pay_way'] = ['egt',0];
$amount_time['_string'] = "payed_time between {$statement_begin_time} and {$statement_end_time} and relation_game_id={$v['relation_game_id']}";
D("Spend")->addSubsiteWhere($amount_time);
$dataAmount = M("spend","tab_")
->field("pay_amount,relation_game_id,relation_game_name,payed_time,game_type_name,substring_index(substring_index(promote.`chain`,'/',2),'/',-1) promote_id,chain,admin_id")
->join("left join tab_promote promote on tab_spend.promote_id=promote.id")
->join("left join tab_game game on tab_spend.game_id=game.id")
->where($amount_time)
->select(false);
$dataAmount = M()->table("({$dataAmount})a")
->field("a.*,sum(pay_amount) pay_amount,promote.account,member.real_name")
->join("left join tab_promote promote on promote_id=promote.id")
->join("left join sys_member member on promote.admin_id=member.uid ")
->where(['promote_id'=>$promote_id])
->group("promote_id")
->find();
$return[$value['company_id']."-".$promote_id."-".$v['relation_game_id']] += !$is_inside?(($dataAmount['pay_amount']*$v['increment_ratio'])/100):0;
}
}
}
}
// dump($return);
return $return;
}
public function test() {
$this->getSpecialComplement(strtotime(date("Y-m-1",strtotime("2020-08"))),strtotime(date("Y-m-t",strtotime("2020-08")))+86399,2259);
// dump(D("CompanyGameRatio")->getPromoteCompanyGameRatio(18,(string)207,1600099200,1603728000,1));
// $this->createMarketBonus("all");
}
// $admin_id = 0,$promote_id = 0,$company_id=0,$relation_game_id=0,$date ='',$pay_amount = 0
public function getCompanyGameRadio($admin_id = 0,$promote_id = 0,$company_id=0,$relation_game_id=0,$begintime=0,$endtime =0,$pay_amount = 0) {
// $company_id=239;
// $relation_game_id=213;
// $pay_amount = 440;
// $date = "2020-08";
// $admin_id = 27;
// $promote_id = 3235;
// $begintime = strtotime(date("Y-m-1",strtotime($date)));
// $endtime = strtotime(date("Y-m-t",strtotime($date)))+86399;
$is_inside = M("PromoteCompany","tab_")->field("is_inside")->where("id='{$company_id}'")->find()['is_inside'];
if ($is_inside == 1) {
return 0;
}
// $company_game_ratio = M("company_game_ratio","tab_")
// ->where(['company_id'=>$company_id,'relation_game_id'=>$relation_game_id])
// ->where("(end_time>={$begintime} and (end_time< ={$endtime} and end_time!=0)) or (begin_time>={$begintime} and begin_time< ={$endtime}) or (begin_time< ={$begintime} and (end_time>={$endtime} or end_time=0))")
// ->order("begin_time ASC")
// ->select();
//
$company_data = M('promote_company','tab_')
->field("company_belong")
->where("id={$company_id}")
->find();
//
// $game_ratio_mould = M("game_ratio_mould","tab_")
// ->where(['relation_game_id'=>$relation_game_id,'company_belong'=>$company_data['company_belong'],
// "_string"=>"begin_time < ={$endtime} AND ( end_time = 0 OR end_time >= {$begintime})"])
// ->select();
$company_game_ratio = D("CompanyGameRatio")->getPromoteCompanyGameRatio($company_id,(string)$relation_game_id,$begintime,$endtime,$company_data['company_belong']);
$company_game_ratio = $company_game_ratio[$relation_game_id];
// $mould = json_decode($company_game_ratio['turnover_ratio'],true);
$amount = 0;
if (!$company_game_ratio) {
// $spend = $this->getSpendData($begintime,$endtime,$company_id,$relation_game_id,$admin_id,$promote_id);
// $amount += $this->setSpendData($spend,$mould,$game_ratio_mould['ratio'],$pay_amount);
return 0;
}
foreach ($company_game_ratio as $key => $value) {
$turnover_ratio = json_decode($value['turnover_ratio'],true);
// dump($value);
$spend = $this->getSpendData($value['begintime'],$value['endtime'],$company_id,$relation_game_id,$admin_id,$promote_id);
// dump($spend);
$amount += $this->setSpendData($spend,$turnover_ratio,$value['ratio'],$pay_amount);
}
// dump($amount);die();
return $amount?$amount:0;
}
public function setSpendData($spend=[],$turnover_ratio=[],$radio=0,$pay_amount=0) {
$turnover = 0;
$amount= 0;
foreach ($spend as $k => $v) {
//获取的金额
$amount = ($v['pay_amount'] * ($radio?$radio:0))/100;
foreach ( $turnover_ratio as $tk => $tv ) {
//判断大于的流水是否比前一个要小
if ($turnover >= $tv['turnover']) {
continue;
}
if ($tv['instanceof']==1) {
if ($pay_amount >= $tv['turnover']) {
$amount = ($v['pay_amount'] * ($tv['ratio']?$tv['ratio']:0))/100;
$turnover = $tv['turnover'];
}
} else {
if ($pay_amount > $tv['turnover']) {
$amount = ($v['pay_amount'] * ($tv['ratio']?$tv['ratio']:0))/100;
$turnover = $tv['turnover'];
}
}
}
}
return $amount;
}
public function getSpendData($begintime = 0,$endtime = 0,$company_id=0,$relation_game_id=0,$admin_id=0,$promote_id=0) {
$map['tab_spend.pay_status'] = 1;
$map['pay_way'] = ['egt',0];
D("Spend")->addSubsiteWhere($map,"tab_spend");
$spend = M("spend","tab_")
->field("sum(pay_amount) pay_amount,
CASE WHEN substring_index(substring_index(`chain`,'/',2),'/',-1) !='' THEN substring_index(substring_index(`chain`,'/',2),'/',-1) ELSE promote_id END promote_id,game.relation_game_id,company_id")
->join("left join tab_game game on tab_spend.game_id = game.id")
->join("left join tab_promote promote on tab_spend.promote_id = promote.id")
->where($map)
->where(['payed_time'=>['between',[$begintime,$endtime]],'company_id'=>$company_id,'relation_game_id'=>$relation_game_id,'market_admin_id'=>$admin_id,'is_check'=>['neq',2]])
->group("tab_spend.id")
->select(false);
$spend = M()->table("({$spend})a")
->field("*,sum(pay_amount) pay_amount")
->where(['promote_id'=>$promote_id])
->group("promote_id")
->select();
return $spend;
}
//计算市场专员业绩公式 参数 time 2020-10
public function caculateMarketStream () {
echo date("Y-m-d H:i:s")."----------------------市场结算管理计算----------------------\n";
$map['pay_time'] = date('Y-m',strtotime(date('Y',time()).'-'.(date('m',time())-1).'-01'));
if ($_REQUEST['time']) {
$map['pay_time'] = $_REQUEST['time'];
}
$spend_map = [];
$time_start = 0;
$time_end = 0;
$month_time = [];
if($_REQUEST['time'] == 'all') {
$belong_map = [];
$month_time[] = date('Y-m',strtotime(date('Y',time()).'-'.(date('m',time())-1).'-01'));
// $month_time[] = date('Y-m',strtotime(date('Y',time()).'-'.(date('m',time())-2).'-01'));
$map['pay_time'] = ['in',$month_time];
$spend_map['pay_time'] = ['elt',strtotime(date('Y-m-t 23:59:59', strtotime(date('Y',time()).'-'.(date('m',time())-1).'-01')))];
$time_end = strtotime(date('Y-m-t',strtotime($month_time)));
} else {
$month_time = $map['pay_time'];
$time_start = strtotime(date('Y-m-1',strtotime($map['pay_time'])));
$time_end = strtotime(date('Y-m-t',strtotime($map['pay_time'])));
$belong_map = "((begin_time< ={$time_start} and (end_time >={$time_start} or end_time=0)) or (begin_time< ={$time_end} and end_time >={$time_end}) or (end_time>={$time_start} and end_time < ={$time_end}))";
}
if ($map['pay_time']) {
SM("settleup_marketorder","tab_")
->where(['pay_time'=>['in',$month_time]])
->delete();
}
$data = M("auth_group")
->where(['title'=>['like','%市场%']])
->select(false);
$data = M("auth_group_access")
->field("auth.market_percentage,real_name,sys_member.uid,sys_auth_group_access.group_id")
->join("left join ({$data}) auth on auth.id = sys_auth_group_access.group_id")
->join("left join sys_member on sys_member.uid = sys_auth_group_access.uid")
->where("auth.title is not null")
->select(false);
$belong_game = M("company_belong_game","tab_")
->field("game_ids,begin_time,end_time")
->where($belong_map)
->select();
// if($belong_game) {
// unset($spend_map['pay_time']);
// }
$unsettlement = $spend_map;
foreach ($belong_game as $key => $value) {
$value['game_ids'] = explode(',',$value['game_ids']);
foreach ($value['game_ids'] as $k => $v) {
if (!$v) {
unset($value['game_ids'][$k]);
}
}
if (!$value['end_time']) {
$value['end_time'] = $time_end;
}
$value['game_ids'] = implode(',',$value['game_ids']);
if (!$spend_map['_string']) {
$spend_map['_string'] = "(pay_time between {$value['begin_time']} and {$value['end_time']}+86399 and relation_game_id in({$value['game_ids']}))";
} else {
$spend_map['_string'] .= " or (pay_time between {$value['begin_time']} and {$value['end_time']}+86399 and relation_game_id in({$value['game_ids']}))";
}
}
if (!$spend_map['_string']) {
$spend_map['_string'] = "relation_game_id = 0";
}
D("Spend")->addSubsiteWhere($spend_map,"tab_spend");
$spend = M("spend","tab_")
->field("sum(pay_amount) as pay_amount,FROM_UNIXTIME(pay_time,'%Y-%m') pay_time,
substring_index(substring_index(tab_spend.game_name,'(',1),'(',-1) game_name,game_id,relation_game_id,tab_spend.sdk_version,
CASE WHEN substring_index(substring_index(`chain`,'/',2),'/',-1) !='' THEN substring_index(substring_index(`chain`,'/',2),'/',-1) ELSE promote_id END promote_id,pay_way,market_admin_id,0 is_settlement,is_check")
->join("left join tab_promote on tab_spend.promote_id = tab_promote.id")
->join("left join tab_game game on game.id=tab_spend.game_id")
->where(['tab_spend.pay_status'=>1,'pay_way'=>['egt',0]])
->where($spend_map)
->group("tab_spend.id")
->select(false);
$not_in_spend = M("spend","tab_")
->field("tab_spend.id id")
->join("left join tab_promote on tab_spend.promote_id = tab_promote.id")
->join("left join tab_game game on game.id=tab_spend.game_id")
->where(['tab_spend.pay_status'=>1,'pay_way'=>['egt',0]])
->where($spend_map)
->group("tab_spend.id")
->select(false);
$unsettlement['_string'] = "tab_spend.id not in($not_in_spend)";
D("Spend")->addSubsiteWhere($unsettlement,"tab_spend");
$unsettlement_spend = M("spend","tab_")
->field("sum(pay_amount) as pay_amount,FROM_UNIXTIME(pay_time,'%Y-%m') pay_time,
substring_index(substring_index(tab_spend.game_name,'(',1),'(',-1) game_name,game_id,relation_game_id,tab_spend.sdk_version,
CASE WHEN substring_index(substring_index(`chain`,'/',2),'/',-1) !='' THEN substring_index(substring_index(`chain`,'/',2),'/',-1) ELSE promote_id END promote_id,pay_way,market_admin_id,1 is_settlement,is_check")
->join("left join tab_promote on tab_spend.promote_id = tab_promote.id")
->join("left join tab_game game on game.id=tab_spend.game_id")
->where(['tab_spend.pay_status'=>1,'pay_way'=>['egt',0]])
->where($unsettlement)
->group("tab_spend.id")
->select(false);
$spend = "{$spend} UNION ALL {$unsettlement_spend}";
$payway_spend = M()->table("({$spend}) spend")
->field("sum(pay_amount) as pay_amount,pay_time,promote_id,game_name,game_id,relation_game_id,pay_way,sdk_version,market_admin_id,is_settlement")
->where(['is_check'=>['neq',2]])
->where($map)
->group("pay_time,promote_id,game_name,pay_way,market_admin_id,is_settlement")
->select();
$channel_fee = [];
$paywayData = M("tool","tab_")
->field("name,config")
->where(['name'=>['in',"alipay,weixin,wei_xin,wei_xin_app,jubaobar,weixin_gf,jft,jft_wap,goldpig,ptb_pay,bind_pay,sqpay,heepay,yeepay,ptb_pay"]])
->select();
//公司税费计算
$tax_radio = [];
$tax_data = M("tax_radio","tab_")
->field("tax_radio,time")
->order("time ASC")
->select();
foreach ($tax_data as $key => $value) {
$tax_radio[$key]['start'] = $value['time'];
$tax_radio[$key]['end'] = $tax_data[$key+1]['time'];
$tax_radio[$key]['tax_radio'] = $value['tax_radio'];
if (!$tax_data[$key+1]['time']) {
$tax_radio[$key]['end'] = 99999999999;
}
}
$pay_rate = [];
foreach ($paywayData as $key => $value) {
$pay_config = json_decode($value['config'],true);
if ($this->getPayway($value['name'])||$this->getPayway($value['name'])=='0') {
$pay_rate[$this->getPayway($value['name'])] = $pay_config['channel_rate']?$pay_config['channel_rate']:0;
}
}
foreach ($payway_spend as $key => $value) {
switch ($value['pay_way']){
case 3: //微信同步
$value['pay_way'] = '2';
break;
case 10: //双乾同步
$value['pay_way'] = '9';
break;
case 15: //双乾同步
$value['pay_way'] = '9';
break;
}
//将时间、推广员id、游戏名、设备类型作为键值标记渠道费用
if (!$channel_fee[$value['pay_time'].$value['promote_id'].$value['game_name'].$value['market_admin_id'].$value['is_settlement']]) {
if (!$value['pay_way']) {
$channel_fee[$value['pay_time'].$value['promote_id'].$value['game_name'].$value['market_admin_id'].$value['is_settlement']] = 0;
}
$channel_fee[$value['pay_time'].$value['promote_id'].$value['game_name'].$value['market_admin_id'].$value['is_settlement']]
= $value['pay_amount'] * ($pay_rate[$value['pay_way']]/100);
} else {
$channel_fee[$value['pay_time'].$value['promote_id'].$value['game_name'].$value['market_admin_id'].$value['is_settlement']]
= $channel_fee[$value['pay_time'].$value['promote_id'].$value['game_name'].$value['market_admin_id'].$value['is_settlement']]+($value['pay_amount'] * ($pay_rate[$value['pay_way']]/100));
}
}
$spend = M()->table("({$spend}) spend")
->field("sum(pay_amount) as pay_amount,pay_time,promote_id,game_name,game_id,relation_game_id,sdk_version,market_admin_id,is_settlement")
->where(['is_check'=>['neq',2]])
->where($map)
->group("pay_time,promote_id,game_name,market_admin_id,is_settlement")
->select(false);
$promote_data = M()->table("({$spend}) spend")
->field("pay_time,company_id,company.company_name,account as promote_account,company.company_belong,develop_type,spend.promote_id,spend.game_name,game_id,relation_game_id,spend.pay_amount,auth.real_name,market_admin_id as admin_id,market_percentage,sdk_version,is_settlement")
->join("left join tab_promote promote on spend.promote_id = promote.id")
->join("left join tab_promote_company company on promote.company_id = company.id")
->join("left join ({$data}) auth on auth.uid=market_admin_id")
->where(['develop_type'=>['egt',1],'group_id'=>['in',['11','12','21']]])
// ->where(['company_id'=>43,'spend.promote_id'=>1498,'relation_game_id'=>191])
// ->order("is_settlement ASC")
->select();
$specialPayAmount = [];
$unsettlement_amount = [];
foreach ($promote_data as $key => $value) {
if ($value['pay_time'] == date("Y-m",time())) {
continue;
}
$cp_radio = getGameCpRadio($value['game_id'],$value['pay_amount'],true);
if (!$cp_radio) {
$cp_radio = getGameCpRadio($value['game_id'],$value['pay_amount'],false);
}
//上游流水
$promote_data[$key]['cp_amount'] = $value['pay_amount'] * ($cp_radio * 0.01);
//下游
// $promote_radio = getGamePromoteCompanyRadio($value['company_id'],$value['relation_game_id'],time(),$value['pay_amount'],true,$value['company_belong']);
// if (!$promote_radio) {
// $promote_radio = getGamePromoteCompanyRadio($value['company_id'],$value['relation_game_id'],time(),$value['pay_amount'],false,$value['company_belong']);
// }
$begin_pay_time = strtotime(date("Y-m-1",strtotime($value['pay_time'])));
$end_pay_time = strtotime(date("Y-m-t",strtotime($value['pay_time'])))+86399;
$company_belong_game = M("company_belong_game","tab_")
->field("game_ids,begin_time,end_time")
->where("begin_time < ={$end_pay_time} AND ( end_time = 0 OR end_time >= {$begin_pay_time})")
// ->where("((begin_time< ={$begin_pay_time} and (end_time >={$begin_pay_time} or end_time=0)) or (begin_time< ={$end_pay_time} and end_time >={$end_pay_time}) or (end_time>={$begin_pay_time} and end_time < ={$end_pay_time}))")
->order("begin_time ASC")
->select();
// dump($company_belong_game);
$promote_data[$key]['promote_amount'] = 0;
foreach ($company_belong_game as $ck => $cv) {
$ungame_ids = explode(',',$cv['game_ids']);
if ($cv['end_time'] == 0 || !$cv['end_time']) {
$cv['end_time'] = 99999999999;
}
$use_begin = 0;
$use_end = 0;
if ($value['is_settlement'] == '0') {
if ($begin_pay_time > $cv['begin_time']) {
$use_begin = $begin_pay_time;
if ($end_pay_time > $cv['end_time']+86399) {
$use_end = $cv['end_time']+86399;
} else {
$use_end = $end_pay_time;
}
} else {
$use_begin = $cv['begin_time'];
if ($end_pay_time > $cv['end_time']) {
$use_end = $cv['end_time']+86399;
} else {
$use_end = $end_pay_time;
}
}
//下游流水
$promote_data[$key]['promote_amount'] += $this->getCompanyGameRadio($value['admin_id'],$value['promote_id'],$value['company_id'],$value['relation_game_id'],$use_begin,$use_end,$value['pay_amount']);
} elseif($value['is_settlement'] == '1') {
if ($ck == 0) {
// echo 1;
if ($cv['begin_time'] >= $begin_pay_time) {
$promote_data[$key]['promote_amount'] += $this->getCompanyGameRadio($value['admin_id'],$value['promote_id'],$value['company_id'],$value['relation_game_id'],$begin_pay_time,$cv['begin_time']-1,$value['pay_amount']);
// dump(date($begin_pay_time)."-".date($cv['begin_time']-1));
// dump($promote_data[$key]['promote_amount']);
}
}
if (!$company_belong_game[$ck+1]) {
// dump($end_pay_time);
// dump($cv['end_time']);
if ($end_pay_time > $cv['end_time']) {
// echo 2;
$promote_data[$key]['promote_amount'] += $this->getCompanyGameRadio($value['admin_id'],$value['promote_id'],$value['company_id'],$value['relation_game_id'],$cv['end_time']+86400,$end_pay_time,$value['pay_amount']);
}
}
if ($ck > 0) {
if (($cv['begin_time'] - $company_belong_game[$ck-1]['end_time'] + 86399) > 1) {
// echo 3;
$promote_data[$key]['promote_amount'] += $this->getCompanyGameRadio($value['admin_id'],$value['promote_id'],$value['company_id'],$value['relation_game_id'],$company_belong_game[$ck-1]['end_time'] + 86400,$cv['begin_time']-1,$value['pay_amount']);
}
}
if (!in_array($value['relation_game_id'],$ungame_ids)) {
// echo 4;
if (($cv['end_time']+86399) > $end_pay_time) {
$cv['end_time'] = $end_pay_time;
} else {
$cv['end_time'] = $cv['end_time']+86399;
}
if ($cv['begin_time'] < $begin_pay_time) {
$cv['begin_time'] = $begin_pay_time;
}
// dump($promote_data[$key]['promote_amount']);
// dump(date($cv['begin_time'])."-".date($cv['end_time']));
$promote_data[$key]['promote_amount'] += $this->getCompanyGameRadio($value['admin_id'],$value['promote_id'],$value['company_id'],$value['relation_game_id'],$cv['begin_time'],$cv['end_time'],$value['pay_amount']);
// dump($promote_data[$key]['promote_amount']);
}
}
// if (!in_array($value['relation_game_id'],$ungame_ids)) {
//
// if ($begin_pay_time > $cv['begin_time']) {
// $use_begin = $begin_pay_time;
// if ($end_pay_time > $cv['end_time']+86399) {
// $use_end = $cv['end_time']+86399;
// } else {
// $use_end = $end_pay_time;
// }
// } else {
//
// $use_begin = $cv['begin_time'];
// if ($end_pay_time > $cv['end_time']) {
// $use_end = $cv['end_time']+86399;
// } else {
// $use_end = $end_pay_time;
// }
//
// }
//
// //下游流水
// $promote_data[$key]['promote_amount'] += $this->getCompanyGameRadio($value['admin_id'],$value['promote_id'],$value['company_id'],$value['relation_game_id'],$use_begin,$use_end,$value['pay_amount']);
// }
}
if (!$company_belong_game) {
$promote_data[$key]['promote_amount'] += $this->getCompanyGameRadio($value['admin_id'],$value['promote_id'],$value['company_id'],$value['relation_game_id'],$begin_pay_time,$end_pay_time,$value['pay_amount']);
}
//下游流水
// $promote_data[$key]['promote_amount'] = $this->getCompanyGameRadio($value['admin_id'],$value['promote_id'],$value['company_id'],$value['relation_game_id'],$value['pay_time'],$value['pay_amount'],$value['is_settlement']);
//下游流水
// $promote_data[$key]['promote_amount'] = $value['pay_amount'] * ($promote_radio * 0.01);
//特殊补点
$specialPayAmount[$value['pay_time']] = $this->getSpecialComplement(strtotime(date("Y-m-1",strtotime($value['pay_time']))),strtotime(date("Y-m-t",strtotime($value['pay_time'])))+86399,$value['promote_id']);
$specialAmount = $specialPayAmount[$value['pay_time']][$value['company_id']."-".$value['promote_id']."-".$value['relation_game_id']]?$specialPayAmount[$value['pay_time']][$value['company_id']."-".$value['promote_id']."-".$value['relation_game_id']]:0;
//渠道费用
$promote_data[$key]['channel_amount'] = $channel_fee[$value['pay_time'].$value['promote_id'].$value['game_name'].$value['admin_id'].$value['is_settlement']];
$tax = 0;
//公司税费
foreach($tax_radio as $k => $v) {
if (strtotime($value['pay_time'])>=$v['start'] & & strtotime($value['pay_time'])< $v['end']) {
$tax = $v['tax_radio'];
}
}
// $belong_game = M("company_belong_game","tab_")
// ->field("game_ids")
// ->where("time='{$value['pay_time']}'")
// ->find();
//
// $belong_game = array_values(explode(",",$belong_game['game_ids']));
//
// if ((in_array($value['relation_game_id'],$belong_game) & & $value['company_belong'] ==1) || $value['company_belong'] !=1) {
// $promote_data[$key]['is_settlement']=1;
// } else {
// $promote_data[$key]['is_settlement']=0;
// }
$promote_data[$key]['is_settlement'] = $value['is_settlement'];
$promote_data[$key]['promote_amount'] += $specialAmount;
$promote_data[$key]['company_tax'] = ($value['pay_amount']-$promote_data[$key]['cp_amount']- $promote_data[$key]['promote_amount'])*($tax/100);
//毛利
$promote_data[$key]['company_profit'] = $value['pay_amount']-$promote_data[$key]['cp_amount']-$promote_data[$key]['promote_amount']-$promote_data[$key]['channel_amount']-$promote_data[$key]['company_tax'];
// dump($promote_data[$key]['promote_amount']);
if ($value['promote_id'] == 0) {
// $promote_data[$key]['promote_account']='官方渠道';
// $promote_data[$key]['company_id']='0';
// $promote_data[$key]['company_belong']='3';
// $promote_data[$key]['develop_type']='0';
continue;
}
unset($promote_data[$key]['market_percentage']);
$marker_data = SM("settleup_marketorder","tab_")
->where(['pay_time'=>$value['pay_time'],'promote_id'=>$value['promote_id'],'game_name'=>$value['game_name'],'admin_id'=>$value['admin_id'],'is_settlement'=>$value['is_settlement']])
->find();
echo "日期:{$value['pay_time']},游戏:{$value['game_name']},推广员:{$value['promote_account']}\n";
echo "市场员:{$value['admin_id']} 推广员:{$value['promote_id']} 公司id: {$value['company_id']} 游戏关联id: {$value['relation_game_id']} 支付时间:{$value['pay_time']} 金额:{$value['pay_amount']}\n";
// dump($promote_data[$key]);die();
if (!$marker_data) {
SM("settleup_marketorder","tab_")
->add($promote_data[$key]);
} else {
SM("settleup_marketorder","tab_")
->where(['pay_time'=>$value['pay_time'],'promote_id'=>$value['promote_id'],'game_name'=>$value['game_name'],'admin_id'=>$value['admin_id'],'is_settlement'=>$value['is_settlement']])
->save($promote_data[$key]);
}
}
// var_dump($_REQUEST['time']);
$this->createMarketBonus($_REQUEST['time']);
echo date("Y-m-d H:i:s")."----------------------市场结算管理计算----------------------\n";
}
public function insertAllUserBonus($time) {
// $time = $_REQUEST['time'];
$data = M("member")
->field("access.uid admin_id,real_name,nickname,group_id level")
->join("left join sys_auth_group_access access on sys_member.uid = access.uid")
->join("left join sys_auth_group auth on access.group_id=auth.id")
->where(['group_id'=>['in','11,12,21']])
->select();
foreach ($data as $key => $value) {
$value['pay_time'] = $time;
$value['remark'] = "";
$value['create_time'] = time();
$sign = SM("market_altogether","tab_")
->where(['admin_id'=>$value['admin_id'],'pay_time'=>$time])
->find();
if (!$sign) {
SM("market_altogether","tab_")->add($value);
} elseif(!$sign['real_name']) {
SM("market_altogether","tab_")->where(['admin_id'=>$value['admin_id'],'pay_time'=>$time])->save(['real_name'=>$value['real_name']]);
}
}
}
public function createMarketBonus($pay_time) {
if ($pay_time& & $pay_time!='all') {
$map['pay_time'] = $pay_time;
}
if (!$pay_time) {
$pay_time = date('Y-m',strtotime(date('Y',time()).'-'.(date('m',time())-1).'-01'));
$map['pay_time'] = date('Y-m',strtotime(date('Y',time()).'-'.(date('m',time())-1).'-01'));
}
// dump(date('Y-m',strtotime(date('Y',time()).'-'.(date('m',time())-1).'-01')));die();
if ($pay_time == 'all') {
$end = date("Y-m",time());
$start = date('Y-m',strtotime(date('Y',time()).'-'.(date('m',time())-1).'-01'));
$i = 0;
do {
$date = date('Y-m', strtotime($start . ' + ' . $i . ' month'));
$i++;
M("market_altogether","tab_")->where(['pay_time'=>$date])->delete();
$this->insertAllUserBonus($date);
} while ($date < date ( ' Y-m ' , strtotime ( date ( ' Y ' , time ( ) ) . ' - ' . ( date ( ' m ' , time ( ) ) -1 ) . ' -01 ' ) ) ) ;
$map['pay_time'] = date('Y-m',strtotime(date('Y',time()).'-'.(date('m',time())-1).'-01'));;
// unset($map['pay_time']);
} else{
SM("market_altogether","tab_")->where(['pay_time'=>$pay_time])->delete();
$this->insertAllUserBonus($pay_time);
}
$map['is_settlement'] = 1;
//获取admin_id
$accessData = M("auth_group_access")
->alias("access")
->join("left join sys_auth_group auth on access.group_id=auth.id")
->join("left join sys_member member on access.uid=member.uid")
->where(['group_id'=>['in','11,12,21']])
->getField("access.uid,group_id,market_percentage,nickname");
$all_data = SM("settleup_marketorder","tab_")
->field("id,admin_id,pay_time,promote_account,company_belong,tab_settleup_marketorder.real_name,develop_type,game_name,
sum(pay_amount) pay_amount,sum(company_profit) company_profit,
sum(if((develop_type = 1 or develop_type = 2), pay_amount, 0)) performance_revenue,sum(if(develop_type = 3, pay_amount, 0)) appraisal_bonuses,
sum(company_tax) company_tax, sum(cp_amount) cp_amount,sum(promote_amount) promote_amount")
->where($map)
->where(["admin_id"=>['in',array_keys($accessData)]])
->group("admin_id,pay_time")
->select();
foreach ($all_data as $key => $value) {
$admin_id = $value['admin_id'];
if(isset($accessData[$admin_id])){
$value = array_merge($value,$accessData[$admin_id]);
}
$sum_amount = $value['performance_revenue'] + $value['appraisal_bonuses'];
$market_percentage = json_decode($value['market_percentage'],true);//业绩提成
if ($value['performance_revenue']=='0.00') {
$market_percentage['develop_commission_ratio'] = 0;
$market_percentage['appraisal_bonuses_ratio'] = 0;
}
if ($value['appraisal_bonuses']=='0.00') {
$market_percentage['maintain_commission_ratio'] = 0;
$market_percentage['maintain_appraisal_bonuses_ratio'] = 0;
}
// echo "{$value['nickname']}:{$value['pay_time']}\n";
// dump($market_percentage);
$settleup_marketorder = SM("settleup_marketorder","tab_")
->where(['admin_id'=>$value['admin_id'],'pay_time'=>$value['pay_time'],'is_settlement'=>1])
->select();
$all_data[$key]['performance_commission'] = 0;
$all_data[$key]['achievement_bonus'] = 0;
foreach ($settleup_marketorder as $k => $v) {
if($v['develop_type'] == 1 || $v['develop_type'] == 2) {
$all_data[$key]['performance_commission'] += $v['company_profit']*($market_percentage['develop_commission_ratio']/100);
$all_data[$key]['achievement_profit'] += $v['company_profit'];
}
if ($v['develop_type'] == 3) {
$all_data[$key]['performance_commission'] += $v['company_profit']*($market_percentage['maintain_commission_ratio']/100);
$all_data[$key]['performance_profit'] += $v['company_profit'];
}
//绩效考核奖金
if($v['develop_type'] == 1 || $v['develop_type'] == 2) {
$all_data[$key]['achievement_bonus'] +=$v['company_profit']*($market_percentage['appraisal_bonuses_ratio']/100);
}
if ($v['develop_type'] == 3) {
$all_data[$key]['achievement_bonus'] += $v['company_profit']*($market_percentage['maintain_appraisal_bonuses_ratio']/100);
}
}
$all_data[$key]['performance_commission'] = number_format($all_data[$key]['performance_commission'], 2, '.', '');
$all_data[$key]['achievement_bonus'] = number_format($all_data[$key]['achievement_bonus'], 2, '.', '');
$sum_amount < $market_percentage['performance_revenue'] ? ($all_data[$key]['performance_commission'] = 0):"";
$sum_amount < $market_percentage['performance_revenue'] ? ($all_data[$key]['achievement_profit'] = 0):"";
$sum_amount < $market_percentage['appraisal_bonuses'] ? ($all_data[$key]['achievement_bonus'] = 0):"";
$sum_amount < $market_percentage['appraisal_bonuses'] ? ($all_data[$key]['performance_profit'] = 0):"";
//总提成
$all_data[$key]['commission'] = number_format($all_data[$key]['performance_commission']+$all_data[$key]['achievement_bonus'], 2, '.', '');
//应发金额
$all_data[$key]['extend_commission'] =
substr(number_format($all_data[$key]['performance_commission'] * ($market_percentage['performance_monthly_ratio']/100)+
$all_data[$key]['achievement_bonus'] * ($market_percentage['month_bonus_ratio']/100), 4, '.', ''),0,-2);
//待发金额
$all_data[$key]['wait_commission'] = substr(number_format($all_data[$key]['commission'] - ( $all_data[$key]['performance_commission'] * ($market_percentage['performance_monthly_ratio']/100)+
$all_data[$key]['achievement_bonus'] * ($market_percentage['month_bonus_ratio']/100) ), 4, '.', ''),0,-2);
$insert['pay_time'] = $value['pay_time'];
$insert['real_name'] = $value['real_name'];
$insert['admin_id'] = $value['admin_id'];
$insert['nickname'] = $value['nickname'];
$insert['level'] = $value['group_id'];
$insert['pay_amount'] = $value['pay_amount'];
$insert['extend_commission'] = substr(
number_format(($all_data[$key]['performance_commission'] * ($market_percentage['performance_monthly_ratio']/100)
+ $all_data[$key]['achievement_bonus'] * ($market_percentage['month_bonus_ratio']/100)), 4, '.', ''),0,-2);
$insert['wait_commission'] = $all_data[$key]['wait_commission'];
$insert['remark'] = '';
$insert['create_time'] = time();
$insert['company_profit'] = $value['company_profit'];
$insert['company_tax'] = $value['company_tax'];
$insert['cp_amount'] = $value['cp_amount'];
$insert['promote_amount'] = $value['promote_amount'];
$insert['performance_revenue'] = $value['performance_revenue'];
$insert['appraisal_bonuses'] = $value['appraisal_bonuses'];
$insert['performance_commission'] = $all_data[$key]['performance_commission'];
$insert['achievement_bonus'] = $all_data[$key]['achievement_bonus'];
//待发业绩奖金
$insert['wait_performance_commission'] = number_format($all_data[$key]['performance_commission'] * (1-($market_percentage['performance_monthly_ratio']/100)), 2, '.', '');
//待发绩效奖金
$insert['wait_achievement_commission'] = number_format($all_data[$key]['achievement_bonus'] * (1-($market_percentage['month_bonus_ratio']/100)), 2, '.', '');
$insert['achievement_profit'] = number_format($all_data[$key]['achievement_profit'], 2, '.', '');
$insert['performance_profit'] = number_format($all_data[$key]['performance_profit'], 2, '.', '');
// $insert['wait_commission'] = ($insert['wait_performance_commission']+$insert['wait_achievement_commission']);
$is_hav = SM("market_altogether","tab_")
->where(['admin_id'=>$value['admin_id'],'pay_time'=>$value['pay_time']])
->find();
if (!$is_hav) {
SM("market_altogether","tab_")->add($insert);
} else {
SM("market_altogether","tab_")
->where(['admin_id'=>$value['admin_id'],'pay_time'=>$value['pay_time']])
->save($insert);
}
}
}
public function sendMarketBonus(){
echo date("Y-m-d H:i:s")."----------------------月初发放市场专员应发份额----------------------\n";
$map['pay_time'] = date('Y-m',strtotime(date('Y',time()).'-'.(date('m',time())-1).'-01'));
if ($_REQUEST['time']) {
$map['pay_time'] = $_REQUEST['time'];
}
if ($_REQUEST['time'] == 'all') {
unset($map['pay_time']);
}
$data = SM("market_altogether","tab_")
->where($map)
->select();
// dump($map);die();
foreach ($data as $key => $value) {
$group_config = M("auth_group_access access")
->field("market_percentage")
->join("left join sys_auth_group auth on access.group_id=auth.id")
->where(['uid'=>$value['admin_id']])
->find();
$group_config = json_decode($group_config['market_percentage'],true);
$month = date("m",strtotime($value['pay_time']));
$yes = date("Y",strtotime($value['pay_time']));
$where =[];
if ($group_config['time'] == 1) {
// var_dump($month);die();
if ($month == '07') {
$where = [$yes.'-'.'01',$yes.'-'.'02',$yes.'-'.'03'];
} elseif($month == '10') {
$where = [$yes.'-'.'04',$yes.'-'.'05',$yes.'-'.'06'];
} elseif($month == '04') {
$where = [($yes-1).'-'.'10',($yes-1).'-'.'11',($yes-1).'-'.'12'];
} elseif($month == '01') {
$where = [($yes-1).'-'.'07',($yes-1).'-'.'08',($yes-1).'-'.'09'];
}
} elseif($group_config['time'] == 2) {
if ($month == '07') {
$where = [$yes.'-'.'01',$yes.'-'.'02',$yes.'-'.'03',$yes.'-'.'04',$yes.'-'.'05',$yes.'-'.'06'];
} elseif($month == '01') {
$where = [($yes-1).'-'.'07',($yes-1).'-'.'08',($yes-1).'-'.'09',($yes-1).'-'.'10',($yes-1).'-'.'11',($yes-1).'-'.'12'];
}
} elseif($group_config['time'] == 3) {
if ($month == '01') {
$where = [($yes-1).'-'.'01',($yes-1).'-'.'02',($yes-1).'-'.'03',($yes-1).'-'.'04',($yes-1).'-'.'05',($yes-1).'-'.'06',
($yes-1).'-'.'07',($yes-1).'-'.'08',($yes-1).'-'.'09',($yes-1).'-'.'10',($yes-1).'-'.'11',($yes-1).'-'.'12'];
}
} else {
$where = [date("Y-m",strtotime("last month",strtotime($value['pay_time'])))];
}
echo "{$value['pay_time']}:{$value['real_name']}发放\n";
$save['status'] = 1;
$save['remark'] = '自动发放';
if ($where) {
$map['pay_time'] = ['in',$where];
$map['admin_id'] = $value['admin_id'];
SM("market_altogether","tab_")
->where($map)
->save($save);
}
}
echo date("Y-m-d H:i:s")."----------------------市场结算管理计算----------------------\n";
}
}