123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | Description: 合同
  4. // +----------------------------------------------------------------------
  5. // | Author: Michael_xu | gengxiaoxu@5kcrm.com
  6. // +----------------------------------------------------------------------
  7. namespace app\crm\model;
  8. use think\Db;
  9. use app\admin\model\Common;
  10. use app\admin\model\Message;
  11. use think\Request;
  12. use think\Validate;
  13. class Contract extends Common
  14. {
  15. /**
  16. * 为了数据库的整洁,同时又不影响Model和Controller的名称
  17. * 我们约定每个模块的数据表都加上相同的前缀,比如CRM模块用crm作为数据表前缀
  18. */
  19. protected $name = 'crm_contract';
  20. protected $createTime = 'create_time';
  21. protected $updateTime = 'update_time';
  22. protected $autoWriteTimestamp = true;
  23. private $statusArr = ['0'=>'待审核','1'=>'审核中','2'=>'审核通过','3'=>'已拒绝','4'=>'已撤回','5'=>'未提交','6'=>'已作废'];
  24. /**
  25. * [getDataList 合同list]
  26. *
  27. * @param $request
  28. * @return array
  29. * @throws \think\db\exception\DataNotFoundException
  30. * @throws \think\db\exception\ModelNotFoundException
  31. * @throws \think\exception\DbException
  32. */
  33. public function getDataList($request)
  34. {
  35. $userModel = new \app\admin\model\User();
  36. $structureModel = new \app\admin\model\Structure();
  37. $fieldModel = new \app\admin\model\Field();
  38. //回款
  39. $receivablesModel = new \app\crm\model\Receivables();
  40. $search = $request['search'];
  41. $user_id = $request['user_id'];
  42. $scene_id = (int)$request['scene_id'];
  43. $order_field = $request['order_field'];
  44. $order_type = $request['order_type'];
  45. $is_excel = $request['is_excel']; //导出
  46. $getCount = $request['getCount'];
  47. unset($request['scene_id']);
  48. unset($request['search']);
  49. unset($request['user_id']);
  50. unset($request['order_field']);
  51. unset($request['order_type']);
  52. unset($request['is_excel']);
  53. unset($request['getCount']);
  54. $request = $this->fmtRequest( $request );
  55. $requestMap = $request['map'] ? : [];
  56. $sceneModel = new \app\admin\model\Scene();
  57. # getCount是代办事项传来的参数,代办事项不需要使用场景
  58. $sceneMap = [];
  59. if (empty($getCount)) {
  60. if ($scene_id) {
  61. //自定义场景
  62. $sceneMap = $sceneModel->getDataById($scene_id, $user_id, 'contract') ? : [];
  63. } else {
  64. //默认场景
  65. $sceneMap = $sceneModel->getDefaultData('crm_contract', $user_id) ? : [];
  66. }
  67. }
  68. if ($search) {
  69. //普通筛选
  70. $sceneMap['name'] = ['condition' => 'contains','value' => $search,'form_type' => 'text','name' => '合同名称'];
  71. }
  72. $partMap = [];
  73. //优先级:普通筛选>高级筛选>场景
  74. if ($sceneMap['contract.ro_user_id'] && $sceneMap['contract.rw_user_id']) {
  75. //相关团队查询
  76. $map = $requestMap;
  77. $partMap = function($query) use ($sceneMap){
  78. $query->where('contract.ro_user_id',array('like','%,'.$sceneMap['ro_user_id'].',%'))
  79. ->whereOr('contract.rw_user_id',array('like','%,'.$sceneMap['rw_user_id'].',%'));
  80. };
  81. } else {
  82. $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
  83. }
  84. //高级筛选
  85. $map = where_arr($map, 'crm', 'contract', 'index');
  86. $order = ['contract.update_time desc'];
  87. $authMap = [];
  88. if (!$partMap) {
  89. $a = 'index';
  90. if ($is_excel) $a = 'excelExport';
  91. $auth_user_ids = $userModel->getUserByPer('crm', 'contract', $a);
  92. if (isset($map['contract.owner_user_id']) && $map['contract.owner_user_id'][0] != 'like') {
  93. if (!is_array($map['contract.owner_user_id'][1])) {
  94. $map['contract.owner_user_id'][1] = [$map['contract.owner_user_id'][1]];
  95. }
  96. if (in_array($map['contract.owner_user_id'][0], ['neq', 'notin'])) {
  97. $auth_user_ids = array_diff($auth_user_ids, $map['contract.owner_user_id'][1]) ? : []; //取差集
  98. } else {
  99. $auth_user_ids = array_intersect($map['contract.owner_user_id'][1], $auth_user_ids) ? : []; //取交集
  100. }
  101. unset($map['contract.owner_user_id']);
  102. $auth_user_ids = array_merge(array_unique(array_filter($auth_user_ids))) ? : ['-1'];
  103. $authMap['contract.owner_user_id'] = array('in',$auth_user_ids);
  104. } else {
  105. $authMapData = [];
  106. $authMapData['auth_user_ids'] = $auth_user_ids;
  107. $authMapData['user_id'] = $user_id;
  108. $authMap = function($query) use ($authMapData){
  109. $query->where('contract.owner_user_id',array('in',$authMapData['auth_user_ids']))
  110. ->whereOr('contract.ro_user_id',array('like','%,'.$authMapData['user_id'].',%'))
  111. ->whereOr('contract.rw_user_id',array('like','%,'.$authMapData['user_id'].',%'));
  112. };
  113. }
  114. }
  115. //合同签约人 | 与高级筛选冲突,加一个is_array判断
  116. if ($map['contract.order_user_id'] && !is_array($map['contract.order_user_id'][1])) {
  117. $map['contract.order_user_id'] = ['like','%,'.$map['contract.order_user_id'][1].',%'];
  118. }
  119. //列表展示字段
  120. $indexField = $fieldModel->getIndexField('crm_contract', $user_id, 1) ? : array('name');
  121. //人员类型
  122. $userField = $fieldModel->getFieldByFormType('crm_contract', 'user');
  123. $structureField = $fieldModel->getFieldByFormType('crm_contract', 'structure'); //部门类型
  124. $datetimeField = $fieldModel->getFieldByFormType('crm_contract', 'datetime'); //日期时间类型
  125. //排序
  126. if ($order_type && $order_field) {
  127. $order = $fieldModel->getOrderByFormtype('crm_contract','contract',$order_field,$order_type);
  128. } else {
  129. $order = 'contract.update_time desc';
  130. }
  131. $readAuthIds = $userModel->getUserByPer('crm', 'contract', 'read');
  132. $updateAuthIds = $userModel->getUserByPer('crm', 'contract', 'update');
  133. $deleteAuthIds = $userModel->getUserByPer('crm', 'contract', 'delete');
  134. $dataCount = db('crm_contract')
  135. ->alias('contract')
  136. ->join('__CRM_CUSTOMER__ customer','contract.customer_id = customer.customer_id','LEFT')
  137. ->join('__CRM_BUSINESS__ business','contract.business_id = business.business_id','LEFT')
  138. ->join('__CRM_CONTACTS__ contacts','contract.contacts_id = contacts.contacts_id','LEFT')
  139. // ->join('__CRM_RECEIVABLES_PLAN__ plan','contract.contract_id = plan.contract_id','LEFT')
  140. ->where($map)->where($partMap)->where($authMap)->group('contract.contract_id')->count('contract.contract_id');
  141. if (!empty($getCount) && $getCount == 1) {
  142. $data['dataCount'] = !empty($dataCount) ? $dataCount : 0;
  143. $contractMoney = $this->getContractMoney($map, $partMap, $authMap);
  144. $receivedMoney = $this->getReceivablesMoney($map, $partMap, $authMap);
  145. $data['extraData']['money'] = [
  146. 'contractMoney' => $this->getContractMoney($map, $partMap, $authMap), # 合同总金额
  147. 'receivedMoney' => $this->getReceivablesMoney($map, $partMap, $authMap), # 回款总金额
  148. 'unReceivedMoney' => sprintf("%.2f", $contractMoney - $receivedMoney) # 未回款
  149. ];
  150. return $data;
  151. }
  152. foreach ($indexField AS $kk => $vv) {
  153. if ($vv == 'contract.customer_name') unset($indexField[(int)$kk]);
  154. if ($vv == 'contract.business_name') unset($indexField[(int)$kk]);
  155. }
  156. $list = db('crm_contract')
  157. ->alias('contract')
  158. ->join('__CRM_CUSTOMER__ customer','contract.customer_id = customer.customer_id','LEFT')
  159. ->join('__CRM_BUSINESS__ business','contract.business_id = business.business_id','LEFT')
  160. ->join('__CRM_CONTACTS__ contacts','contract.contacts_id = contacts.contacts_id','LEFT')
  161. // ->join('__CRM_RECEIVABLES_PLAN__ plan','contract.contract_id = plan.contract_id','LEFT')
  162. ->join('CrmReceivables receivables','receivables.contract_id = contract.contract_id AND receivables.check_status = 2','LEFT')
  163. ->where($map)
  164. ->where($partMap)
  165. ->where($authMap)
  166. ->limit($request['offset'], $request['length'])
  167. ->field(array_merge($indexField, [
  168. 'customer.name' => 'customer_name',
  169. 'business.name' => 'business_name',
  170. 'contacts.name' => 'contacts_name',
  171. 'ifnull(SUM(receivables.money), 0)' => 'done_money',
  172. '(contract.money - ifnull(SUM(receivables.money), 0))' => 'un_money',
  173. ]))
  174. ->orderRaw($order)
  175. ->group('contract.contract_id')
  176. ->select();
  177. foreach ($list as $k=>$v) {
  178. $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
  179. $list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
  180. $list[$k]['create_user_name'] = !empty($list[$k]['create_user_id_info']['realname']) ? $list[$k]['create_user_id_info']['realname'] : '';
  181. $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
  182. foreach ($userField as $key => $val) {
  183. $usernameField = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
  184. $list[$k][$val] = implode($usernameField, ',');
  185. }
  186. foreach ($structureField as $key => $val) {
  187. $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
  188. $list[$k][$val] = implode($structureNameField, ',');
  189. }
  190. foreach ($datetimeField as $key => $val) {
  191. $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
  192. }
  193. $list[$k]['business_id_info']['business_id'] = $v['business_id'];
  194. $list[$k]['business_id_info']['name'] = $v['business_name'];
  195. $list[$k]['customer_id_info']['customer_id'] = $v['customer_id'];
  196. $list[$k]['customer_id_info']['name'] = $v['customer_name'];
  197. $list[$k]['contacts_id_info']['contacts_id'] = $v['contacts_id'];
  198. $list[$k]['contacts_id_info']['name'] = $v['contacts_name'];
  199. $moneyInfo = [];
  200. $moneyInfo = $receivablesModel->getMoneyByContractId($v['contract_id']);
  201. $list[$k]['unMoney'] = $moneyInfo['doneMoney'] ? : '0.00';
  202. if ($list[$k]['un_money'] < 0) $list[$k]['un_money'] = '0.00';
  203. $planInfo = [];
  204. $planInfo = db('crm_receivables_plan')->where(['contract_id' => $v['contract_id']])->find();
  205. $list[$k]['receivables_id'] = $planInfo['receivables_id'] ? : '';
  206. $list[$k]['remind_date'] = $planInfo['remind_date'] ? : '';
  207. $list[$k]['return_date'] = $planInfo['return_date'] ? : '';
  208. //权限
  209. $roPre = $userModel->rwPre($user_id, $v['ro_user_id'], $v['rw_user_id'], 'read');
  210. $rwPre = $userModel->rwPre($user_id, $v['ro_user_id'], $v['rw_user_id'], 'update');
  211. $permission = [];
  212. $is_read = 0;
  213. $is_update = 0;
  214. $is_delete = 0;
  215. if (in_array($v['owner_user_id'],$readAuthIds) || $roPre || $rwPre) $is_read = 1;
  216. if (in_array($v['owner_user_id'],$updateAuthIds) || $rwPre) $is_update = 1;
  217. if (in_array($v['owner_user_id'],$deleteAuthIds)) $is_delete = 1;
  218. $permission['is_read'] = $is_read;
  219. $permission['is_update'] = $is_update;
  220. $permission['is_delete'] = $is_delete;
  221. $list[$k]['permission'] = $permission;
  222. # 下次联系时间
  223. $list[$k]['next_time'] = !empty($v['next_time']) ? date('Y-m-d H:i:s', $v['next_time']) : null;
  224. # 日期
  225. $list[$k]['create_time'] = !empty($v['create_time']) ? date('Y-m-d H:i:s', $v['create_time']) : null;
  226. $list[$k]['update_time'] = !empty($v['update_time']) ? date('Y-m-d H:i:s', $v['update_time']) : null;
  227. $list[$k]['last_time'] = !empty($v['last_time']) ? date('Y-m-d H:i:s', $v['last_time']) : null;
  228. $list[$k]['order_date'] = ($v['order_date']!='0000-00-00') ? $v['order_date'] : null;
  229. $list[$k]['start_time'] = ($v['start_time']!='0000-00-00') ? $v['start_time'] : null;
  230. $list[$k]['end_time'] = ($v['end_time']!='0000-00-00') ? $v['end_time'] : null;
  231. # 签约人姓名
  232. $orderNames = Db::name('admin_user')->whereIn('id', trim($v['order_user_id'], ','))->column('realname');
  233. $list[$k]['order_user_name'] = implode(',', $orderNames);
  234. }
  235. $data = [];
  236. $data['list'] = $list;
  237. $data['dataCount'] = $dataCount ? : 0;
  238. $contractMoney = $this->getContractMoney($map, $partMap, $authMap);
  239. $receivedMoney = $this->getReceivablesMoney($map, $partMap, $authMap);
  240. $data['extraData']['money'] = [
  241. 'contractMoney' => $this->getContractMoney($map, $partMap, $authMap), # 合同总金额
  242. 'receivedMoney' => $this->getReceivablesMoney($map, $partMap, $authMap), # 回款总金额
  243. 'unReceivedMoney' => sprintf("%.2f", $contractMoney - $receivedMoney) # 未回款
  244. ];
  245. return $data;
  246. }
  247. /**
  248. * 获取回款总金额
  249. *
  250. * @param $map
  251. * @param $partMap
  252. * @param $authMap
  253. * @return float|string
  254. */
  255. private function getReceivablesMoney($map, $partMap, $authMap)
  256. {
  257. $contractIds = db('crm_contract')
  258. ->alias('contract')
  259. ->join('__CRM_CUSTOMER__ customer','contract.customer_id = customer.customer_id','LEFT')
  260. ->join('__CRM_BUSINESS__ business','contract.business_id = business.business_id','LEFT')
  261. ->join('__CRM_CONTACTS__ contacts','contract.contacts_id = contacts.contacts_id','LEFT')
  262. ->where('check_status', 2)->where($map)->where($partMap)->where($authMap)->column('contract.contract_id');
  263. $contractIds = array_unique($contractIds);
  264. $money = db('crm_receivables')->where('check_status', 2)->whereIn('contract_id', $contractIds)->sum('money');
  265. return !empty($money) ? sprintf("%.2f", $money) : 0.00;
  266. }
  267. /**
  268. * 获取合同总金额
  269. *
  270. * @param $map
  271. * @param $partMap
  272. * @param $authMap
  273. * @return float|string
  274. */
  275. private function getContractMoney($map, $partMap, $authMap)
  276. {
  277. $money = db('crm_contract')
  278. ->alias('contract')
  279. ->join('__CRM_CUSTOMER__ customer','contract.customer_id = customer.customer_id','LEFT')
  280. ->join('__CRM_BUSINESS__ business','contract.business_id = business.business_id','LEFT')
  281. ->join('__CRM_CONTACTS__ contacts','contract.contacts_id = contacts.contacts_id','LEFT')
  282. ->where('check_status', 2)->where($map)->where($partMap)->where($authMap)->sum('contract.money');
  283. return !empty($money) ? sprintf("%.2f", $money) : 0.00;
  284. }
  285. //根据IDs获取数组
  286. public function getDataByStr($idstr)
  287. {
  288. $idArr = stringToArray($idstr);
  289. if (!$idArr) {
  290. return [];
  291. }
  292. $list = Db::name('CrmContract')->where(['contract_id' => ['in',$idArr]])->select();
  293. return $list;
  294. }
  295. /**
  296. * 创建合同信息
  297. * @author Michael_xu
  298. * @param
  299. * @return
  300. */
  301. public function createData($param)
  302. {
  303. $fieldModel = new \app\admin\model\Field();
  304. $userModel = new \app\admin\model\User();
  305. $productModel = new \app\crm\model\Product();
  306. // 自动验证
  307. $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
  308. $validate = new Validate($validateArr['rule'], $validateArr['message']);
  309. $result = $validate->check($param);
  310. if (!$result) {
  311. $this->error = $validate->getError();
  312. return false;
  313. }
  314. # 处理下次联系时间
  315. if (!empty($param['next_time'])) $param['next_time'] = strtotime($param['next_time']);
  316. //处理部门、员工、附件、多选类型字段
  317. $arrFieldAtt = $fieldModel->getArrayField('crm_contract');
  318. foreach ($arrFieldAtt as $k=>$v) {
  319. $param[$v] = arrayToString($param[$v]);
  320. }
  321. # 下单时间
  322. $param['order_date'] = !empty($param['order_date']) ? $param['order_date'] : date('Y-m-d H:i:s', time());
  323. if (empty($param['start_time'])) $param['start_time'] = null;
  324. if (empty($param['end_time'])) $param['end_time'] = null;
  325. $this->startTrans();
  326. if ($this->data($param)->allowField(true)->save()) {
  327. if ($param['product']) {
  328. //产品数据处理
  329. $resProduct = $productModel->createObject('crm_contract', $param, $this->contract_id);
  330. if ($resProduct == false) {
  331. $this->error = '产品添加失败。' . $productModel->getError();
  332. $this->rollback();
  333. return false;
  334. }
  335. }
  336. //站内信
  337. $send_user_id = stringToArray($param['check_user_id']);
  338. if ($send_user_id && empty($param['check_status'])) {
  339. (new Message())->send(
  340. Message::CONTRACT_TO_DO,
  341. [
  342. 'title' => $param['name'],
  343. 'action_id' => $this->contract_id
  344. ],
  345. $send_user_id
  346. );
  347. }
  348. $data = [];
  349. $data['contract_id'] = $this->contract_id;
  350. $this->commit();
  351. //修改记录
  352. updateActionLog($param['create_user_id'], 'crm_contract', $this->contract_id, '', '', '创建了合同');
  353. # 添加活动记录
  354. Db::name('crm_activity')->insert([
  355. 'type' => 2,
  356. 'activity_type' => 6,
  357. 'activity_type_id' => $data['contract_id'],
  358. 'content' => $param['name'],
  359. 'create_user_id' => $param['create_user_id'],
  360. 'update_time' => time(),
  361. 'create_time' => time(),
  362. 'customer_ids' => $param['customer_id'],
  363. 'contacts_ids' => $param['contacts_id'],
  364. 'business_ids' => $param['business_id']
  365. ]);
  366. return $data;
  367. } else {
  368. $this->error = '添加失败';
  369. $this->rollback();
  370. return false;
  371. }
  372. }
  373. /**
  374. * 编辑合同主表信息
  375. * @author Michael_xu
  376. * @param
  377. * @return
  378. */
  379. public function updateDataById($param, $contract_id = '')
  380. {
  381. $productModel = new \app\crm\model\Product();
  382. $userModel = new \app\admin\model\User();
  383. $dataInfo = db('crm_contract')->where(['contract_id' => $contract_id])->find();
  384. //过滤不能修改的字段
  385. $unUpdateField = ['create_user_id','is_deleted','delete_time'];
  386. foreach ($unUpdateField as $v) {
  387. unset($param[$v]);
  388. }
  389. $param['contract_id'] = $contract_id;
  390. $fieldModel = new \app\admin\model\Field();
  391. // 自动验证
  392. $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
  393. $validate = new Validate($validateArr['rule'], $validateArr['message']);
  394. $result = $validate->check($param);
  395. if (!$result) {
  396. $this->error = $validate->getError();
  397. return false;
  398. }
  399. # 处理下次联系时间
  400. if (!empty($param['next_time'])) $param['next_time'] = strtotime($param['next_time']);
  401. $param['order_date'] = !empty($param['order_date']) ? $param['order_date'] : date('Y-m-d H:i:s', time());
  402. if (empty($param['start_time'])) $param['start_time'] = null;
  403. if (empty($param['end_time'])) $param['end_time'] = null;
  404. //处理部门、员工、附件、多选类型字段
  405. $arrFieldAtt = $fieldModel->getArrayField('crm_contract');
  406. foreach ($arrFieldAtt as $k=>$v) {
  407. $param[$v] = arrayToString($param[$v]);
  408. }
  409. if ($this->update($param, ['contract_id' => $contract_id], true)) {
  410. //产品数据处理
  411. $resProduct = $productModel->createObject('crm_contract', $param, $contract_id);
  412. //修改记录
  413. updateActionLog($param['user_id'], 'crm_contract', $contract_id, $dataInfo, $param);
  414. //站内信
  415. $send_user_id = stringToArray($param['check_user_id']);
  416. if ($send_user_id && empty($param['check_status'])) {
  417. (new Message())->send(
  418. Message::CONTRACT_TO_DO,
  419. [
  420. 'title' => $param['name'],
  421. 'action_id' => $contract_id
  422. ],
  423. $send_user_id
  424. );
  425. }
  426. $data = [];
  427. $data['contract_id'] = $contract_id;
  428. return $data;
  429. } else {
  430. $this->error = '编辑失败';
  431. return false;
  432. }
  433. }
  434. /**
  435. * 合同数据
  436. *
  437. * @param string $id
  438. * @return Common|array|bool|\PDOStatement|string|\think\Model|null
  439. * @throws \think\db\exception\DataNotFoundException
  440. * @throws \think\db\exception\ModelNotFoundException
  441. * @throws \think\exception\DbException
  442. */
  443. public function getDataById($id = '')
  444. {
  445. $receivablesModel = new \app\crm\model\Receivables();
  446. $userModel = new \app\admin\model\User();
  447. $map['contract_id'] = $id;
  448. $dataInfo = db('crm_contract')->where($map)->find();
  449. if (!$dataInfo) {
  450. $this->error = '暂无此数据';
  451. return false;
  452. }
  453. $dataInfo['create_user_info'] = isset($dataInfo['create_user_id']) ? $userModel->getUserById($dataInfo['create_user_id']) : [];
  454. $dataInfo['owner_user_id_info'] = isset($dataInfo['owner_user_id']) ? $userModel->getUserById($dataInfo['owner_user_id']) : [];
  455. $dataInfo['create_user_name'] = !empty($dataInfo['create_user_info']['realname']) ? $dataInfo['create_user_info']['realname'] : '';
  456. $dataInfo['owner_user_name'] = !empty($dataInfo['owner_user_id_info']['realname']) ? $dataInfo['owner_user_id_info']['realname'] : '';
  457. $dataInfo['business_id_info'] = $dataInfo['business_id'] ? db('crm_business')->where(['business_id' => $dataInfo['business_id']])->field('business_id,name')->find() : [];
  458. $dataInfo['business_name'] = !empty($dataInfo['business_id_info']['name']) ? $dataInfo['business_id_info']['name'] : '';
  459. $dataInfo['customer_id_info'] = $dataInfo['customer_id'] ? db('crm_customer')->where(['customer_id' => $dataInfo['customer_id']])->field('customer_id,name')->find() : [];
  460. $dataInfo['customer_name'] = !empty($dataInfo['customer_id_info']['name']) ? $dataInfo['customer_id_info']['name'] : '';
  461. //回款金额
  462. $receivablesMoney = $receivablesModel->getMoneyByContractId($id);
  463. $dataInfo['receivablesMoney'] = $receivablesMoney ? : [];
  464. # 签约人姓名
  465. $orderNames = Db::name('admin_user')->whereIn('id', trim($dataInfo['order_user_id'], ','))->column('realname');
  466. $dataInfo['order_user_name'] = implode(',', $orderNames);
  467. # 处理时间根式
  468. $fieldModel = new \app\admin\model\Field();
  469. $datetimeField = $fieldModel->getFieldByFormType('crm_contract', 'datetime'); //日期时间类型
  470. foreach ($datetimeField as $key => $val) {
  471. $dataInfo[$val] = !empty($dataInfo[$val]) ? date('Y-m-d H:i:s', $dataInfo[$val]) : null;
  472. }
  473. $dataInfo['next_time'] = !empty($dataInfo['next_time']) ? date('Y-m-d H:i:s', $dataInfo['next_time']) : null;
  474. $dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;
  475. $dataInfo['update_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
  476. $dataInfo['last_time'] = !empty($dataInfo['last_time']) ? date('Y-m-d H:i:s', $dataInfo['last_time']) : null;
  477. return $dataInfo;
  478. }
  479. /**
  480. * [合同转移]
  481. * @author Michael_xu
  482. * @param ids 合同ID数组
  483. * @param owner_user_id 变更负责人
  484. * @param is_remove 1移出,2转为团队成员
  485. * @return
  486. */
  487. public function transferDataById($ids, $owner_user_id, $type = 1, $is_remove)
  488. {
  489. $settingModel = new \app\crm\model\Setting();
  490. $errorMessage = [];
  491. foreach ($ids as $id) {
  492. $contractInfo = [];
  493. $contractInfo = db('crm_contract')->where(['contract_id' => $id])->find();
  494. // if (in_array($contractInfo['check_status'],['0','1'])) {
  495. // $errorMessage[] = '合同:'.$contractInfo['name'].'"转移失败,错误原因:审批中,无法转移;';
  496. // continue;
  497. // }
  498. //团队成员
  499. $teamData = [];
  500. $teamData['type'] = $type; //权限 1只读2读写
  501. $teamData['user_id'] = [$contractInfo['owner_user_id']]; //协作人
  502. $teamData['types'] = 'crm_contract'; //类型
  503. $teamData['types_id'] = $id; //类型ID
  504. $teamData['is_del'] = ($is_remove == 1) ? 1 : '';
  505. $res = $settingModel->createTeamData($teamData);
  506. $data = [];
  507. $data['owner_user_id'] = $owner_user_id;
  508. $data['update_time'] = time();
  509. if (!db('crm_contract')->where(['contract_id' => $id])->update($data)) {
  510. $errorMessage[] = '合同:'.$contractInfo['name'].'"转移失败,错误原因:数据出错;';
  511. continue;
  512. } else {
  513. $contractArray = [];
  514. $teamContract = db('crm_contract')->field(['owner_user_id', 'ro_user_id', 'rw_user_id'])->where('contract_id', $id)->find();
  515. if (!empty($teamContract['ro_user_id'])) {
  516. $contractRo = arrayToString(array_diff(stringToArray($teamContract['ro_user_id']), [$teamContract['owner_user_id']]));
  517. $contractArray['ro_user_id'] = $contractRo;
  518. }
  519. if (!empty($teamContract['rw_user_id'])) {
  520. $contractRo = arrayToString(array_diff(stringToArray($teamContract['rw_user_id']), [$teamContract['owner_user_id']]));
  521. $contractArray['rw_user_id'] = $contractRo;
  522. }
  523. db('crm_contract')->where('contract_id', $id)->update($contractArray);
  524. }
  525. }
  526. if ($errorMessage) {
  527. return $errorMessage;
  528. } else {
  529. return true;
  530. }
  531. }
  532. /**
  533. * 根据对象ID 获取该年各个月合同金额
  534. * @return [year] [哪一年]
  535. * @return [owner_user_id] [哪个员工]
  536. * @return [start_time] [开始时间]
  537. * @return [end_time] [结束时间]
  538. */
  539. public function getDataByUserId($param)
  540. {
  541. if ($param['obj_type']) {
  542. if ($param['obj_type'] == 1) { //部门
  543. $userModel = new \app\admin\model\User();
  544. $str = $userModel->getSubUserByStr($param['obj_id'], 1) ? : ['-1'];
  545. $map['owner_user_id'] = array('in',$str);
  546. } else { //员工
  547. $map['owner_user_id'] = $param['obj_id'];
  548. }
  549. }
  550. //审核状态
  551. $start = date('Y-m-d',$param['start_time']);
  552. $stop = date('Y-m-d',$param['end_time']);
  553. $map['check_status'] = 2;
  554. $data = $this->where($map)->where(['order_date' => ['between',[$start, $stop]]])->sum('money');
  555. return $data;
  556. }
  557. /**
  558. * 获取系统信息
  559. *
  560. * @param $id
  561. * @return array
  562. * @throws \think\db\exception\DataNotFoundException
  563. * @throws \think\db\exception\ModelNotFoundException
  564. * @throws \think\exception\DbException
  565. */
  566. public function getSystemInfo($id)
  567. {
  568. # 合同
  569. $business = Db::name('crm_contract')->where('contract_id', $id)->find();
  570. # 创建人
  571. $realname = Db::name('admin_user')->where('id', $business['create_user_id'])->value('realname');
  572. # 跟进时间
  573. $followTime = Db::name('crm_activity')->where(['type' => 1, 'activity_type' => 6, 'activity_type_id' => $id])->order('activity_id', 'desc')->value('update_time');
  574. # 回款
  575. $receivablesModel = new Receivables();
  576. $receivables = $receivablesModel->getMoneyByContractId($id);
  577. return [
  578. 'create_user_name' => $realname,
  579. 'create_time' => date('Y-m-d H:i:s', $business['create_time']),
  580. 'update_time' => date('Y-m-d H:i:s', $business['update_time']),
  581. 'follow_time' => !empty($followTime) ? date('Y-m-d H:i:s', $followTime) : '',
  582. 'done_money' => $receivables['doneMoney'],
  583. 'un_money' => $receivables['unMoney']
  584. ];
  585. }
  586. /**
  587. * 拷贝合同
  588. *
  589. * @param $contractId
  590. * @param $userId
  591. * @return bool
  592. * @throws \think\db\exception\DataNotFoundException
  593. * @throws \think\db\exception\ModelNotFoundException
  594. * @throws \think\exception\DbException
  595. */
  596. public function copy($contractId, $userId)
  597. {
  598. $targetContract = Db::name('crm_contract')->where('contract_id', $contractId)->find();
  599. $targetProduct = Db::name('crm_contract_product')->where('contract_id', $contractId)->select();
  600. if (empty($targetContract['contract_id'])) return false;
  601. # 删除主键
  602. unset($targetContract['contract_id']);
  603. Db::startTrans();
  604. try{
  605. # 合同数据
  606. $targetContract['num'] = 'WKCrm#contract#num#' . date('YmdHis');
  607. $targetContract['name'] = 'WKCrm#contract#name#'. date('YmdHis');
  608. $targetContract['create_user_id'] = $userId;
  609. $targetContract['owner_user_id'] = $userId;
  610. $targetContract['create_time'] = time();
  611. $targetContract['update_time'] = time();
  612. $targetContract['is_visit'] = 2;
  613. $targetContract['expire_remind'] = 1;
  614. if (in_array($targetContract['check_status'], [1, 2, 3, 4])) {
  615. $checkUserId = trim($targetContract['check_user_id'], ',');
  616. $flowUserId = trim($targetContract['flow_user_id'], ',');
  617. $symbol = !empty($checkUserId) ? ',' : '';
  618. $targetContract['check_user_id'] = ',' . $checkUserId . $symbol . $flowUserId . ',';
  619. $targetContract['check_status'] = 0;
  620. }
  621. Db::name('crm_contract')->insert($targetContract);
  622. $newContractId = Db::name('crm_contract')->getLastInsID();
  623. # 产品数据
  624. $productData = [];
  625. foreach ($targetProduct AS $key => $value) {
  626. $productData[] = [
  627. 'contract_id' => $newContractId,
  628. 'product_id' => $value['product_id'],
  629. 'price' => $value['price'],
  630. 'sales_price' => $value['sales_price'],
  631. 'num' => $value['num'],
  632. 'discount' => $value['discount'],
  633. 'subtotal' => $value['subtotal'],
  634. 'unit' => $value['unit']
  635. ];
  636. }
  637. if (!empty($productData)) Db::name('crm_contract_product')->insertAll($productData);
  638. Db::commit();
  639. return true;
  640. } catch (\Exception $e) {
  641. Db::rollback();
  642. return false;
  643. }
  644. }
  645. }