Contract.php 34KB

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