Customer.php 12.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
<?php

namespace addons\antis\model;

use addons\antis\library\Ku;
use addons\qingdong\model\Message;
use addons\qingdong\model\Message2;
use app\common\model\Area;
use think\Db;
use think\Exception;
use think\Model;
use traits\model\SoftDelete;
/**
 *客户
 */
class Customer Extends Model {
	use SoftDelete;
    // 表名,不含前缀
    protected $name = 'qingdong_customer';
	// 开启自动写入时间戳字段
	protected $autoWriteTimestamp = 'int';
	// 定义时间戳字段名
	protected $createTime = 'createtime';
	protected $updateTime = 'updatetime';
	protected $deleteTime = 'deletetime';


	//获取创建时间
	public function getCreatetimeAttr($value) {
		return date('Y-m-d H:i:s', $value);
	}


	//创建人
	public function createStaff() {
		return $this->hasOne(Staff::class, 'id', 'create_staff_id')->field('id,name,post');
	}


	//负责人
	public function ownerStaff() {
		return $this->hasOne(Staff::class, 'id', 'owner_staff_id')->field('id,name,img');
	}


	//获取联系人
	public function contacts() {
		return $this->hasOne(Contacts::class, 'customer_id', 'id')->order('is_major desc')->field('id,customer_id,name,mobile,email');
	}
    //获取联系人
    public function contact() {
        return $this->belongsTo(Contacts::class,'id','customer_id',  [], 'LEFT')->field('id,customer_id,name,mobile,email')->setEagerlyType(0);;
	}

    //获取客户相关信息
    public function customerOther() {
        return $this->belongsTo(CustomerOther::class,'id','id');
	}

	public static function withtrash(){
	    return self::withTrashed();
    }

