Staff.php 14.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
<?php

namespace app\admin\controller\antis\department;

use addons\antis\model\Customer;
use addons\antis\model\Staff as StaffModel;
use addons\antis\model\StaffRole;
use app\admin\model\AuthGroup;
use app\admin\controller\antis\Base;
use fast\Tree;
use think\Db;
use think\Exception;
use app\admin\model\Admin;

/**
 * 员工管理
 */
class Staff extends  Base {

    protected $noNeedLogin = ['index','selectpage','info'];

    protected $childrenAdminIds = null;
    protected $childrenGroupIds = null;

	public function _initialize() {
		parent::_initialize();
		$this->model      = new StaffModel();

        $this->childrenAdminIds = $this->auth->getChildrenAdminIds($this->auth->isSuperAdmin());
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds($this->auth->isSuperAdmin());

        //角色组
        $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();
        Tree::instance()->init($groupList);
        $tree = Tree::instance()->init($groupList,'pid');
        
        // halt($tree);
        $groupdata = [];
        $authlist = [];
        if ($this->auth->isSuperAdmin()) {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            $authlist = $result;
            foreach ($result as $k => $v) {
                $groupdata[$v['id']] = $v['name'];
            }
        } else {
            $result = [];
            $groups = $this->auth->getGroups();
            // halt($groups);
            // $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
            // $authlist = $groups;
            $authlist = $groups;
            // halt($authlist);
            foreach ($groups as $m => $n) {
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                $temp = [];
                foreach ($childlist as $k => $v) {
                    $authlist[] = $v;
                    $temp[$v['id']] = $v['name'];
                }
                $result[__($n['name'])] = $temp;
            }
            $groupdata = $result;
        }
        // $groupList
        // halt($authlist);
        $channelList = [];
        foreach($authlist as &$val){
            $val = str_replace(' ','',str_replace('├','',str_replace('└','',str_replace('&nbsp;', '', $val))));
            
            $data = [
                'id'     => $val['id'],
                'parent' => $val['pid'] ? $val['pid'] : '#',
                'text'   => $val['name'],
            ];
            
            $channelList[] = $data;
            // if()
        }
        
        
        $lookup = [];
        foreach ($channelList as $item) {
            $lookup[$item['id']] = $item;
        }
        
        // 遍历数组,检查并更新 parent
        foreach ($channelList as &$item) {
            $parentId = $item['parent'];
            // 如果上级不存在,则将上级 ID 改为 #
            if (!isset($lookup[$parentId])) {
                $item['parent'] = '#';
            }
        }

        //halt($channelList);

        $this->assignconfig('channelList', $channelList);
        // halt($channelList);
        
        $this->view->assign('groupdata', $groupdata);

	}



    public function export(){

        $list = $this->model->where('status', '1')->where('deletetime','null')->select();

        $data = [];
        foreach ($list as $item){

            $group_ids = $item['group_ids'];
            $group_name =implode(',',AuthGroup::where("find_in_set(id, '$group_ids')")->column('name'));

            //halt($item);
            $data[]=[
                'staff'=>$item['name'],  //姓名
                'group_name'=>$group_name,
                'post'=>$item['post'],
            ];
        }

        $title = [
            '姓名',
            '部门',
            '岗位',
        ];


        $file = export_excel($title, $data, '通讯录');
        if ($file['filePath']) {
            $this->success('导出成功', '', $file);
        }
        $this->error('导出失败');



    }






