Customer.php 20.3 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 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
<?php

namespace addons\antis\controller;

use addons\antis\model\Contacts;
use addons\antis\model\Customer as CustomerModel;
use addons\antis\model\CustomerFile;
use addons\antis\model\CustomerOther;
use addons\antis\model\Business;
use addons\antis\model\Contract;
use addons\antis\model\FormField;
use addons\antis\model\StaffSignIn;
use addons\antis\model\Consume;
use addons\antis\model\Receivables;
use addons\antis\model\OperationLog;
use addons\antis\model\Form;
use addons\antis\model\Record;
use addons\antis\model\Record as RecordModel;
use addons\antis\model\Staff;
use addons\antis\model\StaffCollect;
use addons\antis\model\Message;
use think\Db;
use think\Exception;
use function EasyWeChat\Kernel\Support\get_client_ip;

/**
 * 操作文档:https://doc.fastadmin.net/antis
 * 软件介绍:https://www.fastadmin.net/store/antis.html
 * 售后微信:qingdong_crm
 * 客户接口
 */
class Customer extends StaffApi
{
    protected $noNeedLogin = [];
    protected $noNeedRight = [];


    //获取select客户列表
    public function getSelectList()
    {
        $name = input('name');
        $where = [];
        if ($name) {
            $where['name'] = ['like', "%{$name}%"];
        }

        $staff_id=$this->auth->id;
        $list = CustomerModel::where($where)->where(function ($query) use ($staff_id) {
            $query->where('ro_staff_id', 'like', "%,{$staff_id},%")
                ->whereOr('rw_staff_id', 'like', "%,{$staff_id},%")
                ->whereOr('owner_staff_id', 'in', Staff::getMyStaffIds());
        })->with(['ownerStaff'])->field('id,name,owner_staff_id,follow')->select();
        $this->success('请求成功', $list);
    }

    //获取客户列表
    public function getList()
    {
        $limit = input("limit/d", 10);
        $params = $this->request->post();

        $where= FormField::updateWhereField(FormField::CUSTOMER_TYPE,$params);

        $whereStaff = [];
        if (isset($params['name']) && $params['name']) {//客户名称
            if(is_numeric($params['name'])){
                $whereContact['mobile'] = ['like', "%".$params['name']."%"];
                $customer_id= Contacts::where($whereContact)->column('customer_id');
                $where['id'] = array('in',$customer_id);
            }else{
                $where['name|subname'] = ['like', "%{$params['name']}%"];
            }
        }
        if (isset($params['level']) && $params['level']) {//客户星级
            $where['level'] = $params['level'];
        }
        if (isset($params['source']) && $params['source']) {//客户来源
            $where['source'] = $params['source'];
        }
        if (isset($params['follow']) && $params['follow']) {//跟进状态
            $where['follow'] = $params['follow'];
        }
        if (isset($params['group_id']) && $params['group_id']) {//角色组
            $ids = Staff::getGroupStaffIds($params['group_id']);
            $where['id'] = ['in', $ids];
        }
        if (isset($params['createtime']) && $params['createtime']) {//
            $createtime = $params['createtime'];
            $createtime = explode(',', $createtime);
            $where['createtime'] = ['between', [strtotime($createtime[0]), strtotime($createtime[1]) + 86400 - 1]];
        }
        $order = 'id desc';
        if (isset($params['sort']) && $params['sort']) {
            switch ($params['sort']) {
                case 1://名称正序
                    $order = 'name asc';
                    break;
                case 2://名称倒序
                    $order = 'name desc';
                    break;
                case 3://创建时间正序
                    $order = 'createtime asc';
                    break;
                case 4://创建时间倒序
                    $order = 'createtime desc';
                    break;
                case 5://下次跟进时间正序
                    $order = 'next_time asc';
                    break;
                case 6://下次跟进时间倒序
                    $order = 'next_time desc';
                    break;
            }
        }

        if (isset($params['next_time']) && $params['next_time']) {//下次联系时间
            $next_time = $params['next_time'];
            $next_time = explode(',', $next_time);
            $where['next_time'] = ['between', [$next_time[0], $next_time[1]]];
        }
        if (isset($params['staff_id']) && $params['staff_id']) {//下级员工筛选
            $where['owner_staff_id'] = $params['staff_id'];
        } else {
            $staff_id = $this->auth->id;
            $type = $params['type'] ?? 0;
            if ($type == 1) {//我的客户
                $whereStaff['owner_staff_id'] = $this->auth->id;
            } elseif ($type == 2) {//下属负责的客户
                $whereStaff['owner_staff_id'] = ['in', Staff::getLowerStaffId()];
            } elseif ($type == 3) {//我参与的客户
                $whereStaff = function ($query) use ($staff_id) {
                    $query->where('ro_staff_id', 'like', "%,{$staff_id},%")
                        ->whereOr('rw_staff_id', 'like', "%,{$staff_id},%");
                };
            }else{
                $whereStaff = function ($query) use ($staff_id) {
                    $query->where(['ro_staff_id' => ['like', "%,{$staff_id},%"]])
                        ->whereOr('rw_staff_id', 'like', "%,{$staff_id},%")
                        ->whereOr(['owner_staff_id' => ['in', Staff::getMyStaffIds()]]);
                };
            }

        }
        $whereSeas = ['owner_staff_id' => ['neq', 0]];
        if (isset($params['is_seas']) && $params['is_seas'] == 1) {//公海
            //公海权限
            $whereSeas=[];
            $where['owner_staff_id'] = 0;
            //公海权限
            $rules=Staff::getStaffRule('seas');
            $whereStaff = function ($query) use ($rules) {
                foreach ($rules as $rule) {
                    $query->whereOr(['seas_id' => ['like', "%,{$rule},%"]]);
                }
            };
            $order = 'sea_time desc';
        }
        if(is_array($whereStaff)){
            //查询会冲突
            $whereSeas=[];
        }

        if (isset($params['contract_status']) && $params['contract_status'] !== "") {
            $where['contract_status'] = $params['contract_status'];
        }
        $list = CustomerModel::where($where)->where($whereStaff)->where($whereSeas)->with([
            'ownerStaff',
            'contacts'
        ])->field('id,name,next_time,owner_staff_id,level,follow')->order($order)->paginate($limit);
        $this->success('请求成功', $list);
    }


