Customer.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. <?php
  2. namespace addons\qingdongams\model;
  3. use app\common\model\Area;
  4. use addons\qingdongams\model\CustomerOther;
  5. use addons\qingdongams\model\Form;
  6. use think\Db;
  7. use think\Exception;
  8. use think\Model;
  9. use traits\model\SoftDelete;
  10. /**
  11. *客户
  12. */
  13. class Customer Extends Model {
  14. use SoftDelete;
  15. // 表名,不含前缀
  16. protected $name = 'qingdongams_customer';
  17. // 开启自动写入时间戳字段
  18. protected $autoWriteTimestamp = 'int';
  19. // 定义时间戳字段名
  20. protected $createTime = 'createtime';
  21. protected $updateTime = 'updatetime';
  22. protected $deleteTime = 'deletetime';
  23. //获取创建时间
  24. public function getCreatetimeAttr($value) {
  25. return date('Y-m-d H:i:s', $value);
  26. }
  27. //获取创建时间
  28. public function getUpdatetimeAttr($value) {
  29. return date('Y-m-d H:i:s', $value);
  30. }
  31. //创建人
  32. public function createStaff() {
  33. return $this->hasOne(Staff::class, 'id', 'create_staff_id')->field('id,name,post,img');
  34. }
  35. //负责人
  36. public function ownerStaff() {
  37. return $this->hasOne(Staff::class, 'id', 'owner_staff_id')->field('id,name,img');
  38. }
  39. //获取联系人
  40. public function contacts() {
  41. return $this->hasOne(Contacts::class, 'customer_id', 'id')->order('is_major desc')->field('id,customer_id,name,mobile,email');
  42. }
  43. //获取联系人
  44. public function contact() {
  45. return $this->belongsTo(Contacts::class,'id','customer_id', [], 'LEFT')->field('id,customer_id,name,mobile,email')->setEagerlyType(0);;
  46. }
  47. //获取客户相关信息
  48. public function customerOther() {
  49. return $this->belongsTo(CustomerOther::class,'id','id');
  50. }
  51. public static function withtrash(){
  52. return self::withTrashed();
  53. }
  54. public function contractTotal()
  55. {
  56. return $this->hasOne(Contract::class, 'customer_id', 'id')->group('customer_id')->field('customer_id,sum(money) as c_money')->bind('c_money');
  57. }
  58. public function receivablesTotal()
  59. {
  60. return $this->hasOne(Receivables::class, 'customer_id', 'id')->group('customer_id')->field('customer_id,sum(money) as r_money');
  61. }
  62. public function consumeTotal()
  63. {
  64. 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');
  65. }
  66. public function workorderTotal()
  67. {
  68. return $this->hasOne(Workorder::class, 'customer_id', 'id')->group('customer_id')->field('customer_id,sum(money) as w_money')->bind('w_money');
  69. }
  70. public static function getList() {
  71. $staff = Staff::info();
  72. $staff_id = $staff->id;
  73. $whereStaff = function ($query) use ($staff_id) {
  74. $query->where(['ro_staff_id' => ['like', "%,{$staff_id},%"]])
  75. ->whereOr('rw_staff_id', 'like', "%,{$staff_id},%")
  76. ->whereOr(['owner_staff_id' => ['in', Staff::getMyStaffIds()]]);
  77. };
  78. return self::where($whereStaff)->field('id,name')->select();
  79. }
  80. //创建客户
  81. public static function createCustomer($params,$leads_id=null,$reminds_id=null) {
  82. //自定义字段
  83. $other = [];
  84. foreach ($params as $name => $val) {
  85. if (strstr($name,'other_') !== false) {
  86. if(is_array($val)){
  87. $other[$name] = implode(',',$val);
  88. }else{
  89. $other[$name] = $val;
  90. }
  91. unset($params[$name]);
  92. }else{
  93. if($params[$name] === ''){
  94. $params[$name]=NULL;
  95. }
  96. }
  97. }
  98. $staff = Staff::info();
  99. if(empty($staff)){
  100. // 验证失败 输出错误信息
  101. throw new Exception('账号不存在');
  102. }
  103. $params['create_staff_id'] = $staff->id;
  104. $params['owner_staff_id'] = $staff->id;
  105. $params['next_time'] = date('Y-m-d H:i:s');
  106. $params['last_time'] = date('Y-m-d H:i:s');
  107. $params['receivetime'] = time();
  108. $customer = new self;
  109. $result = $customer->allowField(true)->save($params);
  110. $lastId=$customer->getLastInsID();
  111. if (false === $result) {
  112. // 验证失败 输出错误信息
  113. throw new Exception($customer->getError());
  114. }
  115. $otherModel = new CustomerOther();
  116. if ($otherModel->save(['id' => $lastId, 'otherdata' => json_encode($other, JSON_UNESCAPED_UNICODE)]) === false) {
  117. // 验证失败 输出错误信息
  118. throw new Exception($otherModel->getError());
  119. }
  120. if(isset($leads_id) && $leads_id){
  121. Leads::where(['id' => $leads_id])->update(['is_transform' => 1, 'customer_id' => $lastId]);
  122. }
  123. if (isset($reminds_id['reminds_id']) && $reminds_id['reminds_id']) {//发送通知
  124. $staff_ids = explode(',', $reminds_id['reminds_id']);
  125. foreach ($staff_ids as $staff_id) {
  126. //发送通知
  127. Message::addMessage(Message::CUSTOMER_TYPE, $lastId, $staff_id, $staff->id);
  128. }
  129. }
  130. OperationLog::createLog(OperationLog::CUSTOMER_TYPE, $lastId, '创建客户');
  131. //新增跟进记录
  132. Record::quickCreateRecord(Record::CUSTOMER_TYPE, $lastId, '新增客户:' . $params['name']);
  133. return $lastId;
  134. }
  135. /**
  136. *修改客户信息
  137. */
  138. public static function updateCustomer($params) {
  139. $operator = $params;
  140. //自定义字段
  141. $other = [];
  142. foreach ($params as $name => $val) {
  143. if (strstr($name,'other_') !== false) {
  144. if(is_array($val)){
  145. $other[$name] = implode(',',$val);
  146. }else{
  147. $other[$name] = $val;
  148. }
  149. unset($params[$name]);
  150. }else{
  151. if($params[$name] === ''){
  152. $params[$name]=NULL;
  153. }
  154. }
  155. }
  156. //操作记录处理
  157. $form = Form::where(['type' => 'customer'])->find();
  158. $formdata = json_decode($form['data'],true)['data'];
  159. $forminfo = [
  160. 'address'=>'地址定位',
  161. 'address_detail'=>'详细地址',
  162. 'country'=>'国家',
  163. 'level'=>'客户星级',
  164. 'management_id'=>'客户所属区域',
  165. 'contract_status'=>'客户成交状态',
  166. 'parent_id'=>'上级公司'
  167. ];
  168. foreach($formdata as $k=>$v){
  169. $forminfo[$v['id']] = $v['config']['label'];
  170. }
  171. $customerInfo=self::get($params['id'])->toArray();
  172. $customerOther = CustomerOther::get($params['id'])->toArray();
  173. if($customerOther){
  174. $customerOther = json_decode($customerOther['otherdata'],true);
  175. }
  176. $customerInfo = array_merge($customerInfo,$customerOther);
  177. $customer = new self;
  178. $operation='修改客户信息:将';
  179. foreach ($operator as $name=>$val){
  180. if(isset($customerInfo[$name]) && (is_string($customerInfo[$name]) || is_int($customerInfo[$name])) && $customerInfo[$name] != $val){
  181. $nameinfo = isset($forminfo[$name])?$forminfo[$name]:$name;
  182. if($nameinfo =='客户成交状态'){
  183. if($customerInfo[$name] == 1){
  184. $customerInfo[$name] ='已成交';
  185. }else{
  186. $customerInfo[$name] ='未成交';
  187. }
  188. if($val == 1){
  189. $val ='已成交';
  190. }else{
  191. $val ='未成交';
  192. }
  193. }
  194. if($nameinfo =='上级公司'){
  195. $customerInfo[$name] = $customer->where(array('id'=>$customerInfo[$name]))->value('name');
  196. $val = $customer->where(array('id'=>$val))->value('name');
  197. }
  198. if($nameinfo =='客户所属区域'){
  199. $customerInfo[$name] = AreaManagement::where(array('id'=>$customerInfo[$name]))->value('name');
  200. $val =AreaManagement::where(array('id'=>$val))->value('name');
  201. }
  202. $operation.="[{$nameinfo}]【{$customerInfo[$name]}】修改为【{$val}】;";
  203. }
  204. }
  205. if($operation !='修改客户信息:将'){
  206. OperationLog::createLog(OperationLog::CUSTOMER_TYPE, $params['id'], $operation);
  207. }
  208. // 调用当前模型对应的User验证器类进行数据验证
  209. $result = $customer->save($params, ['id' => $params['id']]);
  210. if (false === $result) {
  211. // 验证失败 输出错误信息
  212. throw new Exception($customer->getError());
  213. }
  214. $otherModel = new CustomerOther();
  215. $otherFind = $otherModel->where(['id' => $params['id']])->find();
  216. if($otherFind){
  217. $resInfo = $otherModel->save(['otherdata' => json_encode($other, JSON_UNESCAPED_UNICODE)],['id' => $params['id']]);
  218. }else{
  219. $resInfo = $otherModel->save(['id' => $params['id'],'otherdata' => json_encode($other, JSON_UNESCAPED_UNICODE)]);
  220. }
  221. if ( $resInfo === false) {
  222. // 验证失败 输出错误信息
  223. throw new Exception($otherModel->getError());
  224. }
  225. return true;
  226. }
  227. /**
  228. * 导入客户
  229. * @param $data
  230. * @return bool
  231. */
  232. public static function importCustomer($data) {
  233. $addCustomers = [];
  234. $addOther = [];
  235. $addcontacts = [];
  236. $addLog=[];
  237. foreach ($data as $params) {
  238. //自定义字段
  239. $other = [];
  240. foreach ($params as $name => $val) {
  241. if (strstr($name, 'other_') !== false) {
  242. if(is_array($val)){
  243. $other[$name] = implode(',',$val);
  244. }else{
  245. $other[$name] = $val;
  246. }
  247. unset($params[$name]);
  248. }else{
  249. if($params[$name] === ''){
  250. $params[$name]=NULL;
  251. }
  252. }
  253. }
  254. $other['id'] = $params['id'];
  255. $params['next_time'] = date('Y-m-d H:i:s');
  256. $params['receivetime'] = time();
  257. $params['createtime'] = time();
  258. $addOther[] = ['id' => $params['id'], 'otherdata' => json_encode($other, JSON_UNESCAPED_UNICODE)];
  259. $addcontacts[] = ['customer_id' => $params['id'],'is_major'=>1,'name'=>$params['name'],'mobile'=>$params['mobile'],'createtime'=>time(),'updatetime'=>time()];
  260. $addLog[] = [
  261. 'content' => '导入客户',
  262. 'operation_type' => 2,
  263. 'operation_id' => 30,
  264. 'relation_type' => OperationLog::CUSTOMER_TYPE,
  265. 'relation_id' => $params['id'],
  266. 'createtime' => time()
  267. ];
  268. $addCustomers[] = $params;
  269. }
  270. $customer = new self;
  271. // 调用当前模型对应的User验证器类进行数据验证
  272. $result = $customer->allowField(true)->insertAll($addCustomers);
  273. $otherModel = new CustomerOther();
  274. $otherModel->allowField(true)->insertAll($addOther);
  275. //联系人
  276. $contactsModel = new Contacts();
  277. $contactsModel->allowField(true)->insertAll($addcontacts);
  278. $logModel = new OperationLog();
  279. $logModel->allowField(true)->insertAll($addLog);
  280. return true;
  281. }
  282. /**
  283. *移入公海
  284. */
  285. public static function moveSeas($id) {
  286. $row = Customer::where(['id' => $id])->find();
  287. $row = $row->toArray();
  288. $row = CustomerOther::getOther($row);
  289. $seastype=Seastype::where([])->select();
  290. $seasIds=[];
  291. foreach ($seastype as $r){
  292. $rules=json_decode($r['rules'],true)?:[];
  293. $is_rule=0;//权限是否匹配
  294. foreach ($rules as $n=>$e){
  295. if($n == 'area_ids'){//区域
  296. $area=Area::where(['id'=>['in',$e]])->column('name');
  297. foreach ($area as $a){
  298. $rs=preg_match("/^{$a}/i",$row['address'],$res);
  299. if($rs){
  300. $is_rule=1;
  301. }
  302. }
  303. }else if (isset($row[$n]) && $row[$n]) {
  304. if (is_string($e)) {
  305. $e = explode(',', $e);
  306. }
  307. $rn = explode(',', $row[$n]);
  308. $intersect = array_intersect($e, $rn);
  309. if($intersect){
  310. $is_rule=1;
  311. }
  312. }
  313. }
  314. if ($is_rule == 1) {
  315. $seasIds[] = $r['id'];
  316. }
  317. }
  318. if(empty($seasIds)){
  319. $seasIds[]=1;//默认公海
  320. }
  321. $seas_id = ',' . implode(',', $seasIds) . ',';
  322. if (Customer::where(['id' => $id])->update(['owner_staff_id' => 0,
  323. 'seas_id' => $seas_id,'sea_time'=>time(),'is_seas'=>1]) == false) {
  324. throw new Exception('修改失败');
  325. }
  326. //回收记录
  327. SeaOperation::where([])->insert(array('customer_id'=>$id,'type'=>1,'owner_staff_id' => $row['owner_staff_id'],'createtime'=>time(),'updatetime'=>time()));
  328. OperationLog::createLog(OperationLog::CUSTOMER_TYPE, $id, '将客户放入公海');
  329. return true;
  330. }
  331. /**
  332. * 转移客户
  333. */
  334. public static function transfer($id, $staff_id) {
  335. Db::startTrans();
  336. try {
  337. if (Customer::where(['id' => $id])->update([
  338. 'owner_staff_id' => $staff_id,
  339. 'updatetime' => time()
  340. ]) == false) {
  341. throw new Exception('修改失败');
  342. }
  343. if (Contacts::where(['customer_id' => $id])->count()) {//存在联系人 则修改负责人
  344. if (Contacts::where(['customer_id' => $id])->update([
  345. 'owner_staff_id' => $staff_id,
  346. 'updatetime' => time()
  347. ]) == false) {
  348. throw new Exception('修改失败');
  349. }
  350. }
  351. $staff = Staff::get($staff_id);
  352. OperationLog::createLog(OperationLog::CUSTOMER_TYPE, $id, '将客户转移给:' . $staff['name']);
  353. Db::commit();
  354. } catch (Exception $e) {
  355. Db::rollback();
  356. throw new Exception($e->getMessage());
  357. }
  358. return true;
  359. }
  360. /**
  361. * 批量转移客户
  362. */
  363. public static function batchTransfer($ids, $staff_id) {
  364. Db::startTrans();
  365. try {
  366. if (Customer::where(['id' => ['in',$ids]])->update([
  367. 'owner_staff_id' => $staff_id,
  368. 'updatetime' => time()
  369. ]) == false) {
  370. throw new Exception('修改失败');
  371. }
  372. if (Contacts::where(['customer_id' => ['in',$ids]])->count()) {//存在联系人 则修改负责人
  373. if (Contacts::where(['customer_id' => ['in',$ids]])->update([
  374. 'owner_staff_id' => $staff_id,
  375. 'updatetime' => time()
  376. ]) == false) {
  377. throw new Exception('修改失败');
  378. }
  379. }
  380. $staff = Staff::get($staff_id);
  381. foreach ($ids as $id){
  382. OperationLog::createLog(OperationLog::CUSTOMER_TYPE, $id, '将客户转移给:' . $staff['name']);
  383. }
  384. Db::commit();
  385. } catch (Exception $e) {
  386. Db::rollback();
  387. throw new Exception($e->getMessage());
  388. }
  389. return true;
  390. }
  391. /**
  392. * 领取客户
  393. */
  394. public static function receive($customer_id) {
  395. $staff = Staff::info();
  396. $where=['owner_staff_id' => 0];
  397. if($customer_id){
  398. $where['id']=$customer_id;
  399. }
  400. $customer = Customer::where($where)->find();
  401. Db::startTrans();
  402. try {
  403. $id = $customer['id'];
  404. $staff_id = $staff->id;
  405. if (Customer::where(['id' => $customer['id']])->update(['owner_staff_id' => $staff->id,'receivetime'=>time(),'is_seas'=>0]) == false) {
  406. throw new Exception('修改失败');
  407. }
  408. if (Contacts::where(['customer_id' => $id])->count()) {//存在联系人 则修改负责人
  409. if (Contacts::where(['customer_id' => $id])->update([
  410. 'owner_staff_id' => $staff_id,
  411. 'updatetime' => time()
  412. ]) == false) {
  413. throw new Exception('修改失败');
  414. }
  415. }
  416. //领取记录
  417. SeaOperation::where([])->insert(array('customer_id'=>$customer['id'],'type'=>0,'owner_staff_id'=>$staff->id,'createtime'=>time(),'updatetime'=>time()));
  418. OperationLog::createLog(OperationLog::CUSTOMER_TYPE, $customer['id'], '领取了客户');
  419. Db::commit();
  420. } catch (Exception $e) {
  421. Db::rollback();
  422. throw new Exception($e->getMessage());
  423. }
  424. return $customer['id'];
  425. }
  426. public static function changeCustomerType($customer_id, $type, $remark)
  427. {
  428. if (Customer::where(['id' => $customer_id])->update(['type' => $type]) == false) {
  429. throw new Exception('修改失败');
  430. }
  431. OperationLog::createLog(OperationLog::CUSTOMER_TYPE, $customer_id, $remark);
  432. return true;
  433. }
  434. }