    /**
     * 员工列表
     * @return string
     */
	public function index() {
	    
		$this->request->filter(['strip_tags']);
		if ($this->request->isAjax()) {
		    
		    // 单独处理组别
            $filter = $this->request->get("filter", '');
            $op=$this->request->get("op", '', 'trim');
            $filter = (array)json_decode($filter, true);
            $op = (array)json_decode($op, true);
            $dateFilter=[];//将筛选的值放在这里
            if(isset($filter['group_ids'])){
                // $dateFilter=$filter['createtime'];
                $dateFilter['group_ids'] = $filter['group_ids'];
                unset($filter['group_ids']);
                unset($op['group_ids']);
                //去掉了createtime 的filter 重新组织到 request中 交给下面 buildparams()方法去构建query 的条件
                \think\Request::instance()->get(['filter'=>json_encode($filter)]);
                \think\Request::instance()->get(['op'=>json_encode($op)]);
            }
            
            
			list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $wheres=[];
            $wheres['id']=['in',StaffModel::getMyStaffIds()];



            //  halt($this->model
            //     ->where($where)->fetchSql()->where(function($query)use($dateFilter){
            //         if(!empty($dateFilter['group_ids'])){
            //             foreach (explode(',',$dateFilter['group_ids']) as $id) {
            //                 $query->whereRaw("FIND_IN_SET($id, group_ids) > 0");
            //             }
            //         }
            //     })->select());
			$list = $this->model->with(['parent','admin','staffrole'])
                ->where($where)->order($sort, $order)->where(function($query)use($dateFilter){
                    if(!empty($dateFilter['group_ids'])){
                        foreach (explode(',',$dateFilter['group_ids']) as $id) {
                            $query->whereOr('FIND_IN_SET(' . $id . ', group_ids) > 0');
                        }
                    }
                })->where('status',"<>",2)->paginate($limit);
			$row  = $list->items();

			$result = array("total" => $list->total(), "rows" => $row);

			return json($result);
		}

		return $this->view->fetch();
	}