    //查重客户名称
    public function selectName()
    {
        $name = input('name');
        if (CustomerModel::where(['name' => $name])->find()) {
            $this->error('客户名称已存在');
        }
        $this->success('当前客户名称可使用');
    }


    //新增客户
    public function addCustomer()
    {
        $params = $this->request->post();
        if (empty($params['customer'])) {
            $this->error('客户信息不能为空');
        }

        // 表单验证
        if (($result = $this->qingdongValidate($params['customer'], get_class(), 'create')) !== true) {
            $this->error($result);
        }
        $result = FormField::checkFields(FormField::CUSTOMER_TYPE,$params['customer']);
        if ($result !== true) {
            $this->error($result);
        }
        if (CustomerModel::where(['name' => $params['customer']['name']])->find()) {
            $this->error('客户名称已存在');
        }

        if (isset($params['is_event']) && $params['is_event'] == 1) {//是否创建跟进任务
            if (empty($params['event'])) {
                $this->error('跟进任务信息不能为空');
            }
            // 表单验证
            if (($result = $this->qingdongValidate($params['event'], str_replace(ucwords($this->request->controller()), 'Event', get_class()), 'create_task')) !== true) {
                $this->error($result);
            }

        }

        Db::startTrans();
        try {
            //线索转化
            $leads_id = '';
            if(isset($params['leads_id'])){
                $leads_id=$params['leads_id'];
            }
            $customerId = CustomerModel::createCustomer($params['customer'],$leads_id,$params['record']);
            if(isset($params['customer']['mobile']) && $params['customer']['mobile']){
                $retC = array(
                    'customer_id'=>$customerId,
                    'is_major'=>1,
                    'name'=>$params['customer']['name'],
                    'mobile'=>$params['customer']['mobile'],
                    'next_time'=>date('Y-m-d H:i:s'),
                );
                Contacts::createContacts($retC);
            }

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('新增客户成功',array('id'=>$customerId));
        }
    }


