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