bztang-admin/plugins/team-dividend/src/admin/TeamAgencyController.php

400 lines
18 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace Yunshop\TeamDividend\admin;
use app\common\components\BaseController;
use app\common\exceptions\AppException;
use app\common\exceptions\ShopException;
use app\common\helpers\PaginationHelper;
use app\common\helpers\Url;
use app\common\models\Member;
use app\common\models\Order;
use Illuminate\Support\Facades\DB;
use Yunshop\TeamDividend\admin\models\TeamDividendAgencyModel;
use Yunshop\TeamDividend\jobs\NewUpgrateJob;
use Yunshop\TeamDividend\models\CodeRecordModel;
use Yunshop\TeamDividend\models\Log;
use Yunshop\TeamDividend\models\OrderModel;
use Yunshop\TeamDividend\models\TeamDividendLevelModel;
use Yunshop\TeamDividend\models\TeamDividendLevelUpgrade;
use Yunshop\TeamDividend\models\Uplog;
use Yunshop\TeamDividend\services\GetAgentsService;
use Yunshop\TeamDividend\services\ReturnConfig;
use Yunshop\TeamDividend\services\UpgradeService;
use Yunshop\TeamDividend\services\FundPoolAwardService;
use app\common\services\ExportService;
use Yunshop\TeamDividend\services\upgrate\UplogService;
class TeamAgencyController extends BaseController
{
private $pageSize = 20;
public function setBlack()
{
$this->validate(['id' => 'required|integer|min:1'], null, [], ['id' => '经销商ID']);
if (!$agent = TeamDividendAgencyModel::uniacid()->find(request()->id)) {
return $this->errorJson('经销商不存在');
}
if (!TeamDividendAgencyModel::setBlack($agent, request()->is_black ? 1 : 0)) {
return $this->message('修改失败','','error');
}
return $this->message('修改成功');
}
public function index()
{
$parames = \YunShop::request();
$uid = $parames->get('uid');
$title = '经销商';
if (strpos($parames['searchtime'], '×') !== FALSE) {
$search_time = explode('×', $parames['searchtime']);
if (!empty($search_time)) {
$parames['searchtime'] = $search_time[0];
$start_time = explode('=', $search_time[1]);
$end_time = explode('=', $search_time[2]);
$parames->times = [
'start' => $start_time[1],
'end' => $end_time[1]
];
}
}
$list = TeamDividendAgencyModel::searchAgency($parames);
$list->with(['hasManyMemberChildren'=>function ($query) {
return $query->select('yz_member.member_id','yz_member.parent_id')->join('yz_team_dividend_agency',function ($join) {
$join->on('yz_team_dividend_agency.uid','=','yz_member.member_id')->whereNull('yz_team_dividend_agency.deleted_at');
});
}]);
if($uid){
$list = $list->where('yz_member.parent_id',$uid);
$title = '下级经销商';
}
$list = $list->paginate($this->pageSize);
$list = $list->toArray();
$pager = PaginationHelper::show($list['total'], $list['current_page'], $this->pageSize);
$starttime = $endtime = time();
if (isset($parames['searchtime']) && ($parames['searchtime'] == 1 || $parames['searchtime'] == 2)) {
if ($parames['times']['start'] != '请选择' && $parames['times']['end'] != '请选择') {
$starttime = strtotime($parames['times']['start']);
$endtime = strtotime($parames['times']['end']);
}
}
// 获取所有经销商的排名信息
$rankList = TeamDividendLevelModel::getRanking();
// 获取每个经销商的赠送名额
$uidS = array_column($list['data'],'uid');
$quotaInfo = Uplog::uniacid()
->select([DB::raw("sum(give_limit) as total_quota"),'uid'])
->whereIn('uid',$uidS)
->orderBy('created_at','ASC')
->groupBy('uid')
->get()
->toArray();
$quotaInfo = array_column($quotaInfo,'total_quota','uid');
// 已使用
$useQuota = TeamDividendAgencyModel::uniacid()
->select([DB::raw("count(id) as total_use_quota"),'give_uid'])
->whereIn('give_uid',$uidS)
->groupBy('uid')
->get()
->toArray();
$useQuota = array_column($useQuota,'total_use_quota','give_uid');
foreach ($list['data'] as $key => $item) {
$list['data'][$key]['total'] = count($item['has_many_member_children']);
// 剩余名额处理
$list['data'][$key]['total_quota'] = (int)$quotaInfo[$item['uid']];
$list['data'][$key]['surplus_quota'] = (int)$quotaInfo[$item['uid']] - (int)$useQuota[$item['uid']];
$list['data'][$key]['use_quota'] = (int)$useQuota[$item['uid']];
// 排名处理
$list['data'][$key]['rank_list'] = array_filter(array_map(function($rankInfo) use ($item){
$rankSort = (string)$rankInfo['up_log'][$item['uid']];
if(($rankSort === '0' || $rankSort) && $rankInfo['level_type'] == 0) {
return [
'id' => $rankInfo['id'],
'level_name' => $rankInfo['level_name'],
'ranking' => ((int)$rankInfo['up_log'][$item['uid']] + 1),
];
}
return [];
},$rankList));
}
$level = TeamDividendLevelModel::getList()->where('level_type',0)->get();
$culturalLevel = TeamDividendLevelModel::getList()->where('level_type',1)->get();
return view('Yunshop\TeamDividend::admin.team-agency', [
'list' => $list,
'endtime' => $endtime,
'starttime' => $starttime,
'total' => $list['total'],
'pager' => $pager,
'title' => $title,
'level' => $level,
'culturalLevel' => $culturalLevel,
'request' => \YunShop::request(),
])->render();
}
/**
* @return mixed|string
* @throws AppException
* @throws \Throwable
*/
public function add()
{
if (\Request::getMethod() == 'POST') {
$agentData = \YunShop::request()->team;
$agentData['uniacid'] = \YunShop::app()->uniacid;
$agentData['upgrade_at'] = time();
if((int)$agentData['level'] <= 0 && (int)$agentData['cultural_level_id'] <= 0) return $this->message('添加失败,请选择代理等级!', '', 'error');
try{
TeamDividendAgencyModel::addTeamAgency($agentData);
return $this->message('经销商操作成功', yzWebUrl('plugin.team-dividend.admin.team-agency'));
}catch(\Exception $e){
return $this->message($e->getMessage(), '', 'error');
}
}
$level_list = TeamDividendLevelModel::getList()->where('level_type',0)->get();
$cultural_level = TeamDividendLevelModel::getList()->where('level_type',1)->get();
return view('Yunshop\TeamDividend::admin.team-agency-add', [
'level' => $level_list,
'cultural_level' => $cultural_level
])->render();
}
public function searchAgency()
{
$keyword = \YunShop::request()->keyword;
$member = Member::getMemberInfoByNickName($keyword);
return view('Yunshop\TeamDividend::admin.query', [
'members' => $member
])->render();
}
public function export()
{
$file_name = date('Ymdhis', time()) . '';
$parames = \YunShop::request();
if (strpos($parames['searchtime'], '×') !== FALSE) {
$search_time = explode('×', $parames['searchtime']);
if (!empty($search_time)) {
$parames['searchtime'] = $search_time[0];
$start_time = explode('=', $search_time[1]);
$end_time = explode('=', $search_time[2]);
$parames->times = [
'start' => $start_time[1],
'end' => $end_time[1]
];
}
}
// $list = TeamDividendAgencyModel::searchAgency($parames)->get()->toArray();
$list = TeamDividendAgencyModel::searchAgency($parames);
$uid = $parames->get('uid');
if($uid){
$list = $list->where('yz_team_dividend_agency.parent_id',$uid);
}
$export_page = request()->export_page ? request()->export_page : 1;
$export_model = new ExportService($list, $export_page);
$list = $list->get()->toArray();
$childe = TeamDividendAgencyModel::getChildNumByPrantId();
foreach ($list as $key => $item) {
foreach ($childe as $c_item ) {
if ($c_item['parent_id'] == $item['uid']) {
$list[$key]['total'] = $c_item['total'];
}
}
}
$export_data[0] = ['ID', '会员', '推荐人会员ID', '成为代理时间', '推荐人姓名', '推荐人手机号', '经销商', '手机号','等级', '文创等级', '一级(直系)总经销商人数', '分红比例', '已结算分红', '未结算分红', '累计结算分红','团队业绩','团队商品销量'];
foreach ($list as $key => $item) {
if (!empty($item['status'])) {
$status = '已使用';
} else {
$status = '未使用';
}
if($item['has_many_team_dividend'][0]['status'] == 1)
$item['dividend_final'] = $item['has_many_team_dividend'][0]['total_amount'];
elseif($item['has_many_team_dividend'][1]['status'] == 1)
$item['dividend_final'] = $item['has_many_team_dividend'][1]['total_amount'];
elseif($item['has_many_team_dividend'][2]['status'] == 1)
$item['dividend_final'] = $item['has_many_team_dividend'][2]['total_amount'];
else
$item['dividend_final'] = 0;
if($item['has_many_team_dividend'][0]['status'] === 0)
$item['dividend_open'] = $item['has_many_team_dividend'][0]['total_amount'];
elseif($item['has_many_team_dividend'][1]['status'] === 0)
$item['dividend_open'] = $item['has_many_team_dividend'][1]['total_amount'];
elseif($item['has_many_team_dividend'][2]['status'] === 0)
$item['dividend_open'] = $item['has_many_team_dividend'][2]['total_amount'];
else
$item['dividend_open'] = 0;
$item['dividend_total'] = $item['has_many_team_dividend'][2]['total_amount'] + $item['has_many_team_dividend'][1]['total_amount'] + $item['has_many_team_dividend'][0]['total_amount']?:0;
$export_data[$key + 1] = [
$item['id'],
$item['has_one_member']['uid'],
$item['to_parent']['uid'] ?? 0,
$item['created_at'],
$item['to_parent']['realname'] ?? '',
$item['to_parent']['mobile'] ?? 0,
$item['has_one_member']['username'],
$item['has_one_member']['mobile'],
$item['has_one_level']['level_name'],
$item['cultural_level']['level_name'],
$item['total'],
$item['has_one_level']['dividend_ratio'],
$item['dividend_final'],
$item['dividend_open'],
$item['dividend_total'],
$item['team_order_price'],
$item['team_goods_total']];
}
$export_model->export($file_name, $export_data, 'plugin.team-dividend.admin.team-agency.index', 'direct_export');
// \Excel::create($file_name, function ($excel) use ($export_data) {
// // Set the title
// $excel->setTitle('Office 2005 XLSX Document');
//
// // Chain the setters
// $excel->setCreator('')
// ->setLastModifiedBy("")
// ->setSubject("Office 2005 XLSX Test Document")
// ->setDescription("Test document for Office 2005 XLSX, generated using PHP classes.")
// ->setKeywords("office 2005 openxml php")
// ->setCategory("report file");
//
// $excel->sheet('info', function ($sheet) use ($export_data) {
// $sheet->rows($export_data);
// });
//
//
// })->export('xls');
}
public function daletedAgency()
{
$id = \YunShop::request()->id;
$agency = TeamDividendAgencyModel::find($id);
if(!$agency) {
return $this->message('无此经销商或已经删除','','error');
}
$uid= TeamDividendAgencyModel::getuid($id);
$result = TeamDividendAgencyModel::daletedAgency($id);
$code_id=CodeRecordModel::daletedCode($uid['uid']);
return $this->message('删除成功',Url::absoluteWeb('plugin.team-dividend.admin.team-agency'));
}
public function change()
{
$id = \YunShop::request()->id;
$levelId = \YunShop::request()->value;
$leveType = \YunShop::request()->leve_type;
TeamDividendAgencyModel::changeLevel($id,$levelId,$leveType);
}
public function test(){
// 经销商升级模拟
// $model = Order::with('hasManyOrderGoods')->find(34);
// $set = \Setting::get('plugin.team_dividend');
// (new NewUpgrateJob($model->uid, $set, $model->uniacid, TeamDividendLevelUpgrade::ORDER_PAY, $model))->handle();
// 经销商提成模拟
// $order = Order::find(43);
// $TeamReturnService = ReturnConfig::getClass();
// if (app('plugins')->isEnabled('team-sideways')) debug('经销商订单创建终止:team-sideways');
// $set = $order->getSetting('plugin.team_dividend');
// if (!$set['is_team_dividend']) debug('是否开启经销商插件');
// $buyMember = $order->belongsToMember;
// $agents = GetAgentsService::index($set, $order->uid, $order->create_time);
// foreach ($order->hasManyOrderGoods as $order_goods) {
// // 普通经销商提成处理
// $TeamReturnService->setData($order, $set, $buyMember, $order_goods, $agents);
// $TeamReturnService->handle();
// $this->totalDividend += $TeamReturnService->totalDividend;
// }
// 等级 升级记录校准
/*$teamDividendList = TeamDividendAgencyModel::uniacid()->select(['id','uid','level','cultural_level_id'])->get()->toArray();
$notUpLog = [];
foreach($teamDividendList as $teamInfo){
// 判断:普通等级是否存在升级记录
if((int)$teamInfo['level'] > 0){
$isHasLevelLog = (int)Uplog::uniacid()->where('uid',$teamInfo['uid'])->where('after_level_id',$teamInfo['level'])->value('id');
if($isHasLevelLog <= 0) $notUpLog[$teamInfo['id']]['level_res'] = $teamInfo;
}
// 文创等级是否存在升级记录
if((int)$teamInfo['cultural_level_id'] > 0){
$isHasCulturalLevelLog = (int)Uplog::uniacid()->where('uid',$teamInfo['uid'])->where('after_level_id',$teamInfo['cultural_level_id'])->value('id');
if($isHasCulturalLevelLog <= 0) {
$teamInfo['info_count'] = Uplog::uniacid()->where('uid',$teamInfo['uid'])->count();
$teamInfo['info_max_id'] = Uplog::uniacid()->where('uid',$teamInfo['uid'])->max('id');
$teamInfo['info_list'] = Uplog::uniacid()->select('id','uid','before_level_id','after_level_id')->where('uid',$teamInfo['uid'])->get()->toArray();
$notUpLog[$teamInfo['id']]['cultural_level_res'] = $teamInfo;
// if($teamInfo['info_count'] >= 2 && $teamInfo['cultural_level_id'] == 6){
// Uplog::uniacid()->where('id',$teamInfo['info_max_id'])->update([
// 'after_level_id' => $teamInfo['cultural_level_id'],
// 'after_level_setting' => '{"id":6,"uniacid":2,"level_name":"\u6d88\u8d39\u5546","cultural_level_name":"\u5e02\u573a\u670d\u52a1\u6d25\u8d34","level_weight":1,"level_type":1,"dividend_ratio":0,"code_num":"0","award_hierarchy":0,"award_ratio":"0","created_at":"2023-11-24 15:05:32","updated_at":"2023-11-30 10:49:36","deleted_at":null,"upgrade_reward_point":"0.00","upgrade_reward_gold":"0.00","award_gratitude":"0","hierarchy_limit":0,"auto_withdraw_day":"","auto_withdraw_period":"","number_limit":0,"culate_model":0,"current_md":null,"upgrade_reward_draw":0,"identity_type":0,"give_limit":0,"give_limit_level_id":5,"has_one_upgrade_set":{"id":6,"uniacid":"2","dividend_id":6,"parase":[{"self_buy_count":"1","become":"0"},{"order_money_2":"","order_num_2":"","order_money":"","first_money":"","order_count":"","first_order_count":"","first_order_count_to_goods":"","team_order_amount":"","team_shop_order_amount":"","team_profit_amount":"","team_goods_amount":"","team_goods_amount_to_goods":"","team_merchants_count":"","team_member_count":"","team_member_count_to_goods":"","first_lower_team_count":"","first_lower_team_count_to_goods":"","all_lower_team_count":"","first_lower_count":"","self_buy_money":"1","self_buy_count":"1","level":{"13":"","12":"","11":"","10":"","9":"","8":"","5":"","7":"","4":"","6":"","3":""},"first_child_level":{"13":"","12":"","11":"","10":"","9":"","8":"","5":"","7":"","4":"","6":"","3":""},"group_level":{"13":"","12":"","11":"","10":"","9":"","8":"","5":"","7":"","4":"","6":"","3":""},"level_line_num":"","level_line_level_id":"5","oneself":"0","level_line_people":"","level_line_area_num":"","level_line_area_level_id":"1","level_line_area_people":"","settle_money":"","first_cost_count":"","first_cost_num":"","dividend_and_peer_sum":"","first_second_cost_count":"","first_second_cost_num":"","team_new_order_number":"","team_new_order_number_to_goods":"","one_or_two":{"one_or_two_level_id":"5","one_or_two_people":""},"goods":"","many_good":["12","13","14"]}],"created_at":"2023-11-24 15:05:32","updated_at":"2023-11-30 10:49:36","deleted_at":null}}'
//
//
// ]);
// }
}
}
}
debug([
'总数' => count($notUpLog),
'uid' => implode(',',array_column(array_column($notUpLog,'cultural_level_res'),'uid')),
'列表' => $notUpLog
]);*/
debug("结束");
}
}