    //编辑客户
    public function editCustomer()
    {
        $id = input('id');
        $params = $this->request->post();
        $row = CustomerModel::where(['id' => $id])->find();
        if (empty($row)) {
            $this->error('客户信息不存在');
        }
        // 表单验证
        if (($result = $this->qingdongValidate($params, get_class(), 'edit')) !== true) {
            $this->error($result);
        }
        $result = FormField::checkFields(FormField::CUSTOMER_TYPE,$params,$id);
        if ($result !== true) {
            $this->error($result);
        }
        Db::startTrans();
        try {
            $result = CustomerModel::updateCustomer($params);
            if(isset($params['mobile']) && $params['mobile']){
                Contacts::where(array('customer_id'=>$id,'is_major'=>1))->update(array('mobile'=>$params['mobile'],'updatetime'=>time()));
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('修改客户成功');
    }


    //获取子公司
    public function getLowerCustomer()
    {
        $id = input('id');
        $customers = CustomerModel::where(['parent_id' => $id])->with([
            'ownerStaff',
            'contacts'
        ])->field('id,name,next_time,owner_staff_id,level,follow')->select();

        $this->success('请求成功', $customers);
    }


    //客户详情
    public function customerDetail()
    {
        $id = input('id');
        $customer = CustomerModel::where(['id' => $id])->with([
            'createStaff',
            'ownerStaff',
            'contacts'
        ])->find();
        if (empty($customer)) {
            $this->error('信息不存在');
        }
        $customer = $customer->toArray();
        $customer['is_collect'] = StaffCollect::isCollect(StaffCollect::CUSTOMER_TYPE, $customer['id']) ? 1 : 0;

        if ($customer['owner_staff_id'] == $this->auth->id ||
            in_array($customer['owner_staff_id'],Staff::getLowerStaffId()) ||
        in_array($this->auth->id, explode(',', $customer['rw_staff_id'])) ) {
            $customer['operation'] = 'update';//修改权限
        } else {
            $customer['operation'] = 'read';//只读权限
        }

        $customer = CustomerOther::getOther($customer);
        $form = Form::getDataValue('customer',$customer);
        foreach($form as $ks=>$vs){
            //备注显示
            if($vs['component'] == 'textarea' && ($vs['config']['label'] == '备注信息' || $vs['config']['label'] == '备注')){
                $customer[$vs['id']] = isset($customer[$vs['id']]) ? $customer[$vs['id']] :$customer['remarks'];
            }
        }
        //商机数量
        $customer['bussinessCount'] = Business::where(['customer_id'=>$id])->count();
        //联系人数量
        $customer['contactsCount'] = Contacts::where(['customer_id'=>$id])->count();
        //签到数量
        $customer['signCount'] = StaffSignIn::where(['customer_id'=>$id])->count();
        //合同数量
        $customer['contractCount'] = Contract::where(['customer_id'=>$id])->count();
        //费用数量
        $customer['consumeCount'] = Consume::where(['customer_id'=>$id])->count();
        //回款数量
        $customer['receivalbleCount'] = Receivables::where(['customer_id'=>$id])->count();
        //子公司
        $customer['companyCount'] = CustomerModel::where(['parent_id'=>$id])->count();
        //团队
        $ro_staff_id = [];
        if($customer['ro_staff_id']){
            $ro_staff_id = array_unique(array_filter(explode(',',$customer['ro_staff_id'])));
        }
        $rw_staff_id = [];
        if($customer['rw_staff_id']){
            $rw_staff_id = array_unique(array_filter(explode(',',$customer['rw_staff_id'])));
        }
        $customer['teamCount'] = count($ro_staff_id)+count($rw_staff_id);
        //附件
        $customer['fileCount'] = CustomerFile::where(['customer_id'=>$id])->count();
        //操作记录
        $customer['operateCount'] = OperationLog::where(['relation_id'=>$id,'relation_type'=>1,'operation_type' => 1])->count();
        //标记通知已读
        Message::setRead(Message::CUSTOMER_TYPE, $id, $this->auth->id);
        $this->success('请求成功', $customer);
    }


    //移入公海
    public function moveSeas()
    {
        $id = input('id');
        $row = CustomerModel::where(['id' => $id, 'owner_staff_id' => $this->auth->id])->find();
        if (empty($row)) {
            $this->error('您不是负责人暂无权限移除');
        }
        Db::startTrans();
        try {
            CustomerModel::moveSeas($id);

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('放入成功');
    }


    //转移客户
    public function transfer()
    {
        $id = input('id');
        $staff_id = input('staff_id');
        if (empty($staff_id)) {
            $this->error('参数错误');
        }
        $staff = Staff::get($staff_id);
        if (empty($staff)) {
            $this->error('接收对象不存在');
        }
        $row = CustomerModel::where(['id' => $id])->find();
        if (empty($row)) {
            $this->error('客户不存在');
        }
        try {
            CustomerModel::transfer($id, $staff_id);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('转移客户成功');
    }


    //领取公海客户
    public function receive()
    {
        $customer_id = input('customer_id');
        $where = ['owner_staff_id' => 0];
        if ($customer_id) {
            $where['id'] = $customer_id;
        }
        $customers = CustomerModel::where($where)->count();
        if ($customers == 0) {
            $this->error('公海内暂无客户');
        }
        try {
            $id = CustomerModel::receive($customer_id);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('领取成功', ['id' => $id]);
    }


    //重点关注客户
    public function collect()
    {
        $customer_id = input('customer_id');
        try {
            StaffCollect::addCollect(StaffCollect::CUSTOMER_TYPE, $customer_id);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('重点关注成功');
    }


    //取消重点关注
    public function cancelCollect()
    {
        $customer_id = input('customer_id');
        try {
            StaffCollect::cancel(StaffCollect::CUSTOMER_TYPE, $customer_id);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('取消重点关注成功');
    }


    //重点关注客户列表
    public function collectList()
    {
        $limit = input("limit/d", 10);
        $ids = StaffCollect::where(['staff_id' => $this->auth->id, 'relation_type' => 1])->column('relation_id');
        $list = CustomerModel::where(['id' => ['in', $ids]])->with([
            'ownerStaff',
            'contacts'
        ])->field('id,name,next_time,owner_staff_id,level,follow')->order('id desc')->paginate($limit);

        $this->success('请求成功', $list);
    }


    //获取附件列表
    public function getFilesList()
    {
        $id = input('customer_id');

        $files = CustomerFile::where(['customer_id' => $id])->field('file_id')->with(['file'])->select();
        $this->success('请求成功', $files);
    }


    //周围客户
    public function nearby()
    {
        $lng = input('lng');
        $lat = input('lat');
        //我的客户
        $type = input('type',0);
        //距离
        $distance = input('distance', 5, 'intval');
        $name = input('name', '', 'trim');

        if (empty($lng) && empty($lat)) {
            $this->error('参数错误');
        }

        $range = 180 / pi() * $distance / 6372.797; //里面的 1 就代表搜索 1km 之内,单位km
        $lngR = $range / cos($lat * pi() / 180);
        $maxLat = $lat + $range; //最大纬度
        $minLat = $lat - $range; //最小纬度
        $maxLng = $lng + $lngR; //最大经度
        $minLng = $lng - $lngR; //最小经度
        $where = ['lng' => ['between', [$minLng, $maxLng]], 'lat' => ['between', [$minLat, $maxLat]]];
        //客户分类
        $whereStaff=[];
        $staff_id=$this->auth->id;
        if ($type == 1) {//我的客户
            $whereStaff['owner_staff_id'] = $this->auth->id;
        } elseif ($type == 2) {//下属负责的客户
            $whereStaff['owner_staff_id'] = ['in', Staff::getLowerStaffId()];
        } elseif ($type == 3) {//我参与的客户
            $whereStaff = function ($query) use ($staff_id) {
                $query->where('ro_staff_id', 'like', "%,{$staff_id},%")
                    ->whereOr('rw_staff_id', 'like', ",{$staff_id},");
            };
        }else{
            $whereStaff = function ($query) use ($staff_id) {
                $query->where('ro_staff_id', 'like', "%,{$staff_id},%")
                    ->whereOr('rw_staff_id', 'like', "%,{$staff_id},%")
                    ->whereOr('owner_staff_id', 'in', Staff::getMyStaffIds());
            };
        }
        if ($name) {
            $where['name'] = ['like', "%{$name}%"];
        }
        $customers = CustomerModel::where($where)->where($whereStaff)->field('id,owner_staff_id,name,location,next_time,lng,lat,address_detail,follow')->with('ownerStaff')->select();
        $data = [];
        //所属员工列表
        $myStaffIds = Staff::getMyStaffIds();
        foreach ($customers as $k => $v) {
            if ($v['owner_staff_id'] == 0) {
                $v['type'] = 0;//公海
            } elseif ($v['owner_staff_id'] == $this->auth->id) {
                $v['type'] = 1;//自己的
            } elseif (in_array($v['owner_staff_id'], $myStaffIds)) {
                $v['type'] = 2;//团队的
            } else {
                $v['type'] = 3;//其他人
            }
            $v['juli_num'] = getdistance($lng, $lat, $v['lng'], $v['lat']);
            $v['juli'] = float_number($v['juli_num']);
            $data[$v['juli']][] = $v;
        }
        ksort($data);


        $result = [];
        foreach ($data as $v) {

            $result = array_merge($result, array_values($v));
        }
        $this->success('请求成功', $result);
    }


    //获取搜索员工列表
    public function getSearchStaffList()
    {
        $name = input('name','');
        $where = [];
        if($name){
            $where['name'] = ['like',"%$name%"];
        }
        $ids = Staff::getMyStaffIds();

        $staff = Staff::where([
            'id' => ['in', $ids],
            'status' => 1
        ])->where($where)->field('id,name,img,post')->select();
        $this->success('请求成功', $staff);
    }

}