DiverseYouthNightSchool/application/admin/controller/manystore/Index.php

678 lines
25 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 app\admin\controller\manystore;
use app\admin\model\Admin;
use app\admin\model\school\classes\ClassesLib;
use app\admin\model\school\classes\Teacher;
use app\admin\model\school\classes\Verification;
use app\admin\model\User;
use app\common\model\manystore\Shop;
use app\common\model\school\classes\Evaluate;
use app\common\model\school\classes\Order;
use app\common\model\school\classes\order\OrderDetail;
use app\common\model\school\classes\order\ServiceOrder;
use app\manystore\model\Manystore;
use app\manystore\model\ManystoreLog;
use app\manystore\model\ManystoreShop;
use app\manystore\model\ManystoreAuthGroup;
use app\manystore\model\ManystoreAuthGroupAccess;
use app\common\controller\Backend;
use fast\Random;
use fast\Tree;
use think\Exception;
use think\Hook;
use think\Validate;
/**
* 管理员管理
*
* @icon fa fa-users
* @remark 一个管理员可以有多个角色组,左侧的菜单根据管理员所拥有的权限进行生成
*/
class Index extends Backend
{
/**
* @var \app\manystore\model\Manystore
*/
protected $model = null;
protected $shopModel = null;
protected $selectpageFields = 'id,username,nickname,avatar';
protected $searchFields = 'id,username,nickname';
protected $childrenGroupIds = [];
protected $childrenAdminIds = [];
//不用审核允许修改的字段
protected $no_auth_fields = [ "yyzzdm","yyzz_images","front_idcard_image", "reverse_idcard_image","name",'image','images','address_city','province',"city","district","address","address_detail",
"longitude","latitude","content","desc"
];
//更新数据是否需要触发审核开关
protected $need_auth = false;
protected $have_auth = false;
protected $success_auth = false;
protected $error_auth = false;
protected $qSwitch = true;
protected $qFields = ["user_id"];
public function _initialize()
{
$this->model = new Manystore();
$this->shopModel = new ManystoreShop();
parent::_initialize();
$this->view->assign("statusList", $this->shopModel->getStatusList());
$this->view->assign("typeList", $this->shopModel->getTypeList());
$this->view->assign("shop_backend_url", config("site.shop_backend_url"));
$this->getCity();
$this->getAuthMsg();
}
/**
* 免登录进入机构后台
* @return string
* @throws \think\Exception
* @throws \think\db\exception\BindParamException
* @throws \think\exception\DbException
* @throws \think\exception\PDOException
*/
public function free($ids = ''){
$param = $this->request->param();
if($this->request->isPost()){
// try{
if(isset($param['ids']))$ids = $param['ids'];
//机构登录
//如果存在登录,先退出登录
$auth = \app\manystore\library\Auth::instance();
if($auth->isLogin()){
$auth->logout();
Hook::listen("manystore_logout_after", $this->request);
}
//执行登录
ManystoreLog::setTitle(__('Login'));
$result = $auth->freelogin($ids, 0);
if ($result === true) {
Hook::listen("admin_login_after", $this->request);
$this->success(__('Login successful'), null, [ 'id' => $auth->id, 'avatar' => $auth->avatar]);
} else {
$msg = $auth->getError();
$msg = $msg ? $msg : __('Username or password is incorrect');
$this->error($msg, null, ['token' => $this->request->token()]);
}
// }catch (\Exception $e){
// $this->error($e->getMessage());
// }
}
$row = $this->model->get($ids);
$this->view->assign('vo', $row);
return $this->view->fetch();
}
/**
* 查看
*/
public function index()
{
//当前是否为关联查询
$this->relationSearch = true;
$this->searchFields = ["id","nickname","shop.tel","shop.desc","shop.legal_entity","shop.name","shop.address","shop.address_detail","shop.address_city"];
//设置过滤方法
$this->request->filter(['strip_tags', 'trim']);
if ($this->request->isAjax()) {
//如果发送的来源是Selectpage则转发到Selectpage
if ($this->request->request('keyField')) {
return $this->selectpage();
}
list($where, $sort, $order, $offset, $limit, $page, $alias, $bind, $excludearray) = $this->buildparams(null, null, ["check_full"]);
if (isset($excludearray['check_full']['value']) && $excludearray['check_full']['value']) {
$check_full = $excludearray['check_full']['value'];
switch ($check_full) {
case 'true': //查完善
$expireWhere = [
function ($query) {
$query->where(function ($query){
$query->where("shop.address_city","<>", '')
->where("shop.province","<>", '')
->where("shop.city","<>", '')
->where("shop.district","<>", '')
->where("shop.longitude","<>", '')
->where("shop.latitude","<>", '')
->where("shop.name","<>", '')
->where("shop.image","<>", '')
->where("shop.images","<>", '')
->where("shop.content","<>", '')
->where("shop.tel","<>", '')
->where("shop.logo","<>", '');
});
}
];
break;
case 'false': //查未完善
$expireWhere = [
function ($query) {
$query->where(function ($query){
$query->where("shop.address_city", '')
->whereOr("shop.province", '')
->whereOr("shop.city", '')
->whereOr("shop.district", '')
->whereOr("shop.longitude", '')
->whereOr("shop.latitude", '')
->whereOr("shop.name", '')
->whereOr("shop.image", '')
->whereOr("shop.images", '')
->whereOr("shop.content", '')
->whereOr("shop.tel", '')
->whereOr("shop.logo", '');
});
}
];
break;
default:
}
} else {
$expireWhere = [[]];
}
$total = $this->model
->with(['shop',"user"])
->where($where)
->where(...$expireWhere)
->where(array('is_main'=>1))
->order($sort, $order)
->count();
$list = $this->model
->with(['shop',"user"])
->where($where)
->where(...$expireWhere)
->where(array('is_main'=>1))
// ->field(['password', 'salt', 'token'], true)
->order($sort, $order)
->limit($offset, $limit)
->select();
// $this->view->assign('check_full',(new \app\common\model\dyqc\ManystoreShop)->checkFull($shop_info->id));
foreach ($list as $k => &$v){
$v["check_full"] = (new \app\common\model\dyqc\ManystoreShop)->checkFull($v["shop"]["id"]);
}
$result = array("total" => $total, "rows" => $list);
return json($result);
}
return $this->view->fetch();
}
protected function authClasses(&$params,&$shop,$row=null){
//审核失败需填写原因
if($shop["status"] == '2' && empty($shop["reason"])){
throw new \Exception("审核失败需填写原因");
}
if($shop["status"] == '2'){
//审核不通过会平台下架
$params["status"] = 'hidden';
}
//更新
if($row){
if($shop["status"] != '1' && $row["status"] == '1'){
throw new \Exception("审核已通过的课程不允许再修改审核状态!");
}
if($shop["status"] != '0' && $row["status"] == '0'){
//填写审核时间和审核人
$shop["auth_time"] = time();
$shop["admin_id"] = $this->auth->id;
if($shop["status"] == '1'){
//审核通过
$this->success_auth = true;
}
if($shop["status"] == '2'){
//审核通过
$this->error_auth = true;
}
}
//审核通过
if($this->success_auth){
//如果是平台下架,则更新成正常下架
if($params["status"] == 'hidden')$params["status"] = 'normal';
//当前密码
// $password = $params['password'] ? $params['password'] : \app\common\model\dyqc\ManystoreShop::getDefaultPassword($params["type"],$params["user_id"],$params);
//调用通过事件
// $data = ['shop' => $row,"password"=>$password];
// \think\Hook::listen('shop_auth_success_after', $data);
}
if($this->error_auth){
//审核不通过会平台下架
$params["status"] = 'hidden';
//调用通过事件
//调用通过事件
// $data = ['shop' => $row];
// \think\Hook::listen('shop_auth_fail_after', $data);
}
}else{
//新增
}
}
protected function updateCheck($id,$params=[],$shop=[],$row=null){
if($shop && $row){
// if(!$this->no_auth_fields_check($shop,$row)){
return true;
// }
}
// 课程存在未完成订单则不允许操作
$order = Order::where("manystore_id",$id)->where("status","in","0,3")->find();
if($order)throw new \Exception("存在正在使用中的课程订单或存在正在售后中的课程订单无法继续操作!");
// 课程存在售后订单则不允许操作
//有课程不允许删
$classesLib = ClassesLib::where("manystore_id",$id)->find();
if($classesLib)throw new \Exception("请先删除课程后再删除机构!");
// //有老师不允许删
// $teacher = Teacher::where("manystore_id",$id)->find();
// if($teacher)throw new \Exception("请先删除老师后再删除机构!");
// //有核销员不允许删
// $verification = Verification::where("manystore_id",$id)->find();
// if($verification)throw new \Exception("请先删除核销员后再删除机构!");
// $shop_id = Manystore::where("id",$id)->value("shop_id");
// //有授权用户不允许删
// $auth = \app\common\model\manystore\UserAuth::where("shop_id",$shop_id)->find();
// if($auth)throw new \Exception("请先删除授权用户后再删除机构!");
}
protected function update_check(&$params,&$shop,$row=null)
{
$shop["user_id"] = $params["user_id"];
if(!$shop["user_id"])throw new \Exception("认证用户不存在!");
$user = User::get($shop["user_id"]);
if(!$user) throw new \Exception("认证用户不存在!");
if($shop["address_city"] && !$shop["district"])throw new Exception("请选择所在城市");
//账号昵称和头像取用户的
$params["nickname"] = $user["realname"] ?: $user["nickname"];
$params["avatar"] = $user["avatar"] ?:"/assets/img/avatar.png";
//判断省市区编码是否在授权列表内
["provinces" =>$provinces,"citys"=> $citys, "districts"=>$districts,"address_citys"=>$address_citys] = Admin::getHaveCity($this->auth->id);
$province = $shop["province"];
$city = $shop["city"];
$district = $shop["district"];
if(is_array($address_citys))$address_citys = implode(",",$address_citys);
if(is_array($provinces)){
if(!in_array($province,$provinces))throw new \Exception("您选择的省份不在您的授权范围({$address_citys})内");
}
if(is_array($citys)){
if(!in_array($city,$citys))throw new \Exception("您选择的城市不在您的授权范围({$address_citys})内");
}
if(is_array($districts)){
if(!in_array($district,$districts))throw new \Exception("您选择的区县不在您的授权范围({$address_citys})内");
}
//独立地点需传定位信息
// if(empty($params["address_city"])
// || empty($params["province"])
// || empty($params["city"])
// || empty($params["district"])
// || empty($params["longitude"])
// || empty($params["latitude"])) $this->error("独立地点需传定位信息");
//特有认证判断
$this->authClasses($params,$shop,$row);
// var_dump($row);die;
//更新
if($row){
$this->have_auth = false;
if($this->need_auth){
//判断更新的变动数据
$this->no_auth_fields_check($params,$shop,$row);
if($this->have_auth){
//注释掉先不一刀切
// $params['status'] = "hidden";
$shop['status'] = "0";
}
}
$this->updateCheck($row->id,$params,$shop,$row);
//名称title不能与其他课程重复
$check_title = $this->shopModel->where('id','<>',$row["id"])->where('name',$shop["name"])->find();
if($check_title){
throw new \Exception("机构或个人认证名称已存在或被其他机构占用,请更改!");
}
//user_id不能与其他机构重复
$check_user_id = $this->shopModel->where('id','<>',$row["id"])->where('user_id',$shop["user_id"])->find();
if($check_user_id){
throw new \Exception("机构或个人认证用户已存在或被其他机构占用,请更改!");
}
}else{
//新增
//名称title不能重复
$check_title = $this->shopModel->where('name',$shop["name"])->find();
if($check_title){
throw new \Exception("机构或个人认证名称已存在或被其他机构占用,请更改!");
}
//user_id不能与其他机构重复
$check_user_id = $this->shopModel->where('user_id',$shop["user_id"])->find();
if($check_user_id){
throw new \Exception("机构或个人认证用户已存在或被其他机构占用,请更改!");
}
}
}
/**
* 添加
*/
public function add()
{
if ($this->request->isPost()) {
$this->token();
$params = $this->request->post("row/a");
$shop = $this->request->post("shop/a");
if ($params) {
if (!Validate::is($params['password'], '\S{6,16}')) {
$this->error(__("Please input correct password"));
}
db()->startTrans();
try{
$shop["user_id"] = $params['user_id'];
$this->update_check($params,$shop,$row=null);
$shop_info = $this->shopModel->save($shop);
if($shop_info === false){
throw new \Exception($this->shopModel->getError());
}
$params['shop_id'] = $this->shopModel->id;
$params['salt'] = Random::alnum();
$params['password'] = md5(md5($params['password']) . $params['salt']);
if(empty($params['avatar']))$params['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
$params['is_main'] = 1;
$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
$result = $this->model->validate($validate)->save($params);
if ($result === false) {
throw new \Exception($this->model->getError());
}
$manystoreAuthGroupModel = new ManystoreAuthGroup();
$group = [];
$group['shop_id'] = $this->shopModel->id;
$group['name'] = '超级管理员';
$group['rules'] = '*';
$group['createtime'] = time();
$group['updatetime'] = time();
$group_id = $manystoreAuthGroupModel->insertGetId($group);
if(!$group_id){
throw new \Exception('添加失败');
}
$manystoreAuthGroupAccessModel = new ManystoreAuthGroupAccess();
$group_access = [];
$group_access['uid'] = $this->model->id;
$group_access['group_id'] = $group_id;
$manystoreAuthGroupAccessModel->insert($group_access);
//调用事件
$data = ['shop' => $shop];
\think\Hook::listen('shop_create_after', $data);
db()->commit();
}catch (\Exception $e){
db()->rollback();
$this->error($e->getMessage());
}
$this->success();
}
$this->error();
}
return $this->view->fetch();
}
/**
* 编辑
*/
public function edit($ids = null)
{
$row = $this->model->get(['id' => $ids,'is_main'=>1]);
if (!$row) {
$this->error(__('No Results were found'));
}
$shop_info = $this->shopModel->get(array('id'=>$row['shop_id']));
if(!$shop_info){
$this->error(__('商家信息资料不存在'));
}
if ($this->request->isPost()) {
$this->token();
$params = $this->request->post("row/a");
$shop = $this->request->post("shop/a");
if ($params) {
$shop["user_id"] = $params['user_id'];
db()->startTrans();
try{
$this->update_check($params,$shop,$shop_info);
$result = $shop_info->save($shop);
if($result === false){
throw new \Exception(__("修改商家信息资料失败"));
}
//当前密码
$password = $params['password'] ? $params['password'] : \app\common\model\dyqc\ManystoreShop::getDefaultPassword($shop["type"],$params["user_id"],$params);
if ($params['password']) {
if (!Validate::is($params['password'], '\S{6,16}')) {
throw new \Exception(__("Please input correct password"));
}
$params['salt'] = Random::alnum();
$params['password'] = md5(md5($params['password']) . $params['salt']);
} else {
unset($params['password'], $params['salt']);
}
//这里需要针对username和email做唯一验证
$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
$manystoreValidate = \think\Loader::validate($validate);
$manystoreValidate->rule([
'username' => 'regex:\w{3,12}|unique:manystore,username,' . $row->id,
'email' => 'require|email|unique:manystore,email,' . $row->id,
'password' => 'regex:\S{32}',
]);
$result = $row->validate($validate)->save($params);
if ($result === false) {
throw new \Exception($row->getError());
}
//调用事件
$data = ['shop' => $shop_info];
\think\Hook::listen('shop_update_after', $data);
if($this->success_auth){
//调用通过事件
$data = ['shop' => $shop_info,"password"=>$password];
\think\Hook::listen('shop_auth_success_after', $data);
}
if($this->error_auth){
//调用通过事件
$data = ['shop' => $shop_info];
\think\Hook::listen('shop_auth_fail_after', $data);
}
db()->commit();
}catch (\Exception $e){
db()->rollback();
$this->error($e->getMessage());
}
$this->success();
}
$this->error();
}
$grouplist = $this->auth->getGroups($row['id']);
$groupids = [];
foreach ($grouplist as $k => $v) {
$groupids[] = $v['id'];
}
$this->view->assign("row", $row);
$this->view->assign("shop", $shop_info);
$this->view->assign('check_full',(new \app\common\model\dyqc\ManystoreShop)->checkFull($shop_info->id));
$this->view->assign('check_full_msg',(new \app\common\model\dyqc\ManystoreShop)->checkFullMsg($shop_info->id));
$this->view->assign("groupids", $groupids);
return $this->view->fetch();
}
/**
* 删除
*/
public function del($ids = "")
{
if ($ids) {
$row = $this->model->get(['id' => $ids,'is_main'=>1]);
if(!$row){
$this->error(__('No Results were found'));
}
db()->startTrans();
try{
$this->updateCheck($ids);
$result = $row->delete();
if(!$result){
exception('账号信息删除失败');
}
$result = $this->shopModel->where(array('id'=>$row['shop_id']))->delete();
\app\common\model\manystore\UserAuth::where(array('shop_id'=>$row['shop_id']))->delete();
\app\common\model\school\classes\Teacher::where(array('shop_id'=>$row['shop_id']))->delete();
\app\common\model\school\classes\Verification::where(array('shop_id'=>$row['shop_id']))->delete();
Order::where(array('shop_id'=>$row['shop_id']))->delete();
OrderDetail::where(array('shop_id'=>$row['shop_id']))->delete();
\app\admin\model\school\classes\hour\Order::where(array('shop_id'=>$row['shop_id']))->delete();
ServiceOrder::where(array('shop_id'=>$row['shop_id']))->delete();
$classesLibs = \app\common\model\school\classes\ClassesLib::where(array('shop_id'=>$row['shop_id']))->select();
foreach( $classesLibs as $lib){
$specs = $lib->specs;
foreach ($specs as $spec){
$spec->delete();
}
$lib->delete();
}
Evaluate::where(array('shop_id'=>$row['shop_id']))->delete();
if(!$result){
exception('商家信息删除失败');
}
db()->commit();
}catch (\Exception $e){
db()->rollback();
$this->error($e->getMessage());
}
$this->success('删除成功');
}
$this->error(__('You have no permission'));
}
/**
* 批量更新
* @internal
*/
public function multi($ids = "")
{
// 管理员禁止批量操作
$this->error();
}
/**
* 下拉搜索
*/
public function selectpage()
{
$this->dataLimit = 'auth';
$this->dataLimitField = 'id';
return parent::selectpage();
}
}