123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827
  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\admin\model\Message;
  10. use app\admin\model\User;
  11. use app\crm\model\NumberSequence;
  12. use app\crm\traits\AutoNumberTrait;
  13. use think\Db;
  14. use think\Hook;
  15. use think\Request;
  16. class Contract extends ApiCommon
  17. {
  18. use AutoNumberTrait;
  19. /**
  20. * 用于判断权限
  21. * @permission 无限制
  22. * @allow 登录用户可访问
  23. * @other 其他根据系统设置
  24. **/
  25. public function _initialize()
  26. {
  27. $action = [
  28. 'permission'=>[''],
  29. 'allow'=>['check', 'revokecheck', 'product', 'system', 'count', 'copy']
  30. ];
  31. Hook::listen('check_auth',$action);
  32. $request = Request::instance();
  33. $a = strtolower($request->action());
  34. if (!in_array($a, $action['permission'])) {
  35. parent::_initialize();
  36. }
  37. }
  38. /**
  39. * 合同列表
  40. * @author Michael_xu
  41. * @return
  42. */
  43. public function index()
  44. {
  45. $contractModel = model('Contract');
  46. $param = $this->param;
  47. $userInfo = $this->userInfo;
  48. $param['user_id'] = $userInfo['id'];
  49. $data = $contractModel->getDataList($param);
  50. return resultArray(['data' => $data]);
  51. }
  52. /**
  53. * 添加合同
  54. *
  55. * @return \think\response\Json
  56. * @throws \think\db\exception\DataNotFoundException
  57. * @throws \think\db\exception\ModelNotFoundException
  58. * @throws \think\exception\DbException
  59. */
  60. public function save()
  61. {
  62. $contractModel = model('Contract');
  63. $param = $this->param;
  64. $userInfo = $this->userInfo;
  65. $examineStepModel = new \app\admin\model\ExamineStep();
  66. $param['create_user_id'] = $userInfo['id'];
  67. $param['owner_user_id'] = $userInfo['id'];
  68. $examineStatus = $param['examineStatus']; // 审批是否停用
  69. unset($param['examineStatus']);
  70. # 自动设置合同编号
  71. $numberInfo = [];
  72. if (empty($param['num'])) {
  73. $numberInfo = $this->getAutoNumbers(1);
  74. if (empty($numberInfo['number'])) return resultArray(['error' => '请填写合同编号!']);
  75. $param['num'] = $numberInfo['number'];
  76. }
  77. if ($param['is_draft'] || (!empty($param['check_status']) && $param['check_status'] == 5)) {
  78. //保存为草稿
  79. $param['check_status'] = 5; //草稿(未提交)
  80. $param['check_user_id'] = $param['check_user_id'] ? ','.$param['check_user_id'].',' : '';
  81. } else {
  82. if (($examineStatus != false && $examineStatus != 'false') || $examineStatus == 1) {
  83. // 审核判断(是否有符合条件的审批流)
  84. $examineFlowModel = new \app\admin\model\ExamineFlow();
  85. if (!$examineFlowModel->checkExamine($param['create_user_id'], 'crm_contract')) {
  86. return resultArray(['error' => '暂无审批人,无法创建']);
  87. }
  88. //添加审批相关信息
  89. $examineFlowData = $examineFlowModel->getFlowByTypes($param['create_user_id'], 'crm_contract');
  90. if (!$examineFlowData) {
  91. return resultArray(['error' => '无可用审批流,请联系管理员']);
  92. }
  93. $param['flow_id'] = $examineFlowData['flow_id'];
  94. //获取审批人信息
  95. if ($examineFlowData['config'] == 1) {
  96. //固定审批流
  97. $nextStepData = $examineStepModel->nextStepUser($userInfo['id'], $examineFlowData['flow_id'], 'crm_contract', 0, 0, 0);
  98. $next_user_ids = arrayToString($nextStepData['next_user_ids']) ? : '';
  99. $check_user_id = $next_user_ids ? : [];
  100. $param['order_id'] = 1;
  101. } else {
  102. $check_user_id = $param['check_user_id'] ? ','.$param['check_user_id'].',' : '';
  103. }
  104. if (!$check_user_id) {
  105. return resultArray(['error' => '无可用审批人,请联系管理员']);
  106. }
  107. $param['check_user_id'] = is_array($check_user_id) ? ','.implode(',',$check_user_id).',' : $check_user_id;
  108. } else {
  109. # 审批流停用,将状态改为审核通过
  110. $param['check_status'] = 2;
  111. }
  112. }
  113. if ($contractModel->createData($param)) {
  114. # 更新crm_number_sequence表中的last_date、create_time字段
  115. if (!empty($numberInfo['data'])) (new NumberSequence())->batchUpdate($numberInfo['data']);
  116. return resultArray(['data' => '添加成功']);
  117. } else {
  118. return resultArray(['error' => $contractModel->getError()]);
  119. }
  120. }
  121. /**
  122. * 合同详情
  123. * @author Michael_xu
  124. * @param
  125. * @return
  126. */
  127. public function read()
  128. {
  129. $contractModel = model('Contract');
  130. $userModel = new \app\admin\model\User();
  131. $receivablesModel = new \app\crm\model\Receivables();
  132. $param = $this->param;
  133. $userInfo = $this->userInfo;
  134. $data = $contractModel->getDataById($param['id']);
  135. //判断权限
  136. $auth_user_ids = $userModel->getUserByPer('crm', 'contract', 'read');
  137. //读权限
  138. $roPre = $userModel->rwPre($userInfo['id'], $data['ro_user_id'], $data['rw_user_id'], 'read');
  139. $rwPre = $userModel->rwPre($userInfo['id'], $data['ro_user_id'], $data['rw_user_id'], 'update');
  140. if (!in_array($data['owner_user_id'],$auth_user_ids) && !$roPre && !$rwPre) {
  141. $authData['dataAuth'] = 0;
  142. return resultArray(['data' => $authData]);
  143. }
  144. if (!$data) {
  145. return resultArray(['error' => $contractModel->getError()]);
  146. }
  147. //回款信息用来作废时二次确认
  148. $auth_user_ids = $userModel->getUserByPer('crm', 'receivables', 'index');
  149. $where['contract_id'] = $param['id'];
  150. $where['pageType'] = 'all';
  151. $where['user_id'] = $userInfo['id'];
  152. $receivablesData = $receivablesModel->getDataList($where);
  153. $receivablesData = $receivablesModel
  154. ->where([
  155. 'contract_id' => $param['id'],
  156. 'owner_user_id' => ['IN', $auth_user_ids]
  157. ])
  158. ->count();
  159. $data['receivablesDataCount'] = $receivablesData;
  160. return resultArray(['data' => $data]);
  161. }
  162. /**
  163. * 编辑合同
  164. *
  165. * @return \think\response\Json
  166. * @throws \think\db\exception\DataNotFoundException
  167. * @throws \think\db\exception\ModelNotFoundException
  168. * @throws \think\exception\DbException
  169. */
  170. public function update()
  171. {
  172. $contractModel = model('Contract');
  173. $userModel = new \app\admin\model\User();
  174. $param = $this->param;
  175. $userInfo = $this->userInfo;
  176. $param['user_id'] = $userInfo['id'];
  177. $dataInfo = $contractModel->getDataById($param['id']);
  178. $examineStatus = $param['examineStatus']; // 审批是否停用
  179. unset($param['examineStatus']);
  180. if (!$dataInfo) {
  181. return resultArray(['error' => '数据不存在或已删除']);
  182. }
  183. //判断权限
  184. $auth_user_ids = $userModel->getUserByPer('crm', 'contract', 'update');
  185. //读写权限
  186. $rwPre = $userModel->rwPre($userInfo['id'], $dataInfo['ro_user_id'], $dataInfo['rw_user_id'], 'update');
  187. if (!in_array($dataInfo['owner_user_id'],$auth_user_ids) && !$rwPre) {
  188. header('Content-Type:application/json; charset=utf-8');
  189. exit(json_encode(['code'=>102,'error'=>'无权操作']));
  190. }
  191. # 自动设置合同编号
  192. $numberInfo = [];
  193. if (empty($param['num'])) {
  194. $numberInfo = $this->getAutoNumbers(1);
  195. if (empty($numberInfo['number'])) return resultArray(['error' => '请填写合同编号!']);
  196. $param['num'] = $numberInfo['number'];
  197. }
  198. //已进行审批,不能编辑
  199. if (!in_array($dataInfo['check_status'], ['3', '4', '5', '6'])) {
  200. return resultArray(['error' => '当前状态为审批中或已审批通过,不可编辑']);
  201. }
  202. if (($examineStatus != false && $examineStatus != 'false') || $examineStatus == 1) {
  203. //将合同审批状态至为待审核,提交后重新进行审批
  204. //审核判断(是否有符合条件的审批流)
  205. $examineFlowModel = new \app\admin\model\ExamineFlow();
  206. $examineStepModel = new \app\admin\model\ExamineStep();
  207. if (!$examineFlowModel->checkExamine($dataInfo['owner_user_id'], 'crm_contract')) {
  208. return resultArray(['error' => '暂无审批人,无法创建']);
  209. }
  210. //添加审批相关信息
  211. $examineFlowData = $examineFlowModel->getFlowByTypes($dataInfo['owner_user_id'], 'crm_contract');
  212. if (!$examineFlowData) {
  213. return resultArray(['error' => '无可用审批流,请联系管理员']);
  214. }
  215. $param['flow_id'] = $examineFlowData['flow_id'];
  216. //获取审批人信息
  217. if ($examineFlowData['config'] == 1) {
  218. //固定审批流
  219. $nextStepData = $examineStepModel->nextStepUser($dataInfo['owner_user_id'], $examineFlowData['flow_id'], 'crm_contract', 0, 0, 0);
  220. $next_user_ids = arrayToString($nextStepData['next_user_ids']) ? : '';
  221. $check_user_id = $next_user_ids ? : [];
  222. $param['order_id'] = 1;
  223. } else {
  224. $check_user_id = $param['check_user_id'] ? ','.$param['check_user_id'].',' : '';
  225. }
  226. if ($param['is_draft'] || (!empty($param['check_status']) && $param['check_status'] == 5)) {
  227. //保存为草稿
  228. $param['check_status'] = 5;
  229. $param['check_user_id'] = $param['check_user_id'] ? ','.$param['check_user_id'].',' : '';
  230. } else {
  231. if (!$check_user_id) {
  232. return resultArray(['error' => '无可用审批人,请联系管理员']);
  233. }
  234. $param['check_user_id'] = is_array($check_user_id) ? ','.implode(',',$check_user_id).',' : $check_user_id;
  235. $param['check_status'] = 0;
  236. }
  237. $param['flow_user_id'] = '';
  238. }
  239. if ($contractModel->updateDataById($param, $param['id'])) {
  240. //将审批记录至为无效
  241. $examineRecordModel = new \app\admin\model\ExamineRecord();
  242. $examineRecordModel->setEnd(['types' => 'crm_contract','types_id' => $param['id']]);
  243. # 更新crm_number_sequence表中的last_date、create_time字段
  244. if (!empty($numberInfo['data'])) (new NumberSequence())->batchUpdate($numberInfo['data']);
  245. return resultArray(['data' => '编辑成功']);
  246. } else {
  247. return resultArray(['error' => $contractModel->getError()]);
  248. }
  249. }
  250. /**
  251. * 删除合同(逻辑删)
  252. * @author Michael_xu
  253. * @param
  254. * @return
  255. */
  256. public function delete()
  257. {
  258. $param = $this->param;
  259. $userInfo = $this->userInfo;
  260. $contractModel = model('Contract');
  261. $recordModel = new \app\admin\model\Record();
  262. $fileModel = new \app\admin\model\File();
  263. $actionRecordModel = new \app\admin\model\ActionRecord();
  264. if (!is_array($param['id'])) {
  265. $contract_id = [$param['id']];
  266. } else {
  267. $contract_id = $param['id'];
  268. }
  269. $delIds = [];
  270. $errorMessage = [];
  271. //数据权限判断
  272. $userModel = new \app\admin\model\User();
  273. $auth_user_ids = $userModel->getUserByPer('crm', 'contract', 'delete');
  274. $adminTypes = adminGroupTypes($userInfo['id']);
  275. foreach ($contract_id as $k=>$v) {
  276. $isDel = true;
  277. //数据详情
  278. $data = $contractModel->getDataById($v);
  279. if (!$data) {
  280. $isDel = false;
  281. $errorMessage[] = 'id为'.$v.'的合同删除失败,错误原因:'.$contractModel->getError();
  282. }
  283. if (!in_array($data['owner_user_id'],$auth_user_ids) && $isDel) {
  284. $isDel = false;
  285. $errorMessage[] = '名称为'.$data['name'].'的合同删除失败,错误原因:无权操作';
  286. }
  287. if ($data['check_status'] == 6 && !in_array(1,$adminTypes)) {
  288. $isDel = false;
  289. $errorMessage[] = '名称为'.$data['name'].'的合同删除失败,错误原因:当前合同已作废,非超级管理员,不可删除';
  290. }
  291. if (!in_array($data['check_status'], [4, 5]) && !in_array(1,$adminTypes)) {
  292. $isDel = false;
  293. $errorMessage[] = '名称为'.$data['name'].'的合同删除失败,错误原因:当前状态为审批中或已审批通过,不可删除';
  294. }
  295. # 检查合同下是否有回款
  296. if ($isDel) {
  297. if (db('crm_receivables')->where(['contract_id' => $v, 'check_status' => ['in', '0,1,2']])->value('receivables_id')) {
  298. $isDel = false;
  299. $errorMessage[] = '名称为'.$data['name'].'的合同删除失败,错误原因:当前合同下有回款,不可删除!';
  300. }
  301. }
  302. if ($isDel) {
  303. $delIds[] = $v;
  304. }
  305. }
  306. if ($delIds) {
  307. $data = $contractModel->delDatas($delIds);
  308. if (!$data) {
  309. return resultArray(['error' => $contractModel->getError()]);
  310. }
  311. //删除跟进记录
  312. $recordModel->delDataByTypes(6,$delIds);
  313. //删除关联附件
  314. $fileModel->delRFileByModule('crm_contract',$delIds);
  315. //删除关联操作记录
  316. $actionRecordModel->delDataById(['types'=>'crm_contract','action_id'=>$delIds]);
  317. // 删除回款记录
  318. \app\crm\model\ReceivablesPlan::where(['contract_id' => ['IN', $delIds]])->delete();
  319. actionLog($delIds,'','','');
  320. }
  321. if ($errorMessage) {
  322. return resultArray(['error' => $errorMessage]);
  323. } else {
  324. return resultArray(['data' => '删除成功']);
  325. }
  326. }
  327. /**
  328. * 合同转移
  329. * @author Michael_xu
  330. * @param owner_user_id 变更负责人
  331. * @param is_remove 1移出,2转为团队成员
  332. * @param type 权限 1只读2读写
  333. * @return
  334. */
  335. public function transfer()
  336. {
  337. $param = $this->param;
  338. $userInfo = $this->userInfo;
  339. $contractModel = model('Contract');
  340. $settingModel = model('Setting');
  341. $userModel = new \app\admin\model\User();
  342. $authIds = $userModel->getUserByPer(); //权限范围的user_id
  343. if (!$param['owner_user_id']) {
  344. return resultArray(['error' => '变更负责人不能为空']);
  345. }
  346. if (!$param['contract_id'] || !is_array($param['contract_id'])) {
  347. return resultArray(['error' => '请选择需要转移的合同']);
  348. }
  349. $is_remove = $param['is_remove'] == 2 ? 2 : 1;
  350. $type = $param['type'] == 2 ? 2 : 1;
  351. $data = [];
  352. $data['owner_user_id'] = $param['owner_user_id'];
  353. $data['update_time'] = time();
  354. $ownerUserName = $userModel->getUserNameById($param['owner_user_id']);
  355. $errorMessage = [];
  356. foreach ($param['contract_id'] as $contract_id) {
  357. $contractInfo = $contractModel->getDataById($contract_id);
  358. if (!$contractInfo) {
  359. $errorMessage[] = '名称:为《'.$contractInfo['name'].'》的合同转移失败,错误原因:数据不存在;';
  360. continue;
  361. }
  362. //权限判断
  363. if (!in_array($contractInfo['owner_user_id'],$authIds)) {
  364. $errorMessage[] = $contractInfo['name'].'"转移失败,错误原因:无权限;';
  365. continue;
  366. }
  367. // if (in_array($contractInfo['check_status'],['0','1'])) {
  368. // $errorMessage[] = $contractInfo['name'].'"转移失败,错误原因:待审或审批中,无法转移;';
  369. // continue;
  370. // }
  371. //团队成员
  372. teamUserId(
  373. 'crm_contract',
  374. $contract_id,
  375. $type,
  376. [$contractInfo['owner_user_id']],
  377. ($is_remove == 1) ? 1 : '',
  378. 0
  379. );
  380. $resContract = db('crm_contract')->where(['contract_id' => $contract_id])->update($data);
  381. if (!$resContract) {
  382. $errorMessage[] = $contractInfo['name'].'"转移失败,错误原因:数据出错;';
  383. continue;
  384. } else {
  385. # 处理负责人重复显示在团队成员中的bug
  386. $contractArray = [];
  387. $teamContract = db('crm_contract')->field(['owner_user_id', 'ro_user_id', 'rw_user_id'])->where('contract_id', $contract_id)->find();
  388. if (!empty($teamContract['ro_user_id'])) {
  389. $contractRo = arrayToString(array_diff(stringToArray($teamContract['ro_user_id']), [$teamContract['owner_user_id']]));
  390. $contractArray['ro_user_id'] = $contractRo;
  391. }
  392. if (!empty($teamContract['rw_user_id'])) {
  393. $contractRo = arrayToString(array_diff(stringToArray($teamContract['rw_user_id']), [$teamContract['owner_user_id']]));
  394. $contractArray['rw_user_id'] = $contractRo;
  395. }
  396. db('crm_contract')->where('contract_id', $contract_id)->update($contractArray);
  397. }
  398. //修改记录
  399. updateActionLog($userInfo['id'], 'crm_contract', $contract_id, '', '', '将合同转移给:'.$ownerUserName);
  400. }
  401. if (!$errorMessage) {
  402. return resultArray(['data' => '转移成功']);
  403. } else {
  404. return resultArray(['error' => $errorMessage]);
  405. }
  406. }
  407. /**
  408. * 合同审核
  409. * @author Michael_xu
  410. * @param
  411. * @return
  412. */
  413. public function check()
  414. {
  415. $param = $this->param;
  416. $userInfo = $this->userInfo;
  417. $user_id = $userInfo['id'];
  418. $contractModel = model('Contract');
  419. $examineStepModel = new \app\admin\model\ExamineStep();
  420. $examineRecordModel = new \app\admin\model\ExamineRecord();
  421. $examineFlowModel = new \app\admin\model\ExamineFlow();
  422. $customerModel = model('Customer');
  423. $contractData = [];
  424. $contractData['update_time'] = time();
  425. $contractData['check_status'] = 1; //0待审核,1审核通中,2审核通过,3审核未通过
  426. //权限判断
  427. if (!$examineStepModel->checkExamine($user_id, 'crm_contract', $param['id'])) {
  428. return resultArray(['error' => $examineStepModel->getError()]);
  429. }
  430. //审批主体详情
  431. $dataInfo = $contractModel->getDataById($param['id']);
  432. $flowInfo = $examineFlowModel->getDataById($dataInfo['flow_id']);
  433. $is_end = 0; // 1审批结束
  434. $status = $param['status'] ? 1 : 0; //1通过,0驳回
  435. $checkData = [];
  436. $checkData['check_user_id'] = $user_id;
  437. $checkData['types'] = 'crm_contract';
  438. $checkData['types_id'] = $param['id'];
  439. $checkData['check_time'] = time();
  440. $checkData['content'] = $param['content'];
  441. $checkData['flow_id'] = $dataInfo['flow_id'];
  442. $checkData['order_id'] = $dataInfo['order_id'] ? : 1;
  443. $checkData['status'] = $status;
  444. if ($status == 1) {
  445. if ($flowInfo['config'] == 1) {
  446. //固定流程
  447. //获取下一审批信息
  448. $nextStepData = $examineStepModel->nextStepUser($dataInfo['owner_user_id'], $dataInfo['flow_id'], 'crm_contract', $param['id'], $dataInfo['order_id'], $user_id);
  449. $next_user_ids = $nextStepData['next_user_ids'] ? : [];
  450. $contractData['order_id'] = $nextStepData['order_id'] ? : '';
  451. if (!$next_user_ids) {
  452. $is_end = 1;
  453. //审批结束
  454. $checkData['check_status'] = !empty($status) ? 2 : 3;
  455. $contractData['check_user_id'] = '';
  456. } else {
  457. //修改主体相关审批信息
  458. $contractData['check_user_id'] = arrayToString($next_user_ids);
  459. }
  460. } else {
  461. //自选流程
  462. $is_end = $param['is_end'] ? 1 : '';
  463. $check_user_id = $param['check_user_id'] ? : '';
  464. if ($is_end !== 1 && empty($check_user_id)) {
  465. return resultArray(['error' => '请选择下一审批人']);
  466. }
  467. $contractData['check_user_id'] = arrayToString($param['check_user_id']);
  468. }
  469. if ($is_end == 1) {
  470. $checkData['check_status'] = !empty($status) ? 2 : 3;
  471. $contractData['check_user_id'] = '';
  472. $contractData['check_status'] = 2;
  473. }
  474. } else {
  475. //审批驳回
  476. $is_end = 1;
  477. $contractData['check_status'] = 3;
  478. //将审批记录至为无效
  479. // $examineRecordModel->setEnd(['types' => 'crm_contract','types_id' => $param['id']]);
  480. }
  481. //已审批人ID
  482. $contractData['flow_user_id'] = stringToArray($dataInfo['flow_user_id']) ? arrayToString(array_merge(stringToArray($dataInfo['flow_user_id']),[$user_id])) : arrayToString([$user_id]);
  483. $resContract = db('crm_contract')->where(['contract_id' => $param['id']])->update($contractData);
  484. if ($resContract) {
  485. //审批记录
  486. $resRecord = $examineRecordModel->createData($checkData);
  487. //审核通过,相关客户状态改为已成交
  488. if ($is_end == 1 && !empty($status)) {
  489. // 审批通过消息告知负责人
  490. (new Message())->send(
  491. Message::CONTRACT_PASS,
  492. [
  493. 'title' => $dataInfo['name'],
  494. 'action_id' => $param['id']
  495. ],
  496. $dataInfo['owner_user_id']
  497. );
  498. $customerData = [];
  499. $customerData['deal_status'] = '已成交';
  500. $customerData['deal_time'] = time();
  501. $customerData['is_lock'] = 0;
  502. db('crm_customer')->where(['customer_id' => $dataInfo['customer_id']])->update($customerData);
  503. } else {
  504. if ($status) {
  505. //发送站内信
  506. // 通过未完成,发送消息给
  507. (new Message())->send(
  508. Message::CONTRACT_TO_DO,
  509. [
  510. 'from_user' => User::where(['id' => $dataInfo['owner_user_id']])->value('realname'),
  511. 'title' => $dataInfo['name'],
  512. 'action_id' => $param['id']
  513. ],
  514. stringToArray($contractData['check_user_id'])
  515. );
  516. } else {
  517. (new Message())->send(
  518. Message::CONTRACT_REJECT,
  519. [
  520. 'title' => $dataInfo['name'],
  521. 'action_id' => $param['id']
  522. ],
  523. $dataInfo['owner_user_id']
  524. );
  525. }
  526. }
  527. return resultArray(['data' => '审批成功']);
  528. } else {
  529. return resultArray(['error' => '审批失败,请重试!']);
  530. }
  531. }
  532. /**
  533. * 合同撤销审核
  534. * @author Michael_xu
  535. * @param
  536. * @return
  537. */
  538. public function revokeCheck()
  539. {
  540. $param = $this->param;
  541. $userInfo = $this->userInfo;
  542. $user_id = $userInfo['id'];
  543. $contractModel = model('Contract');
  544. $examineRecordModel = new \app\admin\model\ExamineRecord();
  545. $customerModel = model('Customer');
  546. $userModel = new \app\admin\model\User();
  547. $contractData = [];
  548. $contractData['update_time'] = time();
  549. $contractData['check_status'] = 0; //0待审核,1审核通中,2审核通过,3审核未通过
  550. //审批主体详情
  551. $dataInfo = $contractModel->getDataById($param['id']);
  552. //权限判断(负责人或管理员)
  553. if ($dataInfo['check_status'] == 2) {
  554. return resultArray(['error' => '已审批结束,不能撤销']);
  555. }
  556. if ($dataInfo['check_status'] == 4) {
  557. return resultArray(['error' => '无需撤销']);
  558. }
  559. $admin_user_ids = $userModel->getAdminId();
  560. if ($dataInfo['owner_user_id'] !== $user_id && !in_array($user_id, $admin_user_ids)) {
  561. return resultArray(['error' => '没有权限']);
  562. }
  563. $is_end = 0; // 1审批结束
  564. $status = 2; //1通过,0驳回, 2撤销
  565. $checkData = [];
  566. $checkData['check_user_id'] = $user_id;
  567. $checkData['types'] = 'crm_contract';
  568. $checkData['types_id'] = $param['id'];
  569. $checkData['check_time'] = time();
  570. $checkData['content'] = $param['content'];
  571. $checkData['flow_id'] = $dataInfo['flow_id'];
  572. $checkData['order_id'] = $dataInfo['order_id'];
  573. $checkData['status'] = $status;
  574. $contractData['check_status'] = 4;
  575. $contractData['check_user_id'] = '';
  576. $examineData['flow_user_id'] = '';
  577. $resContract = db('crm_contract')->where(['contract_id' => $param['id']])->update($contractData);
  578. if ($resContract) {
  579. //将审批记录至为无效
  580. // $examineRecordModel->setEnd(['types' => 'crm_contract','types_id' => $param['id']]);
  581. //审批记录
  582. $resRecord = $examineRecordModel->createData($checkData);
  583. return resultArray(['data' => '撤销成功']);
  584. } else {
  585. return resultArray(['error' => '撤销失败,请重试!']);
  586. }
  587. }
  588. /**
  589. * 相关产品
  590. * @author Michael_xu
  591. * @param
  592. * @return
  593. */
  594. public function product()
  595. {
  596. $productModel = model('Product');
  597. $contractModel = model('Contract');
  598. $userModel = new \app\admin\model\User();
  599. $param = $this->param;
  600. $userInfo = $this->userInfo;
  601. if (!$param['contract_id']) {
  602. return resultArray(['error' => '参数错误']);
  603. }
  604. $contractInfo = db('crm_contract')->where(['contract_id' => $param['contract_id']])->find();
  605. //判断权限
  606. $auth_user_ids = $userModel->getUserByPer('crm', 'contract', 'read');
  607. //读写权限
  608. $roPre = $userModel->rwPre($userInfo['id'], $contractInfo['ro_user_id'], $contractInfo['rw_user_id'], 'read');
  609. $rwPre = $userModel->rwPre($userInfo['id'], $contractInfo['ro_user_id'], $contractInfo['rw_user_id'], 'update');
  610. if (!in_array($contractInfo['owner_user_id'],$auth_user_ids) && !$roPre && !$rwPre) {
  611. header('Content-Type:application/json; charset=utf-8');
  612. exit(json_encode(['code'=>102,'error'=>'无权操作']));
  613. }
  614. $dataList = db('crm_contract_product')->where(['contract_id' => $param['contract_id']])->select();
  615. foreach ($dataList as $k=>$v) {
  616. $where = [];
  617. $where['product_id'] = $v['product_id'];
  618. $productInfo = db('crm_product')->where($where)->field('name,category_id')->find();
  619. $category_name = db('crm_product_category')->where(['category_id' => $productInfo['category_id']])->value('name');
  620. $dataList[$k]['name'] = $productInfo['name'] ? : '';
  621. $dataList[$k]['category_id_info'] = $category_name ? : '';
  622. }
  623. $list['list'] = $dataList ? : [];
  624. $list['total_price'] = $contractInfo['total_price'] ? : '0.00';
  625. $list['discount_rate'] = $contractInfo['discount_rate'] ? : '0.00';
  626. return resultArray(['data' => $list]);
  627. }
  628. /**
  629. * 导出
  630. * @author Michael_xu
  631. * @param
  632. * @return
  633. */
  634. public function excelExport()
  635. {
  636. $param = $this->param;
  637. $userInfo = $this->userInfo;
  638. $param['user_id'] = $userInfo['id'];
  639. if ($param['contract_id']) {
  640. $param['contract_id'] = ['condition' => 'in','value' => $param['contract_id'],'form_type' => 'text','name' => ''];
  641. $param['is_excel'] = 1;
  642. }
  643. $excelModel = new \app\admin\model\Excel();
  644. // 导出的字段列表
  645. $fieldModel = new \app\admin\model\Field();
  646. $field_list = $fieldModel->getIndexFieldConfig('crm_contract', $userInfo['id']);
  647. // 文件名
  648. $file_name = '5kcrm_contract_'.date('Ymd');
  649. $model = model('Contract');
  650. $temp_file = $param['temp_file'];
  651. unset($param['temp_file']);
  652. $page = $param['page'] ?: 1;
  653. unset($param['page']);
  654. unset($param['export_queue_index']);
  655. return $excelModel->batchExportCsv($file_name, $temp_file, $field_list, $page, function($page, $limit) use ($model, $param, $field_list) {
  656. $param['page'] = $page;
  657. $param['limit'] = $limit;
  658. $data = $model->getDataList($param);
  659. $data['list'] = $model->exportHandle($data['list'], $field_list, 'contract');
  660. return $data;
  661. });
  662. }
  663. /**
  664. * 修改已审核过的合同为作废状态
  665. * @author ZFH
  666. * @param
  667. * @return
  668. */
  669. public function cancel()
  670. {
  671. $param = $this->param;
  672. $userInfo = $this->userInfo;
  673. $userModel = new \app\admin\model\User();
  674. $adminTypes = adminGroupTypes($userInfo['id']);
  675. if (!$param['contract_id']) {
  676. return resultArray(['error' => '参数错误']);
  677. }
  678. //判断权限
  679. $auth_user_ids = $userModel->getUserByPer('crm', 'contract', 'cancel');
  680. $contractInfo = db('crm_contract')->where(['contract_id' => $param['contract_id']])->find();
  681. if(!$contractInfo){
  682. return resultArray(['error' => '数据不存在']);
  683. }
  684. if (!in_array($contractInfo['owner_user_id'],$auth_user_ids)) {
  685. header('Content-Type:application/json; charset=utf-8');
  686. exit(json_encode(['code'=>102,'error'=>'无权操作']));
  687. }
  688. if($contractInfo['check_status'] != 2){
  689. return resultArray(['error' => '未审核通过的合同不可作废,请选择撤销或删除']);
  690. }
  691. $data['check_status'] = 6; //变更合同状态为作废
  692. if(db('crm_contract')->where(['contract_id'=>$param['contract_id']])->update($data)){
  693. return resultArray(['data' => '作废成功']);
  694. }else{
  695. return resultArray(['error' => '失败,请重试']);
  696. }
  697. }
  698. /**
  699. * 系统信息
  700. *
  701. * @return \think\response\Json
  702. * @throws \think\db\exception\DataNotFoundException
  703. * @throws \think\db\exception\ModelNotFoundException
  704. * @throws \think\exception\DbException
  705. */
  706. public function system()
  707. {
  708. if (empty($this->param['id'])) return resultArray(['error' => '参数错误!']);
  709. $contractModel = new \app\crm\model\Contract();
  710. $data = $contractModel->getSystemInfo($this->param['id']);
  711. return resultArray(['data' => $data]);
  712. }
  713. /**
  714. * table标签栏数量
  715. *
  716. * @return \think\response\Json
  717. * @throws \think\db\exception\DataNotFoundException
  718. * @throws \think\db\exception\ModelNotFoundException
  719. * @throws \think\exception\DbException
  720. */
  721. public function count()
  722. {
  723. if (empty($this->param['contract_id'])) return resultArray(['error' => '参数错误!']);
  724. $contractId = $this->param['contract_id'];
  725. $contract = Db::name('crm_contract')->field(['owner_user_id', 'ro_user_id', 'rw_user_id'])->where('contract_id', $contractId)->find();
  726. # 团队
  727. $contract['ro_user_id'] = explode(',', trim($contract['ro_user_id'], ','));
  728. $contract['rw_user_id'] = explode(',', trim($contract['rw_user_id'], ','));
  729. $contract['owner_user_id'] = [$contract['owner_user_id']];
  730. $teamCount = array_filter(array_unique(array_merge($contract['ro_user_id'], $contract['rw_user_id'], $contract['owner_user_id'])));
  731. # 产品
  732. $productCount = Db::name('crm_contract_product')->where('contract_id', $contractId)->count();
  733. # 回款
  734. $receivablesCount = Db::name('crm_receivables')->where('contract_id', $contractId)->count();
  735. # 回访
  736. $visitCount = Db::name('crm_visit')->where('contract_id', $contractId)->count();
  737. # 附件
  738. $fileCount = Db::name('crm_contract_file')->alias('contract')->join('__ADMIN_FILE__ file', 'file.file_id = contract.file_id', 'LEFT')->where('contract_id', $contractId)->count();
  739. $data = [
  740. 'productCount' => $productCount,
  741. 'memberCount' => count($teamCount),
  742. 'receivablesCount' => $receivablesCount,
  743. 'returnVisitCount' => $visitCount,
  744. 'fileCount' => $fileCount,
  745. ];
  746. return resultArray(['data' => $data]);
  747. }
  748. /**
  749. * 拷贝合同
  750. *
  751. * @return \think\response\Json
  752. * @throws \think\db\exception\DataNotFoundException
  753. * @throws \think\db\exception\ModelNotFoundException
  754. * @throws \think\exception\DbException
  755. */
  756. public function copy()
  757. {
  758. if (empty($this->param['contract_id'])) return resultArray(['error' => '参数错误!']);
  759. $contractModel = new \app\crm\model\Contract();
  760. $contractId = $this->param['contract_id'];
  761. $userId = $this->userInfo['id'];
  762. if (!$contractModel->copy($contractId, $userId)) return resultArray(['error' => '操作失败!']);
  763. return resultArray(['data' => '操作成功!']);
  764. }
  765. }