	public static function getList() {
	    $staff = Staff::info();
        $staff_id = $staff->id;
        $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()]]);
        };
		return self::where($whereStaff)->field('id,name')->select();
	}


	//创建客户
	public static function createCustomer($params,$leads_id=null,$reminds_id=null) {
		//自定义字段
		$other = [];
		foreach ($params as $name => $val) {
			if (strstr($name,'other_') !== false) {
                if(is_array($val)){
                    $other[$name] = implode(',',$val);
                }else{
                    $other[$name] = $val;
                }
				unset($params[$name]);
			}else{
                if($params[$name] === ''){
                    $params[$name]=NULL;
                }
            }
		}
		$staff = Staff::info();
		if(empty($staff)){
            // 验证失败 输出错误信息
            throw new Exception('账号不存在');
		}
        $params['create_staff_id'] = $staff->id;
        $params['owner_staff_id']  = $staff->id;
		$params['next_time']   = date('Y-m-d H:i:s');
		$params['last_time']   = date('Y-m-d H:i:s');
		$params['receivetime'] = time();
		$customer              = new self;

        $result = $customer->allowField(true)->save($params);
		$lastId=$customer->getLastInsID();
		if (false === $result) {
			// 验证失败 输出错误信息
			throw new Exception($customer->getError());
		}
		$otherModel = new CustomerOther();
		if ($otherModel->save(['id' => $lastId, 'otherdata' => json_encode($other, JSON_UNESCAPED_UNICODE)]) === false) {
			// 验证失败 输出错误信息
			throw new Exception($otherModel->getError());
		}
        if(isset($leads_id) && $leads_id){
            Leads::where(['id' => $leads_id])->update(['is_transform' => 1, 'customer_id' => $lastId]);
        }
        if (isset($reminds_id['reminds_id']) && $reminds_id['reminds_id']) {//发送通知
            $staff_ids = explode(',', $reminds_id['reminds_id']);
            foreach ($staff_ids as $staff_id) {
                //发送通知
                Message::addMessage(Message::CUSTOMER_TYPE, $lastId, $staff_id, $staff->id);
            }
        }

        Message2::addMessage2(Message::CUSTOMER_TYPE, $lastId, 1, $staff->id);

        OperationLog::createLog(OperationLog::CUSTOMER_TYPE, $lastId, '创建客户');

        //新增跟进记录
		Record::quickCreateRecord2(Record::CUSTOMER_TYPE, $lastId, '新增客户:' . $params['name'],'新增客户');
		return $lastId;
	}


	/**
	 *修改客户信息
	 */
	public static function updateCustomer($params) {
		//自定义字段
		$other = [];
		foreach ($params as $name => $val) {
			if (strstr($name,'other_') !== false) {
                if(is_array($val)){
                    $other[$name] = implode(',',$val);
                }else{
                    $other[$name] = $val;
                }
				unset($params[$name]);
			}else{
                if($params[$name] === ''){
                    $params[$name]=NULL;
                }
            }
		}

		$customer = new self;
		// 调用当前模型对应的User验证器类进行数据验证
		$result = $customer->save($params, ['id' => $params['id']]);
		if (false === $result) {
			// 验证失败 输出错误信息
			throw new Exception($customer->getError());
		}
		$otherModel = new CustomerOther();
		$otherFind = $otherModel->where(['id' => $params['id']])->find();
		if($otherFind){
            $resInfo = $otherModel->save(['otherdata' => json_encode($other, JSON_UNESCAPED_UNICODE)],['id' => $params['id']]);
        }else{
            $resInfo = $otherModel->save(['id' => $params['id'],'otherdata' => json_encode($other, JSON_UNESCAPED_UNICODE)]);
        }
		if ( $resInfo === false) {
			// 验证失败 输出错误信息
			throw new Exception($otherModel->getError());
		}
        //同步数据
        $ku = new Ku();
        $ku->editCustomer($params);
		return true;
	}

    /**
     * 导入客户
     * @param $data
     * @return bool
     */
	public static function importCustomer($data) {
		$addCustomers = [];
		$addOther     = [];
        $addcontacts = [];
		$addLog=[];
		foreach ($data as $params) {
			//自定义字段
			$other = [];
			foreach ($params as $name => $val) {
				if (strstr($name, 'other_') !== false) {
                    if(is_array($val)){
                        $other[$name] = implode(',',$val);
                    }else{
                        $other[$name] = $val;
                    }
					unset($params[$name]);
				}else{
                    if($params[$name] === ''){
                        $params[$name]=NULL;
                    }
                }
			}
			$other['id']           = $params['id'];
			$params['next_time']   = date('Y-m-d H:i:s');
			$params['receivetime'] = time();
			$params['createtime'] = time();
			$addOther[]            = ['id' => $params['id'], 'otherdata' => json_encode($other, JSON_UNESCAPED_UNICODE)];
            $addcontacts[] = ['customer_id' => $params['id'],'is_major'=>1,'name'=>$params['name'],'mobile'=>$params['mobile'],'createtime'=>time(),'updatetime'=>time()];

			$addLog[] = [
				'content'        => '导入客户',
				'operation_type' => 2,
				'operation_id'   => 30,
				'relation_type'  => OperationLog::CUSTOMER_TYPE,
				'relation_id'    => $params['id'],
				'createtime'     => time()
			];
			$addCustomers[]        = $params;
		}

		$customer = new self;
		// 调用当前模型对应的User验证器类进行数据验证
		$result = $customer->allowField(true)->insertAll($addCustomers);

		$otherModel = new CustomerOther();
		$otherModel->allowField(true)->insertAll($addOther);

        //联系人
        $contactsModel = new Contacts();
        $contactsModel->allowField(true)->insertAll($addcontacts);

		$logModel = new OperationLog();
		$logModel->allowField(true)->insertAll($addLog);

		return true;
	}

	/**
	 *移入公海
	 */
	public static function moveSeas($id) {
        $row = Customer::where(['id' => $id])->find();
        $row = $row->toArray();
        $row = CustomerOther::getOther($row);
        $seastype=Seastype::where([])->select();
        $seasIds=[];
        foreach ($seastype as $r){
            $rules=json_decode($r['rules'],true)?:[];
            $is_rule=0;//权限是否匹配
            foreach ($rules as $n=>$e){

                if($n == 'area_ids'){//区域
                    $area=Area::where(['id'=>['in',$e]])->column('name');
                    foreach ($area as $a){
                        $rs=preg_match("/^{$a}/i",$row['address'],$res);
                        if($rs){
                            $is_rule=1;
                        }
                    }
                }else if (isset($row[$n]) && $row[$n]) {
                    if (is_string($e)) {
                        $e = explode(',', $e);
                    }
                    $rn = explode(',', $row[$n]);
                    $intersect = array_intersect($e, $rn);
                    if($intersect){
                        $is_rule=1;
                    }
                }

            }
            if ($is_rule == 1) {
                $seasIds[] = $r['id'];
            }

        }
        if(empty($seasIds)){
            $seasIds[]=1;//默认公海
        }
        $seas_id = ',' . implode(',', $seasIds) . ',';
        if (Customer::where(['id' => $id])->update(['owner_staff_id' => 0,
                'seas_id' => $seas_id,'sea_time'=>time()]) == false) {
            throw new Exception('修改失败');
        }
		OperationLog::createLog(OperationLog::CUSTOMER_TYPE, $id, '将客户放入公海');

		return true;
	}


	/**
	 * 转移客户
	 */
	public static function transfer($id, $staff_id) {
		Db::startTrans();
		try {
			if (Customer::where(['id' => $id])->update([
					'owner_staff_id' => $staff_id,
					'updatetime'     => time()
				]) == false) {
				throw new Exception('修改失败');
			}
			if (Contacts::where(['customer_id' => $id])->count()) {//存在联系人 则修改负责人
				if (Contacts::where(['customer_id' => $id])->update([
						'owner_staff_id' => $staff_id,
						'updatetime'     => time()
					]) == false) {
					throw new Exception('修改失败');
				}
			}
			$staff = Staff::get($staff_id);
			OperationLog::createLog(OperationLog::CUSTOMER_TYPE, $id, '将客户转移给:' . $staff['name']);

			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			throw new Exception($e->getMessage());
		}

		return true;
	}


	/**
	 * 批量转移客户
	 */
	public static function batchTransfer($ids, $staff_id) {
		Db::startTrans();
		try {
			if (Customer::where(['id' => ['in',$ids]])->update([
					'owner_staff_id' => $staff_id,
					'updatetime'     => time()
				]) == false) {
				throw new Exception('修改失败');
			}
			if (Contacts::where(['customer_id' => ['in',$ids]])->count()) {//存在联系人 则修改负责人
				if (Contacts::where(['customer_id' => ['in',$ids]])->update([
						'owner_staff_id' => $staff_id,
						'updatetime'     => time()
					]) == false) {
					throw new Exception('修改失败');
				}
			}
			$staff = Staff::get($staff_id);
			foreach ($ids as $id){
				OperationLog::createLog(OperationLog::CUSTOMER_TYPE, $id, '将客户转移给:' . $staff['name']);
			}

			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			throw new Exception($e->getMessage());
		}

		return true;
	}


	/**
	 * 领取客户
	 */
	public static function receive($customer_id) {
		$staff    = Staff::info();
		$where=['owner_staff_id' => 0];
		if($customer_id){
			$where['id']=$customer_id;
		}
		$customer = Customer::where($where)->find();
		Db::startTrans();
		try {
			$id       = $customer['id'];
			$staff_id = $staff->id;
			if (Customer::where(['id' => $customer['id']])->update(['owner_staff_id' => $staff->id,'receivetime'=>time()]) == false) {
				throw new Exception('修改失败');
			}
			if (Contacts::where(['customer_id' => $id])->count()) {//存在联系人 则修改负责人
				if (Contacts::where(['customer_id' => $id])->update([
						'owner_staff_id' => $staff_id,
						'updatetime'     => time()
					]) == false) {
					throw new Exception('修改失败');
				}
			}

			OperationLog::createLog(OperationLog::CUSTOMER_TYPE, $customer['id'], '领取了客户');

			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			throw new Exception($e->getMessage());
		}

		return $customer['id'];
	}
}