Xiahai před 6 měsíci
rodič
revize
b5d9d164f9

+ 358 - 324
addons/qingdongams/model/Customer.php

@@ -5,65 +5,79 @@ namespace addons\qingdongams\model;
 use app\common\model\Area;
 use addons\qingdongams\model\CustomerOther;
 use addons\qingdongams\model\Form;
+use fast\Random;
 use think\Db;
 use think\Exception;
 use think\Model;
 use traits\model\SoftDelete;
+
 /**
  *客户
  */
-class Customer Extends Model {
-	use SoftDelete;
+class Customer extends Model
+{
+    use SoftDelete;
+
     // 表名,不含前缀
     protected $name = 'qingdongams_customer';
-	// 开启自动写入时间戳字段
-	protected $autoWriteTimestamp = 'int';
-	// 定义时间戳字段名
-	protected $createTime = 'createtime';
-	protected $updateTime = 'updatetime';
-	protected $deleteTime = 'deletetime';
+    // 开启自动写入时间戳字段
+    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 getCreatetimeAttr($value) {
-		return date('Y-m-d H:i:s', $value);
-	}
 
+    //获取创建时间
+    public function getUpdatetimeAttr($value)
+    {
+        return date('Y-m-d H:i:s', $value);
+    }
 
-	//获取创建时间
-	public function getUpdatetimeAttr($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,img');
+    }
 
-	//创建人
-	public function createStaff() {
-		return $this->hasOne(Staff::class, 'id', 'create_staff_id')->field('id,name,post,img');
-	}
 
+    //负责人
+    public function ownerStaff()
+    {
+        return $this->hasOne(Staff::class, 'id', 'owner_staff_id')->field('id,name,img');
+    }
 
-	//负责人
-	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 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 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 function customerOther()
+    {
+        return $this->belongsTo(CustomerOther::class, 'id', 'id');
+    }
 
-	public static function withtrash(){
-	    return self::withTrashed();
+    public static function withtrash()
+    {
+        return self::withTrashed();
     }
+
     public function contractTotal()
     {
         return $this->hasOne(Contract::class, 'customer_id', 'id')->group('customer_id')->field('customer_id,sum(money) as c_money')->bind('c_money');
@@ -84,61 +98,63 @@ class Customer Extends Model {
         return $this->hasOne(Workorder::class, 'customer_id', 'id')->group('customer_id')->field('customer_id,sum(money) as w_money')->bind('w_money');
     }
 
-	public static function getList() {
-	    $staff = Staff::info();
+    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{
+        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;
+                unset($params[$name]);
+            } else {
+                if ($params[$name] === '') {
+                    $params[$name] = NULL;
                 }
             }
-		}
-		$staff = Staff::info();
-		if(empty($staff)){
+        }
+        $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;
+        $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){
+        $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']) {//发送通知
@@ -150,199 +166,214 @@ class Customer Extends Model {
         }
 
         OperationLog::createLog(OperationLog::CUSTOMER_TYPE, $lastId, '创建客户');
-		//新增跟进记录
-		Record::quickCreateRecord(Record::CUSTOMER_TYPE, $lastId, '新增客户:' . $params['name']);
-		return $lastId;
-	}
+        //新增跟进记录
+        Record::quickCreateRecord(Record::CUSTOMER_TYPE, $lastId, '新增客户:' . $params['name']);
+        return $lastId;
+    }
 
 
-	/**
-	 *修改客户信息
-	 */
-	public static function updateCustomer($params) {
+    /**
+     *修改客户信息
+     */
+    public static function updateCustomer($params)
+    {
         $operator = $params;
-		//自定义字段
-		$other = [];
-		foreach ($params as $name => $val) {
-			if (strstr($name,'other_') !== false) {
-                if(is_array($val)){
-                    $other[$name] = implode(',',$val);
-                }else{
+        //自定义字段
+        $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;
+                unset($params[$name]);
+            } else {
+                if ($params[$name] === '') {
+                    $params[$name] = NULL;
                 }
             }
-		}
+        }
         //操作记录处理
         $form = Form::where(['type' => 'customer'])->find();
-        $formdata = json_decode($form['data'],true)['data'];
+        $formdata = json_decode($form['data'], true)['data'];
         $forminfo = [
-            'address'=>'地址定位',
-            'address_detail'=>'详细地址',
-            'country'=>'国家',
-            'level'=>'客户星级',
-            'management_id'=>'客户所属区域',
-            'contract_status'=>'客户成交状态',
-            'parent_id'=>'上级公司'
+            'address' => '地址定位',
+            'address_detail' => '详细地址',
+            'country' => '国家',
+            'level' => '客户星级',
+            'management_id' => '客户所属区域',
+            'contract_status' => '客户成交状态',
+            'parent_id' => '上级公司'
         ];
-        foreach($formdata as $k=>$v){
+        foreach ($formdata as $k => $v) {
             $forminfo[$v['id']] = $v['config']['label'];
         }
-        $customerInfo=self::get($params['id'])->toArray();
+        $customerInfo = self::get($params['id'])->toArray();
         $customerOther = CustomerOther::get($params['id'])->toArray();
-        if($customerOther){
-            $customerOther = json_decode($customerOther['otherdata'],true);
+        if ($customerOther) {
+            $customerOther = json_decode($customerOther['otherdata'], true);
         }
 
-        $customerInfo = array_merge($customerInfo,$customerOther);
+        $customerInfo = array_merge($customerInfo, $customerOther);
         $customer = new self;
-        $operation='修改客户信息:将';
-        foreach ($operator as $name=>$val){
-            if(isset($customerInfo[$name]) && (is_string($customerInfo[$name]) || is_int($customerInfo[$name])) && $customerInfo[$name] != $val){
-                $nameinfo = isset($forminfo[$name])?$forminfo[$name]:$name;
-                if($nameinfo =='客户成交状态'){
-                    if($customerInfo[$name] == 1){
-                        $customerInfo[$name] ='已成交';
-                    }else{
-                        $customerInfo[$name] ='未成交';
+        $operation = '修改客户信息:将';
+        foreach ($operator as $name => $val) {
+            if (isset($customerInfo[$name]) && (is_string($customerInfo[$name]) || is_int($customerInfo[$name])) && $customerInfo[$name] != $val) {
+                $nameinfo = isset($forminfo[$name]) ? $forminfo[$name] : $name;
+                if ($nameinfo == '客户成交状态') {
+                    if ($customerInfo[$name] == 1) {
+                        $customerInfo[$name] = '已成交';
+                    } else {
+                        $customerInfo[$name] = '未成交';
                     }
-                    if($val == 1){
-                        $val ='已成交';
-                    }else{
-                        $val ='未成交';
+                    if ($val == 1) {
+                        $val = '已成交';
+                    } else {
+                        $val = '未成交';
                     }
                 }
-                if($nameinfo =='上级公司'){
-                    $customerInfo[$name] = $customer->where(array('id'=>$customerInfo[$name]))->value('name');
-                    $val = $customer->where(array('id'=>$val))->value('name');
+                if ($nameinfo == '上级公司') {
+                    $customerInfo[$name] = $customer->where(array('id' => $customerInfo[$name]))->value('name');
+                    $val = $customer->where(array('id' => $val))->value('name');
                 }
-                if($nameinfo =='客户所属区域'){
-                    $customerInfo[$name] = AreaManagement::where(array('id'=>$customerInfo[$name]))->value('name');
-                    $val =AreaManagement::where(array('id'=>$val))->value('name');
+                if ($nameinfo == '客户所属区域') {
+                    $customerInfo[$name] = AreaManagement::where(array('id' => $customerInfo[$name]))->value('name');
+                    $val = AreaManagement::where(array('id' => $val))->value('name');
                 }
-                $operation.="[{$nameinfo}]【{$customerInfo[$name]}】修改为【{$val}】;";
+                $operation .= "[{$nameinfo}]【{$customerInfo[$name]}】修改为【{$val}】;";
             }
         }
-        if($operation !='修改客户信息:将'){
+        if ($operation != '修改客户信息:将') {
             OperationLog::createLog(OperationLog::CUSTOMER_TYPE, $params['id'], $operation);
         }
 
-		// 调用当前模型对应的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)]);
+        // 调用当前模型对应的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());
-		}
-		return true;
-	}
+        if ($resInfo === false) {
+            // 验证失败 输出错误信息
+            throw new Exception($otherModel->getError());
+        }
+        return true;
+    }
 
     /**
      * 导入客户
      * @param $data
      * @return bool
      */
-	public static function importCustomer($data) {
-		$addCustomers = [];
-		$addOther     = [];
+    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{
+        $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;
+                    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);
+            }
+            $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);
+        $logModel = new OperationLog();
+        $logModel->allowField(true)->insertAll($addLog);
+
+        //创建账号
+        $data = [
+            'customer_id' => $params['id'],
+            'nickname' => $params['name'],
+            'password' => 'a123456',
+            'email' => '',
+            'account' => $params['mobile']];
+        $data['salt'] = Random::alnum();
+        $data['password'] = md5(md5($data['password']) . $data['salt']);
+        $person = new \addons\qingdongams\model\Person();
+        $person->allowField(true)->save($data);
 
-		return true;
-	}
+        return true;
+    }
 
-	/**
-	 *移入公海
-	 */
-	public static function moveSeas($id) {
+    /**
+     *移入公海
+     */
+    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;
+        $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]) {
+                } 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 ($intersect) {
+                        $is_rule = 1;
                     }
                 }
 
@@ -352,129 +383,132 @@ class Customer Extends Model {
             }
 
         }
-        if(empty($seasIds)){
-            $seasIds[]=1;//默认公海
+        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(),'is_seas'=>1]) == false) {
+                'seas_id' => $seas_id, 'sea_time' => time(), 'is_seas' => 1]) == false) {
             throw new Exception('修改失败');
         }
 
         //回收记录
-        SeaOperation::where([])->insert(array('customer_id'=>$id,'type'=>1,'owner_staff_id' => $row['owner_staff_id'],'createtime'=>time(),'updatetime'=>time()));
-		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(),'is_seas'=>0]) == 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('修改失败');
-				}
-			}
+        SeaOperation::where([])->insert(array('customer_id' => $id, 'type' => 1, 'owner_staff_id' => $row['owner_staff_id'], 'createtime' => time(), 'updatetime' => time()));
+        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(), 'is_seas' => 0]) == 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('修改失败');
+                }
+            }
             //领取记录
