Contract.php 35KB

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