Contract.php 36KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  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. // 处理日期(date)类型
  367. $dateField = $fieldModel->getFieldByFormType('crm_contract', 'date');
  368. if (!empty($dateField)) {
  369. foreach ($param AS $key => $value) {
  370. if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
  371. }
  372. }
  373. # 下单时间
  374. $param['order_date'] = !empty($param['order_date']) ? $param['order_date'] : date('Y-m-d H:i:s', time());
  375. if (empty($param['start_time'])) $param['start_time'] = null;
  376. if (empty($param['end_time'])) $param['end_time'] = null;
  377. $this->startTrans();
  378. if ($this->data($param)->allowField(true)->save()) {
  379. if ($param['product']) {
  380. //产品数据处理
  381. $resProduct = $productModel->createObject('crm_contract', $param, $this->contract_id);
  382. if ($resProduct == false) {
  383. $this->error = '产品添加失败。' . $productModel->getError();
  384. $this->rollback();
  385. return false;
  386. }
  387. }
  388. //站内信
  389. $send_user_id = stringToArray($param['check_user_id']);
  390. if ($send_user_id && empty($param['check_status'])) {
  391. (new Message())->send(
  392. Message::CONTRACT_TO_DO,
  393. [
  394. 'title' => $param['name'],
  395. 'action_id' => $this->contract_id
  396. ],
  397. $send_user_id
  398. );
  399. }
  400. $data = [];
  401. $data['contract_id'] = $this->contract_id;
  402. $this->commit();
  403. //修改记录
  404. updateActionLog($param['create_user_id'], 'crm_contract', $this->contract_id, '', '', '创建了合同');
  405. RecordActionLog($param['create_user_id'],'crm_contract','save',$param['name'],'','','新增了合同'.$param['name']);
  406. # 添加活动记录
  407. Db::name('crm_activity')->insert([
  408. 'type' => 2,
  409. 'activity_type' => 6,
  410. 'activity_type_id' => $data['contract_id'],
  411. 'content' => $param['name'],
  412. 'create_user_id' => $param['create_user_id'],
  413. 'update_time' => time(),
  414. 'create_time' => time(),
  415. 'customer_ids' => ',' . $param['customer_id'] . ',',
  416. 'contacts_ids' => ',' . $param['contacts_id'] . ',',
  417. 'business_ids' => ',' . $param['business_id'] . ','
  418. ]);
  419. # 创建待办事项的关联数据
  420. $checkUserIds = db('crm_contract')->where('contract_id', $data['contract_id'])->value('check_user_id');
  421. $checkUserIdArray = stringToArray($checkUserIds);
  422. $dealtData = [];
  423. foreach ($checkUserIdArray AS $kk => $vv) {
  424. $dealtData[] = [
  425. 'types' => 'crm_contract',
  426. 'types_id' => $data['contract_id'],
  427. 'user_id' => $vv
  428. ];
  429. }
  430. if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData);
  431. return $data;
  432. } else {
  433. $this->error = '添加失败';
  434. $this->rollback();
  435. return false;
  436. }
  437. }
  438. /**
  439. * 编辑合同主表信息
  440. * @author Michael_xu
  441. * @param
  442. * @return
  443. */
  444. public function updateDataById($param, $contract_id = '')
  445. {
  446. $productModel = new \app\crm\model\Product();
  447. $userModel = new \app\admin\model\User();
  448. $dataInfo = db('crm_contract')->where(['contract_id' => $contract_id])->find();
  449. //过滤不能修改的字段
  450. $unUpdateField = ['create_user_id','is_deleted','delete_time'];
  451. foreach ($unUpdateField as $v) {
  452. unset($param[$v]);
  453. }
  454. $param['contract_id'] = $contract_id;
  455. $fieldModel = new \app\admin\model\Field();
  456. // 自动验证
  457. // $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
  458. $validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
  459. $validate = new Validate($validateArr['rule'], $validateArr['message']);
  460. $result = $validate->check($param);
  461. if (!$result) {
  462. $this->error = $validate->getError();
  463. return false;
  464. }
  465. # 处理下次联系时间
  466. if (!empty($param['next_time'])) $param['next_time'] = strtotime($param['next_time']);
  467. $param['order_date'] = !empty($param['order_date']) ? $param['order_date'] : date('Y-m-d H:i:s', time());
  468. if (empty($param['start_time'])) $param['start_time'] = null;
  469. if (empty($param['end_time'])) $param['end_time'] = null;
  470. // 处理部门、员工、附件、多选类型字段
  471. $arrFieldAtt = $fieldModel->getArrayField('crm_contract');
  472. foreach ($arrFieldAtt as $k=>$v) {
  473. if (isset($param[$v])) $param[$v] = arrayToString($param[$v]);
  474. }
  475. // 处理日期(date)类型
  476. $dateField = $fieldModel->getFieldByFormType('crm_contract', 'date');
  477. if (!empty($dateField)) {
  478. foreach ($param AS $key => $value) {
  479. if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
  480. }
  481. }
  482. if ($this->update($param, ['contract_id' => $contract_id], true)) {
  483. //产品数据处理
  484. $resProduct = $productModel->createObject('crm_contract', $param, $contract_id);
  485. //修改记录
  486. updateActionLog($param['user_id'], 'crm_contract', $contract_id, $dataInfo, $param);
  487. RecordActionLog($param['user_id'], 'crm_contract', 'update',$dataInfo['name'], $dataInfo, $param);
  488. //站内信
  489. $send_user_id = stringToArray($param['check_user_id']);
  490. if ($send_user_id && empty($param['check_status'])) {
  491. (new Message())->send(
  492. Message::CONTRACT_TO_DO,
  493. [
  494. 'title' => $param['name'],
  495. 'action_id' => $contract_id
  496. ],
  497. $send_user_id
  498. );
  499. }
  500. $data = [];
  501. $data['contract_id'] = $contract_id;
  502. # 删除待办事项的关联数据
  503. db('crm_dealt_relation')->where(['types' => ['eq', 'crm_contract'], 'types_id' => ['eq', $data['contract_id']]])->delete();
  504. # 创建待办事项的关联数据
  505. $checkUserIds = db('crm_contract')->where('contract_id', $data['contract_id'])->value('check_user_id');
  506. $checkUserIdArray = stringToArray($checkUserIds);
  507. $dealtData = [];
  508. foreach ($checkUserIdArray AS $kk => $vv) {
  509. $dealtData[] = [
  510. 'types' => 'crm_contract',
  511. 'types_id' => $data['contract_id'],
  512. 'user_id' => $vv
  513. ];
  514. }
  515. if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData);
  516. return $data;
  517. } else {
  518. $this->error = '编辑失败';
  519. return false;
  520. }
  521. }
  522. /**
  523. * 合同数据
  524. *
  525. * @param string $id
  526. * @return Common|array|bool|\PDOStatement|string|\think\Model|null
  527. * @throws \think\db\exception\DataNotFoundException
  528. * @throws \think\db\exception\ModelNotFoundException
  529. * @throws \think\exception\DbException
  530. */
  531. public function getDataById($id = '', $userId = 0)
  532. {
  533. $receivablesModel = new \app\crm\model\Receivables();
  534. $userModel = new \app\admin\model\User();
  535. $map['contract_id'] = $id;
  536. $dataInfo = db('crm_contract')->where($map)->find();
  537. if (!$dataInfo) {
  538. $this->error = '暂无此数据';
  539. return false;
  540. }
  541. $dataInfo['create_user_info'] = isset($dataInfo['create_user_id']) ? $userModel->getUserById($dataInfo['create_user_id']) : [];
  542. $dataInfo['owner_user_id_info'] = isset($dataInfo['owner_user_id']) ? $userModel->getUserById($dataInfo['owner_user_id']) : [];
  543. $dataInfo['create_user_name'] = !empty($dataInfo['create_user_info']['realname']) ? $dataInfo['create_user_info']['realname'] : '';
  544. $dataInfo['owner_user_name'] = !empty($dataInfo['owner_user_id_info']['realname']) ? $dataInfo['owner_user_id_info']['realname'] : '';
  545. $dataInfo['business_id_info'] = $dataInfo['business_id'] ? db('crm_business')->where(['business_id' => $dataInfo['business_id']])->field('business_id,name')->find() : [];
  546. $dataInfo['business_name'] = !empty($dataInfo['business_id_info']['name']) ? $dataInfo['business_id_info']['name'] : '';
  547. $dataInfo['customer_id_info'] = $dataInfo['customer_id'] ? db('crm_customer')->where(['customer_id' => $dataInfo['customer_id']])->field('customer_id,name')->find() : [];
  548. $dataInfo['customer_name'] = !empty($dataInfo['customer_id_info']['name']) ? $dataInfo['customer_id_info']['name'] : '';
  549. //回款金额
  550. $receivablesMoney = $receivablesModel->getMoneyByContractId($id);
  551. $dataInfo['receivablesMoney'] = $receivablesMoney ? : [];
  552. # 签约人姓名
  553. $orderNames = Db::name('admin_user')->whereIn('id', trim($dataInfo['order_user_id'], ','))->column('realname');
  554. $dataInfo['order_user_name'] = implode(',', $orderNames);
  555. # 处理时间根式
  556. $fieldModel = new \app\admin\model\Field();
  557. $datetimeField = $fieldModel->getFieldByFormType('crm_contract', 'datetime'); //日期时间类型
  558. foreach ($datetimeField as $key => $val) {
  559. $dataInfo[$val] = !empty($dataInfo[$val]) ? date('Y-m-d H:i:s', $dataInfo[$val]) : null;
  560. }
  561. $dataInfo['next_time'] = !empty($dataInfo['next_time']) ? date('Y-m-d H:i:s', $dataInfo['next_time']) : null;
  562. $dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;
  563. $dataInfo['update_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
  564. $dataInfo['last_time'] = !empty($dataInfo['last_time']) ? date('Y-m-d H:i:s', $dataInfo['last_time']) : null;
  565. // 字段授权
  566. if (!empty($userId)) {
  567. $grantData = getFieldGrantData($userId);
  568. $userLevel = isSuperAdministrators($userId);
  569. foreach ($dataInfo AS $key => $value) {
  570. if (!$userLevel && !empty($grantData['crm_contract'])) {
  571. $status = getFieldGrantStatus($key, $grantData['crm_contract']);
  572. # 查看权限
  573. if ($status['read'] == 0) unset($dataInfo[$key]);
  574. }
  575. }
  576. if (!$userLevel && !empty($grantData['crm_contract'])) {
  577. # 客户名称
  578. $customerStatus = getFieldGrantStatus('customer_id', $grantData['crm_contract']);
  579. if ($customerStatus['read'] == 0) {
  580. $dataInfo['customer_name'] = '';
  581. $dataInfo['customer_id_info'] = [];
  582. }
  583. # 回款金额
  584. $doneMoneyStatus = getFieldGrantStatus('done_money', $grantData['crm_contract']);
  585. if ($doneMoneyStatus['read'] == 0) $dataInfo['receivablesMoney'] = '';
  586. }
  587. }
  588. return $dataInfo;
  589. }
  590. /**
  591. * [合同转移]
  592. * @author Michael_xu
  593. * @param ids 合同ID数组
  594. * @param owner_user_id 变更负责人
  595. * @param is_remove 1移出,2转为团队成员
  596. * @return
  597. */
  598. public function transferDataById($ids, $owner_user_id, $type = 1, $is_remove)
  599. {
  600. $settingModel = new \app\crm\model\Setting();
  601. $errorMessage = [];
  602. foreach ($ids as $id) {
  603. $contractInfo = [];
  604. $contractInfo = db('crm_contract')->where(['contract_id' => $id])->find();
  605. // if (in_array($contractInfo['check_status'],['0','1'])) {
  606. // $errorMessage[] = '合同:'.$contractInfo['name'].'"转移失败,错误原因:审批中,无法转移;';
  607. // continue;
  608. // }
  609. //团队成员
  610. $teamData = [];
  611. $teamData['type'] = $type; //权限 1只读2读写
  612. $teamData['user_id'] = [$contractInfo['owner_user_id']]; //协作人
  613. $teamData['types'] = 'crm_contract'; //类型
  614. $teamData['types_id'] = $id; //类型ID
  615. $teamData['is_del'] = ($is_remove == 1) ? 1 : '';
  616. $res = $settingModel->createTeamData($teamData);
  617. $data = [];
  618. $data['owner_user_id'] = $owner_user_id;
  619. $data['update_time'] = time();
  620. if (!db('crm_contract')->where(['contract_id' => $id])->update($data)) {
  621. $errorMessage[] = '合同:'.$contractInfo['name'].'"转移失败,错误原因:数据出错;';
  622. continue;
  623. } else {
  624. $contractArray = [];
  625. $teamContract = db('crm_contract')->field(['owner_user_id', 'ro_user_id', 'rw_user_id'])->where('contract_id', $id)->find();
  626. if (!empty($teamContract['ro_user_id'])) {
  627. $contractRo = arrayToString(array_diff(stringToArray($teamContract['ro_user_id']), [$teamContract['owner_user_id']]));
  628. $contractArray['ro_user_id'] = $contractRo;
  629. }
  630. if (!empty($teamContract['rw_user_id'])) {
  631. $contractRo = arrayToString(array_diff(stringToArray($teamContract['rw_user_id']), [$teamContract['owner_user_id']]));
  632. $contractArray['rw_user_id'] = $contractRo;
  633. }
  634. db('crm_contract')->where('contract_id', $id)->update($contractArray);
  635. }
  636. }
  637. if ($errorMessage) {
  638. return $errorMessage;
  639. } else {
  640. return true;
  641. }
  642. }
  643. /**
  644. * 根据对象ID 获取该年各个月合同金额
  645. * @return [year] [哪一年]
  646. * @return [owner_user_id] [哪个员工]
  647. * @return [start_time] [开始时间]
  648. * @return [end_time] [结束时间]
  649. */
  650. public function getDataByUserId($param)
  651. {
  652. if ($param['obj_type']) {
  653. if ($param['obj_type'] == 1) { //部门
  654. $userModel = new \app\admin\model\User();
  655. $str = $userModel->getSubUserByStr($param['obj_id'], 1) ? : ['-1'];
  656. $map['owner_user_id'] = array('in',$str);
  657. } else { //员工
  658. $map['owner_user_id'] = $param['obj_id'];
  659. }
  660. }
  661. //审核状态
  662. $start = date('Y-m-d',$param['start_time']);
  663. $stop = date('Y-m-d',$param['end_time']);
  664. $map['check_status'] = 2;
  665. $data = $this->where($map)->where(['order_date' => ['between',[$start, $stop]]])->sum('money');
  666. return $data;
  667. }
  668. /**
  669. * 获取系统信息
  670. *
  671. * @param $id
  672. * @return array
  673. * @throws \think\db\exception\DataNotFoundException
  674. * @throws \think\db\exception\ModelNotFoundException
  675. * @throws \think\exception\DbException
  676. */
  677. public function getSystemInfo($id)
  678. {
  679. # 合同
  680. $business = Db::name('crm_contract')->where('contract_id', $id)->find();
  681. # 创建人
  682. $realname = Db::name('admin_user')->where('id', $business['create_user_id'])->value('realname');
  683. # 回款
  684. $receivablesModel = new Receivables();
  685. $receivables = $receivablesModel->getMoneyByContractId($id);
  686. return [
  687. 'create_user_id' => $realname,
  688. 'create_time' => date('Y-m-d H:i:s', $business['create_time']),
  689. 'update_time' => date('Y-m-d H:i:s', $business['update_time']),
  690. 'last_time' => !empty($business['last_time']) ? date('Y-m-d H:i:s', $business['last_time']) : '',
  691. 'done_money' => $receivables['doneMoney'],
  692. 'un_money' => $receivables['unMoney']
  693. ];
  694. }
  695. /**
  696. * 拷贝合同
  697. *
  698. * @param $contractId
  699. * @param $userId
  700. * @return bool
  701. * @throws \think\db\exception\DataNotFoundException
  702. * @throws \think\db\exception\ModelNotFoundException
  703. * @throws \think\exception\DbException
  704. */
  705. public function copy($contractId, $userId)
  706. {
  707. $targetContract = Db::name('crm_contract')->where('contract_id', $contractId)->find();
  708. $targetProduct = Db::name('crm_contract_product')->where('contract_id', $contractId)->select();
  709. if (empty($targetContract['contract_id'])) return false;
  710. # 删除主键
  711. unset($targetContract['contract_id']);
  712. Db::startTrans();
  713. try{
  714. # 合同数据
  715. $targetContract['num'] = 'WKCrm#contract#num#' . date('YmdHis');
  716. $targetContract['name'] = 'WKCrm#contract#name#'. date('YmdHis');
  717. $targetContract['create_user_id'] = $userId;
  718. $targetContract['owner_user_id'] = $userId;
  719. $targetContract['create_time'] = time();
  720. $targetContract['update_time'] = time();
  721. $targetContract['is_visit'] = 2;
  722. $targetContract['expire_remind'] = 1;
  723. if (in_array($targetContract['check_status'], [1, 2, 3, 4])) {
  724. $checkUserId = trim($targetContract['check_user_id'], ',');
  725. $flowUserId = trim($targetContract['flow_user_id'], ',');
  726. $symbol = !empty($checkUserId) ? ',' : '';
  727. $targetContract['check_user_id'] = ',' . $checkUserId . $symbol . $flowUserId . ',';
  728. $targetContract['check_status'] = 0;
  729. }
  730. Db::name('crm_contract')->insert($targetContract);
  731. $newContractId = Db::name('crm_contract')->getLastInsID();
  732. # 产品数据
  733. $productData = [];
  734. foreach ($targetProduct AS $key => $value) {
  735. $productData[] = [
  736. 'contract_id' => $newContractId,
  737. 'product_id' => $value['product_id'],
  738. 'price' => $value['price'],
  739. 'sales_price' => $value['sales_price'],
  740. 'num' => $value['num'],
  741. 'discount' => $value['discount'],
  742. 'subtotal' => $value['subtotal'],
  743. 'unit' => $value['unit']
  744. ];
  745. }
  746. if (!empty($productData)) Db::name('crm_contract_product')->insertAll($productData);
  747. Db::commit();
  748. return true;
  749. } catch (\Exception $e) {
  750. Db::rollback();
  751. return false;
  752. }
  753. }
  754. }