123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522 |
- <?php
- 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;
- // 表名,不含前缀
- protected $name = 'qingdongams_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 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 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 function contractTotal()
- {
- return $this->hasOne(Contract::class, 'customer_id', 'id')->group('customer_id')->field('customer_id,sum(money) as c_money')->bind('c_money');
- }
- public function receivablesTotal()
- {
- return $this->hasOne(Receivables::class, 'customer_id', 'id')->group('customer_id')->field('customer_id,sum(money) as r_money');
- }
- public function consumeTotal()
- {
- return $this->hasOne(Consume::class, 'customer_id', 'id')->group('customer_id')->where(['check_status' => 2])->field('customer_id,sum(money) as s_money')->bind('s_money');
- }
- public function workorderTotal()
- {
- 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();
- $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);
- }
- }
- OperationLog::createLog(OperationLog::CUSTOMER_TYPE, $lastId, '创建客户');
- //新增跟进记录
- Record::quickCreateRecord(Record::CUSTOMER_TYPE, $lastId, '新增客户:' . $params['name']);
- return $lastId;
- }
- /**
- *修改客户信息
- */
- 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[$name] = $val;
- }
- unset($params[$name]);
- } else {
- if ($params[$name] === '') {
- $params[$name] = NULL;
- }
- }
- }
- //操作记录处理
- $form = Form::where(['type' => 'customer'])->find();
- $formdata = json_decode($form['data'], true)['data'];
- $forminfo = [
- 'address' => '地址定位',
- 'address_detail' => '详细地址',
- 'country' => '国家',
- 'level' => '客户星级',
- 'management_id' => '客户所属区域',
- 'contract_status' => '客户成交状态',
- 'parent_id' => '上级公司'
- ];
- foreach ($formdata as $k => $v) {
- $forminfo[$v['id']] = $v['config']['label'];
- }
- $customerInfo = self::get($params['id'])->toArray();
- $customerOther = CustomerOther::get($params['id'])->toArray();
- if ($customerOther) {
- $customerOther = json_decode($customerOther['otherdata'], true);
- }
- $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] = '未成交';
- }
- 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] = AreaManagement::where(array('id' => $customerInfo[$name]))->value('name');
- $val = AreaManagement::where(array('id' => $val))->value('name');
- }
- $operation .= "[{$nameinfo}]【{$customerInfo[$name]}】修改为【{$val}】;";
- }
- }
- 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)]);
- }
- if ($resInfo === false) {
- // 验证失败 输出错误信息
- throw new Exception($otherModel->getError());
- }
- 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);
- //创建账号
- $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;
- }
- /**
- *移入公海
- */
- 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(), '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' => $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());
- }
- return $customer['id'];
- }
- public static function changeCustomerType($customer_id, $type, $remark)
- {
- if (Customer::where(['id' => $customer_id])->update(['type' => $type]) == false) {
- throw new Exception('修改失败');
- }
- OperationLog::createLog(OperationLog::CUSTOMER_TYPE, $customer_id, $remark);
- return true;
- }
- }
|