Business.php 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | Description: 商机
  4. // +----------------------------------------------------------------------
  5. // | Author: Michael_xu | gengxiaoxu@5kcrm.com
  6. // +----------------------------------------------------------------------
  7. namespace app\crm\controller;
  8. use app\admin\controller\ApiCommon;
  9. use app\crm\traits\StarTrait;
  10. use think\Hook;
  11. use think\Request;
  12. use think\Db;
  13. class Business extends ApiCommon
  14. {
  15. use StarTrait;
  16. /**
  17. * 用于判断权限
  18. * @permission 无限制
  19. * @allow 登录用户可访问
  20. * @other 其他根据系统设置
  21. **/
  22. public function _initialize()
  23. {
  24. $action = [
  25. 'permission'=>[''],
  26. 'allow'=>['statuslist','advance','product','system','count','setprimary']
  27. ];
  28. Hook::listen('check_auth',$action);
  29. $request = Request::instance();
  30. $a = strtolower($request->action());
  31. if (!in_array($a, $action['permission'])) {
  32. parent::_initialize();
  33. }
  34. }
  35. /**
  36. * 商机列表
  37. * @author Michael_xu
  38. * @return
  39. */
  40. public function index()
  41. {
  42. $businessModel = model('Business');
  43. $param = $this->param;
  44. $userInfo = $this->userInfo;
  45. $param['user_id'] = $userInfo['id'];
  46. $data = $businessModel->getDataList($param);
  47. return resultArray(['data' => $data]);
  48. }
  49. /**
  50. * 添加商机
  51. * @author Michael_xu
  52. * @param
  53. * @return
  54. */
  55. public function save()
  56. {
  57. $businessModel = model('Business');
  58. $param = $this->param;
  59. $userInfo = $this->userInfo;
  60. $param['create_user_id'] = $userInfo['id'];
  61. $param['owner_user_id'] = $userInfo['id'];
  62. if ($businessModel->createData($param)) {
  63. return resultArray(['data' => '添加成功']);
  64. } else {
  65. return resultArray(['error' => $businessModel->getError()]);
  66. }
  67. }
  68. /**
  69. * 商机详情
  70. * @author Michael_xu
  71. * @param
  72. * @return
  73. */
  74. public function read()
  75. {
  76. $businessModel = model('Business');
  77. $businessStatusModel = model('BusinessStatus');
  78. $userModel = new \app\admin\model\User();
  79. $param = $this->param;
  80. $userInfo = $this->userInfo;
  81. $data = $businessModel->getDataById($param['id'], $userInfo['id']);
  82. //判断权限
  83. $auth_user_ids = $userModel->getUserByPer('crm', 'business', 'read');
  84. //读权限
  85. $roPre = $userModel->rwPre($userInfo['id'], $data['ro_user_id'], $data['rw_user_id'], 'read');
  86. $rwPre = $userModel->rwPre($userInfo['id'], $data['ro_user_id'], $data['rw_user_id'], 'update');
  87. if (!in_array($data['owner_user_id'],$auth_user_ids) && !$rwPre && !$roPre) {
  88. $authData['dataAuth'] = 0;
  89. return resultArray(['data' => $authData]);
  90. }
  91. //商机状态组
  92. $data['status_list'] = $businessStatusModel->getDataById($data['type_id']);
  93. $data['lose_reason'] = Db::name('CrmBusinessLog')
  94. ->where(['business_id' => $data['business_id']])
  95. ->order(['id' => 'DESC'])
  96. ->value('remark');
  97. if (!$data) {
  98. return resultArray(['error' => $businessModel->getError()]);
  99. }
  100. return resultArray(['data' => $data]);
  101. }
  102. /**
  103. * 编辑商机
  104. * @author Michael_xu
  105. * @param
  106. * @return
  107. */
  108. public function update()
  109. {
  110. $businessModel = model('Business');
  111. $userModel = new \app\admin\model\User();
  112. $param = $this->param;
  113. $userInfo = $this->userInfo;
  114. $param['user_id'] = $userInfo['id'];
  115. //判断权限
  116. $data = $businessModel->getDataById($param['id']);
  117. $auth_user_ids = $userModel->getUserByPer('crm', 'business', 'update');
  118. //读写权限
  119. $rwPre = $userModel->rwPre($userInfo['id'], $data['ro_user_id'], $data['rw_user_id'], 'update');
  120. if (!in_array($data['owner_user_id'],$auth_user_ids) && !$rwPre) {
  121. header('Content-Type:application/json; charset=utf-8');
  122. exit(json_encode(['code'=>102,'error'=>'无权操作']));
  123. }
  124. if ($businessModel->updateDataById($param, $param['id'])) {
  125. return resultArray(['data' => '编辑成功']);
  126. } else {
  127. return resultArray(['error' => $businessModel->getError()]);
  128. }
  129. }
  130. /**
  131. * 删除商机(逻辑删)
  132. * @author Michael_xu
  133. * @param
  134. * @return
  135. */
  136. public function delete()
  137. {
  138. $param = $this->param;
  139. $businessModel = model('Business');
  140. $recordModel = new \app\admin\model\Record();
  141. $fileModel = new \app\admin\model\File();
  142. $actionRecordModel = new \app\admin\model\ActionRecord();
  143. if (!is_array($param['id'])) {
  144. $business_id[] = $param['id'];
  145. } else {
  146. $business_id = $param['id'];
  147. }
  148. $delIds = [];
  149. $errorMessage = [];
  150. //数据权限判断
  151. $userModel = new \app\admin\model\User();
  152. $auth_user_ids = $userModel->getUserByPer('crm', 'business', 'delete');
  153. foreach ($business_id as $k=>$v) {
  154. $isDel = true;
  155. //数据详情
  156. $data = $businessModel->getDataById($v);
  157. if (!$data) {
  158. $isDel = false;
  159. $errorMessage[] = 'id为'.$v.'的商机删除失败,错误原因:'.$businessModel->getError();
  160. }
  161. if (!in_array($data['owner_user_id'],$auth_user_ids)) {
  162. $isDel = false;
  163. $errorMessage[] = '名称为'.$data['name'].'的商机删除失败,错误原因:无权操作';
  164. }
  165. if ($isDel) {
  166. if (db('crm_contract')->where(['business_id'=> $v, 'check_status' => ['in', '0,1,2']])->value('contract_id')) {
  167. $isDel = false;
  168. $errorMessage[] = '名称为'.$data['name'].'的商机删除失败,错误原因:商机下关联的有合同,无法删除!';
  169. }
  170. }
  171. if ($isDel) {
  172. $delIds[] = $v;
  173. }
  174. }
  175. if ($delIds) {
  176. $data = $businessModel->delDatas($delIds);
  177. if (!$data) {
  178. return resultArray(['error' => $businessModel->getError()]);
  179. }
  180. //删除跟进记录
  181. $recordModel->delDataByTypes(5,$delIds);
  182. //删除关联附件
  183. $fileModel->delRFileByModule('crm_business',$delIds);
  184. //删除关联操作记录
  185. $actionRecordModel->delDataById(['types'=>'crm_business','action_id'=>$delIds]);
  186. actionLog($delIds,'','','');
  187. }
  188. if ($errorMessage) {
  189. return resultArray(['error' => $errorMessage]);
  190. } else {
  191. return resultArray(['data' => '删除成功']);
  192. }
  193. }
  194. /**
  195. * 符合条件的商机状态组
  196. * @author Michael_xu
  197. * @param
  198. * @return
  199. */
  200. public function statusList()
  201. {
  202. $businessStatusModel = model('BusinessStatus');
  203. $key = 'BI_queryCache_StatusList_Data1';
  204. $list = cache($key);
  205. if (!$list) {
  206. $userInfo = $this->userInfo;
  207. $list = db('crm_business_type')
  208. ->field(['name', 'status', 'structure_id', 'type_id'])
  209. ->where(['structure_id' => ['like','%,'.$userInfo['structure_id'].',%'],'status' => 1])
  210. ->where('is_display', 1)
  211. ->whereOr('structure_id','')
  212. ->select();
  213. foreach ($list as $k=>$v) {
  214. $list[$k]['statusList'] = $businessStatusModel->getDataList($v['type_id']);
  215. }
  216. cache($key, $list, true);
  217. }
  218. return resultArray(['data' => $list]);
  219. }
  220. /**
  221. * 商机转移
  222. * @author Michael_xu
  223. * @param owner_user_id 变更负责人
  224. * @param is_remove 1移出,2转为团队成员
  225. * @param type 权限 1只读2读写
  226. * @return
  227. */
  228. public function transfer()
  229. {
  230. $param = $this->param;
  231. $userInfo = $this->userInfo;
  232. $businessModel = model('Business');
  233. $settingModel = model('Setting');
  234. $userModel = new \app\admin\model\User();
  235. $authIds = $userModel->getUserByPer(); //权限范围的user_id
  236. if (!$param['owner_user_id']) {
  237. return resultArray(['error' => '变更负责人不能为空']);
  238. }
  239. if (!$param['business_id'] || !is_array($param['business_id'])) {
  240. return resultArray(['error' => '请选择需要转移的商机']);
  241. }
  242. $is_remove = $param['is_remove'] == 2 ? 2 : 1;
  243. $type = $param['type'] == 2 ? 2 : 1;
  244. $data = [];
  245. $data['owner_user_id'] = $param['owner_user_id'];
  246. $data['update_time'] = time();
  247. $ownerUserName = $userModel->getUserNameById($param['owner_user_id']);
  248. $errorMessage = [];
  249. foreach ($param['business_id'] as $business_id) {
  250. $businessInfo = $businessModel->getDataById($business_id);
  251. if (!$businessInfo) {
  252. $errorMessage[] = '名称:为《'.$businessInfo['name'].'》的商机转移失败,错误原因:数据不存在;';
  253. continue;
  254. }
  255. //权限判断
  256. if (!in_array($businessInfo['owner_user_id'],$authIds)) {
  257. $errorMessage[] = $businessInfo['name'].'"转移失败,错误原因:无权限;';
  258. continue;
  259. }
  260. //团队成员
  261. teamUserId(
  262. 'crm_business',
  263. $business_id,
  264. $type,
  265. [$businessInfo['owner_user_id']],
  266. $is_remove,
  267. 0
  268. );
  269. $resBusiness = db('crm_business')->where(['business_id' => $business_id])->update($data);
  270. if (!$resBusiness) {
  271. $errorMessage[] = $businessInfo['name'].'"转移失败,错误原因:数据出错;';
  272. continue;
  273. } else {
  274. $businessArray = [];
  275. $teamBusiness = db('crm_business')->field(['owner_user_id', 'ro_user_id', 'rw_user_id'])->where('business_id', $business_id)->find();
  276. if (!empty($teamBusiness['ro_user_id'])) {
  277. $businessRo = arrayToString(array_diff(stringToArray($teamBusiness['ro_user_id']), [$teamBusiness['owner_user_id']]));
  278. $businessArray['ro_user_id'] = $businessRo;
  279. }
  280. if (!empty($teamBusiness['rw_user_id'])) {
  281. $businessRo = arrayToString(array_diff(stringToArray($teamBusiness['rw_user_id']), [$teamBusiness['owner_user_id']]));
  282. $businessArray['rw_user_id'] = $businessRo;
  283. }
  284. db('crm_business')->where('business_id', $business_id)->update($businessArray);
  285. }
  286. //修改记录
  287. updateActionLog($userInfo['id'], 'crm_business', $business_id, '', '', '将商机转移给:'.$ownerUserName);
  288. }
  289. if (!$errorMessage) {
  290. return resultArray(['data' => '转移成功']);
  291. } else {
  292. return resultArray(['error' => $errorMessage]);
  293. }
  294. }
  295. /**
  296. * 相关产品
  297. * @author Michael_xu
  298. * @param
  299. * @return
  300. */
  301. public function product()
  302. {
  303. $productModel = model('Product');
  304. $userModel = new \app\admin\model\User();
  305. $param = $this->param;
  306. $userInfo = $this->userInfo;
  307. if (!$param['business_id']) {
  308. return resultArray(['error' => '参数错误']);
  309. }
  310. $businessInfo = db('crm_business')->where(['business_id' => $param['business_id']])->find();
  311. //判断权限
  312. $auth_user_ids = $userModel->getUserByPer('crm', 'business', 'read');
  313. //读写权限
  314. $roPre = $userModel->rwPre($userInfo['id'], $businessInfo['ro_user_id'], $businessInfo['rw_user_id'], 'read');
  315. $rwPre = $userModel->rwPre($userInfo['id'], $businessInfo['ro_user_id'], $businessInfo['rw_user_id'], 'update');
  316. if (!in_array($businessInfo['owner_user_id'],$auth_user_ids) && !$roPre && !$rwPre) {
  317. header('Content-Type:application/json; charset=utf-8');
  318. exit(json_encode(['code'=>102,'error'=>'无权操作']));
  319. }
  320. $dataList = db('crm_business_product')->where(['business_id' => $param['business_id']])->select();
  321. foreach ($dataList as $k=>$v) {
  322. $where = [];
  323. $where['product_id'] = $v['product_id'];
  324. $productInfo = db('crm_product')->where($where)->field('name,category_id')->find();
  325. $category_name = db('crm_product_category')->where(['category_id' => $productInfo['category_id']])->value('name');
  326. $dataList[$k]['name'] = $productInfo['name'] ? : '';
  327. $dataList[$k]['category_id_info'] = $category_name ? : '';
  328. }
  329. $list['list'] = $dataList ? : [];
  330. $list['total_price'] = $businessInfo['total_price'] ? : '0.00';
  331. $list['discount_rate'] = $businessInfo['discount_rate'] ? : '0.00';
  332. return resultArray(['data' => $list]);
  333. }
  334. /**
  335. * 商机状态推进
  336. * @author Michael_xu
  337. * @param business_id 商机ID
  338. * @param status_id 推进商机状态ID
  339. * @return
  340. */
  341. public function advance()
  342. {
  343. $param = $this->param;
  344. $userInfo = $this->userInfo;
  345. $userModel = new \app\admin\model\User();
  346. $is_end = $param['is_end'] ? : 0; //1赢单2输单3无效
  347. if (!$param['business_id']) {
  348. return resultArray(['error' => '参数错误']);
  349. }
  350. $businessInfo = db('crm_business')->where(['business_id' => $param['business_id']])->find();
  351. if ($businessInfo['is_end']) {
  352. return resultArray(['error' => '已结束,不能推进']);
  353. }
  354. //判断权限
  355. $auth_user_ids = $userModel->getUserByPer('crm', 'business', 'update');
  356. //读写权限
  357. $rwPre = $userModel->rwPre($userInfo['id'], $businessInfo['ro_user_id'], $businessInfo['rw_user_id'], 'update');
  358. if (!in_array($businessInfo['owner_user_id'],$auth_user_ids) && !$rwPre) {
  359. header('Content-Type:application/json; charset=utf-8');
  360. exit(json_encode(['code'=>102,'error'=>'无权操作']));
  361. }
  362. $status_id = $param['status_id'] ? : $businessInfo['status_id'];
  363. $statusInfo = db('crm_business_status')->where(['type_id' => $businessInfo['type_id'],'status_id' => $status_id])->find();
  364. if (!$statusInfo && !$is_end) {
  365. return resultArray(['error' => '参数错误']);
  366. }
  367. $data = [];
  368. $data['update_time'] = time();
  369. $data['is_end'] = $is_end;
  370. // if ($is_end) {
  371. // $status_id = $is_end;
  372. // }
  373. $data['status_id'] = $status_id;
  374. $data['status_time'] = time();
  375. $res = db('crm_business')->where(['business_id' => $param['business_id']])->update($data);
  376. if (!$res) {
  377. return resultArray(['error' => '推进失败,请重试']);
  378. } else {
  379. # 商机变更后的名称
  380. $businessStatusName = Db::name('crm_business_status')->where('status_id', $param['status_id'])->value('name');
  381. if (empty($businessStatusName) && $is_end == 1) $businessStatusName = '赢单';
  382. if (empty($businessStatusName) && $is_end == 2) $businessStatusName = '输单';
  383. if (empty($businessStatusName) && $is_end == 3) $businessStatusName = '无效';
  384. # 添加活动记录
  385. Db::name('crm_activity')->insert([
  386. 'type' => 3,
  387. 'activity_type' => 5,
  388. 'activity_type_id' => $businessInfo['business_id'],
  389. 'content' => '阶段变更为 ' . $businessStatusName,
  390. 'create_user_id' => $businessInfo['owner_user_id'],
  391. 'update_time' => time(),
  392. 'create_time' => time(),
  393. 'customer_ids' => $businessInfo['customer_id']
  394. ]);
  395. //推进记录添加
  396. $temp['status_id'] = $status_id ? : 0;
  397. $temp['is_end'] = $is_end ? : 0;
  398. $temp['business_id'] = $param['business_id'];
  399. $temp['create_time'] = time();
  400. $temp['owner_user_id'] = $userInfo['id'];
  401. $temp['remark'] = $param['remark'] ? : '';
  402. Db::name('CrmBusinessLog')->insert($temp);
  403. return resultArray(['data' => '推进成功']);
  404. }
  405. }
  406. /**
  407. * 商机导出
  408. * @author Michael_xu
  409. * @param
  410. * @return
  411. */
  412. public function excelExport()
  413. {
  414. $param = $this->param;
  415. $userInfo = $this->userInfo;
  416. $param['user_id'] = $userInfo['id'];
  417. if ($param['business_id']) {
  418. $param['business_id'] = ['condition' => 'in','value' => $param['business_id'],'form_type' => 'text','name' => ''];
  419. $param['is_excel'] = 1;
  420. }
  421. $excelModel = new \app\admin\model\Excel();
  422. // 导出的字段列表
  423. $fieldModel = new \app\admin\model\Field();
  424. $field_list = $fieldModel->getIndexFieldConfig('crm_business', $userInfo['id']);
  425. // 文件名
  426. $file_name = '5kcrm_business_'.date('Ymd');
  427. $model = model('Business');
  428. $temp_file = $param['temp_file'];
  429. unset($param['temp_file']);
  430. $page = $param['page'] ?: 1;
  431. unset($param['page']);
  432. unset($param['export_queue_index']);
  433. return $excelModel->batchExportCsv($file_name, $temp_file, $field_list, $page, function($page, $limit) use ($model, $param, $field_list) {
  434. $param['page'] = $page;
  435. $param['limit'] = $limit;
  436. $data = $model->getDataList($param);
  437. $data['list'] = $model->exportHandle($data['list'], $field_list, 'business');
  438. return $data;
  439. });
  440. }
  441. /**
  442. * 设置关注
  443. *
  444. * @return \think\response\Json
  445. * @throws \think\Exception
  446. * @throws \think\exception\PDOException
  447. */
  448. public function star()
  449. {
  450. $userId = $this->userInfo['id'];
  451. $targetId = $this->param['target_id'];
  452. $type = $this->param['type'];
  453. if (empty($userId) || empty($targetId) || empty($type)) return resultArray(['error' => '缺少必要参数!']);
  454. if (!$this->setStar($type, $userId, $targetId)) {
  455. return resultArray(['error' => '设置关注失败!']);
  456. }
  457. return resultArray(['data' => '设置关注成功!']);
  458. }
  459. /**
  460. * 系统信息
  461. *
  462. * @return \think\response\Json
  463. * @throws \think\db\exception\DataNotFoundException
  464. * @throws \think\db\exception\ModelNotFoundException
  465. * @throws \think\exception\DbException
  466. */
  467. public function system()
  468. {
  469. if (empty($this->param['id'])) return resultArray(['error' => '参数错误!']);
  470. $businessModel = new \app\crm\model\Business();
  471. $data = $businessModel->getSystemInfo($this->param['id']);
  472. return resultArray(['data' => $data]);
  473. }
  474. /**
  475. * table栏数量统计
  476. *
  477. * @return \think\response\Json
  478. * @throws \think\db\exception\DataNotFoundException
  479. * @throws \think\db\exception\ModelNotFoundException
  480. * @throws \think\exception\DbException
  481. */
  482. public function count()
  483. {
  484. if (empty($this->param['business_id'])) return resultArray(['error' => '参数错误!']);
  485. $businessId = $this->param['business_id'];
  486. # 联系人
  487. $contactsCount = Db::name('crm_contacts_business')->alias('business')
  488. ->join('__CRM_CONTACTS__ contacts', 'contacts.contacts_id = business.contacts_id')
  489. ->join('__CRM_CUSTOMER__ customer', 'customer.customer_id = contacts.customer_id')
  490. ->where('business_id', $businessId)->count();
  491. # 合同
  492. $contractCount = Db::name('crm_contract')->where('business_id', $businessId)->count();
  493. # 产品
  494. $productCount = Db::name('crm_business_product')->where('business_id', $businessId)->count();
  495. # 附件
  496. $fileCount = Db::name('crm_business_file')->alias('business')->join('__ADMIN_FILE__ file', 'file.file_id = business.file_id', 'LEFT')->where('business_id', $businessId)->count();
  497. # 团队
  498. $business = Db::name('crm_business')->field(['owner_user_id', 'ro_user_id', 'rw_user_id'])->where('business_id', $businessId)->find();
  499. $business['ro_user_id'] = explode(',', trim($business['ro_user_id'], ','));
  500. $business['rw_user_id'] = explode(',', trim($business['rw_user_id'], ','));
  501. $business['owner_user_id'] = [$business['owner_user_id']];
  502. $teamCount = array_filter(array_unique(array_merge($business['ro_user_id'], $business['rw_user_id'], $business['owner_user_id'])));
  503. $data = [
  504. 'contactCount' => $contactsCount,
  505. 'contractCount' => $contractCount,
  506. 'fileCount' => $fileCount,
  507. 'memberCount' => count($teamCount),
  508. 'productCount' => $productCount
  509. ];
  510. return resultArray(['data' => $data]);
  511. }
  512. /**
  513. * 设置首要联系人
  514. *
  515. * @return \think\response\Json
  516. * @throws \think\Exception
  517. * @throws \think\exception\PDOException
  518. */
  519. public function setPrimary()
  520. {
  521. $businessId = $this->param['business_id'];
  522. $contactsId = $this->param['contacts_id'];
  523. if (empty($businessId) || empty($contactsId)) return resultArray(['error' => '参数错误!']);
  524. if (!Db::name('crm_business')->where('business_id', $businessId)->update(['contacts_id' => $contactsId])) {
  525. return resultArray(['error' => '操作失败!']);
  526. }
  527. return resultArray(['data' => '操作成功!']);
  528. }
  529. }