Customer.php 19 KB

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