bztang-admin/plugins/area-dividend/src/admin/AgentController.php

467 lines
19 KiB
PHP

<?php
namespace Yunshop\AreaDividend\admin;
use app\common\components\BaseController;
use app\common\exceptions\ShopException;
use app\common\facades\Setting;
use app\common\helpers\PaginationHelper;
use app\common\helpers\Url;
use app\common\models\Member;
use Illuminate\Support\Facades\Storage;
use Yunshop\AreaDividend\models\AreaDividendAgent;
use Yunshop\AreaDividend\models\Lock;
use Yunshop\AreaDividend\models\weiqing\WeiQingUsers;
use Yunshop\AreaDividend\services\AgentService;
use Yunshop\AreaDividend\services\MessageService;
/**
* Created by PhpStorm.
* User: yanglei
* Date: 2017/4/24
* Time: 下午4:50
*/
class AgentController extends BaseController
{
public function index()
{
$search = \YunShop::request()->search;
$pageSize = 20;
$list = AreaDividendAgent::getAgents($search)->orderBy('id','DESC')->paginate($pageSize);
$pager = PaginationHelper::show($list->total(), $list->currentPage(), $list->perPage());
if(!$search['time']){
$search['time']['start'] = date("Y-m-d H:i:s",time());
$search['time']['end'] = date("Y-m-d H:i:s",time());
}
return view('Yunshop\AreaDividend::admin.list', [
'list' => $list->toarray(),
'pager' => $pager,
'total' => $list->total(),
'search' => $search,
])->render();
}
public function createAgent()
{
$agentData = \YunShop::request()->agent;
$wq_data = \YunShop::request()->wq;
if ($agentData) {
$agent = AreaDividendAgent::getAgentByMemberId($agentData['member_id'])->where('status','<>',-1)->first();
if(!empty($agent)){
$set = Setting::get('plugin.area_dividend');
if($agent->status == 0){
return $this->message('添加失败,此会员已进行申请,请在申请列表进行审核', '', 'error');
}else if($agent->status == 1 && !$set['agent_many']){
return $this->message('添加失败,此会员已是代理商', '', 'error');
}
}
$agentData = AgentService::setAgentData($agentData);
$retLock = Lock::verify($agentData);
if ($retLock) return $this->message('该区域已被锁定', '', 'error');
if (trim($wq_data['username']) && trim($wq_data['password'])) {
if (trim($wq_data['password_again']) != trim($wq_data['password'])) {
return $this->message('两次密码不相同', '', 'error');
}
$verifyPassword = verifyPasswordStrength(trim($wq_data['password']));
if($verifyPassword !== true){
return $this->message($verifyPassword, '', 'error');
}
$result = WeiQingUsers::getUserByUserName(trim($wq_data['username']))->first();
if ($result) {
return $this->message('用户名已存在', '', 'error');
}
$user = WeiQingUsers::register(trim($wq_data['username']), $wq_data['password']);
$agentData['user_id'] = $user['user_id'];
$agentData['username'] = $user['username'];
$agentData['password'] = $user['password'];
$agentData['salt'] = $user['salt'];
}
$agentModel = new AreaDividendAgent();
//将数据赋值到model
$agentModel->setRawAttributes($agentData);
//其他字段赋值
$agentModel->uniacid = \YunShop::app()->uniacid;
$agentModel->status = 1;
$agentModel->agent_at = time();
$agentModel->title = request()->title;
$agentModel->min_status = request()->min_status;
$agentModel->min_app_id = request()->min_app_id;
$agentModel->min_app_secret = request()->min_app_secret;
$agentModel->min_mch_id = request()->min_mch_id;
$agentModel->min_api_secret = request()->min_api_secret;
if (request()->file('apiclient_cert')) $agentModel->min_apiclient_cert = $this->uploadFile('apiclient_cert', $agentModel->min_app_id);
if (request()->file('apiclient_key')) $agentModel->min_apiclient_key = $this->uploadFile('apiclient_key', $agentModel->min_app_id);
//字段检测
$validator = $agentModel->validator($agentModel->getAttributes());
if ($validator->fails()) {
//检测失败
$this->error($validator->messages());
} else {
//数据保存
if ($agentModel->save()) {
$data=[
'member_id'=>$agentData['member_id'],
'username'=>$agentData['username'],
'created_at' => time(),
];
event(new \app\common\events\plugin\AreaDividendEvent($data));
// 发送消息
$member = Member::getMemberByUid($agentModel->member_id)->with('hasOneFans')->first();
MessageService::becomeAgent($agentModel, $member->hasOneFans);
//显示信息并跳转
return $this->message('添加成功', yzWebUrl('plugin.area-dividend.admin.agent'));
} else {
return $this->message('添加失败', '', 'error');
}
}
}
return view('Yunshop\AreaDividend::admin.create-agent', [
'wq_data' => $wq_data,
])->render();
}
public function editAgency(){
$id = \YunShop::request()->id;
$agency = AreaDividendAgent::find($id);
if(!$agency) return $this->message('无此区域代理或已经删除','','error');
if ($agency->user_id) {
$user = WeiQingUsers::getUserByUid($agency->user_id)->first();
if (!$user) return $this->message('微擎账号不存在','','error');
}
if (request()->isMethod('post')) {
$wq_data = \YunShop::request()->wq;
if ($wq_data['password'] && $wq_data['password_again']) {
if (trim($wq_data['password_again']) != trim($wq_data['password'])) {
return $this->message('两次密码不相同', '', 'error');
}
$verifyPassword = verifyPasswordStrength(trim($wq_data['password']));
if($verifyPassword !== true){
return $this->message($verifyPassword, '', 'error');
}
if ($agency->user_id && $user) {
WeiQingUsers::editPwd(trim($wq_data['password']), $user);
return $this->message('修改密码成功', yzWebUrl('plugin.area-dividend.admin.agent'));
} else {
$result = WeiQingUsers::getUserByUserName(trim($wq_data['username']))->first();
if ($result) {
return $this->message('用户名已存在', '', 'error');
}
$user = WeiQingUsers::register(trim($wq_data['username']), $wq_data['password']);
$agentData['user_id'] = $user['user_id'];
$agentData['username'] = $user['username'];
$agentData['password'] = $user['password'];
$agentData['salt'] = $user['salt'];
$agentData['user_id'] = $user['user_id'];
$agency->setRawAttributes($agentData);
if ($agency->save()) {
//显示信息并跳转
return $this->message('账号添加成功', yzWebUrl('plugin.area-dividend.admin.agent'));
} else {
return $this->message('账号添加失败', '', 'error');
}
}
}
else {
if (request()->order_manage == 1) {
$whereColumn = 'province_id';
if ($agency->agent_level == 4) {
$whereColumn = 'street_id';
} else if ($agency->agent_level == 3) {
$whereColumn = 'district_id';
} else if ($agency->agent_level == 2) {
$whereColumn = 'city_id';
}
$existModel = AreaDividendAgent::uniacid()
->where('agent_level', $agency->agent_level)
->where('status', 1)
->where($whereColumn, $agency->$whereColumn)
->where('manage', 1)
->where('id', '!=', $agency->id)
->first();
if ($existModel) {
return $this->message('该区域下已存在[订单管理权限]的代理商', '', 'error');
}
}
$agency->manage = request()->order_manage;
$agency->ratio = request()->ratio;
$agency->has_ratio = request()->has_ratio;
$agency->title = request()->title;
// 支付信息修改
$agency->min_status = request()->min_status;
$agency->min_app_id = request()->min_app_id;
$agency->min_app_secret = request()->min_app_secret;
$agency->min_mch_id = request()->min_mch_id;
$agency->min_api_secret = request()->min_api_secret;
if (request()->file('apiclient_cert')) $agency->min_apiclient_cert = $this->uploadFile('apiclient_cert', $agency->min_app_id);
if (request()->file('apiclient_key')) $agency->min_apiclient_key = $this->uploadFile('apiclient_key', $agency->min_app_id);
if (intval(request()->input('agent')['investor_uid'])) $agency->investor_uid = intval(request()->input('agent')['investor_uid']);
$agency->save();
return $this->message('账号编辑成功', yzWebUrl('plugin.area-dividend.admin.agent'));
}
}
return view('Yunshop\AreaDividend::admin.change-pwd', [
'username' => $user->username,
'agency' => $agency->toArray()
])->render();
}
public function agentApply()
{
$search = request()->search;
if ($search) {
$pageSize = 20;
$list = AreaDividendAgent::getApplyAgentsBySearch($search)->paginate($pageSize);
$pager = PaginationHelper::show($list->total(), $list->currentPage(), $list->perPage());
return view('Yunshop\AreaDividend::admin.apply', [
'list' => $list->toarray(),
'pager' => $pager,
])->render();
}
$pageSize = 20;
$list = AreaDividendAgent::getApplyAgents()->paginate($pageSize);
$pager = PaginationHelper::show($list->total(), $list->currentPage(), $list->perPage());
return view('Yunshop\AreaDividend::admin.apply', [
'list' => $list->toarray(),
'pager' => $pager,
])->render();
}
public function copeApply()
{
$id = \YunShop::request()->id;
$status = \YunShop::request()->status;
$agentModel = AreaDividendAgent::find($id);
if (!$agentModel) {
return $this->message('操作失败,代理商不存在!', '', 'error');
}
$result = false;
if ($status == '1') {
if ($agentModel->username) {
$user = WeiQingUsers::getUserByUserName($agentModel->username)->first();
if ($user) {
return $this->message('用户名已存在,请驳回后重新申请','','error');
}
}
$result = static::setApplyAdopt($agentModel, $status);
} elseif ($status == '-1') {
$result = static::setApplyReject($agentModel, $status);
}
if ($result) {
if ($status == '1') {
$member = Member::getMemberByUid($agentModel->member_id)->with('hasOneFans')->first();
MessageService::becomeAgent($agentModel, $member->hasOneFans);
}
$data=[
'member_id'=>$agentModel['member_id'],
'username'=>$agentModel['real_name'],
'created_at' => time(),
];
event(new \app\common\events\plugin\AreaDividendEvent($data));
if (app('plugins')->isEnabled('instation-message')) {
//开启了站内消息插件
$agentModelNew = AreaDividendAgent::find($id);
event(new \Yunshop\InstationMessage\event\AreaDividendEvent($agentModelNew));
}
return $this->message('操作成功', yzWebUrl('plugin.area-dividend.admin.agent.agent-apply'));
} else {
return $this->message('操作失败', '', 'error');
}
}
protected static function setApplyAdopt($agentModel, $status)
{
$agentModel->status = $status;
if (!empty($agentModel->username) && !empty($agentModel->password)) {
$user_uid= WeiQingUsers::registerBySalt($agentModel->username, $agentModel->password, $agentModel->salt);
$agentModel->user_id = $user_uid;
}
$agentModel->agent_at = time();
return $agentModel->save();
}
protected static function setApplyReject($agentModel, $status)
{
$agentModel->status = $status;
return $agentModel->save();
}
/**
* 数据导出
*
*/
public function export()
{
$file_name = date('Ymdhis', time()) . '区域代理导出';
$search = \YunShop::request()->search;
$list = AreaDividendAgent::getAgents($search)
->get()
->toArray();
$export_data[0] = [
'ID',
'会员id',
'会员',
'姓名/手机号',
'成为代理时间',
'申请区域',
'申请等级',
'区域消费总额',
'分红比例',
'累计结算佣金',
'已结算分红金额',
'未结算分红金额'
];
foreach ($list as $key => $item) {
$area = '';
if ($item['province_name']) {
$area .= $item['province_name'];
}
if ($item['city_name']) {
$area .= $item['city_name'];
}
if ($item['district_name']) {
$area .= $item['district_name'];
}
if ($item['street_name']) {
$area .= $item['street_name'];
}
$export_data[$key + 1] = [
$item['id'],
$item['has_one_member']['uid'] ?: '',
$item['has_one_member']['nickname'] ?: '',
$item['has_one_member']['realname'].'/'.$item['has_one_member']['mobile'],
$item['created_at'],
$area,
$item['level_name'],
$item['count_order_amount']."",
$item['rate']."%",
$item['count_settle_amount']."",
$item['settle_dividend_amount']."",
$item['unsettled_dividend_amount'].""
];
}
return \app\exports\ExcelService::fromArrayExport($export_data,$file_name);
// 商城更新,无法使用
// \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 change()
{
$id = \YunShop::request()->id;
$agent = AreaDividendAgent::find($id);
$agentData = \YunShop::request()->value;
$agentData = AgentService::setAgentData($agentData);
$whereColumn = 'province_id';
if ($agentData['agent_level'] == 4) {
$whereColumn = 'street_id';
} else if ($agentData['agent_level'] == 3) {
$whereColumn = 'district_id';
} else if ($agentData['agent_level'] == 2) {
$whereColumn = 'city_id';
}
$existModel = AreaDividendAgent::uniacid()
->where('agent_level', $agentData['agent_level'])
->where('status', 1)
->where($whereColumn, $agentData[$whereColumn])
->where('manage', 1)
->where('id', '!=', $id)
->first();
if ($existModel) {
return $this->errorJson('该区域下已存在[订单管理权限]的代理商');
} else {
$agent->setRawAttributes($agentData);
$agent->save();
return $this->errorJson('成功');
}
}
public function daletedAgency()
{
$id = \YunShop::request()->id;
$agency = AreaDividendAgent::find($id);
if(!$agency) {
return $this->message('无此区域代理或已经删除','','error');
}
//删除登录
if ($agency->user_id) {
WeiQingUsers::delUser($agency->user_id);
}
$result = AreaDividendAgent::daletedAgency($id);
if($result) {
return $this->message('删除成功',Url::absoluteWeb('plugin.area-dividend.admin.agent'));
}else{
return $this->message('删除失败','','error');
}
}
/**
* Common: 证书上传 - 仅用于区域代理中的微信小程序配置中证书文件上传
* Author: wu-hui
* Time: 2023/05/31 17:08
* @param $fileKey
* @param $appId
* @return string
* @throws ShopException
*/
private function uploadFile($fileKey,$appId){
$file = request()->file($fileKey);
if ($file->isValid()) {
//文件原名
$originalName = $file->getClientOriginalName();
//扩展名
$fileExt = $file->getClientOriginalExtension();
//临时文件的绝对路径
$realPath = $file->getRealPath();
//新文件名
$fileName = "area_pem_{$appId}_{$originalName}";
if ($fileExt != 'pem') throw new ShopException("{$originalName}文件格式错误");
$bool = Storage::disk('cert')->put($fileName, file_get_contents($realPath));
if ($bool) return storage_path("cert/{$fileName}");
}
throw new ShopException("{$fileKey}.pem文件上传错误");
}
}