1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | Description: 合同
  4. // +----------------------------------------------------------------------
  5. // | Author: Michael_xu | gengxiaoxu@5kcrm.com
  6. // +----------------------------------------------------------------------
  7. namespace app\crm\model;
  8. use app\admin\traits\FieldVerificationTrait;
  9. use think\Db;
  10. use app\admin\model\Common;
  11. use app\admin\model\Message;
  12. class Contract extends Common
  13. {
  14. use FieldVerificationTrait;
  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'=>'已作废', '7'=>'正常'];
  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. // if($param['check_status'] == 2){
  36. // die('11');
  37. // }
  38. $userModel = new \app\admin\model\User();
  39. $structureModel = new \app\admin\model\Structure();
  40. $fieldModel = new \app\admin\model\Field();
  41. //回款
  42. $receivablesModel = new \app\crm\model\Receivables();
  43. $search = $request['search'];
  44. $user_id = $request['user_id'];
  45. $scene_id = (int)$request['scene_id'];
  46. $order_field = $request['order_field'];
  47. $order_type = $request['order_type'];
  48. $is_excel = $request['is_excel']; //导出
  49. $getCount = $request['getCount'];
  50. $contractIdArray = $request['contractIdArray']; // 待办事项提醒参数
  51. $isMessage = !empty($request['isMessage']);
  52. unset($request['scene_id']);
  53. unset($request['search']);
  54. unset($request['user_id']);
  55. unset($request['order_field']);
  56. unset($request['order_type']);
  57. unset($request['is_excel']);
  58. unset($request['getCount']);
  59. unset($request['contractIdArray']);
  60. unset($request['isMessage']);
  61. $request = $this->fmtRequest( $request );
  62. $requestMap = $request['map'] ? : [];
  63. $sceneModel = new \app\admin\model\Scene();
  64. # getCount是代办事项传来的参数,代办事项不需要使用场景
  65. $sceneMap = [];
  66. if (empty($getCount)) {
  67. if ($scene_id) {
  68. //自定义场景
  69. $sceneMap = $sceneModel->getDataById($scene_id, $user_id, 'contract') ? : [];
  70. } else {
  71. //默认场景
  72. $sceneMap = $sceneModel->getDefaultData('crm_contract', $user_id) ? : [];
  73. }
  74. }
  75. $searchWhere = [];
  76. if ($search || $search == '0') {
  77. //普通筛选
  78. $searchWhere = function ($query) use ($search) {
  79. $query->where(function ($query) use ($search){
  80. $query->whereLike('customer.name', '%' . $search . '%');
  81. })->whereOr(function ($query) use ($search) {
  82. $query->whereLike('contract.num', '%' . $search . '%');
  83. })->whereOr(function ($query) use ($search) {
  84. $query->whereLike('contract.name', '%' . $search . '%');
  85. });
  86. };
  87. }
  88. $partMap = [];
  89. //优先级:普通筛选>高级筛选>场景
  90. if ($requestMap['team_id']) {
  91. //相关团队查询
  92. $map = $requestMap;
  93. $partMap= advancedQueryFormatForTeam($requestMap,'crm_contract','contract_id');
  94. unset($map['team_id']);
  95. } else {
  96. $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
  97. }
  98. //高级筛选
  99. $map = advancedQuery($map, 'crm', 'contract', 'index');
  100. $order = ['contract.update_time desc'];
  101. $authMap = [];
  102. if (!$partMap) {
  103. $a = 'index';
  104. if ($is_excel) $a = 'excelExport';
  105. $auth_user_ids = $userModel->getUserByPer('crm', 'contract', $a);
  106. if (isset($map['contract.owner_user_id']) && $map['contract.owner_user_id'][0] != 'like') {
  107. if (!is_array($map['contract.owner_user_id'][1])) {
  108. $map['contract.owner_user_id'][1] = [$map['contract.owner_user_id'][1]];
  109. }
  110. if (in_array($map['contract.owner_user_id'][0], ['neq', 'notin'])) {
  111. $auth_user_ids = array_diff($auth_user_ids, $map['contract.owner_user_id'][1]) ? : []; //取差集
  112. } else {
  113. $auth_user_ids = array_intersect($map['contract.owner_user_id'][1], $auth_user_ids) ? : []; //取交集
  114. }
  115. unset($map['contract.owner_user_id']);
  116. $auth_user_ids = array_merge(array_unique(array_filter($auth_user_ids))) ? : ['-1'];
  117. $authMap['contract.owner_user_id'] = array('in',$auth_user_ids);
  118. } else {
  119. // 待办事项的待审核合同不一定是自己创建的
  120. if (!$isMessage) {
  121. $authMapData = [];
  122. $authMapData['auth_user_ids'] = $auth_user_ids;
  123. $authMapData['user_id'] = $user_id;
  124. $authMap = function($query) use ($authMapData){
  125. $query->where('contract.owner_user_id',array('in',$authMapData['auth_user_ids']))
  126. ->whereOr('contract.ro_user_id',array('like','%,'.$authMapData['user_id'].',%'))
  127. ->whereOr('contract.rw_user_id',array('like','%,'.$authMapData['user_id'].',%'));
  128. };
  129. }
  130. }
  131. }
  132. //合同签约人 | 与高级筛选冲突,加一个is_array判断
  133. if ($map['contract.order_user_id'] && !is_array($map['contract.order_user_id'][1])) {
  134. $map['contract.order_user_id'] = ['like','%,'.$map['contract.order_user_id'][1].',%'];
  135. }
  136. //列表展示字段
  137. $indexField = $fieldModel->getIndexField('crm_contract', $user_id, 1) ? : array('name');
  138. //人员类型
  139. $userField = $fieldModel->getFieldByFormType('crm_contract', 'user');
  140. $structureField = $fieldModel->getFieldByFormType('crm_contract', 'structure'); //部门类型
  141. $datetimeField = $fieldModel->getFieldByFormType('crm_contract', 'datetime'); //日期时间类型
  142. $booleanField = $fieldModel->getFieldByFormType('crm_contract', 'boolean_value'); //布尔值
  143. $dateIntervalField = $fieldModel->getFieldByFormType('crm_contract', 'date_interval'); // 日期区间类型字段
  144. $positionField = $fieldModel->getFieldByFormType('crm_contract', 'position'); // 地址类型字段
  145. $handwritingField = $fieldModel->getFieldByFormType('crm_contract', 'handwriting_sign'); // 手写签名类型字段
  146. $locationField = $fieldModel->getFieldByFormType('crm_contract', 'location'); // 定位类型字段
  147. $boxField = $fieldModel->getFieldByFormType('crm_contract', 'checkbox'); // 多选类型字段
  148. $floatField = $fieldModel->getFieldByFormType('crm_contract', 'floatnumber'); // 货币类型字段
  149. # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
  150. $temporaryField = str_replace('_name', '', $order_field);
  151. if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
  152. $order_field = $temporaryField;
  153. }
  154. //排序
  155. if ($order_type && $order_field) {
  156. $order = $fieldModel->getOrderByFormtype('crm_contract','contract',$order_field,$order_type);
  157. } else {
  158. $order = 'contract.update_time desc';
  159. }
  160. # 待办事项查询参数
  161. $dealtWhere = [];
  162. if (!empty($contractIdArray)) $dealtWhere['contract.contract_id'] = ['in', $contractIdArray];
  163. $readAuthIds = $userModel->getUserByPer('crm', 'contract', 'read');
  164. $updateAuthIds = $userModel->getUserByPer('crm', 'contract', 'update');
  165. $deleteAuthIds = $userModel->getUserByPer('crm', 'contract', 'delete');
  166. $dataCount = db('crm_contract')
  167. ->alias('contract')
  168. ->join('__CRM_CUSTOMER__ customer','contract.customer_id = customer.customer_id','LEFT')
  169. ->join('__CRM_BUSINESS__ business','contract.business_id = business.business_id','LEFT')
  170. ->join('__CRM_CONTACTS__ contacts','contract.contacts_id = contacts.contacts_id','LEFT')
  171. // ->join('__CRM_RECEIVABLES_PLAN__ plan','contract.contract_id = plan.contract_id','LEFT')
  172. ->where($searchWhere)->where($map)->where($partMap)->where($authMap)->where($dealtWhere)->group('contract.contract_id')->count('contract.contract_id');
  173. if (!empty($getCount) && $getCount == 1) {
  174. $data['dataCount'] = !empty($dataCount) ? $dataCount : 0;
  175. $contractMoney = $this->getContractMoney($map, $partMap, $authMap);
  176. $data['extraData']['money'] = [
  177. 'contractMoney' => $contractMoney['contractMoney'], # 合同总金额
  178. 'receivedMoney' => $contractMoney['receivablesMoney'], # 回款总金额
  179. 'unReceivedMoney' => $contractMoney['arrearsMoney'] # 未回款总金额
  180. ];
  181. return $data;
  182. }
  183. foreach ($indexField AS $kk => $vv) {
  184. if ($vv == 'contract.customer_name') unset($indexField[(int)$kk]);
  185. if ($vv == 'contract.business_name') unset($indexField[(int)$kk]);
  186. }
  187. # zjf 20210727 添加回款绑定合同 合同列表 状态为审核通过和正常
  188. if($requestMap['check_status'] == 2){
  189. $map['contract.check_status'] = ['in', [2,7]];
  190. }
  191. $list = db('crm_contract')
  192. ->alias('contract')
  193. ->join('__CRM_CUSTOMER__ customer','contract.customer_id = customer.customer_id','LEFT')
  194. ->join('__CRM_BUSINESS__ business','contract.business_id = business.business_id','LEFT')
  195. ->join('__CRM_CONTACTS__ contacts','contract.contacts_id = contacts.contacts_id','LEFT')
  196. // ->join('__CRM_RECEIVABLES_PLAN__ plan','contract.contract_id = plan.contract_id','LEFT')
  197. ->join('CrmReceivables receivables','receivables.contract_id = contract.contract_id AND receivables.check_status = 2','LEFT')
  198. ->where($searchWhere)
  199. ->where($map)
  200. ->where($partMap)
  201. ->where($authMap)
  202. ->where($dealtWhere)
  203. ->limit($request['offset'], $request['length'])
  204. ->field(array_merge($indexField, [
  205. 'customer.name' => 'customer_name',
  206. 'business.name' => 'business_name',
  207. 'contacts.name' => 'contacts_name',
  208. 'ifnull(SUM(receivables.money), 0)' => 'done_money',
  209. '(contract.money - ifnull(SUM(receivables.money), 0))' => 'un_money',
  210. ]))
  211. ->orderRaw($order)
  212. ->group('contract.contract_id')
  213. ->select();
  214. # 扩展数据
  215. $extraData = [];
  216. $contract_id_list = !empty($list) ? array_column($list, 'contract_id') : [];
  217. $extraList = db('crm_contract_data')->whereIn('contract_id', $contract_id_list)->select();
  218. foreach ($extraList AS $key => $value) {
  219. $extraData[$value['contract_id']][$value['field']] = $value['content'];
  220. }
  221. $grantData = getFieldGrantData($user_id);
  222. foreach ($grantData['crm_contract'] as $key => $value) {
  223. foreach ($value as $ke => $va) {
  224. if($va['maskType']!=0){
  225. $fieldGrant[$ke]['maskType'] = $va['maskType'];
  226. $fieldGrant[$ke]['form_type'] = $va['form_type'];
  227. $fieldGrant[$ke]['field'] = $va['field'];
  228. }
  229. }
  230. }
  231. foreach ($list as $k=>$v) {
  232. $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
  233. $list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
  234. $list[$k]['create_user_name'] = !empty($list[$k]['create_user_id_info']['realname']) ? $list[$k]['create_user_id_info']['realname'] : '';
  235. $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
  236. foreach ($userField as $key => $val) {
  237. $usernameField = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
  238. $list[$k][$val] = implode($usernameField, ',');
  239. }
  240. foreach ($structureField as $key => $val) {
  241. $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
  242. $list[$k][$val] = implode($structureNameField, ',');
  243. }
  244. foreach ($datetimeField as $key => $val) {
  245. $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
  246. }
  247. foreach ($booleanField as $key => $val) {
  248. $list[$k][$val] = !empty($v[$val]) ? (string)$v[$val] : '0';
  249. }
  250. // 处理日期区间类型字段的格式
  251. foreach ($dateIntervalField AS $key => $val) {
  252. $list[$k][$val] = !empty($extraData[$v['contract_id']][$val]) ? json_decode($extraData[$v['contract_id']][$val], true) : null;
  253. }
  254. // 处理地址类型字段的格式
  255. foreach ($positionField AS $key => $val) {
  256. $list[$k][$val] = !empty($extraData[$v['contract_id']][$val]) ? json_decode($extraData[$v['contract_id']][$val], true) : null;
  257. }
  258. // 手写签名类型字段
  259. foreach ($handwritingField AS $key => $val) {
  260. $handwritingData = !empty($v[$val]) ? db('admin_file')->where('file_id', $v[$val])->value('file_path') : null;
  261. $list[$k][$val] = ['url' => !empty($handwritingData) ? getFullPath($handwritingData) : null];
  262. }
  263. // 定位类型字段
  264. foreach ($locationField AS $key => $val) {
  265. $list[$k][$val] = !empty($extraData[$v['contract_id']][$val]) ? json_decode($extraData[$v['contract_id']][$val], true) : null;
  266. }
  267. // 多选框类型字段
  268. foreach ($boxField AS $key => $val) {
  269. $list[$k][$val] = !empty($v[$val]) ? trim($v[$val], ',') : null;
  270. }
  271. // 货币类型字段
  272. foreach ($floatField AS $key => $val) {
  273. $list[$k][$val] = $v[$val]!='0.00' ? (string)$v[$val] : null;
  274. }
  275. //掩码相关类型字段
  276. foreach ($fieldGrant AS $key => $val){
  277. //掩码相关类型字段
  278. if ($val['maskType']!=0 && $val['form_type'] == 'mobile') {
  279. $pattern = "/(1[3458]{1}[0-9])[0-9]{4}([0-9]{4})/i";
  280. $rs = preg_replace($pattern, "$1****$2", $v[$val['field']]);
  281. $list[$k][$val['field']] = !empty($v[$val['field']]) ? (string)$rs : null;
  282. } elseif ($val['maskType']!=0 && $val['form_type'] == 'email') {
  283. $email_array = explode("@", $v[$val['field']]);
  284. $prevfix = (strlen($email_array[0]) < 4) ? "" : substr($v[$val['field']], 0, 2); //邮箱前缀
  285. $str = preg_replace('/([\d\w+_-]{0,100})@/', "***@", $v[$val['field']], -1, $count);
  286. $rs = $prevfix . $str;
  287. $list[$k][$val['field']] = !empty($v[$val['field']]) ?$rs: null;
  288. } elseif ($val['maskType']!=0 && in_array($val['form_type'],['position','floatnumber'])) {
  289. $list[$k][$val['field']] = !empty($v[$val['field']]) ? (string)substr_replace($v[$val['field']], '*****',0,strlen($v[$val['field']])) : null;
  290. }
  291. }
  292. $list[$k]['business_id_info']['business_id'] = $v['business_id'];
  293. $list[$k]['business_id_info']['name'] = $v['business_name'];
  294. $list[$k]['customer_id_info']['customer_id'] = $v['customer_id'];
  295. $list[$k]['customer_id_info']['name'] = $v['customer_name'];
  296. $list[$k]['contacts_id_info']['contacts_id'] = $v['contacts_id'];
  297. $list[$k]['contacts_id_info']['name'] = $v['contacts_name'];
  298. $list[$k]['check_status_info'] = $this->statusArr[$v['check_status']];
  299. $moneyInfo = [];
  300. $moneyInfo = $receivablesModel->getMoneyByContractId($v['contract_id']);
  301. $list[$k]['unMoney'] = $moneyInfo['doneMoney'] ? : '0.00';
  302. if ($list[$k]['un_money'] < 0) $list[$k]['un_money'] = '0.00';
  303. $planInfo = [];
  304. $planInfo = db('crm_receivables_plan')->where(['contract_id' => $v['contract_id']])->find();
  305. $list[$k]['receivables_id'] = $planInfo['receivables_id'] ? : '';
  306. $list[$k]['remind_date'] = $planInfo['remind_date'] ? : '';
  307. $list[$k]['return_date'] = $planInfo['return_date'] ? : '';
  308. //权限
  309. $roPre = $userModel->rwPre($user_id, $v['ro_user_id'], $v['rw_user_id'], 'read');
  310. $rwPre = $userModel->rwPre($user_id, $v['ro_user_id'], $v['rw_user_id'], 'update');
  311. $permission = [];
  312. $is_read = 0;
  313. $is_update = 0;
  314. $is_delete = 0;
  315. if (in_array($v['owner_user_id'],$readAuthIds) || $roPre || $rwPre) $is_read = 1;
  316. if (in_array($v['owner_user_id'],$updateAuthIds) || $rwPre) $is_update = 1;
  317. if (in_array($v['owner_user_id'],$deleteAuthIds)) $is_delete = 1;
  318. $permission['is_read'] = $is_read;
  319. $permission['is_update'] = $is_update;
  320. $permission['is_delete'] = $is_delete;
  321. $list[$k]['permission'] = $permission;
  322. # 下次联系时间
  323. $list[$k]['next_time'] = !empty($v['next_time']) ? date('Y-m-d H:i:s', $v['next_time']) : null;
  324. # 日期
  325. $list[$k]['create_time'] = !empty($v['create_time']) ? date('Y-m-d H:i:s', $v['create_time']) : null;
  326. $list[$k]['update_time'] = !empty($v['update_time']) ? date('Y-m-d H:i:s', $v['update_time']) : null;
  327. $list[$k]['last_time'] = !empty($v['last_time']) ? date('Y-m-d H:i:s', $v['last_time']) : null;
  328. $list[$k]['order_date'] = ($v['order_date']!='0000-00-00') ? $v['order_date'] : null;
  329. $list[$k]['start_time'] = ($v['start_time']!='0000-00-00') ? $v['start_time'] : null;
  330. $list[$k]['end_time'] = ($v['end_time']!='0000-00-00') ? $v['end_time'] : null;
  331. # 签约人姓名
  332. $orderNames = Db::name('admin_user')->whereIn('id', trim($v['order_user_id'], ','))->column('realname');
  333. $list[$k]['order_user_name'] = implode(',', $orderNames);
  334. unset($list[$k]['order_user_id']);
  335. $list[$k]['order_user_id_name'] = $v['order_user_id'];
  336. # 系统字段 负责人部门 zjf 20210726
  337. $list[$k]['owner_user_structure_name'] = $list[$k]['owner_user_id_info']['structure_name'];
  338. }
  339. $data = [];
  340. $data['list'] = $list;
  341. $data['dataCount'] = $dataCount ? : 0;
  342. $contractMoney = $this->getContractMoney($map, $partMap, $authMap);
  343. $data['extraData']['money'] = [
  344. 'contractMoney' => $contractMoney['contractMoney'], # 合同总金额
  345. 'receivedMoney' => $contractMoney['receivablesMoney'], # 回款总金额
  346. 'unReceivedMoney' => $contractMoney['arrearsMoney'] # 未回款
  347. ];
  348. return $data;
  349. }
  350. /**
  351. * 获取合同相关金额
  352. *
  353. * @param $map
  354. * @param $partMap
  355. * @param $authMap
  356. * @author fanqi
  357. * @date 2021-03-03
  358. * @return array
  359. */
  360. private function getContractMoney($map, $partMap, $authMap)
  361. {
  362. $contractMoney = 0.00; # 合同总金额
  363. $receivablesMoney = 0.00; # 回款总金额
  364. $arrearsMoney = 0.00; # 未回款总金额
  365. # 过滤审核状态参数,只查询审核成功的数据。
  366. foreach ($map AS $key => $value) {
  367. if ($key === 'contract.check_status') unset($map[$key]);
  368. }
  369. $data = db('crm_contract')
  370. ->alias('contract')
  371. ->join('__CRM_CUSTOMER__ customer','contract.customer_id = customer.customer_id','LEFT')
  372. ->join('__CRM_BUSINESS__ business','contract.business_id = business.business_id','LEFT')
  373. ->join('__CRM_CONTACTS__ contacts','contract.contacts_id = contacts.contacts_id','LEFT')
  374. ->join('__CRM_RECEIVABLES__ receivables','receivables.contract_id = contract.contract_id','LEFT')
  375. ->where('contract.check_status', 2)
  376. ->where($map)
  377. ->where($partMap)
  378. ->where($authMap)
  379. ->field(['contract.contract_id', 'contract.money AS contractMoney', 'receivables.money AS receivablesMoney', 'receivables.check_status AS receivablesStatus'])
  380. ->select();
  381. # 将同一合同下的回款进行整合
  382. $result = [];
  383. foreach ($data AS $key => $value) {
  384. # 同属于一个合同下的回款
  385. if (!empty($result[$value['contract_id']])) {
  386. if ($value['receivablesStatus'] == 2) $result[$value['contract_id']]['receivablesMoney'] += $value['receivablesMoney'];
  387. continue;
  388. }
  389. $result[$value['contract_id']] = [
  390. 'contractMoney' => $value['contractMoney'],
  391. 'receivablesMoney' => $value['receivablesStatus'] == 2 ? $value['receivablesMoney'] : 0,
  392. ];
  393. }
  394. # 统计各金额总和
  395. foreach ($result AS $key => $value) {
  396. $contractMoney += $value['contractMoney']; # 合同金额
  397. $receivablesMoney += $value['receivablesMoney']; # 回款金额
  398. # 未回款金额
  399. if ($value['contractMoney'] > $value['receivablesMoney']) $arrearsMoney += $value['contractMoney'] - $value['receivablesMoney'];
  400. }
  401. return [
  402. 'contractMoney' => sprintf("%.2f", $contractMoney),
  403. 'receivablesMoney' => sprintf("%.2f", $receivablesMoney),
  404. 'arrearsMoney' => sprintf("%.2f", $arrearsMoney)
  405. ];
  406. }
  407. //根据IDs获取数组
  408. public function getDataByStr($idstr)
  409. {
  410. $idArr = stringToArray($idstr);
  411. if (!$idArr) {
  412. return [];
  413. }
  414. $list = Db::name('CrmContract')->where(['contract_id' => ['in',$idArr]])->select();
  415. return $list;
  416. }
  417. /**
  418. * 创建合同信息
  419. * @author Michael_xu
  420. * @param
  421. * @return
  422. */
  423. public function createData($param)
  424. {
  425. // 合同扩展表数据
  426. $contractData = [];
  427. $fieldModel = new \app\admin\model\Field();
  428. $userModel = new \app\admin\model\User();
  429. $productModel = new \app\crm\model\Product();
  430. // 数据验证
  431. $validateResult = $this->fieldDataValidate($param, $this->name, $param['create_user_id']);
  432. if (!empty($validateResult)) {
  433. $this->error = $validateResult;
  434. return false;
  435. }
  436. # 处理下次联系时间
  437. if (!empty($param['next_time'])) $param['next_time'] = strtotime($param['next_time']);
  438. // 处理部门、员工、附件、多选类型字段
  439. $arrFieldAtt = $fieldModel->getArrayField('crm_contract');
  440. foreach ($arrFieldAtt as $k=>$v) {
  441. $param[$v] = arrayToString($param[$v]);
  442. }
  443. // 处理日期(date)类型
  444. $dateField = $fieldModel->getFieldByFormType('crm_contract', 'date');
  445. if (!empty($dateField)) {
  446. foreach ($param AS $key => $value) {
  447. if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
  448. }
  449. }
  450. // 处理手写签名类型
  451. $handwritingField = $fieldModel->getFieldByFormType('crm_contract', 'handwriting_sign');
  452. if (!empty($handwritingField)) {
  453. foreach ($param AS $key => $value) {
  454. if (in_array($key, $handwritingField)) {
  455. $param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
  456. }
  457. }
  458. }
  459. // 处理地址、定位、日期区间、明细表格类型字段
  460. $positionField = $fieldModel->getFieldByFormType($this->name, 'position');
  461. $locationField = $fieldModel->getFieldByFormType($this->name, 'location');
  462. $dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
  463. $detailTableField = $fieldModel->getFieldByFormType($this->name, 'detail_table');
  464. foreach ($param AS $key => $value) {
  465. // 处理地址类型字段数据
  466. if (in_array($key, $positionField)) {
  467. if (!empty($value)) {
  468. $contractData[] = [
  469. 'field' => $key,
  470. 'content' => json_encode($value, JSON_NUMERIC_CHECK),
  471. 'create_time' => time()
  472. ];
  473. $positionNames = array_column($value, 'name');
  474. $param[$key] = implode(',', $positionNames);
  475. } else {
  476. $param[$key] = '';
  477. }
  478. }
  479. // 处理定位类型字段数据
  480. if (in_array($key, $locationField)) {
  481. if (!empty($value)) {
  482. $contractData[] = [
  483. 'field' => $key,
  484. 'content' => json_encode($value, JSON_NUMERIC_CHECK),
  485. 'create_time' => time()
  486. ];
  487. $param[$key] = $value['address'];
  488. } else {
  489. $param[$key] = '';
  490. }
  491. }
  492. // 处理日期区间类型字段数据
  493. if (in_array($key, $dateIntervalField)) {
  494. if (!empty($value)) {
  495. $contractData[] = [
  496. 'field' => $key,
  497. 'content' => json_encode($value, JSON_NUMERIC_CHECK),
  498. 'create_time' => time()
  499. ];
  500. $param[$key] = implode('_', $value);
  501. } else {
  502. $param[$key] = '';
  503. }
  504. }
  505. // 处理明细表格类型字段数据
  506. if (in_array($key, $detailTableField)) {
  507. if (!empty($value)) {
  508. $contractData[] = [
  509. 'field' => $key,
  510. 'content' => json_encode($value, JSON_NUMERIC_CHECK),
  511. 'create_time' => time()
  512. ];
  513. $param[$key] = $key;
  514. } else {
  515. $param[$key] = '';
  516. }
  517. }
  518. }
  519. # 下单时间
  520. $param['order_date'] = !empty($param['order_date']) ? $param['order_date'] : date('Y-m-d H:i:s', time());
  521. if (empty($param['start_time'])) $param['start_time'] = null;
  522. if (empty($param['end_time'])) $param['end_time'] = null;
  523. $this->startTrans();
  524. if ($this->data($param)->allowField(true)->save()) {
  525. if ($param['product']) {
  526. //产品数据处理
  527. $resProduct = $productModel->createObject('crm_contract', $param, $this->contract_id);
  528. if ($resProduct == false) {
  529. $this->error = '产品添加失败。' . $productModel->getError();
  530. $this->rollback();
  531. return false;
  532. }
  533. }
  534. //站内信
  535. $send_user_id = stringToArray($param['check_user_id']);
  536. if ($send_user_id && empty($param['check_status'])) {
  537. (new Message())->send(
  538. Message::CONTRACT_TO_DO,
  539. [
  540. 'title' => $param['name'],
  541. 'action_id' => $this->contract_id
  542. ],
  543. $send_user_id
  544. );
  545. }
  546. $data = [];
  547. $data['contract_id'] = $this->contract_id;
  548. $this->commit();
  549. //修改记录
  550. updateActionLog($param['create_user_id'], 'crm_contract', $this->contract_id, '', '', '创建了合同');
  551. RecordActionLog($param['create_user_id'],'crm_contract','save',$param['name'],'','','新增了合同'.$param['name']);
  552. # 添加活动记录
  553. Db::name('crm_activity')->insert([
  554. 'type' => 2,
  555. 'activity_type' => 6,
  556. 'activity_type_id' => $data['contract_id'],
  557. 'content' => $param['name'],
  558. 'create_user_id' => $param['create_user_id'],
  559. 'update_time' => time(),
  560. 'create_time' => time(),
  561. 'customer_ids' => ',' . $param['customer_id'] . ',',
  562. 'contacts_ids' => ',' . $param['contacts_id'] . ',',
  563. 'business_ids' => ',' . $param['business_id'] . ','
  564. ]);
  565. # 创建待办事项的关联数据
  566. $checkUserIds = db('crm_contract')->where('contract_id', $data['contract_id'])->value('check_user_id');
  567. $checkUserIdArray = stringToArray($checkUserIds);
  568. $dealtData = [];
  569. foreach ($checkUserIdArray AS $kk => $vv) {
  570. $dealtData[] = [
  571. 'types' => 'crm_contract',
  572. 'types_id' => $data['contract_id'],
  573. 'user_id' => $vv
  574. ];
  575. }
  576. if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData);
  577. // 添加合同扩展数据
  578. array_walk($contractData, function (&$val) use ($data) {
  579. $val['contract_id'] = $data['contract_id'];
  580. });
  581. db('crm_contract_data')->insertAll($contractData);
  582. return $data;
  583. } else {
  584. $this->error = '添加失败';
  585. $this->rollback();
  586. return false;
  587. }
  588. }
  589. /**
  590. * 编辑合同主表信息
  591. * @author Michael_xu
  592. * @param
  593. * @return
  594. */
  595. public function updateDataById($param, $contract_id = '')
  596. {
  597. // 合同扩展表数据
  598. $contractData = [];
  599. $productModel = new \app\crm\model\Product();
  600. $userModel = new \app\admin\model\User();
  601. $dataInfo = db('crm_contract')->where(['contract_id' => $contract_id])->find();
  602. //过滤不能修改的字段
  603. $unUpdateField = ['create_user_id','is_deleted','delete_time'];
  604. foreach ($unUpdateField as $v) {
  605. unset($param[$v]);
  606. }
  607. $param['contract_id'] = $contract_id;
  608. $fieldModel = new \app\admin\model\Field();
  609. // 数据验证
  610. $validateResult = $this->fieldDataValidate($param, $this->name, $param['user_id'], $param['contract_id']);
  611. if (!empty($validateResult)) {
  612. $this->error = $validateResult;
  613. return false;
  614. }
  615. # 处理下次联系时间
  616. if (!empty($param['next_time'])) $param['next_time'] = strtotime($param['next_time']);
  617. $param['order_date'] = !empty($param['order_date']) ? $param['order_date'] : date('Y-m-d H:i:s', time());
  618. if (empty($param['start_time'])) $param['start_time'] = null;
  619. if (empty($param['end_time'])) $param['end_time'] = null;
  620. // 处理部门、员工、附件、多选类型字段
  621. $arrFieldAtt = $fieldModel->getArrayField('crm_contract');
  622. foreach ($arrFieldAtt as $k=>$v) {
  623. if (isset($param[$v])) $param[$v] = arrayToString($param[$v]);
  624. }
  625. // 处理日期(date)类型
  626. $dateField = $fieldModel->getFieldByFormType('crm_contract', 'date');
  627. if (!empty($dateField)) {
  628. foreach ($param AS $key => $value) {
  629. if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
  630. }
  631. }
  632. // 处理手写签名类型
  633. $handwritingField = $fieldModel->getFieldByFormType('crm_contract', 'handwriting_sign');
  634. if (!empty($handwritingField)) {
  635. foreach ($param AS $key => $value) {
  636. if (in_array($key, $handwritingField)) {
  637. $param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
  638. }
  639. }
  640. }
  641. // 处理地址、定位、日期区间、明细表格类型字段
  642. $positionField = $fieldModel->getFieldByFormType($this->name, 'position');
  643. $locationField = $fieldModel->getFieldByFormType($this->name, 'location');
  644. $dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
  645. $detailTableField = $fieldModel->getFieldByFormType($this->name, 'detail_table');
  646. foreach ($param AS $key => $value) {
  647. // 处理地址类型字段数据
  648. if (in_array($key, $positionField)) {
  649. if (!empty($value)) {
  650. $contractData[] = [
  651. 'field' => $key,
  652. 'content' => json_encode($value, JSON_NUMERIC_CHECK),
  653. 'create_time' => time()
  654. ];
  655. $positionNames = array_column($value, 'name');
  656. $param[$key] = implode(',', $positionNames);
  657. } else {
  658. $param[$key] = '';
  659. }
  660. }
  661. // 处理定位类型字段数据
  662. if (in_array($key, $locationField)) {
  663. if (!empty($value)) {
  664. $contractData[] = [
  665. 'field' => $key,
  666. 'content' => json_encode($value, JSON_NUMERIC_CHECK),
  667. 'create_time' => time()
  668. ];
  669. $param[$key] = $value['address'];
  670. } else {
  671. $param[$key] = '';
  672. }
  673. }
  674. // 处理日期区间类型字段数据
  675. if (in_array($key, $dateIntervalField)) {
  676. if (!empty($value)) {
  677. $contractData[] = [
  678. 'field' => $key,
  679. 'content' => json_encode($value, JSON_NUMERIC_CHECK),
  680. 'create_time' => time()
  681. ];
  682. $param[$key] = implode('_', $value);
  683. } else {
  684. $param[$key] = '';
  685. }
  686. }
  687. // 处理明细表格类型字段数据
  688. if (in_array($key, $detailTableField)) {
  689. if (!empty($value)) {
  690. $contractData[] = [
  691. 'field' => $key,
  692. 'content' => json_encode($value, JSON_NUMERIC_CHECK),
  693. 'create_time' => time()
  694. ];
  695. $param[$key] = $key;
  696. } else {
  697. $param[$key] = '';
  698. }
  699. }
  700. }
  701. if ($this->update($param, ['contract_id' => $contract_id], true)) {
  702. //产品数据处理
  703. $resProduct = $productModel->createObject('crm_contract', $param, $contract_id);
  704. //修改记录
  705. updateActionLog($param['user_id'], 'crm_contract', $contract_id, $dataInfo, $param);
  706. RecordActionLog($param['user_id'], 'crm_contract', 'update',$dataInfo['name'], $dataInfo, $param);
  707. //站内信
  708. $send_user_id = stringToArray($param['check_user_id']);
  709. if ($send_user_id && empty($param['check_status'])) {
  710. (new Message())->send(
  711. Message::CONTRACT_TO_DO,
  712. [
  713. 'title' => $param['name'],
  714. 'action_id' => $contract_id
  715. ],
  716. $send_user_id
  717. );
  718. }
  719. $data = [];
  720. $data['contract_id'] = $contract_id;
  721. # 删除待办事项的关联数据
  722. db('crm_dealt_relation')->where(['types' => ['eq', 'crm_contract'], 'types_id' => ['eq', $data['contract_id']]])->delete();
  723. # 创建待办事项的关联数据
  724. $checkUserIds = db('crm_contract')->where('contract_id', $data['contract_id'])->value('check_user_id');
  725. $checkUserIdArray = stringToArray($checkUserIds);
  726. $dealtData = [];
  727. foreach ($checkUserIdArray AS $kk => $vv) {
  728. $dealtData[] = [
  729. 'types' => 'crm_contract',
  730. 'types_id' => $data['contract_id'],
  731. 'user_id' => $vv
  732. ];
  733. }
  734. if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData);
  735. // 添加合同扩展数据
  736. db('crm_contract_data')->where('contract_id', $contract_id)->delete();
  737. array_walk($contractData, function (&$val) use ($contract_id) {
  738. $val['contract_id'] = $contract_id;
  739. });
  740. db('crm_contract_data')->insertAll($contractData);
  741. return $data;
  742. } else {
  743. $this->error = '编辑失败';
  744. return false;
  745. }
  746. }
  747. /**
  748. * 合同数据
  749. *
  750. * @param string $id
  751. * @return Common|array|bool|\PDOStatement|string|\think\Model|null
  752. * @throws \think\db\exception\DataNotFoundException
  753. * @throws \think\db\exception\ModelNotFoundException
  754. * @throws \think\exception\DbException
  755. */
  756. public function getDataById($id = '', $userId = 0,$model='')
  757. {
  758. $receivablesModel = new \app\crm\model\Receivables();
  759. $userModel = new \app\admin\model\User();
  760. $map['contract_id'] = $id;
  761. $dataInfo = db('crm_contract')->where($map)->find();
  762. if (!$dataInfo) {
  763. $this->error = '暂无此数据';
  764. return false;
  765. }
  766. if(empty($model) && $model!='update'){
  767. $grantData = getFieldGrantData($userId);
  768. foreach ($grantData['crm_contract'] as $key => $value) {
  769. foreach ($value as $ke => $va) {
  770. if($va['maskType']!=0){
  771. $fieldGrant[$ke]['maskType'] = $va['maskType'];
  772. $fieldGrant[$ke]['form_type'] = $va['form_type'];
  773. $fieldGrant[$ke]['field'] = $va['field'];
  774. }
  775. }
  776. }
  777. foreach ($fieldGrant AS $key => $val){
  778. //掩码相关类型字段
  779. if ($val['maskType']!=0 && $val['form_type'] == 'mobile') {
  780. $pattern = "/(1[3458]{1}[0-9])[0-9]{4}([0-9]{4})/i";
  781. $rs = preg_replace($pattern, "$1****$2", $dataInfo[$val['field']]);
  782. $dataInfo[$val['field']] = !empty($dataInfo[$val['field']]) ? (string)$rs : null;
  783. } elseif ($val['maskType']!=0 && $val['form_type'] == 'email') {
  784. $email_array = explode("@", $dataInfo[$val['field']]);
  785. $prevfix = (strlen($email_array[0]) < 4) ? "" : substr($dataInfo[$val['field']], 0, 2); //邮箱前缀
  786. $str = preg_replace('/([\d\w+_-]{0,100})@/', "***@", $dataInfo[$val['field']], -1, $count);
  787. $rs = $prevfix . $str;
  788. $dataInfo[$val['field']] = !empty($dataInfo[$val['field']]) ?$rs: null;
  789. } elseif ($val['maskType']!=0 && in_array($val['form_type'],['position','floatnumber'])) {
  790. $dataInfo[$val['field']] = !empty($dataInfo[$val['field']]) ? (string)substr_replace($dataInfo[$val['field']], '*****',0,strlen($dataInfo[$val['field']])) : null;
  791. }
  792. }
  793. }
  794. $dataInfo['create_user_info'] = isset($dataInfo['create_user_id']) ? $userModel->getUserById($dataInfo['create_user_id']) : [];
  795. $dataInfo['owner_user_id_info'] = isset($dataInfo['owner_user_id']) ? $userModel->getUserById($dataInfo['owner_user_id']) : [];
  796. $dataInfo['create_user_name'] = !empty($dataInfo['create_user_info']['realname']) ? $dataInfo['create_user_info']['realname'] : '';
  797. $dataInfo['owner_user_name'] = !empty($dataInfo['owner_user_id_info']['realname']) ? $dataInfo['owner_user_id_info']['realname'] : '';
  798. $dataInfo['business_id_info'] = $dataInfo['business_id'] ? db('crm_business')->where(['business_id' => $dataInfo['business_id']])->field('business_id,name')->find() : [];
  799. $dataInfo['business_name'] = !empty($dataInfo['business_id_info']['name']) ? $dataInfo['business_id_info']['name'] : '';
  800. $dataInfo['customer_id_info'] = $dataInfo['customer_id'] ? db('crm_customer')->where(['customer_id' => $dataInfo['customer_id']])->field('customer_id,name')->find() : [];
  801. $dataInfo['customer_name'] = !empty($dataInfo['customer_id_info']['name']) ? $dataInfo['customer_id_info']['name'] : '';
  802. //回款金额
  803. $receivablesMoney = $receivablesModel->getMoneyByContractId($id);
  804. $dataInfo['receivablesMoney'] = $receivablesMoney ? : [];
  805. # 签约人姓名
  806. $orderNames = Db::name('admin_user')->whereIn('id', trim($dataInfo['order_user_id'], ','))->column('realname');
  807. $dataInfo['order_user_name'] = implode(',', $orderNames);
  808. # 处理时间根式
  809. $fieldModel = new \app\admin\model\Field();
  810. $datetimeField = $fieldModel->getFieldByFormType('crm_contract', 'datetime'); //日期时间类型
  811. foreach ($datetimeField as $key => $val) {
  812. $dataInfo[$val] = !empty($dataInfo[$val]) ? date('Y-m-d H:i:s', $dataInfo[$val]) : null;
  813. }
  814. $dataInfo['next_time'] = !empty($dataInfo['next_time']) ? date('Y-m-d H:i:s', $dataInfo['next_time']) : null;
  815. $dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;
  816. $dataInfo['update_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
  817. $dataInfo['last_time'] = !empty($dataInfo['last_time']) ? date('Y-m-d H:i:s', $dataInfo['last_time']) : null;
  818. // 字段授权
  819. if (!empty($userId)) {
  820. $grantData = getFieldGrantData($userId);
  821. $userLevel = isSuperAdministrators($userId);
  822. foreach ($dataInfo AS $key => $value) {
  823. if (!$userLevel && !empty($grantData['crm_contract'])) {
  824. $status = getFieldGrantStatus($key, $grantData['crm_contract']);
  825. # 查看权限
  826. if ($status['read'] == 0) unset($dataInfo[$key]);
  827. }
  828. }
  829. if (!$userLevel && !empty($grantData['crm_contract'])) {
  830. # 客户名称
  831. $customerStatus = getFieldGrantStatus('customer_id', $grantData['crm_contract']);
  832. if ($customerStatus['read'] == 0) {
  833. $dataInfo['customer_name'] = '';
  834. $dataInfo['customer_id_info'] = [];
  835. }
  836. # 回款金额
  837. $doneMoneyStatus = getFieldGrantStatus('done_money', $grantData['crm_contract']);
  838. if ($doneMoneyStatus['read'] == 0) $dataInfo['receivablesMoney'] = '';
  839. }
  840. }
  841. return $dataInfo;
  842. }
  843. /**
  844. * [合同转移]
  845. * @author Michael_xu
  846. * @param ids 合同ID数组
  847. * @param owner_user_id 变更负责人
  848. * @param is_remove 1移出,2转为团队成员
  849. * @return
  850. */
  851. public function transferDataById($ids, $owner_user_id, $type = 1, $is_remove)
  852. {
  853. $settingModel = new \app\crm\model\Setting();
  854. $errorMessage = [];
  855. foreach ($ids as $id) {
  856. $contractInfo = [];
  857. $contractInfo = db('crm_contract')->where(['contract_id' => $id])->find();
  858. // if (in_array($contractInfo['check_status'],['0','1'])) {
  859. // $errorMessage[] = '合同:'.$contractInfo['name'].'"转移失败,错误原因:审批中,无法转移;';
  860. // continue;
  861. // }
  862. //团队成员
  863. $teamData = [];
  864. $teamData['type'] = $type; //权限 1只读2读写
  865. $teamData['user_id'] = [$contractInfo['owner_user_id']]; //协作人
  866. $teamData['types'] = 'crm_contract'; //类型
  867. $teamData['types_id'] = $id; //类型ID
  868. $teamData['is_del'] = ($is_remove == 1) ? 1 : '';
  869. $res = $settingModel->createTeamData($teamData);
  870. $data = [];
  871. $data['owner_user_id'] = $owner_user_id;
  872. $data['update_time'] = time();
  873. if (!db('crm_contract')->where(['contract_id' => $id])->update($data)) {
  874. $errorMessage[] = '合同:'.$contractInfo['name'].'"转移失败,错误原因:数据出错;';
  875. continue;
  876. } else {
  877. $contractArray = [];
  878. $teamContract = db('crm_contract')->field(['owner_user_id', 'ro_user_id', 'rw_user_id'])->where('contract_id', $id)->find();
  879. if (!empty($teamContract['ro_user_id'])) {
  880. $contractRo = arrayToString(array_diff(stringToArray($teamContract['ro_user_id']), [$teamContract['owner_user_id']]));
  881. $contractArray['ro_user_id'] = $contractRo;
  882. }
  883. if (!empty($teamContract['rw_user_id'])) {
  884. $contractRo = arrayToString(array_diff(stringToArray($teamContract['rw_user_id']), [$teamContract['owner_user_id']]));
  885. $contractArray['rw_user_id'] = $contractRo;
  886. }
  887. db('crm_contract')->where('contract_id', $id)->update($contractArray);
  888. }
  889. }
  890. if ($errorMessage) {
  891. return $errorMessage;
  892. } else {
  893. return true;
  894. }
  895. }
  896. /**
  897. * 根据对象ID 获取该年各个月合同金额
  898. * @return [year] [哪一年]
  899. * @return [owner_user_id] [哪个员工]
  900. * @return [start_time] [开始时间]
  901. * @return [end_time] [结束时间]
  902. */
  903. public function getDataByUserId($param)
  904. {
  905. if ($param['obj_type']) {
  906. if ($param['obj_type'] == 1) { //部门
  907. $userModel = new \app\admin\model\User();
  908. $str = $userModel->getSubUserByStr($param['obj_id'], 1) ? : ['-1'];
  909. $map['owner_user_id'] = array('in',$str);
  910. } else { //员工
  911. $map['owner_user_id'] = $param['obj_id'];
  912. }
  913. }
  914. //审核状态
  915. $start = date('Y-m-d',$param['start_time']);
  916. $stop = date('Y-m-d',$param['end_time']);
  917. $map['check_status'] = 2;
  918. $data = $this->where($map)->where(['order_date' => ['between',[$start, $stop]]])->sum('money');
  919. return $data;
  920. }
  921. /**
  922. * 获取系统信息
  923. *
  924. * @param $id
  925. * @return array
  926. * @throws \think\db\exception\DataNotFoundException
  927. * @throws \think\db\exception\ModelNotFoundException
  928. * @throws \think\exception\DbException
  929. */
  930. public function getSystemInfo($id)
  931. {
  932. # 合同
  933. $contract = Db::name('crm_contract')->where('contract_id', $id)->find();
  934. # 创建人
  935. $realname = Db::name('admin_user')->where('id', $contract['create_user_id'])->value('realname');
  936. # zjf 20210726
  937. $userModel = new \app\admin\model\User();
  938. $ownerUserInfo = $userModel->getUserById($contract['owner_user_id']);
  939. # 负责人部门
  940. $ownerStructureName = $ownerUserInfo['structure_name'];
  941. # 负责人
  942. $ownerUserName = $ownerUserInfo['realname'];
  943. # 回款
  944. $receivablesModel = new Receivables();
  945. $receivables = $receivablesModel->getMoneyByContractId($id);
  946. return [
  947. 'create_user_id' => $realname,
  948. 'owner_user_id' => $ownerUserName,
  949. 'create_time' => date('Y-m-d H:i:s', $contract['create_time']),
  950. 'update_time' => date('Y-m-d H:i:s', $contract['update_time']),
  951. 'last_time' => !empty($contract['last_time']) ? date('Y-m-d H:i:s', $contract['last_time']) : '',
  952. 'done_money' => $receivables['doneMoney'],
  953. 'un_money' => $receivables['unMoney'],
  954. 'owner_user_structure_name' => $ownerStructureName
  955. ];
  956. }
  957. /**
  958. * 拷贝合同
  959. *
  960. * @param $contractId
  961. * @param $userId
  962. * @return bool
  963. * @throws \think\db\exception\DataNotFoundException
  964. * @throws \think\db\exception\ModelNotFoundException
  965. * @throws \think\exception\DbException
  966. */
  967. public function copy($contractId, $userId)
  968. {
  969. $targetContract = Db::name('crm_contract')->where('contract_id', $contractId)->find();
  970. $targetProduct = Db::name('crm_contract_product')->where('contract_id', $contractId)->select();
  971. if (empty($targetContract['contract_id'])) return false;
  972. # 删除主键
  973. unset($targetContract['contract_id']);
  974. Db::startTrans();
  975. try{
  976. # 合同数据
  977. $targetContract['num'] = 'WKCrm#contract#num#' . date('YmdHis');
  978. $targetContract['name'] = 'WKCrm#contract#name#'. date('YmdHis');
  979. $targetContract['create_user_id'] = $userId;
  980. $targetContract['owner_user_id'] = $userId;
  981. $targetContract['create_time'] = time();
  982. $targetContract['update_time'] = time();
  983. $targetContract['is_visit'] = 2;
  984. $targetContract['expire_remind'] = 1;
  985. if (in_array($targetContract['check_status'], [1, 2, 3, 4])) {
  986. $checkUserId = trim($targetContract['check_user_id'], ',');
  987. $flowUserId = trim($targetContract['flow_user_id'], ',');
  988. $symbol = !empty($checkUserId) ? ',' : '';
  989. $targetContract['check_user_id'] = ',' . $checkUserId . $symbol . $flowUserId . ',';
  990. $targetContract['check_status'] = 0;
  991. }
  992. Db::name('crm_contract')->insert($targetContract);
  993. $newContractId = Db::name('crm_contract')->getLastInsID();
  994. # 产品数据
  995. $productData = [];
  996. foreach ($targetProduct AS $key => $value) {
  997. $productData[] = [
  998. 'contract_id' => $newContractId,
  999. 'product_id' => $value['product_id'],
  1000. 'price' => $value['price'],
  1001. 'sales_price' => $value['sales_price'],
  1002. 'num' => $value['num'],
  1003. 'discount' => $value['discount'],
  1004. 'subtotal' => $value['subtotal'],
  1005. 'unit' => $value['unit']
  1006. ];
  1007. }
  1008. if (!empty($productData)) Db::name('crm_contract_product')->insertAll($productData);
  1009. Db::commit();
  1010. return true;
  1011. } catch (\Exception $e) {
  1012. Db::rollback();
  1013. return false;
  1014. }
  1015. }
  1016. }