    /**
     * 添加员工
     * @return string
     */
	public function add() {
        if ($this->request->isAjax()) {
            $data = $this->request->post('row/a');
            $mobile=$data['mobile'];
            $count = StaffModel::where(['mobile'=>$mobile])->count();
            if($count > 0){
                $this->error('员工手机号已存在');
            }

            $newSalt = substr(md5(uniqid(true)), 0, 6);
            $newPassword = md5(md5($data['password']) . $newSalt);
            $data['salt'] = $newSalt;
            $data['password'] = $newPassword;
            $data['status'] = 1;
            if(!empty($data['img'])){
                $data['img'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
            }

		  if(empty($data['sr'])){
                $data['sr'] = strtotime($data['sr']);
            }

            
            Db::startTrans();
            try {
                $group = $this->request->post("group/a");
                //过滤不允许的组别,避免越权
                $group = array_intersect($this->childrenGroupIds, $group);
                if (!$group) {
                    exception(__('The parent group exceeds permission limit'));
                }
                $data['group_ids']=implode(',',$group);
                // halt(1);
                $result =  $this->model->save($data);
                Db::commit();
            }catch (Exception $e){
                Db::rollback();
                $this->error($e->getMessage());
            }

            if (!$result) {
                $this->error('提交失败');
            }
            $this->success('提交成功');
        }

		$staffname = StaffModel::where([])->column('id,name');
		$staffs    = ['' => '无'];
		foreach ($staffname as $id => $name) {
			$staffs[$id] = $name;
		}
        $this->view->assign('roles',StaffRole::where([])->column('name','id'));
		$this->view->assign('staffs', $staffs);
		return $this->view->fetch();
	}


    /**
     * 修改员工
     * @param null $ids
     * @return string
     */
	public function edit($ids = null) {
		$map['id'] = $ids;
		if ($this->request->isAjax()) {
			$data   = $this->request->post('row/a');


            if($data['password']){
                $newSalt = substr(md5(uniqid(true)), 0, 6);
                $newPassword = md5(md5($data['password']) . $newSalt);
                $data['salt'] = $newSalt;
                $data['password'] = $newPassword;
            }else{
                unset($data['password']);
            }
            $mobile=$data['mobile'];
            $count = StaffModel::where(['mobile'=>$mobile,'id'=>['neq',$ids]])->count();
            if($count > 0){
                $this->error('员工手机号已存在');
            }
            if(empty($data['img'])){
                $data['img'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
            }

            if(!empty($data['sr'])){
                $data['sr'] = strtotime($data['sr']);
            }

//            halt($data);

            Db::startTrans();
            try {
                $group = $this->request->post("group/a",[]);
                //过滤不允许的组别,避免越权
                $group = array_intersect($this->childrenGroupIds, $group);
                if (!$group) {
                    exception(__('The parent group exceeds permission limit'));
                }
                $data['group_ids']=implode(',',$group);
                $data['id']=$map['id'];
                $result=$this->model->save($data,$map);
                Db::commit();
            }catch (Exception $e){
                Db::rollback();
                $this->error($e->getMessage());
            }

			if (!$result) {
				$this->error('修改失败');
			}
			$this->success('修改成功');
		}
		$data = StaffModel::where($map)->find();
		$data['sr'] = date('Y-m-d',$data['sr']);
		$this->view->assign("row", $data);

		$staffname = StaffModel::where([])->column('id,name');
		$staffs    = ['' => '无'];
		foreach ($staffname as $id => $name) {
			$staffs[$id] = $name;
		}
        $this->view->assign('roles',StaffRole::where([])->column('name','id'));
		$this->view->assign('staffs', $staffs);

		return $this->view->fetch();
	}

    /**
     * 删除员工
     */
	public function del($ids = null) {
		if ($this->request->isAjax()) {
			$map['id'] = array('in', $ids);
            $findinfo = StaffModel::where($map)->select();
            foreach($findinfo as $k=>$v){
                if($v['admin_id'] ==1){
                    $this->error('管理员不可删除');
                }
            }
			$result    = StaffModel::destroy($map);

			if (!$result) {
				$this->error('删除失败');
			}
			$cids = Customer::where(['owner_staff_id' => $ids])->column('id');
			try {
				foreach ($cids as $id) {
					Customer::moveSeas($id);
				}
			} catch (Exception $e) {
                $this->error($e->getMessage());
			}

			$this->success('删除成功');
		}

		return $this->view->fetch();
	}


    /**
     * 更新状态禁用账号
     */
	public function update_status() {
		$id     = input('ids');
		$status = input('status', 2, 'intval');

		$staff = $this->model->where(['id' => $id])->find();
		if (empty($staff)) {
			$this->error('员工不存在');
		}
		if ($this->model->isUpdate(true)->save(['id' => $id, 'status' => $status])) {
			$this->success('操作成功');
		}
		$this->error('操作失败');
	}

    /**
     * 获取员工角色
     */
    public function getstaffrole(){
        $model=new StaffRole();
        $result = $model->where([])->field('id,name')->select();
        $searchlist = [];
        foreach ($result as $key => $value) {
            $searchlist[] = ['id' => $value['id'], 'name' => $value['name']];
        }
        $data = ['searchlist' => $searchlist];
        $this->success('', null, $data);
    }

    /**
     * 获取管理员账户
     */
    public function admin_username()
    {
        $params = input('name', '');
        $where['username'] = array('like', '%' . $params . '%');
        $list = Admin::where($where)->field('id,username as name')->select();
        $data['list'] = $list;
        return json_encode($data);
    }

    /**
     * 获取管理员邮箱
     */
    public function admin_email()
    {
        $params = input('name', '');
        $where['email'] = array('like', '%' . $params . '%');
        $list = Admin::where($where)->field('id,email as name')->select();
        $data['list'] = $list;
        return json_encode($data);
    }


    /**
     * 获取当前登录员工信息
     */
    public function info() {
        $staff = $this->getStaff();
        if ($staff) {
            // 获取admin用户名
            $adminUsername = '';
            if ($staff->admin_id) {
                $admin = \app\admin\model\Admin::get($staff->admin_id);
                if ($admin) {
                    $adminUsername = $admin->username;
                }
            }
            
            return $this->success('获取成功', '', [
                'id' => $staff->id,
                'name' => $staff->name,
                'mobile' => $staff->mobile,
                'email' => $staff->email,
                'admin_id' => $staff->admin_id,
                'admin_username' => $adminUsername
            ]);
        } else {
            return $this->error('未找到员工信息');
        }
    }

    public function selectpage(){




        $param = $this->request->param();

        $count = $this->model->with(['parent','admin','staffrole'])
            ->where('status',"<>",2)
            ->where('name','LIKE','%'.$param['name'].'%')
            ->count();
        $list = $this->model->with(['parent','admin','staffrole'])
            ->where('status',"<>",2)
            ->where('name','LIKE','%'.$param['name'].'%')
            ->page($param['pageNumber'], $param['pageSize'])
            ->select();

        $result = array("total" => $count, "rows" => $list);

        return json($result);

    }
}