You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1253 lines
43 KiB
PHP

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace Admin\Controller;
use Think\Controller;
/**
* 聚合渠道结算接口对接
* @author cz
* TODO: 罚款的游戏没有流水不统计补点为0 无法重算
*/
class CompanyStatementSetController extends Controller {
public $cpapihost;
public $TYPE=[
"0"=>"周结",
"1"=>"月结",
"2"=>"补点"
];
public $token = "LYHTQDJS";
public function _initialize(){
$cpapihost = M("Kv")->field("value")->where("`key` = 'aggregate_cp_settlement_api'")->find();
if(empty($cpapihost)){
echo "请先设置请求接口aggregate_cp_settlement_api的值".PHP_EOL;die;
}
$this->cpapihost = $cpapihost['value'];
}
/**
* Undocumented function
*
* @param [type] $begin 开始时间 2020-04-01
* @param string $end 结束时间,默认今天
* @param string $company all/pc/cp/pu 全部 下游公司 上游 下游个人
* @return void
*/
public function setFreeDateCount($begin,$end='',$company='all')
{
if($end == '') $end = $begin;
//判断日期格式
$patten = "/^\d{4}[\-](0?[1-9]|1[012])[\-](0?[1-9]|[12][0-9]|3[01])$/";
if (!preg_match($patten, $begin)) {
die("开始时间格式错误");
}
if (!preg_match($patten, $end)) {
die("结束时间格式错误");
}
if(strtotime($end) < strtotime($begin)){
die("结束时间不能比开始时间小");
}
if(strtotime($end)+86399-24*3600 > time()){
die("结束时间不能大于当前");
}
$starttime = $begin?strtotime($begin):mktime(0,0,0,date('m'),date('d'),date('Y'));
$endtime = $end?strtotime($end)+86399:$starttime+86399;
$datelist = get_date_list($starttime,$endtime,1);
$countdate = count($datelist);
for($i=0;$i<$countdate;$i++){
$this->setDailyCount($datelist[$i],$company);
}
}
public function setDailyCount($stime="now",$company='all')
{
if(!IS_CLI){
die("只支持脚本访问");
}
if($stime=="now"){
$stime=time();
}else{
$stime = strtotime($stime);
}
$nowdate = date("Y-m-d",$stime);
$w = (int)date("w",$stime);
$d = (int)date("d",$stime);
if($w == 1 || $d == 1){
if($w == 1){
if($company == "all"){
echo $nowdate.":".PHP_EOL;
echo "--周结begin".PHP_EOL;
$this->cpStatement(0,$stime);
echo "∟----CP周结统计ok".PHP_EOL;
$this->promoteCompanyStatement(0,$stime);
echo "∟----推广公司周结统计ok".PHP_EOL;
$this->promoteUserPool(0,$stime);
echo "∟----推广个人周结ok".PHP_EOL;
}
if($company == "cp"){
$this->cpStatement(0,$stime);
echo "∟----CP周结统计ok".PHP_EOL;
}
if($company == "pc"){
$this->promoteCompanyStatement(0,$stime);
echo "∟----推广公司周结统计ok".PHP_EOL;
}
if($company == "pu"){
$this->promoteUserPool(0,$stime);
echo "∟----推广个人周结ok".PHP_EOL;
}
}
if($d == 1){
if($company == "all"){
echo $nowdate.":".PHP_EOL;
echo "--月结&补点begin".PHP_EOL;
$this->cpStatement(1,$stime);
$this->cpStatement(2,$stime);
echo "∟----CP月结&补点统计ok".PHP_EOL;
$this->promoteCompanyStatement(1,$stime);
$this->promoteCompanyStatement(2,$stime);
echo "∟----推广公司月结&补点统计ok".PHP_EOL;
$this->promoteUserPool(1,$stime);
$this->promoteUserPool(2,$stime);
echo "∟----推广个人月结&补点统计ok".PHP_EOL;
}
if($company == "cp"){
$this->cpStatement(1,$stime);
$this->cpStatement(2,$stime);
echo "∟----CP月结&补点统计ok".PHP_EOL;
}
if($company == "pc"){
$this->promoteCompanyStatement(1,$stime);
$this->promoteCompanyStatement(2,$stime);
echo "∟----推广公司月结&补点统计ok".PHP_EOL;
}
if($company == "pu"){
$this->promoteUserPool(1,$stime);
$this->promoteUserPool(2,$stime);
echo "∟----推广个人月结&补点统计ok".PHP_EOL;
}
}
}else{
echo $nowdate."非周一和月初,无需任何处理".PHP_EOL;
}
}
/**
* 上游结算
* @param [string] $type 0:周结 1:月结 2周结补点
*/
public function cpStatement($type,$stime,$company_id=false,$recount=true)
{
$t = $this->setBeginAndEndTime($type,$stime);;
$begintime = $t[0];
$endtime = $t[1];
if($company_id === false){
//非重算
$where = [
"_string"=>"first_company_type = '1' OR second_company_type = '1'"
];
}else{
$where = [
"_string"=>"(first_company_type = '1' AND first_company_id in ({$company_id}) ) OR (second_company_type = '1' AND second_company_id in ({$company_id}) )"
];
}
//获取哪些要结算
if($type == 1){
$where['settlement_type']=2;
$cpDbRes = M("CompanyRelation","tab_")->where($where)->select();
}else{
$where['settlement_type']=1;
$cpDbRes = M("CompanyRelation","tab_")->where($where)->select();
}
$cpList=[];
$js_id = [];//己方公司
foreach ($cpDbRes as $k => $v) {
if($v['first_company_type'] == 1){
$cpList[$v['first_company_id']] =$v;
$js_id[] =$v['second_company_id'];
}else{
$cpList[$v['second_company_id']] =$v;
$js_id[] =$v['first_company_id'];
}
}
if(count($js_id) ==0 || count($cpList) == 0){return ;}
$cp_id = implode(",",array_flip(array_flip(array_keys($cpList))));//已绑定关系
$js_id = implode(",",array_unique($js_id));
//获取cp公司
$cpmap = [
"id"=>['in',$cp_id],
"_string"=>"(validity_start_time > 0 AND validity_end_time = 0 ) OR validity_end_time >= {$endtime}"
];
$tmpp = M("Partner","tab_")->field("id,partner,link_man,link_phone,address,company_tax_no,payee_name,bank_account,opening_bank,channel_rate,invoice_rate,taxation_rate,company_type,ali_user,ali_account,has_advance_charge,has_server_fee,server_fee")->where($cpmap)->select();
if(empty($tmpp)){
return true;
}
$cp =[];
foreach ($tmpp as $v) {
$cp[$v['id']]=$v;
}
$cp_id = implode(",",array_column($tmpp,"id")); //结算的id
unset($tmpp);
//获取己方公司
$our = [];
$tmpp = M("CompanyInfo","tab_")->field("id,partner,link_man,link_phone,address,company_tax_no,payee_name,bank_account,opening_bank")->where(["id"=>['in',$js_id]])->select();
foreach ($tmpp as $v) {
$our[$v['id']]=$v;
}
unset($tmpp);
unset($js_id);
//获取本地数据
$locals = $this->getLocalStatementData($begintime,$endtime,$cp_id);
//获取聚合数据
$sign = md5($begintime.$endtime."1".$this->token);
$arr = [
"begintime"=>$begintime,
"endtime"=>$endtime,
"type"=>1,
"sign"=>$sign,
"cp_id"=>$cp_id
];
$dataurl .= $this->cpapihost."&".http_build_query($arr);
$html = file_get_contents($dataurl);
//防止并发压力
sleep(3);
$rsp = json_decode($html,true);
if($rsp['code'] != 1){
echo $rsp['error'].PHP_EOL;die;
}else{
$rsp = $rsp['data'];
}
//整合数据本地
foreach($locals as $k=>$v){
$cpList[$k]["list"] = $v["list"];
}
//整合数据,聚合
foreach($rsp as $k=>$v){
if(isset($cpList[$k]["list"])){
//已经存在
foreach($rsp[$k]["list"] as $ke=>$va){
if(isset($cpList[$k]["list"][$ke])){
$cpList[$k]["list"][$ke]['pay_money'] += $va['pay_money'];
}else{
$cpList[$k]["list"][$ke] = $va;
}
}
}else{
$cpList[$k]["list"] = $v["list"];
}
}
//比例计算及保存
// TODO:此处不判断现游戏名=原包名,但却不是同一款游戏
$verify_log=json_encode(["create_user"=>"system","create_time"=>date("Y-m-d H:i:s")]);
$GameDb = M("Game","tab_");
$StatementDb = M("CompanyStatement","tab_");
$statement_begin_time = date("Y.m.d",$begintime);
$statement_end_time = date("Y.m.d",$endtime);
foreach($cpList as $k=>$v){
$add_data=[];
//1.获取甲乙方信息
if($v['first_company_type'] == 1){
//甲方上游
$cp[$v['first_company_id']]['invoice_type'] = $v['invoice_type'];
$cp[$v['first_company_id']]['invoice_content'] = $v['invoice_content'];
$add_data['first_party_info'] = json_encode($cp[$v['first_company_id']],JSON_UNESCAPED_UNICODE);
$add_data['second_party_info'] = json_encode($our[$v['second_company_id']],JSON_UNESCAPED_UNICODE);
$add_data['company_id'] = $v['first_company_id'];
$add_data['company_name'] = $v['first_company_name'];
}else{
//乙方上游
$cp[$v['second_company_id']]['invoice_type'] = $v['invoice_type'];
$cp[$v['second_company_id']]['invoice_content'] = $v['invoice_content'];
$add_data['first_party_info'] = json_encode($our[$v['first_company_id']],JSON_UNESCAPED_UNICODE);
$add_data['second_party_info'] = json_encode($cp[$v['second_company_id']],JSON_UNESCAPED_UNICODE);
$add_data['company_id'] = $v['second_company_id'];
$add_data['company_name'] = $v['second_company_name'];
}
$add_data['pay_type'] = $v['collection'];
$add_data['withdraw_type'] = $type;
$add_data['statement_begin_time'] = $begintime;
$add_data['statement_end_time'] = $endtime;
$add_data['statement_money'] = 0;
$add_data['pay_amount'] = 0;
$add_data['verify_log'] = $verify_log;
$add_data['op_time'] =time();
$add_data['statement_info'] =[];
$add_data['company_belong']=9;//上游
$add_data['company_type']=$cp[$add_data['company_id']]['company_type'];
$add_data['is_payment']=$v['is_payment'];
//获取渠道及税费费率
$promote_ratio = $cp[$add_data['company_id']]['channel_rate'] ?? 0;
$fax_ratio = $cp[$add_data['company_id']]['taxation_rate'] ?? 0;
//游戏统计
if(!isset($v['list'])){continue;}
foreach($v['list'] as $ke=>$va){
$game =[];
$game['pay_amount'] =$va['pay_money'];
$game['game_name'] =$ke;
//获取游戏id及比例
$game_id = $GameDb->where("relation_game_name='{$ke}' OR original_package_name='{$ke}'")->field("id,relation_game_id")->find();
if(empty($game_id) && isset($va['unique_code']) && !empty($va['unique_code'])){
$unique_code = $va['unique_code'];
$game_id = $GameDb->where("unique_code='{$unique_code }'")->field("id,relation_game_id")->find();
}
if(empty($game_id)){
$game['relation_game_id']=0;
$tratio = 0;
}else{
//获取比例
$game['relation_game_id']=$game_id['relation_game_id'];
if($type == 1){
$tratio = getGameCpRadio($game_id['id'],$va['pay_money'],true);
}elseif($type == 0){
$tratio = getGameCpRadio($game_id['id'],$va['pay_money'],false);
}else{
//补丁
$tratio1 = getGameCpRadio($game_id['id'],$va['pay_money'],true);
$tratio2 = getGameCpRadio($game_id['id'],$va['pay_money'],false);
$tratio = $tratio1-$tratio2;
if($tratio <= 0){continue;}
}
}
if($v['first_company_type'] == 1){
$game['first_ratio']=$tratio-0;
$game['second_ratio']=100-$tratio;
}else{
$game['first_ratio']=100-$tratio;
$game['second_ratio']=$tratio-0;
}
$add_data['pay_amount'] += $va['pay_money'];
$game['sum_money']=round($va['pay_money']*(100-$promote_ratio)*$tratio*(100-$fax_ratio)/(100*100*100),2);//结算金额=平台总额*1-渠道费)*分成比例*(1-税费费率)
$add_data['statement_money'] += $game['sum_money'];
$game['fax_ratio']=$fax_ratio;
$game['promote_ratio']=$promote_ratio;
$game['statement_begin_time']=$statement_begin_time;
$game['statement_end_time']=$statement_end_time;
$game['statement_type']=0;
$add_data['statement_info'][] = $game;
}
$add_data['platform_amount'] = $add_data['pay_amount'];
if($type < 2){
//非补点奖罚
$rrmap = array(
"confirm_time" => ['between', [$begintime,$endtime]],
"company_type"=>1,
"company_id"=>$add_data['company_id'],
"settlement_type"=>2,
);
$rfres = M("RewardDetail","tab_")
->field("
IFNULL(SUM(CASE WHEN type = 1 THEN amount ELSE 0 END),0) as reward_count,
IFNULL(SUM(CASE WHEN type = 2 THEN amount ELSE 0 END),0) as fine_count
")
->where($rrmap)->find();
if($rfres['reward_count'] > 0){
$reward_count = $rfres['reward_count'];
$add_data['statement_info'][] = array(
"statement_begin_time"=>$statement_begin_time,
"statement_end_time"=>$statement_end_time,
'statement_type'=>2,
"game_name"=>"奖励",
'pay_amount'=>$reward_count,
'sum_money'=>$reward_count,
);
$add_data['statement_money']+=$reward_count;
$add_data['pay_amount']+=$reward_count;
}
if($rfres['fine_count'] > 0){
$fine_count = $rfres['fine_count'];
$add_data['statement_info'][] = array(
"statement_begin_time"=>$statement_begin_time,
"statement_end_time"=>$statement_end_time,
'statement_type'=>1,
"game_name"=>"罚款",
'pay_amount'=>$fine_count,
'sum_money'=>$fine_count,
);
$add_data['statement_money'] -= $fine_count;
$add_data['pay_amount'] -= $fine_count;;
}
//获取服务器费用
$tmp_company_info= $cp[$add_data['company_id']];
if($tmp_company_info['has_server_fee'] == 1 && $tmp_company_info['server_fee'] >0){
$server_count = $tmp_company_info['server_fee'];
$add_data['statement_info'][] = array(
"statement_begin_time"=>$statement_begin_time,
"statement_end_time"=>$statement_end_time,
'statement_type'=>1,
"game_name"=>"服务器费用",
'pay_amount'=>$server_count,
'sum_money'=>$server_count,
);
$add_data['statement_money'] -= $server_count;
$add_data['pay_amount'] -= $server_count;;
}
}
$add_data['statement_info'] = json_encode($add_data['statement_info'],JSON_UNESCAPED_UNICODE);
if($type == 2 && $add_data['statement_money'] == 0){
//金额为0不补点
continue;
}
if($add_data['platform_amount'] == 0){
//全等于0表示没有流水小于0依旧要结算
return;
}
//添加
if($recount && $company_id !== false){
//非重算
return $add_data;
}
$StatementDb->add($add_data);
}
}
/**
* 获取本地上游结算
*/
public function getLocalStatementData($begintime,$endtime,$cp_id)
{
$game_where = "partner_id in ({$cp_id})";
$game = M('game','tab_');
$gameDbRes = $game->field("id,relation_game_name as game_name,partner_id as cp_id,original_package_name,select_package_name")->where($game_where)->select();
$gameList=[];
foreach ($gameDbRes as $k => $v) {
$gameList[$v['id']] =$v;
}
//获取所有id
$gmstr = implode(",",array_flip(array_flip(array_column($gameDbRes,'id'))));
//获取支付记录
$paywhere = [
"pay_status"=>1,
"pay_game_status"=>1,
"payed_time"=>["BETWEEN",[$begintime,$endtime]],
"game_id"=>["in",$gmstr]
];
$paydb = M('spend','tab_');
$paylist = $paydb->field("game_id,SUM(pay_amount) pay_amount")->where($paywhere)->group("game_id")->select();
if(empty($paylist)){
return [];
}
//绑定价格
foreach ($paylist as $k => $v) {
$gameList[$v['game_id']]['pay_money'] =$v["pay_amount"];
}
unset($paylist);
//按游戏名称及cp整理数据
$cplList = [];
foreach ($gameList as $k => $v) {
if($v['pay_money'] <= 0) continue; //0值不发送
if(empty($v['original_package_name'])){
$game_name = $v['game_name'];
}else{
if($v['select_package_name'] == 0){
$game_name = $v['original_package_name'];
}else{
$game_name = $v['game_name'];
}
}
$cp_id = $v['cp_id'];
unset($v['cp_id']);
$ymoney = $cplList[$cp_id]['list'][$game_name]["pay_money"]?:0;
$cplList[$cp_id]['list'][$game_name]["pay_money"] =$ymoney+$v["pay_money"];
// if($type==2){
// $cplList[$cp_id]['list'][$game_name]["list"][] =$v; //传递列表详情
// }
}
return $cplList;
}
/**
* 下游结算
*/
public function promoteCompanyStatement($type,$stime,$company_id=false,$recount=true)
{
$t = $this->setBeginAndEndTime($type,$stime);
$begintime = $t[0];
$endtime = $t[1];
if($company_id === false){
//非重算
$where = [
"_string"=>"first_company_type = '2' OR second_company_type = '2'"
];
}else{
$where = [
"_string"=>"(first_company_type = '2' AND first_company_id in ({$company_id}) ) OR (second_company_type = '2' AND second_company_id in ({$company_id}) )"
];
}
//获取哪些要结算
if($type == 1){
$where['settlement_type']=2;
$pcDbRes = M("CompanyRelation","tab_")->where($where)->select();
}else{
$where['settlement_type']=1;
$pcDbRes = M("CompanyRelation","tab_")->where($where)->select();
}
$pcList=[];
$js_id = [];//己方公司
foreach ($pcDbRes as $k => $v) {
if($v['first_company_type'] == 2){
$pcList[$v['first_company_id']] =$v;
$js_id[] =$v['second_company_id'];
}else{
$pcList[$v['second_company_id']] =$v;
$js_id[] =$v['first_company_id'];
}
}
$pc_id = implode(",",array_flip(array_flip(array_keys($pcList))));
$js_id = implode(",",array_unique($js_id));
if(count($js_id) ==0 || count($pcList) == 0){
//无需处理
return ;
}
$pc_map = [
"id"=>["IN",$pc_id],
"_string"=>"(validity_start_time > 0 AND validity_end_time = 0 ) OR validity_end_time >= {$endtime}",
"company_type"=>1
];
//获取pc公司
$tmpp = M("PromoteCompany","tab_")->field("id,uid,company_name partner,settlement_contact link_man,address,contact_phone link_phone,bank_name opening_bank,bank_address payee_name,bank_card bank_account,fax_ratio,taxation_rate,company_belong,company_type,ali_user,ali_account,has_server_fee,server_fee,has_ratio,turnover_ratio")
->where($pc_map)
->select();
if(empty($tmpp)){
return true;
}
$pc =[];
$Promote = M("Promote","tab_");
foreach ($tmpp as $v) {
//获取会长的支付宝账号
$p_map = [
"company_id"=>$v['id'],
"withdraw_done"=>1
];
$pres = $Promote->field("alipay_account,alipay_real_name")->where($p_map)->find();
if(!empty($pres) && !empty($pres['alipay_account']) && !empty($pres['alipay_real_name'])){
$v['ali_user'] = $pres['alipay_real_name'];
$v['ali_account'] = $pres['alipay_account'];
}
if($v['has_ratio']){
$v['turnover_ratio'] = json_decode($v['turnover_ratio'],true);
}
$pc[$v['id']]=$v;
}
unset($tmpp);
//获取己方公司
$our = [];
$tmpp = M("CompanyInfo","tab_")->field("id,partner,link_man,link_phone,address,company_tax_no,payee_name,bank_account,opening_bank")->where(["id"=>['in',$js_id]])->select();
foreach ($tmpp as $v) {
$our[$v['id']]=$v;
}
unset($tmpp);
unset($js_id);
$this->getPromoteCompanySpend($pcList,array_unique(array_keys($pcList)),$begintime,$endtime);
//数据整合
$verify_log=json_encode(["create_user"=>"system","create_time"=>date("Y-m-d H:i:s")]);
$StatementDb = M("CompanyStatement","tab_");
$statement_begin_time = date("Y.m.d",$begintime);
$statement_end_time = date("Y.m.d",$endtime);
$RewardRecord = M("RewardDetail","tab_");
foreach($pcList as $k=>$v){
if(!isset($pc[$k])){continue;}//不存在的公司不结算
if($pc[$k]['has_ratio'] == 1){
$company_ratio = $this->getCompanyRatio($v['pay_amount'],$pc[$k]['turnover_ratio']);
}else{
$company_ratio = 0;
}
$add_data=[];
//1.获取甲乙方信息
if($v['first_company_type'] > 0){
//甲方合作
$pc[$v['first_company_id']]['invoice_type'] = $v['invoice_type'];
$pc[$v['first_company_id']]['invoice_content'] = $v['invoice_content'];
$add_data['first_party_info'] = json_encode($pc[$v['first_company_id']],JSON_UNESCAPED_UNICODE);
$add_data['second_party_info'] = json_encode($our[$v['second_company_id']],JSON_UNESCAPED_UNICODE);
$add_data['company_id'] = $v['first_company_id'];
$add_data['company_name'] = $v['first_company_name'];
}else{
//乙方合作
$pc[$v['second_company_id']]['invoice_type'] = $v['invoice_type'];
$pc[$v['second_company_id']]['invoice_content'] = $v['invoice_content'];
$add_data['first_party_info'] = json_encode($our[$v['first_company_id']],JSON_UNESCAPED_UNICODE);
$add_data['second_party_info'] = json_encode($pc[$v['second_company_id']],JSON_UNESCAPED_UNICODE);
$add_data['company_id'] = $v['second_company_id'];
$add_data['company_name'] = $v['second_company_name'];
}
$add_data['pay_type'] = $v['collection'];
$add_data['withdraw_type'] = $type;
$add_data['statement_begin_time'] = $begintime;
$add_data['statement_end_time'] = $endtime;
$add_data['statement_money'] = 0;
$add_data['pay_amount'] = 0;
$add_data['verify_log'] = $verify_log;
$add_data['op_time'] =time();
$add_data['is_payment']=$v['is_payment'];
$add_data['statement_info'] =[];
//获取渠道及发票税率
$fax_ratio = $pc[$add_data['company_id']]['taxation_rate'] ?? 0; //税费费率
$company_belong = $pc[$add_data['company_id']]['company_belong'];
$add_data['company_belong']=$company_belong;
$add_data['company_type']=$pc[$add_data['company_id']]['company_type'];
if(!isset($v['list'])){continue;}
//游戏统计
foreach($v['list'] as $ke=>$va){
$game =[];
$game['pay_amount'] =$va['pay_amount'];
$game['game_name'] =$va['game_name'];
//获取比例
$game['relation_game_id']=$va['relation_game_id'];
if($type == 1){
$tratio = getGamePromoteCompanyRadio($add_data['company_id'],$va['relation_game_id'],$endtime,$va['pay_amount'],true,$company_belong);
$tratio += $company_ratio;
}elseif($type == 0){
$tratio = getGamePromoteCompanyRadio($add_data['company_id'],$va['relation_game_id'],$endtime,$va['pay_amount'],false,$company_belong);
}else{
//补点
$tratio1 = getGamePromoteCompanyRadio($add_data['company_id'],$va['relation_game_id'],$endtime,$va['pay_amount'],true,$company_belong);;
$tratio2 = getGamePromoteCompanyRadio($add_data['company_id'],$va['relation_game_id'],$endtime,$va['pay_amount'],false,$company_belong);
$tratio = $tratio1-$tratio2+$company_ratio;
if($tratio <= 0){ continue;}
}
$tratio = $tratio-0;
if($v['type'] == 2){
$game['increment_ratio']=$tratio;
}else{
$game['ratio']=$tratio;
}
$add_data['pay_amount'] += $va['pay_amount'];
$game['sum_money']=round($va['pay_amount']*$tratio*(100-$fax_ratio)/(100*100),2);//结算金额=平台总额*(分成比例+补点比例)*(1-税费费率)
$add_data['statement_money'] += $game['sum_money'];
$game['fax_ratio']=$fax_ratio;
$game['statement_begin_time']=$statement_begin_time;
$game['statement_end_time']=$statement_end_time;
$game['statement_type']=0;
$add_data['statement_info'][] = $game;
}
$add_data['platform_amount'] = $add_data['pay_amount'];
if($type < 2){
//非补点计算奖罚
$rrmap = array(
"confirm_time" => ['between', [$begintime,$endtime]],
"company_type"=>2,
"company_id"=>$add_data['company_id'],
"settlement_type"=>2,
);
$rfres = M("RewardDetail","tab_")
->field("
IFNULL(SUM(CASE WHEN type = 1 THEN amount ELSE 0 END),0) as reward_count,
IFNULL(SUM(CASE WHEN type = 2 THEN amount ELSE 0 END),0) as fine_count
")
->where($rrmap)->find();
if($rfres['reward_count'] > 0){
$reward_count = $rfres['reward_count'];
$add_data['statement_info'][] = array(
"statement_begin_time"=>$statement_begin_time,
"statement_end_time"=>$statement_end_time,
'statement_type'=>2,
"game_name"=>"奖励",
'pay_amount'=>$reward_count,
'sum_money'=>$reward_count,
);
$add_data['statement_money']+=$reward_count;
$add_data['pay_amount']+=$reward_count;
}
if($rfres['fine_count'] > 0){
$fine_count = $rfres['fine_count'];
$add_data['statement_info'][] = array(
"statement_begin_time"=>$statement_begin_time,
"statement_end_time"=>$statement_end_time,
'statement_type'=>1,
"game_name"=>"罚款",
'pay_amount'=>$fine_count,
'sum_money'=>$fine_count,
);
$add_data['statement_money'] -= $fine_count;
$add_data['pay_amount'] -= $fine_count;;
}
//获取服务器费用
$tmp_company_info= $pc[$add_data['company_id']];
if($tmp_company_info['has_server_fee'] == 1 && $tmp_company_info['server_fee'] >0){
$server_count = $tmp_company_info['server_fee'];
$add_data['statement_info'][] = array(
"statement_begin_time"=>$statement_begin_time,
"statement_end_time"=>$statement_end_time,
'statement_type'=>1,
"game_name"=>"服务器费用",
'pay_amount'=>$server_count,
'sum_money'=>$server_count,
);
$add_data['statement_money'] -= $server_count;
$add_data['pay_amount'] -= $server_count;;
}
}
$add_data['statement_info'] = json_encode($add_data['statement_info'],JSON_UNESCAPED_UNICODE);
if($type == 2 && $add_data['statement_money'] == 0){
//金额为0不补点
continue;
}
if($add_data['platform_amount'] == 0){
return;
}
// dd($add_data);
//添加
if($recount && $company_id !== false){
//非重算
return $add_data;
}
$StatementDb->add($add_data);
}
}
//设定开始结束时间
public function setBeginAndEndTime($type,$stime){
if($type == 0){
$begintime = mktime(0,0,0,date('m',$stime),date('d',$stime)-7,date('Y',$stime));
$endtime = mktime(0,0,0,date('m',$stime),date('d',$stime),date('Y',$stime))-1;
}else{
$thismonth = date('m',$stime);
$thisyear = date('Y',$stime);
if ($thismonth == 1) {
$lastmonth = 12;
$lastyear = $thisyear - 1;
} else {
$lastmonth = $thismonth - 1;
$lastyear = $thisyear;
}
$lastStartDay = $lastyear . '-' . $lastmonth . '-1';
$lastEndDay = $lastyear . '-' . $lastmonth . '-' . date('t', strtotime($lastStartDay));
$begintime = strtotime($lastStartDay);//上个月的月初时间戳
$endtime = strtotime($lastEndDay)+24*3600-1;//上个月的月末时间戳
}
return [$begintime,$endtime];
}
//获取推广公司推广金额
public function getPromoteCompanySpend(&$pcList,$idarr,$begintime,$endtime){
$res = [];
//获取推广员
if(count($idarr) == 0){return $res;}
$Promote = M("Promote","tab_");
$Spend = M("Spend","tab_");
$spenMap = [
"s.pay_status"=>1,
"s.payed_time"=>['between', [$begintime,$endtime]],
];
for ($i=0; $i <count($idarr); $i++) {
$company_id = $idarr[$i];
$pres = $Promote->field("group_concat(id) ids,count(id) count")->where("company_id = '{$company_id}'")->group("company_id")->find();
if($pres['count'] ==0 ){continue;}
$spenMap['s.promote_id']=["in",$pres['ids']];
//获取支付记录
$list = $Spend->alias('s')->field('sum(s.pay_amount) pay_amount,s.game_id,g.relation_game_id,g.relation_game_name game_name')->where($spenMap)->group('game_id')
->join("left join tab_game g on s.game_id = g.id")
->select();
if(empty($list)){continue;}
foreach($list as $k=>$v){
try {
$res[$company_id]["pay_amount"] += $v['pay_amount'];
} catch (\Throwable $th) {
$res[$company_id]["pay_amount"] = $v['pay_amount'];
}
if(isset($res[$company_id][$v['relation_game_id']])){
//
$res[$company_id][$v['relation_game_id']]['pay_amount'] += $v['pay_amount'];
}else{
unset($v['game_id']);
$res[$company_id][$v['relation_game_id']]= $v;
}
}
}
foreach($res as $k=>$v){
$pcList[$k]["pay_amount"] = $v['pay_amount'];
unset($v['pay_amount']);
$pcList[$k]['list'] = $v;
}
}
public function promoteUserPool($type,$stime,$recount = false){
$t = $this->setBeginAndEndTime($type,$stime);
$begintime = $t[0];
$endtime = $t[1];
$user = [
"pay_amount"=>0,
"statement_money"=>0,
"lack_statement_money"=>0,
"withdraw_type"=>$type,
"platform_amount"=>0,
"create_lack_ids"=>[],
"del_lack_ids"=>[],
"statement_begin_time"=>$begintime,
"statement_end_time"=>$endtime,
"fine"=>0,
"reward"=>0,
"verify_status"=>0,
"company_type"=>2,
"verify_log"=>json_encode(["create_user"=>"system","create_time"=>date("Y-m-d H:i:s")]),
"op_time"=>time(),
"statement_num"=>"PL_".date('Ymd').date('His').sp_random_num(3)
];
// $users = $user = $basedata;
// $users['is_payment'] = 1;
// $users['statement_num'] = "PL_".date('Ymd').date('His').sp_random_num(3);
// $user['is_payment'] = 2;
// $user['statement_num'] = "PL_".date('Ymd').date('His').sp_random_num(3);
if($type == 0){//周结
$this->doPromoteUserPool($user,0,$stime,$recount);
}else if($type == 1){
$users['withdraw_type'] = 1;
$user['withdraw_type'] = 1;
//月结&补点
$this->doPromoteUserPool($user,1,$stime,$recount);
}else{
$users['withdraw_type'] = 2;
$user['withdraw_type'] = 2;
$this->doPromoteUserPool($user,2,$stime,$recount);
}
$this->savePromotateUserPool($user);
}
/**
* 下游个人汇总单
*/
public function doPromoteUserPool(&$user,$type,$stime,$recount = false)
{
$t = $this->setBeginAndEndTime($type,$stime);
$begintime = $t[0];
$endtime = $t[1];
$where = [
"_string"=>"first_company_type = '2' OR second_company_type = '2'"
];
//获取哪些要结算
if($type == 1){//月结
$where['settlement_type']=2;
$pcDbRes = M("CompanyRelation","tab_")->where($where)->select();
}else{
$where['settlement_type']=1;
$pcDbRes = M("CompanyRelation","tab_")->where($where)->select();
}
$pcList=[];
$js_id = [];//己方公司
foreach ($pcDbRes as $k => $v) {
if($v['first_company_type'] == 2){
$pcList[$v['first_company_id']] =$v;
$js_id[] =$v['second_company_id'];
}else{
$pcList[$v['second_company_id']] =$v;
$js_id[] =$v['first_company_id'];
}
}
//获取pc公司
$pc_id = implode(",",array_flip(array_flip(array_keys($pcList))));
$pu_map = [
"id"=>["IN",$pc_id],
"_string"=>"(validity_start_time > 0 AND validity_end_time = 0 ) OR validity_end_time >= {$endtime}",
"company_type"=>2
];
$tmpp = M("PromoteCompany","tab_")
->field("id,uid,company_name partner,settlement_contact link_man,contact_phone link_phone,bank_name opening_bank,bank_address payee_name,bank_card bank_account,fax_ratio,taxation_rate,company_belong,company_type,ali_user,ali_account,has_server_fee,server_fee,has_ratio,turnover_ratio")
->where($pu_map)
->select();
if(count($tmpp)<1){return;}
$pc =[];
$Promote = M("Promote","tab_");
foreach ($tmpp as $v) {
$p_map = [
"company_id"=>$v['id'],
"withdraw_done"=>1
];
// $pres = $Promote->field("alipay_account,alipay_real_name")->where($p_map)->find();
// if(!empty($pres) && !empty($pres['alipay_account']) && !empty($pres['alipay_real_name'])){
// $v['ali_user'] = $pres['alipay_real_name'];
// $v['ali_account'] = $pres['alipay_account'];
// }
if($v['has_ratio']){
$v['turnover_ratio'] = json_decode($v['turnover_ratio'],true);
}
$pc[$v['id']]=$v;
$pc[$v['id']]['is_payment']=$pcList[$v['id']]['is_payment'];
}
unset($tmpp);
$this->getPromoteCompanySpend($pc,array_unique(array_keys($pc)),$begintime,$endtime);
$StatementDb = M("CompanyStatement","tab_");
$statement_begin_time = date("Y.m.d",$begintime);
$statement_end_time = date("Y.m.d",$endtime);
// $RewardRecord = M("RewardRecord","tab_");
$LackStatement = M("company_lack_statement_info","tab_");
$StatementInfo = M("company_statement_info","tab_");
foreach($pc as $k=>&$v){
$fax_ratio = $v['taxation_rate'];
$RewardRecordRes = $this->getPromoteUserRewardRecord($v['id'],$begintime,$endtime);
if($v['has_ratio'] == 1){
$company_ratio = $this->getCompanyRatio($v['pay_amount'],$pc[$k]['turnover_ratio']);
}else{
$company_ratio = 0;
}
//获取其他信息
$v = $this->getCompanyOtherInfo($v,$k);
$countdata = &$user;
$v['statement_money'] = 0;
$v['pay_amount'] = 0;
$v['fine'] = 0;
$v['reward'] = 0;
$v['platform_amount'] = 0;
if(!isset($v['list'])){continue;}
$company_belong = $pc[$v['id']]['company_belong'];
//服务器费用
if ($type < 2) {
if ($v['has_server_fee'] == 1 && $v['server_fee'] > 0) {
$v['statement_info'][] = [
"game_name"=>"服务器费用",
"sum_money"=>-$v['server_fee'],
"pay_amount"=>-$v['server_fee'],
'statement_type'=>1,
"statement_begin_time"=>$statement_begin_time,
"statement_end_time"=>$statement_end_time
];
$v['pay_amount'] -= $v['server_fee'];
$v['statement_money'] -= $v['server_fee'];
}
}
foreach($v['list'] as $ke=>$va){
$game =[];
$game['pay_amount'] =$va['pay_amount'];
$game['game_name'] =$va['game_name'];
//获取比例
$game['relation_game_id']=$va['relation_game_id'];
$game['game_type_name'] = $this->getGameTypeName($va['relation_game_id']);
if($type == 1){
$tratio = getGamePromoteCompanyRadio($v['id'],$va['relation_game_id'],$endtime,$va['pay_amount'],true,$company_belong);
$tratio += $company_ratio;
}elseif($type == 0){
$tratio = getGamePromoteCompanyRadio($v['id'],$va['relation_game_id'],$endtime,$va['pay_amount'],false,$company_belong);
}else{
//补点
$tratio1 = getGamePromoteCompanyRadio($v['id'],$va['relation_game_id'],$endtime,$va['pay_amount'],true,$company_belong);;
$tratio2 = getGamePromoteCompanyRadio($v['id'],$va['relation_game_id'],$endtime,$va['pay_amount'],false,$company_belong);
$tratio = $tratio1-$tratio2+$company_ratio;
if($tratio <= 0){
continue;
}
}
if($type == 2){
$game['increment_ratio']=$tratio;
}else{
$game['ratio']=$tratio;
}
$v['pay_amount'] += $va['pay_amount'];
$v['platform_amount'] += $va['pay_amount'];
//判断是否是个人
if($type < 2){
//非补点
if($RewardRecordRes){
$rrfres = $RewardRecordRes[$va['relation_game_id']];
}else{
$rrfres = [
'reward_count'=>0,
'fine_count'=>0,
];
}
$game['reward'] = $rrfres['reward_count'];
$game['fine'] = $rrfres['fine_count'];
}
$game['sum_money']=round($va['pay_amount']*$tratio/100,2)+$game['reward']-$game['fine']; //个人等于 结算金额*比例-罚款+奖励
$v['statement_money'] += $game['sum_money'];
$game['fax_ratio']=$fax_ratio;
$game['statement_begin_time']=$statement_begin_time;
$game['statement_end_time']=$statement_end_time;
$game['statement_type']=0;
$v['statement_info'][] = $game;
}
$company_info = [
'account'=>$v['account'],
"company_relation_str"=>$v['company_relation_str'],
"company_type_str"=>$v['company_type_str'],
"nickname"=>$v['nickname'],
"payee_name"=>$v['payee_name'],
"bank_account"=>$v['bank_account'],
"opening_bank"=>$v['opening_bank'],
"ali_user"=>$v['ali_user'],
"ali_account"=>$v['ali_account']
];
if($v['pay_amount'] < 300){
$lackcompany =[
"company_id"=>$k,
"company_type"=>2,
"company_name"=>$v['partner'],
"company_info"=>json_encode($company_info,JSON_UNESCAPED_UNICODE),
"statement_money"=>$v['statement_money'],
"pay_amount"=>$v['pay_amount'],
"platform_amount"=>$v['platform_amount'],
"fine"=>$v['fine'],
"reward"=>$v['reward'],
"statement_begin_time"=>$begintime,
"statement_end_time"=>$endtime,
"statement_pool_num"=>$countdata['statement_num'],//母单
"is_payment"=>$v['is_payment'],
"statement_info"=>json_encode($v['statement_info'],JSON_UNESCAPED_UNICODE)
];
}
//聚合未结算数据
$lsres = $LackStatement->where("company_id='{$k}' and is_pool = 0")->select();
$del_lack_ids = [];
if(count($lsres) > 0){
//进行聚合
foreach($lsres as $key=>$val){
$del_lack_ids[] = $val['id'];
$v['statement_money'] += $val['statement_money'];
$v['pay_amount'] += $val['pay_amount'];
$v['fine'] += $val['fine'];
$v['reward'] += $val['reward'];
$v['platform_amount'] += $val['platform_amount'];
$v['statement_info'] = array_merge($v['statement_info'],json_decode($val['statement_info'],true));
$last_names = array_column($v['statement_info'],'game_name');
array_multisort($last_names,SORT_DESC,SORT_STRING,$v['statement_info']);
}
}
if($type == 2 && $v['statement_money'] == 0){
//补点不存
}else{
if($v['platform_amount'] < 300){
//存未满
if($lackcompany['pay_amount'] != 0){
$lask_id = $LackStatement->add($lackcompany);
$countdata['create_lack_ids'][] =$lask_id;
$countdata['lack_statement_money'] +=$lackcompany['statement_money'];
$countdata['lack_platform_amount'] +=$lackcompany['platform_amount'];
}
}else{
if($v['pay_amount'] != 0){
//存成功配置单号
$company =[
"pool_id"=>0,
"company_id"=>$k,
"company_type"=>2,
"company_name"=>$v['partner'],
"company_info"=>json_encode($company_info,JSON_UNESCAPED_UNICODE),
"statement_money"=>$v['statement_money'],
"pay_amount"=>$v['pay_amount'],
"platform_amount"=>$v['platform_amount'],
"fine"=>$v['fine'],
"reward"=>$v['reward'],
"statement_begin_time"=>$begintime,
"statement_end_time"=>$endtime,
"statement_info"=>json_encode($v['statement_info'],JSON_UNESCAPED_UNICODE),
"statement_num"=>"JS_".date('Ymd').date('His').$v['company_id'].sp_random_string(5)
];
if($v['is_payment'] == 1){
$company['verify_status'] = 0;
}else{
$company['verify_status'] = 2;
}
$companyid = $StatementInfo->add($company);
$countdata['info_ids'][] =$companyid;
$countdata['del_lack_ids'] =array_merge($countdata['del_lack_ids'],$del_lack_ids);
$countdata['statement_money'] +=$v['statement_money'];
$countdata['pay_amount'] +=$v['pay_amount'];
$countdata['platform_amount'] +=$v['platform_amount'];
$countdata['fine'] +=$v['fine'];
$countdata['reward'] +=$v['reward'];
}
}
}
}
}
/**
* 保存信息汇总信息
*/
public function savePromotateUserPool($data){
if(IS_CLI){
$op_name ="system";
}else{
$op_name =$_SESSION['onethink_admin']['user_auth']["username"];
}
if(empty($data['create_lack_ids']) && empty($data['del_lack_ids']) && empty($data['info_ids'])){ //补点为空不重算
return ;
}
if($data['statement_money'] == 0){
$data['verify_status'] = 5;
$data['verify_log'] = json_encode(["create_user"=>$op_name,"create_time"=>date("Y-m-d H:i:s"),"verify_user"=>"system","verify_time"=>date("Y-m-d H:i:s"),"payment_user"=>"system","payment_time"=>date("Y-m-d H:i:s")]);
}else{
$data['verify_log'] = json_encode(["create_user"=>$op_name,"create_time"=>date("Y-m-d H:i:s")]);
}
$data['create_lack_ids'] = implode(",",$data['create_lack_ids']);
$data['del_lack_ids'] = implode(",",$data['del_lack_ids']);
$info = implode(",",$data['info_ids']);
unset($data['info_ids']);
$id = M("company_statement_pool","tab_")->add($data);
//回写
if(!empty($info)){
$save["pool_id"]=$id;
M("company_statement_info","tab_")->where("id in ({$info})")->save($save);
}
if(!empty($data['del_lack_ids'])){
M("company_lack_statement_info","tab_")->where("id in ({$data['del_lack_ids']})")->save(["is_pool"=>1]);
}
}
/**
* 获取公司额为信息
*/
public function getCompanyOtherInfo($company_info,$company_id)
{
$pl = M("promote_company","tab_")
->alias('pc')
->field("p.account,p.company_relation,IFNULL(s.nickname,'admin') nickname")
->join("left join (select company_id,account,company_relation,admin_id from tab_promote where level = 1 group by company_id ) p on p.company_id = pc.id")//获取会长
->join("left join sys_member s on s.uid = p.admin_id")
->where("pc.id = {$company_id}")
->find();
$company = array_merge($company_info,$pl);
$company['company_relation_str'] =getCompanyBlong($company['company_belong']).getCompanyRelation($company['company_relation']);
$company['company_type_str'] = "个人";
return $company;
}
/**
* 获取游戏分类名称
*/
public function getGameTypeName($relation_game_id){
return M("Game","tab_")->field("game_type_name")->where("relation_game_id = '{$relation_game_id}'")->find()['game_type_name'];
}
/**
* 获取公司比例加成
* @param [type] $paymount 支付金额
* @param [type] $turnover_ratio 梯度
*/
protected function getCompanyRatio($paymount,$turnover_ratio)
{
$ratio = 0;
foreach($turnover_ratio as $k=>$v){
if($v['instanceof'] == 1){
if($paymount >= $v['turnover']){
$ratio = $v['ratio'];
}
}else{
if($paymount > $v['turnover']){
$ratio = $v['ratio'];
}
}
}
return $ratio;
}
/**
* 获取公司比例加成
* @param [type] $paymount 支付金额
* @param [type] $turnover_ratio 梯度
*/
protected function getPromoteUserRewardRecord($cpmpamy_id,$begintime,$endtime)
{
//获取所有公司的奖罚
$rrmap = array(
"d.confirm_time" => ['between', [$begintime,$endtime]],
"d.company_type"=>2,
"d.company_id"=>$cpmpamy_id,
"d.settlement_type"=>2,
);
$rfres = M("RewardDetail","tab_")
->alias("d")
->field("
IFNULL(SUM(CASE WHEN type = 1 THEN amount ELSE 0 END),0) as reward_count,
IFNULL(SUM(CASE WHEN type = 2 THEN amount ELSE 0 END),0) as fine_count,
r.relation_game_id
")
->where($rrmap)
->join("tab_reward_record as r on d.record_id = r.id")
->group("record_id,company_id")
->select();
if(empty($rfres)){
return false;
}else{
$s = [];
foreach($rfres as $k=>$v){
$s[$v['relation_game_id']] = $v;
}
return $s;
}
}
/**
* 重算接口
* 不进行结算方式重算
* @param [type] $id 原数据id
* @param string $admin_user 操作用户
* @return void bool
*/
public function updateCompanyStatementData($id,$admin_user='system')
{
//获取数据
$StatementDb = M("CompanyStatement","tab_");
$dbres = $StatementDb->where("id='{$id}'")->find();
//获取时间
$stime = $dbres['statement_end_time']-0+1;
$company_id = $dbres['company_id'];
if($dbres['company_belong'] == 9){
//上游
$savedata = $this->cpStatement($dbres['withdraw_type'],$stime,$company_id);
}else{
$savedata = $this->promoteCompanyStatement($dbres['withdraw_type'],$stime,$company_id);
}
//重写用户
$savedata['verify_log'] = json_encode(["create_user"=>$admin_user,"create_time"=>date("Y-m-d H:i:s")]);
$savedata['verify_status'] = 0;
$savedata['confirm_status'] = 0;
$savedata['confirm_log'] = '';
$savedata['id'] = $dbres['id'];
return $StatementDb->save($savedata);
}
}