-            SeaOperation::where([])->insert(array('customer_id'=>$customer['id'],'type'=>0,'owner_staff_id'=>$staff->id,'createtime'=>time(),'updatetime'=>time()));
-			OperationLog::createLog(OperationLog::CUSTOMER_TYPE, $customer['id'], '领取了客户');
+            SeaOperation::where([])->insert(array('customer_id' => $customer['id'], 'type' => 0, 'owner_staff_id' => $staff->id, 'createtime' => time(), 'updatetime' => time()));
+            OperationLog::createLog(OperationLog::CUSTOMER_TYPE, $customer['id'], '领取了客户');
 
-			Db::commit();
-		} catch (Exception $e) {
-			Db::rollback();
-			throw new Exception($e->getMessage());
-		}
+            Db::commit();
+        } catch (Exception $e) {
+            Db::rollback();
+            throw new Exception($e->getMessage());
+        }
 
-		return $customer['id'];
-	}
+        return $customer['id'];
+    }
 
     public static function changeCustomerType($customer_id, $type, $remark)
     {

+ 6 - 2
application/admin/controller/qingdongams/Dashboard.php

@@ -89,7 +89,9 @@ class Dashboard extends Base
         if ($allwork > 0 && $allworklv > 0) {
             $allxunjianlv = $allworklv / $allwork * 100;
         }
-        $this->view->assign('allxunjianlv', number_format($allxunjianlv, 2));
+
+        $format_allxunjianlv = number_format($allxunjianlv ?? 0, 2);
+        $this->view->assign('allxunjianlv', $format_allxunjianlv ?? 0);
 
         // 获取今年的开始时间和结束时间
         $startOfYear = strtotime(date('Y-01-01 00:00:00'));
@@ -111,7 +113,9 @@ class Dashboard extends Base
         if ($allworkn > 0 && $wallworklvn > 0) {
             $wallxunjianlvn = $wallworklvn / $allworkn * 100;
         }
-        $this->view->assign('wallxunjianlvn', number_format($wallxunjianlvn, 2));
+
+        $format_wallxunjianlvn = number_format($wallxunjianlvn ?? 0, 2);
+        $this->view->assign('wallxunjianlvn', $format_wallxunjianlvn);
 
         $this->view->assign('xunjianlv', number_format($xunjianlv, 2));
         $this->view->assign('weixiulv', number_format($weixiulv, 2));

+ 76 - 73
application/admin/controller/qingdongams/customer/Customer.php

@@ -189,8 +189,8 @@ class Customer extends Base
                 if ($result !== true) {
                     $this->error($result);
                 }
-                $user=$this->Person->where(array('account'=>$params['mobile']))->find();
-                if($user){
+                $user = $this->Person->where(array('account' => $params['mobile']))->find();
+                if ($user) {
                     $this->error("手机号已存在,请更换手机号");
                 }
                 $result = false;
@@ -199,21 +199,21 @@ class Customer extends Base
                     $params = Form::updateFormParams(Form::CUSTOMER_TYPE, $params);
                     $customerId = $this->model::createCustomer($params);
 
-                    if(isset($params['mobile']) && $params['mobile']){
+                    if (isset($params['mobile']) && $params['mobile']) {
                         $retC = array(
-                            'customer_id'=>$customerId,
-                            'is_major'=>1,
-                            'region'=>1,
-                            'name'=>$params['name'],
-                            'mobile'=>$params['mobile'],
-                            'next_time'=>date('Y-m-d H:i:s'),
+                            'customer_id' => $customerId,
+                            'is_major' => 1,
+                            'region' => 1,
+                            'name' => $params['name'],
+                            'mobile' => $params['mobile'],
+                            'next_time' => date('Y-m-d H:i:s'),
                         );
                         Contacts::createContacts($retC);
                     }
 
                     //创建账号
                     $data = [
-                        'customer_id'=>$customerId,
+                        'customer_id' => $customerId,
                         'nickname' => $params['name'],
                         'password' => $params['password'],
                         'email' => '',
@@ -275,7 +275,7 @@ class Customer extends Base
                     $this->error($result);
                 }
 
-                $result = FormField::checkFields(FormField::CUSTOMER_TYPE, $params,$ids);
+                $result = FormField::checkFields(FormField::CUSTOMER_TYPE, $params, $ids);
 
                 if ($result !== true) {
                     $this->error($result);
@@ -286,19 +286,19 @@ class Customer extends Base
                     $params = Form::updateFormParams(Form::CUSTOMER_TYPE, $params);
 
                     $params['id'] = $ids;
-                    if(isset($params['password']) && $params['password']){
+                    if (isset($params['password']) && $params['password']) {
                         $data['salt'] = Random::alnum();
                         $data['password'] = md5(md5($params['password']) . $data['salt']);
-                        $this->Person->where(array('customer_id'=>$ids))->update($data);
+                        $this->Person->where(array('customer_id' => $ids))->update($data);
 
                     }
                     unset($params['password']);
                     $result = $this->model::updateCustomer($params);
-                    if(isset($params['mobile']) && $params['mobile']){
-                        Contacts::where(array('customer_id'=>$ids,'is_major'=>1))->update(array('mobile'=>$params['mobile'],'updatetime'=>time()));
+                    if (isset($params['mobile']) && $params['mobile']) {
+                        Contacts::where(array('customer_id' => $ids, 'is_major' => 1))->update(array('mobile' => $params['mobile'], 'updatetime' => time()));
                     }
 
-                  
+
                     Db::commit();
                 } catch (Exception $e) {
                     Db::rollback();
@@ -312,7 +312,7 @@ class Customer extends Base
             }
             $this->error(__('Parameter %s can not be empty', ''));
         }
-        $row=$row->toArray();
+        $row = $row->toArray();
         $other = CustomerOther::getOther($row);
         $row = array_merge($row, $other);
         $form = Form::getDataValue(Form::CUSTOMER_TYPE, $row);
@@ -486,7 +486,6 @@ class Customer extends Base
     }
 
 
-
     /**
      * 获取相关联系人
      * @param null $ids
@@ -561,7 +560,7 @@ class Customer extends Base
         list($where, $sort, $order, $offset, $limit) = $this->buildparams();
         $list = Consume::where([
             'customer_id' => $ids,
-        ])->with(['follow_staff','staff'])->order('id desc')->paginate($limit);
+        ])->with(['follow_staff', 'staff'])->order('id desc')->paginate($limit);
         $result = array("total" => $list->total(), "rows" => $list->items());
 
         return json($result);
@@ -1070,7 +1069,7 @@ class Customer extends Base
 
             $file = $this->request->request('file');
             $staff_id = $this->request->request('staff_id', 0);
-            $seas_type_id = input('seas_type_id',0);
+            $seas_type_id = input('seas_type_id', 0);
             if (!$file) {
                 $this->error(__('Parameter %s can not be empty', 'file'));
             }
@@ -1142,11 +1141,11 @@ class Customer extends Base
             $formrow = [];
             $names = $this->model->where([])->column('name');
             $fieldnames = FormField::where(['types' => FormField::CUSTOMER_TYPE])->column('field', 'name');
-            if(!$fieldnames){
+            if (!$fieldnames) {
                 $this->error('请在系统管理->字段管理中保存客户管理表单生成客户导入字段');
             }
             $forms = Form::getDataValue(Form::CUSTOMER_TYPE);
-            foreach($forms as $k=>$v){
+            foreach ($forms as $k => $v) {
                 $formrow[$v['id']] = $v['name'];
             }
             $fn = [];
@@ -1180,15 +1179,15 @@ class Customer extends Base
                     $addCustomers[$fn[$kv]] = $value;
                 }
                 //日期格式处理
-                foreach($formrow as $k=>$v){
-                    if($v=='日期选择框'){
-                        if(isset($addCustomers[$k]) && $addCustomers[$k]){
-                            $addCustomers[$k] =date("Y-m-d", ($addCustomers[$k] - 25569) * 24 * 3600);
+                foreach ($formrow as $k => $v) {
+                    if ($v == '日期选择框') {
+                        if (isset($addCustomers[$k]) && $addCustomers[$k]) {
+                            $addCustomers[$k] = date("Y-m-d", ($addCustomers[$k] - 25569) * 24 * 3600);
                         }
                     }
-                    if($v=='时间选择框'){
-                        if(isset($addCustomers[$k]) && $addCustomers[$k]){
-                            $addCustomers[$k] =date("Y-m-d H:i:s", ($addCustomers[$k] - 25569) * 24 * 3600);
+                    if ($v == '时间选择框') {
+                        if (isset($addCustomers[$k]) && $addCustomers[$k]) {
+                            $addCustomers[$k] = date("Y-m-d H:i:s", ($addCustomers[$k] - 25569) * 24 * 3600);
                         }
                     }
                 }
@@ -1200,9 +1199,9 @@ class Customer extends Base
                     $errorInfo[] = "第{$currentRow}行,客户名称`{$addCustomers['name']}`已存在;";
                     continue;
                 }
-                $addCustomers['seas_id']=",{$seas_type_id},";
-                if($staff_id == 0){
-                    $addCustomers['is_seas'] =1;
+                $addCustomers['seas_id'] = ",{$seas_type_id},";
+                if ($staff_id == 0) {
+                    $addCustomers['is_seas'] = 1;
                 }
                 $customerRow[] = $addCustomers;
             }
@@ -1221,7 +1220,7 @@ class Customer extends Base
         }
 
         $this->assign('seas_type', Seastype::where([])->field('id,name')->select());
-        $this->assign('staffs', Staff::getList());
+        $this->assign('staffs', Staff::getList([1, 15]));
         return $this->view->fetch();
     }
 
@@ -1345,7 +1344,7 @@ class Customer extends Base
         }
         $owner_staff_id = $wheres['owner_staff_id'];
         unset($wheres['owner_staff_id']);
-        $list = $this->model->where($where)->with(['ownerStaff','customerOther'])
+        $list = $this->model->where($where)->with(['ownerStaff', 'customerOther'])
             ->where($wheres)
             ->where(function ($query) use ($staff_id, $owner_staff_id, $type) {
                 if ($type == 0) {//全部
@@ -1375,11 +1374,11 @@ class Customer extends Base
         foreach ($dataValue as $val) {
             $title[] = $val['config']['label'];
         }
-        $data=[];
+        $data = [];
         foreach ($list as $k => $v) {
-            if($v['customer_other']){//其他客户
-                $other=$v['customer_other']['otherdata'];
-                $other=json_decode($other,true);
+            if ($v['customer_other']) {//其他客户
+                $other = $v['customer_other']['otherdata'];
+                $other = json_decode($other, true);
                 $v = array_merge($v, $other);
             }
             $field = array(
@@ -1413,19 +1412,19 @@ class Customer extends Base
     {
         if ($this->request->isPost()) {
             $file = input('file', '');
-            $is_template=input('is_template',0);
-            $template_name=input('template_name','');
+            $is_template = input('is_template', 0);
+            $template_name = input('template_name', '');
             if (empty($file)) {
                 $this->error('导出模板');
             }
-            if($is_template == 1){
-                if(empty($template_name)){
+            if ($is_template == 1) {
+                if (empty($template_name)) {
                     $this->error('模板名称不能为空');
                 }
-                $create=[
-                    'type'=>'customer',
-                    'name'=>$template_name,
-                    'url'=>$file
+                $create = [
+                    'type' => 'customer',
+                    'name' => $template_name,
+                    'url' => $file
                 ];
                 $wordTemplateModel = new WordTemplate();
                 $wordTemplateModel->save($create);
@@ -1439,31 +1438,31 @@ class Customer extends Base
             $other = CustomerOther::getOther($row);
             $row = array_merge($row, $other);
             $form = Form::getDataValue(Form::CUSTOMER_TYPE);
-            $imgNames=[];
-            foreach($form as $k=>$v){
-                if($v['component'] == 'uploadImage'){
-                    $imgNames[]=$v['id'];
+            $imgNames = [];
+            foreach ($form as $k => $v) {
+                if ($v['component'] == 'uploadImage') {
+                    $imgNames[] = $v['id'];
                 }
             }
             foreach ($row as $key => $item) {
-                if(in_array($key,$imgNames) && $item ){
-                    if(is_array($item)){
-                        foreach ($item as $it){
-                            $tmp->setImageValue($key,ltrim(parse_url($it['file_path'])['path'],'/'));
+                if (in_array($key, $imgNames) && $item) {
+                    if (is_array($item)) {
+                        foreach ($item as $it) {
+                            $tmp->setImageValue($key, ltrim(parse_url($it['file_path'])['path'], '/'));
                         }
-                    }else{
-                        $fileinfo = File::where(['id'=>['in',$item]])->field('id,name,file_path,save_name')->select();
-                        foreach ($fileinfo as $it){
-                            $tmp->setImageValue($key,ltrim(parse_url($it['file_path'])['path'],'/'));
+                    } else {
+                        $fileinfo = File::where(['id' => ['in', $item]])->field('id,name,file_path,save_name')->select();
+                        foreach ($fileinfo as $it) {
+                            $tmp->setImageValue($key, ltrim(parse_url($it['file_path'])['path'], '/'));
                         }
                     }
 
-                }else{
-                    if(is_array($item)){
-                        $tmp->setValue($key , '');//
+                } else {
+                    if (is_array($item)) {
+                        $tmp->setValue($key, '');//
                         continue;
                     }
-                    $tmp->setValue($key , $item);//
+                    $tmp->setValue($key, $item);//
                 }
             }
             $contacts = Contacts::where(['customer_id' => $ids])->find();
@@ -1472,7 +1471,7 @@ class Customer extends Base
                 $contactsOther = ContactsOther::getOther($contacts);
                 $contacts = array_merge($contacts, $contactsOther);
                 foreach ($contacts as $key => $item) {
-                    if(is_array($item)){
+                    if (is_array($item)) {
                         continue;
                     }
                     if ($key == 'name') {
@@ -1483,7 +1482,7 @@ class Customer extends Base
                     }
                     $tmp->setValue($key, $item);//
                 }
-            }else{
+            } else {
                 $form = Form::getDataValue(Form::CONTACTS_TYPE);
                 foreach ($form as $f) {
                     if ($f['id'] == 'name') {
@@ -1529,7 +1528,7 @@ class Customer extends Base
                 'name' => $v['config']['label'],
             );
         }
-        $templates=WordTemplate::where(['type'=>'customer'])->select();
+        $templates = WordTemplate::where(['type' => 'customer'])->select();
         $contacts = Form::getDataValue(Form::CONTACTS_TYPE);
         $columns = array();
         foreach ($contacts as $k => $v) {
@@ -1553,24 +1552,27 @@ class Customer extends Base
         $this->assign('ids', $ids);
         return $this->view->fetch();
     }
+
     /**
      * 获取公司报价
      */
-    public function get_quote($ids = null) {
+    public function get_quote($ids = null)
+    {
         list($where, $sort, $order, $offset, $limit) = $this->buildparams();
-        $list = \addons\qingdongams\model\Quote::where(['customer_id' => $ids])->with(['product','createStaff'])->order('id desc')->paginate($limit);
+        $list = \addons\qingdongams\model\Quote::where(['customer_id' => $ids])->with(['product', 'createStaff'])->order('id desc')->paginate($limit);
 
         $result = array("total" => $list->total(), "rows" => $list->items());
 
         return json($result);
     }
 
-     /**
-      * 获取公司产品
+    /**
+     * 获取公司产品
      */
-    public function get_product($ids = null) {
+    public function get_product($ids = null)
+    {
         list($where, $sort, $order, $offset, $limit) = $this->buildparams();
-        $list = \addons\qingdongams\model\CustomerProduct::where(['customer_id' => $ids])->with(['product','contracts'])->order('id desc')->paginate($limit);
+        $list = \addons\qingdongams\model\CustomerProduct::where(['customer_id' => $ids])->with(['product', 'contracts'])->order('id desc')->paginate($limit);
 
         $result = array("total" => $list->total(), "rows" => $list->items());
 
@@ -1579,8 +1581,9 @@ class Customer extends Base
 
     /**
      * 获取客户工单
-    */
-    public function get_workorder($ids = null) {
+     */
+    public function get_workorder($ids = null)
+    {
         list($where, $sort, $order, $offset, $limit) = $this->buildparams();
         $list = \addons\qingdongams\model\Workorder::where(['customer_id' => $ids])->order('id desc')->paginate($limit);
 

+ 92 - 79
application/admin/controller/qingdongams/customer/Record.php

@@ -1,6 +1,7 @@
 <?php
 
 namespace app\admin\controller\qingdongams\customer;
+
 use addons\qingdongams\model\Field;
 use addons\qingdongams\model\File;
 use addons\qingdongams\model\Message;
@@ -18,145 +19,152 @@ use think\Exception;
 /**
  * 客户跟进记录
  */
-class Record extends Base {
-    public function _initialize() {
+class Record extends Base
+{
+    public function _initialize()
+    {
         parent::_initialize();
         $this->model = new RecordModel();
+
+        // 获取跟进类型
+        $record_type = Field::getField('跟进类型');
+        $this->assignconfig('recordType', $record_type);
     }
 
     /**
      * 客户跟进记录
      */
-    public function index() {
+    public function index()
+    {
 
-        $need = input('need','','trim');
-        $customer_id = input('customer_id','','trim');
-        $contacts_id = input('contacts_id','','trim');
-        $leads_id = input('leads_id','','trim');
-        $contract_id = input('contract_id','','trim');
-        $busniess_id = input('busniess_id','','trim');
+        $need = input('need', '', 'trim');
+        $customer_id = input('customer_id', '', 'trim');
+        $contacts_id = input('contacts_id', '', 'trim');
+        $leads_id = input('leads_id', '', 'trim');
+        $contract_id = input('contract_id', '', 'trim');
+        $busniess_id = input('busniess_id', '', 'trim');
         //0:全部 1:我负责的 2:下属负责的 3:今日待跟进 4:今日已跟进
-        $type = input('type',0);
+        $type = input('type', 0);
         $this->request->filter(['strip_tags']);
         if ($this->request->isAjax()) {
             list($where, $sort, $order, $offset, $limit) = $this->buildparams();
-            switch($type){
+            switch ($type) {
                 case 1:
                     $staff = Staff::info();
-                    $wheres['create_staff_id'] =  $staff->id;
+                    $wheres['create_staff_id'] = $staff->id;
                     break;
                 case 2:
-                    $wheres['create_staff_id'] =  array('in',Staff::getLowerStaffId());
+                    $wheres['create_staff_id'] = array('in', Staff::getLowerStaffId());
                     break;
                 case 3:
                     $start = date('Y-m-d 00:00:00');
                     $end = date('Y-m-d 23:59:59');
-                    $record = collection(RecordModel::where(array('relation_type'=>1,'next_time'=>array(array('egt',$start),array('elt',$end))))->field("id,relation_id")->select())->toArray();
+                    $record = collection(RecordModel::where(array('relation_type' => 1, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select())->toArray();
                     $relationId = [];
-                    foreach($record as $k=>$v){
-                        $whereRe['id'] = array('gt',$v['id']);
+                    foreach ($record as $k => $v) {
+                        $whereRe['id'] = array('gt', $v['id']);
                         $whereRe['relation_id'] = $v['relation_id'];
                         $recordData = RecordModel::where($whereRe)->count();
-                        if($recordData == 0){
+                        if ($recordData == 0) {
                             $relationId[] = $v['id'];
                         }
 
                     }
-                    $wheres['id'] =  array('in',$relationId);
+                    $wheres['id'] = array('in', $relationId);
                     $staff = Staff::info();
-                    $wheres['create_staff_id'] =  $staff->id;
+                    $wheres['create_staff_id'] = $staff->id;
                     break;
                 case 4:
                     $start = date('Y-m-d 00:00:00');
                     $end = date('Y-m-d 23:59:59');
-                    $record = collection(RecordModel::where(array('relation_type'=>1,'next_time'=>array(array('egt',$start),array('elt',$end))))->field("id,relation_id")->select())->toArray();
+                    $record = collection(RecordModel::where(array('relation_type' => 1, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select())->toArray();
                     $relationId = [];
-                    foreach($record as $k=>$v){
-                        $whereRe['id'] = array('gt',$v['id']);
+                    foreach ($record as $k => $v) {
+                        $whereRe['id'] = array('gt', $v['id']);
                         $whereRe['relation_id'] = $v['relation_id'];
                         $recordData = RecordModel::where($whereRe)->count();
-                        if($recordData >=1){
+                        if ($recordData >= 1) {
                             $relationId[] = $v['id'];
                         }
 
                     }
-                    $wheres['id'] =  array('in',$relationId);
+                    $wheres['id'] = array('in', $relationId);
                     $staff = Staff::info();
-                    $wheres['create_staff_id'] =  $staff->id;
+                    $wheres['create_staff_id'] = $staff->id;
                     break;
                 default:
-                    $wheres['create_staff_id'] =  array('in',Staff::getMyStaffIds());
+                    $wheres['create_staff_id'] = array('in', Staff::getMyStaffIds());
                     break;
 
             }
 
             $wheres['relation_type'] = 1;
-            $wheres['follow_type'] = ['neq','其它'];
-            if(isset($need) && $need =='customer'){
+            $wheres['follow_type'] = ['neq', '其它'];
+            if (isset($need) && $need == 'customer') {
                 $staff = Staff::info();
-                $wheres['create_staff_id'] =  $staff->id;
+                $wheres['create_staff_id'] = $staff->id;
                 $wheres['status'] = 0;
-                $wheres['next_time'] = array(array('egt',date('Y-m-d 00:00:00')),array('lt',date('Y-m-d 23:59:59')));
+                $wheres['next_time'] = array(array('egt', date('Y-m-d 00:00:00')), array('lt', date('Y-m-d 23:59:59')));
                 $customerlist = $this->model->where($wheres)->column('relation_id');
-                if($customerlist){
-                    $whereExit['relation_id'] = array('in',$customerlist);
-                    $whereExit['next_time'] = array('gt',date('Y-m-d 23:59:59'));
+                if ($customerlist) {
+                    $whereExit['relation_id'] = array('in', $customerlist);
+                    $whereExit['next_time'] = array('gt', date('Y-m-d 23:59:59'));
                     $recordIds = $this->model->where($whereExit)->column('id');
-                    if($recordIds){
-                        $wheres['id'] = array('in',$recordIds);
+                    if ($recordIds) {
+                        $wheres['id'] = array('in', $recordIds);
                     }
                 }
             }
-            if(isset($need) && $need =='contacts'){
+            if (isset($need) && $need == 'contacts') {
                 $staff = Staff::info();
-                $wheres['create_staff_id'] =  $staff->id;
+                $wheres['create_staff_id'] = $staff->id;
                 $wheres['status'] = 0;
                 $wheres['relation_type'] = 2;
-                $wheres['next_time'] = array(array('egt',date('Y-m-d 00:00:00')),array('lt',date('Y-m-d 23:59:59')));
+                $wheres['next_time'] = array(array('egt', date('Y-m-d 00:00:00')), array('lt', date('Y-m-d 23:59:59')));
                 $customerlist = $this->model->where($wheres)->column('relation_id');
-                if($customerlist){
-                    $whereExit['relation_id'] = array('in',$customerlist);
-                    $whereExit['next_time'] = array('gt',date('Y-m-d 23:59:59'));
+                if ($customerlist) {
+                    $whereExit['relation_id'] = array('in', $customerlist);
+                    $whereExit['next_time'] = array('gt', date('Y-m-d 23:59:59'));
                     $recordIds = $this->model->where($whereExit)->column('id');
-                    if($recordIds){
-                        $wheres['id'] = array('in',$recordIds);
+                    if ($recordIds) {
+                        $wheres['id'] = array('in', $recordIds);
                     }
                 }
             }
-            if(isset($customer_id) && $customer_id){
+            if (isset($customer_id) && $customer_id) {
                 $wheres['relation_type'] = 1;
                 $wheres['relation_id'] = $customer_id;
                 unset($wheres['create_staff_id']);
             }
-            if(isset($contacts_id) && $contacts_id){
+            if (isset($contacts_id) && $contacts_id) {
                 $wheres['relation_type'] = 2;
                 $wheres['relation_id'] = $contacts_id;
                 unset($wheres['create_staff_id']);
             }
-            if(isset($leads_id) && $leads_id){
+            if (isset($leads_id) && $leads_id) {
                 $wheres['relation_type'] = 4;
                 $wheres['relation_id'] = $leads_id;
                 unset($wheres['create_staff_id']);
 
             }
-            if(isset($contract_id) && $contract_id){
+            if (isset($contract_id) && $contract_id) {
                 $wheres['relation_type'] = 3;
                 $wheres['relation_id'] = $contract_id;
                 unset($wheres['create_staff_id']);
             }
-            if(isset($busniess_id) && $busniess_id){
+            if (isset($busniess_id) && $busniess_id) {
                 $wheres['relation_type'] = 5;
                 $wheres['relation_id'] = $busniess_id;
                 unset($wheres['create_staff_id']);
             }
 
-            $list   = $this->model->where($where)->where($wheres)->with(['staff','customer'])->order($sort, $order)->paginate($limit);
-            foreach($list as $k=>$v){
-                if(!isset($v['customer']) || !$v['customer']){
-                    $v['customer'] = array('id'=>'','name'=>'');
+            $list = $this->model->where($where)->where($wheres)->with(['staff', 'customer'])->order($sort, $order)->paginate($limit);
+            foreach ($list as $k => $v) {
+                if (!isset($v['customer']) || !$v['customer']) {
+                    $v['customer'] = array('id' => '', 'name' => '');
                 }
             }
-            $row    = $list->items();
+            $row = $list->items();
             $result = array("total" => $list->total(), "rows" => $row);
 
             return json($result);
@@ -176,8 +184,9 @@ class Record extends Base {
     /**
      * 添加跟进
      */
-    public function add($ids = null) {
-        $relation_type=input('relation_type',1);
+    public function add($ids = null)
+    {
+        $relation_type = input('relation_type', 1);
         if ($this->request->isPost()) {
             $params = $this->request->post('row/a');
             // 表单验证
@@ -185,13 +194,13 @@ class Record extends Base {
                 $this->error($result);
             }
 
-            if(!empty($params['files'])){
-                $params['files']=File::getId($params['files']);
+            if (!empty($params['files'])) {
+                $params['files'] = File::getId($params['files']);
             }
             $reminds_id = $this->request->post('reminds_id/a');
-            $params['reminds_id']='';
-            if($reminds_id){
-                $params['reminds_id'] = implode(',',$reminds_id);
+            $params['reminds_id'] = '';
+            if ($reminds_id) {
+                $params['reminds_id'] = implode(',', $reminds_id);
             }
 
             Db::startTrans();
@@ -208,42 +217,44 @@ class Record extends Base {
             $this->error('创建失败');
         }
 
-        $follow= Field::getField('客户状态');
-        $customer=Customer::getList();
+        $follow = Field::getField('客户状态');
+        $customer = Customer::getList();
         $customers = [];
-        foreach($customer as $k=>$v){
+        foreach ($customer as $k => $v) {
             $customers[$v['id']] = $v['name'];
         }
-        if($relation_type == 2){
-            $contacts=Contacts::where(['id'=>$ids])->column('id,name');
-            $this->assign('contacts',$contacts);
+        if ($relation_type == 2) {
+            $contacts = Contacts::where(['id' => $ids])->column('id,name');
+            $this->assign('contacts', $contacts);
         }
 
-        $remind=Remind::where(['type'=>Remind::RECORD_TYPE])->find();
-        $staff_ids=$remind['staff_ids']??'';
+        $remind = Remind::where(['type' => Remind::RECORD_TYPE])->find();
+        $staff_ids = $remind['staff_ids'] ?? '';
         $this->assign('staff_ids', $staff_ids);
         $this->assign('ids', $ids);
         $this->assign('relation_type', $relation_type);
         $this->assign('customer', $customers);
         $this->assign('follow', $follow);
-        $this->assign('staff', Staff::where([])->column('name','id'));
+        $this->assign('staff', Staff::where([])->column('name', 'id'));
         return $this->view->fetch();
     }
+
     /**
      * 跟进详情
      */
-    public function detail($ids = null) {
-        $row = $this->model->with(['staff','file'])->where([
+    public function detail($ids = null)
+    {
+        $row = $this->model->with(['staff', 'file'])->where([
             'id' => $ids,
         ])->find();
         if (empty($row)) {
             $this->error(__('No Results were found'));
         }
         $row = $row->toArray();
-        if($row['staff_id']){
-            $createname = Staff::where(['id'=>$row['staff_id']])->value('name');
-        }else{
-            $createname = isset($row['staff']['name']) ?  $row['staff']['name'] : '';
+        if ($row['staff_id']) {
+            $createname = Staff::where(['id' => $row['staff_id']])->value('name');
+        } else {
+            $createname = isset($row['staff']['name']) ? $row['staff']['name'] : '';
         }
         //标记通知已读
         Message::setRead(Message::RECORD_TYPE, $ids, $this->_staff->id);
@@ -254,17 +265,19 @@ class Record extends Base {
         $this->assignconfig("idinfo", ['id' => $ids]);
         return $this->view->fetch();
     }
+
     /**
      * 评论
      */
-    public function comment() {
+    public function comment()
+    {
         $this->request->filter(['strip_tags']);
         if ($this->request->isAjax()) {
-            $record_id = input('record_id','');
+            $record_id = input('record_id', '');
             $wheres['relation_id'] = $record_id;
             list($where, $sort, $order, $offset, $limit) = $this->buildparams();
-            $list   = Comment::where($where)->where($wheres)->with(['staff','record'])->order($sort, $order)->paginate($limit);
-            $row    = $list->items();
+            $list = Comment::where($where)->where($wheres)->with(['staff', 'record'])->order($sort, $order)->paginate($limit);
+            $row = $list->items();
             $result = array("total" => $list->total(), "rows" => $row);
 
             return json($result);

+ 2 - 2
application/admin/controller/qingdongams/department/Staff.php

@@ -118,7 +118,7 @@ class Staff extends  Base {
             $this->success('提交成功');
         }
 
-        $staffname = StaffModel::column('id,name');
+        $staffname = StaffModel::where(['id' => ['neq', 1]])->column('id,name');
         $staffs    = ['' => '请选择'];
         foreach ($staffname as $id => $name) {
             $staffs[$id] = $name;
@@ -204,7 +204,7 @@ class Staff extends  Base {
         $data = StaffModel::where($map)->find();
         $this->view->assign("row", $data);
 
-        $staffname = StaffModel::where([])->column('id,name');
+        $staffname = StaffModel::where(['id' => ['neq', 1]])->column('id,name');
         $staffs    = ['' => '请选择'];
         foreach ($staffname as $id => $name) {
             $staffs[$id] = $name;

+ 2 - 2
application/admin/view/qingdongams/customer/contacts/index.html

@@ -22,8 +22,8 @@
                         <a class="btn btn-warning btn-change btn-imports {:$auth->check('qingdongams/customer/contacts/import')?'':'hide'}"  data-params="action=start"  href="javascript:;"><i class="fa fa-upload dz-message"></i> 导入</a>
                         <a class="btn btn-success btn-export {:$auth->check('qingdongams/customer/contacts/export')?'':'hide'}" data-multiple="false"  href="javascript:;"><i class="fa fa-download dz-message"></i> 导出</a>
 
-                        <a class="btn btn-danger btn-send-email" data-url="qingdongams/general/email/batch_send_email" data-types="contacts" data-title="批量发送邮件" ><i class="fa fa-envelope-square"></i> 批量发送邮件</a>
-                        <a class="btn btn-info  btn-send-sms" data-url="qingdongams/general/sms/batch_send_sms" data-types="contacts" data-title="批量发送短信" ><i class="fa fa-telegram"></i> 批量发送短信</a>
+<!--                        <a class="btn btn-danger btn-send-email" data-url="qingdongams/general/email/batch_send_email" data-types="contacts" data-title="批量发送邮件" ><i class="fa fa-envelope-square"></i> 批量发送邮件</a>-->
+<!--                        <a class="btn btn-info  btn-send-sms" data-url="qingdongams/general/sms/batch_send_sms" data-types="contacts" data-title="批量发送短信" ><i class="fa fa-telegram"></i> 批量发送短信</a>-->
 
                     </div>
                     <table id="table" class="table table-striped table-bordered table-hover table-nowrap"

+ 28 - 26
application/admin/view/qingdongams/customer/customer/add.html

@@ -1,40 +1,42 @@
 <style>
-	label{
-		font-weight:unset !important;
-	}
+    label {
+        font-weight: unset !important;
+    }
 </style>
 <form id="edit-form" class="form-horizontal col-sm-12" role="form" data-toggle="validator" method="POST" action="">
-	{:token()}
+    {:token()}
 
 
-	<div class="form-group">
+    <div class="form-group">
 
-		{include file="qingdongams/common/form_add" /}
+        {include file="qingdongams/common/form_add" /}
 
-		<div class="col-xs-12 col-sm-12">
-			<div class="form-group col-sm-10">
-				<label >设置登录密码:</label>
+        <div class="col-xs-12 col-sm-12">
+            <div class="form-group col-sm-10">
+                <label><span style="color:red;">*</span>设置登录密码:</label>
 
-				<input type="password" data-rule="required" name="row[password]" class="form-control" size="10" placeholder="设置登录密码">
+                <input type="password" data-rule="required" name="row[password]" class="form-control" size="10"
+                       placeholder="设置登录密码">
 
-			</div>
-		</div>
+            </div>
+        </div>
 
-		<div class="col-xs-12 col-sm-12">
-			<div class="form-group col-sm-10">
-				<label >提醒谁看:</label>
+        <div class="col-xs-12 col-sm-12">
+            <div class="form-group col-sm-10">
+                <label>提醒谁看:</label>
 
-				{:build_select('row[reminds_id]', $staff, $staff_ids, ['class'=>'form-control selectpicker', 'multiple'=>'', 'data-rule'=>'', 'data-live-search'=>'true'])}
-			</div>
-		</div>
-	</div>
+                {:build_select('row[reminds_id]', $staff, $staff_ids, ['class'=>'form-control selectpicker',
+                'multiple'=>'', 'data-rule'=>'', 'data-live-search'=>'true'])}
+            </div>
+        </div>
+    </div>
 
 
-	<div class="form-group layer-footer">
-		<label class="control-label col-xs-12 col-sm-2"></label>
-		<div class="col-xs-12 col-sm-8">
-			<button type="submit" class="btn btn-success btn-embossed disabled">{:__('OK')}</button>
-			<button type="reset" class="btn btn-default btn-embossed">{:__('Reset')}</button>
-		</div>
-	</div>
+    <div class="form-group layer-footer">
+        <label class="control-label col-xs-12 col-sm-2"></label>
+        <div class="col-xs-12 col-sm-8">
+            <button type="submit" class="btn btn-success btn-embossed disabled">{:__('OK')}</button>
+            <button type="reset" class="btn btn-default btn-embossed">{:__('Reset')}</button>
+        </div>
+    </div>
 </form>

+ 29 - 25
application/admin/view/qingdongams/customer/customer/import.html

@@ -1,41 +1,45 @@
-
 <form id="add-form" class="form-horizontal form-ajax" role="form" data-toggle="validator" method="POST" action="">
-	<div class="form-group" >
-		<label class="control-label col-xs-3 col-sm-3">归属人:</label>
-		<div class="col-xs-8 col-sm-8">
-			<select name="staff_id" class="form-control selectpicker" 	data-live-search="true">
-				<option value="0">公海客户</option>
-				{foreach name="staffs" item="val"}
-					<option value="{$val.id}">{$val.name}</option>
-				{/foreach}
-			</select>
-		</div>
-	</div>
-<!--    <div class="form-group" id="seas_type">-->
-<!--        <label class="control-label col-xs-3 col-sm-3">放入公海池:</label>-->
-<!--        <div class="col-xs-8 col-sm-8">-->
-<!--            <select name="seas_type_id" class="form-control" >-->
-<!--                {foreach name="seas_type" item="val"}-->
-<!--                <option value="{$val.id}">{$val.name}</option>-->
-<!--                {/foreach}-->
-<!--            </select>-->
-<!--        </div>-->
-<!--    </div>-->
+    <div class="form-group">
+        <label class="control-label col-xs-3 col-sm-3">归属人:</label>
+        <div class="col-xs-8 col-sm-8">
+            <select name="staff_id" class="form-control selectpicker" data-live-search="true">
+                <option value="">请选择</option>
+                {foreach name="staffs" item="val"}
+                <option value="{$val.id}">{$val.name}</option>
+                {/foreach}
+            </select>
+        </div>
+    </div>
+    <!--    <div class="form-group" id="seas_type">-->
+    <!--        <label class="control-label col-xs-3 col-sm-3">放入公海池:</label>-->
+    <!--        <div class="col-xs-8 col-sm-8">-->
+    <!--            <select name="seas_type_id" class="form-control" >-->
+    <!--                {foreach name="seas_type" item="val"}-->
+    <!--                <option value="{$val.id}">{$val.name}</option>-->
+    <!--                {/foreach}-->
+    <!--            </select>-->
+    <!--        </div>-->
+    <!--    </div>-->
     <div class="form-group" style="margin-top:20px;margin-bottom:20px;">
         <label class="control-label col-xs-3 col-sm-3">文件上传:</label>
         <div class="col-xs-8 col-sm-8">
             <div class="input-group">
                 <input type="text" name="file" id="file" class="form-control" value=""/>
                 <div class="input-group-addon no-border no-padding">
-                    <span><button type="button" id="plupload-local" class="btn btn-primary faupload" data-input-id="file" data-mimetype="xlsx,xls" data-multiple="false" data-url="{:url('ajax/upload')}"><i class="fa fa-upload"></i>&nbsp;&nbsp;选择文件</button></span>
+                    <span><button type="button" id="plupload-local" class="btn btn-primary faupload"
+                                  data-input-id="file" data-mimetype="csv,xls,xlsx" data-multiple="false"
+                                  data-url="{:url('ajax/upload')}"><i
+                            class="fa fa-upload"></i>&nbsp;&nbsp;选择文件</button></span>
                 </div>
             </div>
         </div>
     </div>
     <div class="form-group">
-        <label  class="control-label col-xs-3 col-sm-3">模板下载:</label>
+        <label class="control-label col-xs-3 col-sm-3">模板下载:</label>
         <div class="col-xs-8 col-sm-8">
-            <a href="{:url('/qingdongams/customer/customer/template')}" download="导入客户模板.xls"><button type="button"  class="btn btn-danger" ><i class="fa fa-upload"></i> 模板下载</button></a>
+            <a href="{:url('/qingdongams/customer/customer/template')}" download="导入客户模板.xls">
+                <button type="button" class="btn btn-danger"><i class="fa fa-upload"></i> 模板下载</button>
+            </a>
         </div>
     </div>
     <div class="form-group  layer-footer">

+ 13 - 13
application/admin/view/qingdongams/department/role/rule.html

@@ -45,19 +45,19 @@
             </div>
         </div>
     </div>
-    <div class="form-group">
-        <div class="col-sm-12">
-            <blockquote style="padding: 2px 10px;text-align: left">
-                <p>模块功能
-                    <span style="padding:5px;"></span>
-                    <a href="javascript:;" id="seas" data-toggle="popover" data-placement="right" data-trigger="hover" data-content="公海权限:设置不同员工可查看公海客户的数据权限,勾选后员工可看到对应设置下的客户信息。<br>小程序菜单权限:设置小程序菜单功能的显示和隐藏,可指定员工操作的功能" data-original-title="" title=""><i class="fa fa-question-circle" style="font-size:16px;"></i></a>
-                </p>
-            </blockquote>
-            <div class="col-sm-11">
-                <div id="treeview" class="treeview"></div>
-            </div>
-        </div>
-    </div>
+<!--    <div class="form-group">-->
+<!--        <div class="col-sm-12">-->
+<!--            <blockquote style="padding: 2px 10px;text-align: left">-->
+<!--                <p>模块功能-->
+<!--                    <span style="padding:5px;"></span>-->
+<!--                    <a href="javascript:;" id="seas" data-toggle="popover" data-placement="right" data-trigger="hover" data-content="公海权限:设置不同员工可查看公海客户的数据权限,勾选后员工可看到对应设置下的客户信息。<br>小程序菜单权限:设置小程序菜单功能的显示和隐藏,可指定员工操作的功能" data-original-title="" title=""><i class="fa fa-question-circle" style="font-size:16px;"></i></a>-->
+<!--                </p>-->
+<!--            </blockquote>-->
+<!--            <div class="col-sm-11">-->
+<!--                <div id="treeview" class="treeview"></div>-->
+<!--            </div>-->
+<!--        </div>-->
+<!--    </div>-->
 
     <div class="form-group layer-footer">
         <label class="control-label col-xs-12 col-sm-2"></label>

+ 1 - 1
application/admin/view/qingdongams/department/staff/add.html

@@ -42,7 +42,7 @@
     <div class="form-group">
 		<label class="control-label col-xs-12 col-sm-2">直属上级:</label>
 		<div class="col-xs-12 col-sm-8">
-			{:build_select('row[parent_id]', $staffs,null, ['class'=>'form-control selectpicker', 'data-live-search'=>'true'])}
+			{:build_select('row[parent_id]', $staffs, null, ['class'=>'form-control selectpicker', 'data-live-search'=>'true'])}
 		</div>
     </div>
     <div class="form-group">

+ 1 - 1
application/extra/upload.php

@@ -21,7 +21,7 @@ return [
     /**
      * 可上传的文件类型
      */
-    'mimetype'  => 'jpg,png,bmp,jpeg,gif,webp,zip,rar,wav,mp4,mp3,webm,doc,docx,excel,pdf,ppt',
+    'mimetype'  => 'jpg,png,bmp,jpeg,gif,webp,zip,rar,wav,mp4,mp3,webm,doc,docx,excel,pdf,ppt,csv,xls,xlsx',
     /**
      * 是否支持批量上传
      */

+ 1 - 1
public/assets/js/backend/qingdongams/customer/contacts.js

@@ -276,7 +276,7 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefin
 					{checkbox : true},
 
 					{
-						field : 'name', title : '姓名', fixedColumns : true, formatter : function (value, row, index) {
+						field : 'name', title : '姓名', operate: 'like',fixedColumns : true, formatter : function (value, row, index) {
 							if(value ==''){
 								value = '无';
 							}

+ 1 - 1
public/assets/js/backend/qingdongams/customer/record.js

@@ -58,7 +58,7 @@ define(['jquery', 'bootstrap', 'backend', 'form', 'table'], function ($, undefin
 
                                 },operate:false
                             },
-                            {field: 'follow_type', title: __('跟进类型'), },
+                            {field: 'follow_type', title: __('跟进类型'), searchList: Config.recordType},
                             {field: 'follow_time', title: __('跟进时间'), operate:'RANGE', addclass:'datetimerange'},
                             {field : 'status', title : '跟进状态',operate:'=',searchList:{0:'未跟进',1:'已跟进'},formatter:Table.api.formatter.status},
                             {field: 'content', title: __('跟进内容'), operate: 'like'},