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