123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  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'], $userInfo['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. $dataInfo = $contractModel->where('contract_id',['in',$delIds])->select();
  308. if ($delIds) {
  309. $data = $contractModel->delDatas($delIds);
  310. if (!$data) {
  311. return resultArray(['error' => $contractModel->getError()]);
  312. }
  313. //删除跟进记录
  314. $recordModel->delDataByTypes(6,$delIds);
  315. //删除关联附件
  316. $fileModel->delRFileByModule('crm_contract',$delIds);
  317. //删除关联操作记录
  318. $actionRecordModel->delDataById(['types'=>'crm_contract','action_id'=>$delIds]);
  319. // 删除回款记录
  320. \app\crm\model\ReceivablesPlan::where(['contract_id' => ['IN', $delIds]])->delete();
  321. $userInfo = $this->userInfo;
  322. foreach ($dataInfo as $k => $v) {
  323. RecordActionLog($userInfo['id'], 'crm_contacts', 'delete', $v['name'], '', '', '删除了合同:' . $v['name']);
  324. }
  325. }
  326. if ($errorMessage) {
  327. return resultArray(['error' => $errorMessage]);
  328. } else {
  329. return resultArray(['data' => '删除成功']);
  330. }
  331. }
  332. /**
  333. * 合同转移
  334. * @author Michael_xu
  335. * @param owner_user_id 变更负责人
  336. * @param is_remove 1移出,2转为团队成员
  337. * @param type 权限 1只读2读写
  338. * @return
  339. */
  340. public function transfer()
  341. {
  342. $param = $this->param;
  343. $userInfo = $this->userInfo;
  344. $contractModel = model('Contract');
  345. $settingModel = model('Setting');
  346. $userModel = new \app\admin\model\User();
  347. $authIds = $userModel->getUserByPer(); //权限范围的user_id
  348. if (!$param['owner_user_id']) {
  349. return resultArray(['error' => '变更负责人不能为空']);
  350. }
  351. if (!$param['contract_id'] || !is_array($param['contract_id'])) {
  352. return resultArray(['error' => '请选择需要转移的合同']);
  353. }
  354. $is_remove = $param['is_remove'] == 2 ? 2 : 1;
  355. $type = $param['type'] == 2 ? 2 : 1;
  356. $data = [];
  357. $data['owner_user_id'] = $param['owner_user_id'];
  358. $data['update_time'] = time();
  359. $ownerUserName = $userModel->getUserNameById($param['owner_user_id']);
  360. $errorMessage = [];
  361. foreach ($param['contract_id'] as $contract_id) {
  362. $contractInfo = $contractModel->getDataById($contract_id);
  363. if (!$contractInfo) {
  364. $errorMessage[] = '名称:为《'.$contractInfo['name'].'》的合同转移失败,错误原因:数据不存在;';
  365. continue;
  366. }
  367. //权限判断
  368. if (!in_array($contractInfo['owner_user_id'],$authIds)) {
  369. $errorMessage[] = $contractInfo['name'].'"转移失败,错误原因:无权限;';
  370. continue;
  371. }
  372. // if (in_array($contractInfo['check_status'],['0','1'])) {
  373. // $errorMessage[] = $contractInfo['name'].'"转移失败,错误原因:待审或审批中,无法转移;';
  374. // continue;
  375. // }
  376. //团队成员
  377. teamUserId(
  378. 'crm_contract',
  379. $contract_id,
  380. $type,
  381. [$contractInfo['owner_user_id']],
  382. ($is_remove == 1) ? 1 : '',
  383. 0
  384. );
  385. $resContract = db('crm_contract')->where(['contract_id' => $contract_id])->update($data);
  386. if (!$resContract) {
  387. $errorMessage[] = $contractInfo['name'].'"转移失败,错误原因:数据出错;';
  388. continue;
  389. } else {
  390. # 处理负责人重复显示在团队成员中的bug
  391. $contractArray = [];
  392. $teamContract = db('crm_contract')->field(['owner_user_id', 'ro_user_id', 'rw_user_id'])->where('contract_id', $contract_id)->find();
  393. if (!empty($teamContract['ro_user_id'])) {
  394. $contractRo = arrayToString(array_diff(stringToArray($teamContract['ro_user_id']), [$teamContract['owner_user_id']]));
  395. $contractArray['ro_user_id'] = $contractRo;
  396. }
  397. if (!empty($teamContract['rw_user_id'])) {
  398. $contractRo = arrayToString(array_diff(stringToArray($teamContract['rw_user_id']), [$teamContract['owner_user_id']]));
  399. $contractArray['rw_user_id'] = $contractRo;
  400. }
  401. db('crm_contract')->where('contract_id', $contract_id)->update($contractArray);
  402. }
  403. //修改记录
  404. updateActionLog($userInfo['id'], 'crm_contract', $contract_id, '', '', '将合同转移给:'.$ownerUserName);
  405. RecordActionLog($userInfo['id'], 'crm_contract', 'transfer',$contractInfo['name'], '','','将合同:'.$contractInfo['name'].'转移给:' . $ownerUserName);
  406. }
  407. if (!$errorMessage) {
  408. return resultArray(['data' => '转移成功']);
  409. } else {
  410. return resultArray(['error' => $errorMessage]);
  411. }
  412. }
  413. /**
  414. * 合同审核
  415. * @author Michael_xu
  416. * @param
  417. * @return
  418. */
  419. public function check()
  420. {
  421. $param = $this->param;
  422. $userInfo = $this->userInfo;
  423. $user_id = $userInfo['id'];
  424. $contractModel = model('Contract');
  425. $examineStepModel = new \app\admin\model\ExamineStep();
  426. $examineRecordModel = new \app\admin\model\ExamineRecord();
  427. $examineFlowModel = new \app\admin\model\ExamineFlow();
  428. $customerModel = model('Customer');
  429. $contractData = [];
  430. $contractData['update_time'] = time();
  431. $contractData['check_status'] = 1; //0待审核,1审核通中,2审核通过,3审核未通过
  432. //权限判断
  433. if (!$examineStepModel->checkExamine($user_id, 'crm_contract', $param['id'])) {
  434. return resultArray(['error' => $examineStepModel->getError()]);
  435. }
  436. //审批主体详情
  437. $dataInfo = $contractModel->getDataById($param['id']);
  438. $flowInfo = $examineFlowModel->getDataById($dataInfo['flow_id']);
  439. $is_end = 0; // 1审批结束
  440. $status = $param['status'] ? 1 : 0; //1通过,0驳回
  441. $checkData = [];
  442. $checkData['check_user_id'] = $user_id;
  443. $checkData['types'] = 'crm_contract';
  444. $checkData['types_id'] = $param['id'];
  445. $checkData['check_time'] = time();
  446. $checkData['content'] = $param['content'];
  447. $checkData['flow_id'] = $dataInfo['flow_id'];
  448. $checkData['order_id'] = $dataInfo['order_id'] ? : 1;
  449. $checkData['status'] = $status;
  450. if ($status == 1) {
  451. if ($flowInfo['config'] == 1) {
  452. //固定流程
  453. //获取下一审批信息
  454. $nextStepData = $examineStepModel->nextStepUser($dataInfo['owner_user_id'], $dataInfo['flow_id'], 'crm_contract', $param['id'], $dataInfo['order_id'], $user_id);
  455. $next_user_ids = $nextStepData['next_user_ids'] ? : [];
  456. $contractData['order_id'] = $nextStepData['order_id'] ? : '';
  457. if (!$next_user_ids) {
  458. $is_end = 1;
  459. //审批结束
  460. $checkData['check_status'] = !empty($status) ? 2 : 3;
  461. $contractData['check_user_id'] = '';
  462. } else {
  463. //修改主体相关审批信息
  464. $contractData['check_user_id'] = arrayToString($next_user_ids);
  465. }
  466. } else {
  467. //自选流程
  468. $is_end = $param['is_end'] ? 1 : '';
  469. $check_user_id = $param['check_user_id'] ? : '';
  470. if ($is_end !== 1 && empty($check_user_id)) {
  471. return resultArray(['error' => '请选择下一审批人']);
  472. }
  473. $contractData['check_user_id'] = arrayToString($param['check_user_id']);
  474. }
  475. if ($is_end == 1) {
  476. $checkData['check_status'] = !empty($status) ? 2 : 3;
  477. $contractData['check_user_id'] = '';
  478. $contractData['check_status'] = 2;
  479. }
  480. } else {
  481. //审批驳回
  482. $is_end = 1;
  483. $contractData['check_status'] = 3;
  484. //将审批记录至为无效
  485. // $examineRecordModel->setEnd(['types' => 'crm_contract','types_id' => $param['id']]);
  486. }
  487. //已审批人ID
  488. $contractData['flow_user_id'] = stringToArray($dataInfo['flow_user_id']) ? arrayToString(array_merge(stringToArray($dataInfo['flow_user_id']),[$user_id])) : arrayToString([$user_id]);
  489. $resContract = db('crm_contract')->where(['contract_id' => $param['id']])->update($contractData);
  490. if ($resContract) {
  491. //审批记录
  492. $resRecord = $examineRecordModel->createData($checkData);
  493. //审核通过,相关客户状态改为已成交
  494. if ($is_end == 1 && !empty($status)) {
  495. // 审批通过消息告知负责人
  496. (new Message())->send(
  497. Message::CONTRACT_PASS,
  498. [
  499. 'title' => $dataInfo['name'],
  500. 'action_id' => $param['id']
  501. ],
  502. $dataInfo['owner_user_id']
  503. );
  504. $customerData = [];
  505. $customerData['deal_status'] = '已成交';
  506. $customerData['deal_time'] = time();
  507. $customerData['is_lock'] = 0;
  508. db('crm_customer')->where(['customer_id' => $dataInfo['customer_id']])->update($customerData);
  509. } else {
  510. if ($status) {
  511. //发送站内信
  512. // 通过未完成,发送消息给
  513. (new Message())->send(
  514. Message::CONTRACT_TO_DO,
  515. [
  516. 'from_user' => User::where(['id' => $dataInfo['owner_user_id']])->value('realname'),
  517. 'title' => $dataInfo['name'],
  518. 'action_id' => $param['id']
  519. ],
  520. stringToArray($contractData['check_user_id'])
  521. );
  522. } else {
  523. (new Message())->send(
  524. Message::CONTRACT_REJECT,
  525. [
  526. 'title' => $dataInfo['name'],
  527. 'action_id' => $param['id']
  528. ],
  529. $dataInfo['owner_user_id']
  530. );
  531. }
  532. }
  533. return resultArray(['data' => '审批成功']);
  534. } else {
  535. return resultArray(['error' => '审批失败,请重试!']);
  536. }
  537. }
  538. /**
  539. * 合同撤销审核
  540. * @author Michael_xu
  541. * @param
  542. * @return
  543. */
  544. public function revokeCheck()
  545. {
  546. $param = $this->param;
  547. $userInfo = $this->userInfo;
  548. $user_id = $userInfo['id'];
  549. $contractModel = model('Contract');
  550. $examineRecordModel = new \app\admin\model\ExamineRecord();
  551. $customerModel = model('Customer');
  552. $userModel = new \app\admin\model\User();
  553. $contractData = [];
  554. $contractData['update_time'] = time();
  555. $contractData['check_status'] = 0; //0待审核,1审核通中,2审核通过,3审核未通过
  556. //审批主体详情
  557. $dataInfo = $contractModel->getDataById($param['id']);
  558. //权限判断(负责人或管理员)
  559. if ($dataInfo['check_status'] == 2) {
  560. return resultArray(['error' => '已审批结束,不能撤销']);
  561. }
  562. if ($dataInfo['check_status'] == 4) {
  563. return resultArray(['error' => '无需撤销']);
  564. }
  565. $admin_user_ids = $userModel->getAdminId();
  566. if ($dataInfo['owner_user_id'] !== $user_id && !in_array($user_id, $admin_user_ids)) {
  567. return resultArray(['error' => '没有权限']);
  568. }
  569. $is_end = 0; // 1审批结束
  570. $status = 2; //1通过,0驳回, 2撤销
  571. $checkData = [];
  572. $checkData['check_user_id'] = $user_id;
  573. $checkData['types'] = 'crm_contract';
  574. $checkData['types_id'] = $param['id'];
  575. $checkData['check_time'] = time();
  576. $checkData['content'] = $param['content'];
  577. $checkData['flow_id'] = $dataInfo['flow_id'];
  578. $checkData['order_id'] = $dataInfo['order_id'];
  579. $checkData['status'] = $status;
  580. $contractData['check_status'] = 4;
  581. $contractData['check_user_id'] = '';
  582. $examineData['flow_user_id'] = '';
  583. $resContract = db('crm_contract')->where(['contract_id' => $param['id']])->update($contractData);
  584. if ($resContract) {
  585. //将审批记录至为无效
  586. // $examineRecordModel->setEnd(['types' => 'crm_contract','types_id' => $param['id']]);
  587. //审批记录
  588. $resRecord = $examineRecordModel->createData($checkData);
  589. return resultArray(['data' => '撤销成功']);
  590. } else {
  591. return resultArray(['error' => '撤销失败,请重试!']);
  592. }
  593. }
  594. /**
  595. * 相关产品
  596. * @author Michael_xu
  597. * @param
  598. * @return
  599. */
  600. public function product()
  601. {
  602. $productModel = model('Product');
  603. $contractModel = model('Contract');
  604. $userModel = new \app\admin\model\User();
  605. $param = $this->param;
  606. $userInfo = $this->userInfo;
  607. if (!$param['contract_id']) {
  608. return resultArray(['error' => '参数错误']);
  609. }
  610. $contractInfo = db('crm_contract')->where(['contract_id' => $param['contract_id']])->find();
  611. //判断权限
  612. $auth_user_ids = $userModel->getUserByPer('crm', 'contract', 'read');
  613. //读写权限
  614. $roPre = $userModel->rwPre($userInfo['id'], $contractInfo['ro_user_id'], $contractInfo['rw_user_id'], 'read');
  615. $rwPre = $userModel->rwPre($userInfo['id'], $contractInfo['ro_user_id'], $contractInfo['rw_user_id'], 'update');
  616. if (!in_array($contractInfo['owner_user_id'],$auth_user_ids) && !$roPre && !$rwPre) {
  617. header('Content-Type:application/json; charset=utf-8');
  618. exit(json_encode(['code'=>102,'error'=>'无权操作']));
  619. }
  620. $dataList = db('crm_contract_product')->where(['contract_id' => $param['contract_id']])->select();
  621. foreach ($dataList as $k=>$v) {
  622. $where = [];
  623. $where['product_id'] = $v['product_id'];
  624. $productInfo = db('crm_product')->where($where)->field('name,category_id')->find();
  625. $category_name = db('crm_product_category')->where(['category_id' => $productInfo['category_id']])->value('name');
  626. $dataList[$k]['name'] = $productInfo['name'] ? : '';
  627. $dataList[$k]['category_id_info'] = $category_name ? : '';
  628. }
  629. $list['list'] = $dataList ? : [];
  630. $list['total_price'] = $contractInfo['total_price'] ? : '0.00';
  631. $list['discount_rate'] = $contractInfo['discount_rate'] ? : '0.00';
  632. return resultArray(['data' => $list]);
  633. }
  634. /**
  635. * 导出
  636. * @author Michael_xu
  637. * @param
  638. * @return
  639. */
  640. public function excelExport()
  641. {
  642. $param = $this->param;
  643. $userInfo = $this->userInfo;
  644. $param['user_id'] = $userInfo['id'];
  645. $action_name = '导出全部';
  646. if ($param['contract_id']) {
  647. $param['contract_id'] = ['condition' => 'in','value' => $param['contract_id'],'form_type' => 'text','name' => ''];
  648. $param['is_excel'] = 1;
  649. $action_name='导出选中';
  650. }
  651. $excelModel = new \app\admin\model\Excel();
  652. // 导出的字段列表
  653. $fieldModel = new \app\admin\model\Field();
  654. $field_list = $fieldModel->getIndexFieldConfig('crm_contract', $userInfo['id']);
  655. // 文件名
  656. $file_name = '5kcrm_contract_'.date('Ymd');
  657. $model = model('Contract');
  658. $temp_file = $param['temp_file'];
  659. unset($param['temp_file']);
  660. $page = $param['page'] ?: 1;
  661. unset($param['page']);
  662. unset($param['export_queue_index']);
  663. RecordActionLog($userInfo['id'],'crm_contract','excelexport',$action_name,'','','导出合同');
  664. return $excelModel->batchExportCsv($file_name, $temp_file, $field_list, $page, function($page, $limit) use ($model, $param, $field_list) {
  665. $param['page'] = $page;
  666. $param['limit'] = $limit;
  667. $data = $model->getDataList($param);
  668. $data['list'] = $model->exportHandle($data['list'], $field_list, 'contract');
  669. return $data;
  670. });
  671. }
  672. /**
  673. * 修改已审核过的合同为作废状态
  674. * @author ZFH
  675. * @param
  676. * @return
  677. */
  678. public function cancel()
  679. {
  680. $param = $this->param;
  681. $userInfo = $this->userInfo;
  682. $userModel = new \app\admin\model\User();
  683. $adminTypes = adminGroupTypes($userInfo['id']);
  684. if (!$param['contract_id']) {
  685. return resultArray(['error' => '参数错误']);
  686. }
  687. //判断权限
  688. $auth_user_ids = $userModel->getUserByPer('crm', 'contract', 'cancel');
  689. $contractInfo = db('crm_contract')->where(['contract_id' => $param['contract_id']])->find();
  690. if(!$contractInfo){
  691. return resultArray(['error' => '数据不存在']);
  692. }
  693. if (!in_array($contractInfo['owner_user_id'],$auth_user_ids)) {
  694. header('Content-Type:application/json; charset=utf-8');
  695. exit(json_encode(['code'=>102,'error'=>'无权操作']));
  696. }
  697. if($contractInfo['check_status'] != 2){
  698. return resultArray(['error' => '未审核通过的合同不可作废,请选择撤销或删除']);
  699. }
  700. $data['check_status'] = 6; //变更合同状态为作废
  701. if(db('crm_contract')->where(['contract_id'=>$param['contract_id']])->update($data)){
  702. return resultArray(['data' => '作废成功']);
  703. }else{
  704. return resultArray(['error' => '失败,请重试']);
  705. }
  706. }
  707. /**
  708. * 系统信息
  709. *
  710. * @return \think\response\Json
  711. * @throws \think\db\exception\DataNotFoundException
  712. * @throws \think\db\exception\ModelNotFoundException
  713. * @throws \think\exception\DbException
  714. */
  715. public function system()
  716. {
  717. if (empty($this->param['id'])) return resultArray(['error' => '参数错误!']);
  718. $contractModel = new \app\crm\model\Contract();
  719. $data = $contractModel->getSystemInfo($this->param['id']);
  720. return resultArray(['data' => $data]);
  721. }
  722. /**
  723. * table标签栏数量
  724. *
  725. * @return \think\response\Json
  726. * @throws \think\db\exception\DataNotFoundException
  727. * @throws \think\db\exception\ModelNotFoundException
  728. * @throws \think\exception\DbException
  729. */
  730. public function count()
  731. {
  732. if (empty($this->param['contract_id'])) return resultArray(['error' => '参数错误!']);
  733. $contractId = $this->param['contract_id'];
  734. $userInfo = $this->userInfo;
  735. $contract = Db::name('crm_contract')->field(['owner_user_id', 'ro_user_id', 'rw_user_id'])->where('contract_id', $contractId)->find();
  736. # 团队
  737. $contract['ro_user_id'] = explode(',', trim($contract['ro_user_id'], ','));
  738. $contract['rw_user_id'] = explode(',', trim($contract['rw_user_id'], ','));
  739. $contract['owner_user_id'] = [$contract['owner_user_id']];
  740. $teamCount = array_filter(array_unique(array_merge($contract['ro_user_id'], $contract['rw_user_id'], $contract['owner_user_id'])));
  741. # 查询合同和产品的关联数据
  742. $productIds = Db::name('crm_contract_product')->where('contract_id', $contractId)->column('product_id');
  743. # 产品
  744. $productAuth = $this->getProductSearchWhere();
  745. $productCount = Db::name('crm_product')->whereIn('product_id', $productIds)->whereIn('owner_user_id', $productAuth)->count();
  746. # 回款
  747. $receivablesAuth = $this->getReceivablesSearchWhere();
  748. $receivablesCount = Db::name('crm_receivables')->where('contract_id', $contractId)->whereIn('owner_user_id', $receivablesAuth)->count();
  749. # 回访
  750. $visitAuth = $this->getVisitSearchWhere($userInfo['id']);
  751. $visitCount = Db::name('crm_visit')->where('contract_id', $contractId)->where($visitAuth)->count();
  752. # 附件
  753. $fileCount = Db::name('crm_contract_file')->alias('contract')->join('__ADMIN_FILE__ file', 'file.file_id = contract.file_id', 'LEFT')->where('contract_id', $contractId)->count();
  754. $data = [
  755. 'productCount' => $productCount,
  756. 'memberCount' => count($teamCount),
  757. 'receivablesCount' => $receivablesCount,
  758. 'returnVisitCount' => $visitCount,
  759. 'fileCount' => $fileCount,
  760. ];
  761. return resultArray(['data' => $data]);
  762. }
  763. /**
  764. * 拷贝合同
  765. *
  766. * @return \think\response\Json
  767. * @throws \think\db\exception\DataNotFoundException
  768. * @throws \think\db\exception\ModelNotFoundException
  769. * @throws \think\exception\DbException
  770. */
  771. public function copy()
  772. {
  773. if (empty($this->param['contract_id'])) return resultArray(['error' => '参数错误!']);
  774. $contractModel = new \app\crm\model\Contract();
  775. $contractId = $this->param['contract_id'];
  776. $userId = $this->userInfo['id'];
  777. if (!$contractModel->copy($contractId, $userId)) return resultArray(['error' => '操作失败!']);
  778. return resultArray(['data' => '操作成功!']);
  779. }
  780. }