Contract.php 36KB

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