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