Contract.php 36KB

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