Receivables.php 31KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | Description: 回款
  4. // +----------------------------------------------------------------------
  5. // | Author: Michael_xu | gengxiaoxu@5kcrm.com
  6. // +----------------------------------------------------------------------
  7. namespace app\crm\model;
  8. use think\Db;
  9. use app\crm\model\Contract as ContractModel;
  10. use app\admin\model\Common;
  11. use app\admin\model\Message;
  12. use think\Request;
  13. use think\Validate;
  14. class Receivables extends Common
  15. {
  16. /**
  17. * 为了数据库的整洁,同时又不影响Model和Controller的名称
  18. * 我们约定每个模块的数据表都加上相同的前缀,比如CRM模块用crm作为数据表前缀
  19. */
  20. protected $name = 'crm_receivables';
  21. protected $createTime = 'create_time';
  22. protected $updateTime = 'update_time';
  23. protected $autoWriteTimestamp = true;
  24. private $statusArr = ['0'=>'待审核','1'=>'审核中','2'=>'审核通过','3'=>'已拒绝','4'=>'已撤回'];
  25. /**
  26. * [getDataList 回款list]
  27. *
  28. * @param $request
  29. * @return array
  30. * @throws \think\db\exception\DataNotFoundException
  31. * @throws \think\db\exception\ModelNotFoundException
  32. * @throws \think\exception\DbException
  33. */
  34. public function getDataList($request)
  35. {
  36. $userModel = new \app\admin\model\User();
  37. $structureModel = new \app\admin\model\Structure();
  38. $fieldModel = new \app\admin\model\Field();
  39. $search = $request['search'];
  40. $user_id = $request['user_id'];
  41. $scene_id = (int)$request['scene_id'];
  42. $order_field = $request['order_field'];
  43. $order_type = $request['order_type'];
  44. $getCount = $request['getCount'];
  45. $receivablesIdArray = $request['receivablesIdArray']; // 待办事项提醒参数
  46. unset($request['scene_id']);
  47. unset($request['search']);
  48. unset($request['user_id']);
  49. unset($request['order_field']);
  50. unset($request['order_type']);
  51. unset($request['getCount']);
  52. unset($request['receivablesIdArray']);
  53. $request = $this->fmtRequest( $request );
  54. $requestMap = $request['map'] ? : [];
  55. $sceneModel = new \app\admin\model\Scene();
  56. # getCount是代办事项传来的参数,代办事项不需要使用场景
  57. $sceneMap = [];
  58. if (empty($getCount)) {
  59. if ($scene_id) {
  60. //自定义场景
  61. $sceneMap = $sceneModel->getDataById($scene_id, $user_id, 'receivables') ? : [];
  62. } else {
  63. //默认场景
  64. $sceneMap = $sceneModel->getDefaultData('crm_receivables', $user_id) ? : [];
  65. }
  66. }
  67. $searchWhere = [];
  68. if (!empty($search) || $search == '0') {
  69. //普通筛选
  70. $searchWhere = function ($query) use ($search) {
  71. $query->where(function ($query) use ($search){
  72. $query->whereLike('customer.name', '%' . $search . '%');
  73. })->whereOr(function ($query) use ($search) {
  74. $query->whereLike('receivables.number', '%' . $search . '%');
  75. });
  76. };
  77. // if (db('crm_customer')->whereLike('name', '%' . $search . '%')->value('customer_id')) {
  78. // $sceneMap['customer_name'] = ['condition' => 'contains', 'value' => $search, 'form_type' => 'text', 'name' => '客户名称'];
  79. // } else {
  80. // $sceneMap['number'] = ['condition' => 'contains','value' => $search,'form_type' => 'text','name' => '回款编号'];
  81. // }
  82. }
  83. //优先级:普通筛选>高级筛选>场景
  84. $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
  85. //高级筛选
  86. $map = where_arr($map, 'crm', 'receivables', 'index');
  87. //权限
  88. $authMap = [];
  89. $auth_user_ids = $userModel->getUserByPer('crm', 'receivables', 'index');
  90. if (isset($map['receivables.owner_user_id']) && $map['receivables.owner_user_id'][0] != 'like') {
  91. if (!is_array($map['receivables.owner_user_id'][1])) {
  92. $map['receivables.owner_user_id'][1] = [$map['receivables.owner_user_id'][1]];
  93. }
  94. if (in_array($map['receivables.owner_user_id'][0], ['neq', 'notin'])) {
  95. $auth_user_ids = array_diff($auth_user_ids, $map['receivables.owner_user_id'][1]) ? : []; //取差集
  96. } else {
  97. $auth_user_ids = array_intersect($map['receivables.owner_user_id'][1], $auth_user_ids) ? : []; //取交集
  98. }
  99. unset($map['receivables.owner_user_id']);
  100. }
  101. $auth_user_ids = array_merge(array_unique(array_filter($auth_user_ids))) ? : ['-1'];
  102. //负责人、相关团队
  103. $authMap['receivables.owner_user_id'] = ['in',$auth_user_ids];
  104. //列表展示字段
  105. $indexField = $fieldModel->getIndexField('crm_receivables', $user_id, 1) ? : array('number');
  106. //人员类型
  107. $userField = $fieldModel->getFieldByFormType('crm_receivables', 'user');
  108. $structureField = $fieldModel->getFieldByFormType('crm_receivables', 'structure'); //部门类型
  109. $datetimeField = $fieldModel->getFieldByFormType('crm_receivables', 'datetime'); //日期时间类型
  110. # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
  111. $temporaryField = str_replace('_name', '', $order_field);
  112. if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
  113. $order_field = $temporaryField;
  114. }
  115. //排序
  116. if ($order_type && $order_field) {
  117. $order = $fieldModel->getOrderByFormtype('crm_receivables','receivables',$order_field, $order_type);
  118. } else {
  119. $order = 'receivables.update_time desc';
  120. }
  121. # 待办事项查询参数
  122. $dealtWhere = [];
  123. if (!empty($receivablesIdArray)) $dealtWhere['receivables.receivables_id'] = ['in', $receivablesIdArray];
  124. $readAuthIds = $userModel->getUserByPer('crm', 'receivables', 'read');
  125. $updateAuthIds = $userModel->getUserByPer('crm', 'receivables', 'update');
  126. $deleteAuthIds = $userModel->getUserByPer('crm', 'receivables', 'delete');
  127. $dataCount = db('crm_receivables')
  128. ->alias('receivables')
  129. ->join('__CRM_CUSTOMER__ customer','receivables.customer_id = customer.customer_id','LEFT')
  130. ->join('__CRM_CONTRACT__ contract','receivables.contract_id = contract.contract_id','LEFT')
  131. ->where($searchWhere)->where($map)->where($authMap)->where($dealtWhere)->count('receivables_id');
  132. if (!empty($getCount) && $getCount == 1) {
  133. $data['dataCount'] = !empty($dataCount) ? $dataCount : 0;
  134. $data['extraData']['money'] = ['receivablesMoney' => $this->getReceivablesMoney($map, $authMap)];
  135. return $data;
  136. }
  137. foreach ($indexField AS $kk => $vv) {
  138. if ($vv == 'receivables.contract_num') unset($indexField[(int)$kk]);
  139. }
  140. $list = db('crm_receivables')
  141. ->alias('receivables')
  142. ->join('__CRM_CUSTOMER__ customer','receivables.customer_id = customer.customer_id','LEFT')
  143. ->join('__CRM_CONTRACT__ contract','receivables.contract_id = contract.contract_id','LEFT')
  144. ->where($searchWhere)
  145. ->where($map)
  146. ->where($authMap)
  147. ->where($dealtWhere)
  148. ->limit($request['offset'], $request['length'])
  149. ->field('receivables.*,customer.name as customer_name,contract.name as contract_name,contract.num as contract_num,contract.money as contract_money')
  150. ->orderRaw($order)
  151. ->select();
  152. foreach ($list as $k=>$v) {
  153. $list[$k]['create_user_id_info'] = $v['create_user_id'] ? $userModel->getUserById($v['create_user_id']) : [];
  154. $list[$k]['owner_user_id_info'] = $v['owner_user_id'] ? $userModel->getUserById($v['owner_user_id']) : [];
  155. $list[$k]['create_user_name'] = !empty($list[$k]['create_user_id_info']['realname']) ? $list[$k]['create_user_id_info']['realname'] : '';
  156. $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
  157. $list[$k]['customer_id_info']['customer_id'] = $v['customer_id'] ? : '';
  158. $list[$k]['customer_id_info']['name'] = $v['customer_name'] ? : '';
  159. $list[$k]['contract_id_info']['contract_id'] = $v['contract_id'] ? : '';
  160. $list[$k]['contract_id_info']['name'] = $v['contract_num'] ? : '';
  161. $list[$k]['contract_id_info']['money'] = $v['contract_money'] ? : '0.00';
  162. $list[$k]['contract_money'] = $v['contract_money'] ? : '0.00';
  163. foreach ($userField as $key => $val) {
  164. $usernameField = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
  165. $list[$k][$val.'_name'] = implode($usernameField, ',');
  166. }
  167. foreach ($structureField as $key => $val) {
  168. $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
  169. $list[$k][$val.'_name'] = implode($structureNameField, ',');
  170. }
  171. foreach ($datetimeField as $key => $val) {
  172. $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
  173. }
  174. $list[$k]['check_status_info'] = $this->statusArr[$v['check_status']];
  175. //期数
  176. $plan_num = db('crm_receivables_plan')->where(['plan_id' => $v['plan_id']])->value('num');
  177. $list[$k]['plan_id_info'] = $plan_num ? : '';
  178. //权限
  179. $permission = [];
  180. $is_read = 0;
  181. $is_update = 0;
  182. $is_delete = 0;
  183. if (in_array($v['owner_user_id'],$readAuthIds)) $is_read = 1;
  184. if (in_array($v['owner_user_id'],$updateAuthIds)) $is_update = 1;
  185. if (in_array($v['owner_user_id'],$deleteAuthIds)) $is_delete = 1;
  186. $permission['is_read'] = $is_read;
  187. $permission['is_update'] = $is_update;
  188. $permission['is_delete'] = $is_delete;
  189. $list[$k]['permission'] = $permission;
  190. # 日期
  191. $list[$k]['create_time'] = !empty($v['create_time']) ? date('Y-m-d H:i:s', $v['create_time']) : null;
  192. $list[$k]['update_time'] = !empty($v['update_time']) ? date('Y-m-d H:i:s', $v['update_time']) : null;
  193. }
  194. $data = [];
  195. $data['list'] = $list;
  196. $data['dataCount'] = $dataCount ? : 0;
  197. $data['extraData']['money'] = ['receivablesMoney' => $this->getReceivablesMoney($map, $authMap)];
  198. return $data;
  199. }
  200. /**
  201. * 获取回款总金额
  202. *
  203. * @param $map
  204. * @param $authMap
  205. * @return float|string
  206. */
  207. private function getReceivablesMoney($map, $authMap)
  208. {
  209. $money = db('crm_receivables')->alias('receivables')
  210. ->join('__CRM_CUSTOMER__ customer','receivables.customer_id = customer.customer_id','LEFT')
  211. ->join('__CRM_CONTRACT__ contract','receivables.contract_id = contract.contract_id','LEFT')
  212. ->where($map)->where($authMap)->where('receivables.check_status', 2)->sum('receivables.money');
  213. return !empty($money) ? sprintf("%.2f", $money) : 0.00;
  214. }
  215. /**
  216. * 创建回款信息
  217. * @author Michael_xu
  218. * @param
  219. * @return
  220. */
  221. public function createData($param)
  222. {
  223. if (!$param['customer_id']) {
  224. $this->error = '请先选择客户';
  225. return false;
  226. }
  227. // 仅允许审批通过,且未作废的合同添加回款
  228. if ($param['contract_id']) {
  229. $check_status = ContractModel::where(['contract_id' => $param['contract_id']])->value('check_status');
  230. if ($check_status == 6) {
  231. $this->error = '合同已作废';
  232. return false;
  233. } elseif ($check_status != 2) {
  234. $this->error = '合同未审核通过';
  235. return false;
  236. }
  237. } else {
  238. $this->error = '请先选择合同';
  239. return false;
  240. }
  241. $fieldModel = new \app\admin\model\Field();
  242. // 自动验证
  243. $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
  244. $validate = new Validate($validateArr['rule'], $validateArr['message']);
  245. $result = $validate->check($param);
  246. if (!$result) {
  247. $this->error = $validate->getError();
  248. return false;
  249. }
  250. # 验证回款计划是否已经被关联
  251. if (!empty($param['plan_id']) && db('crm_receivables_plan')->where('plan_id', $param['plan_id'])->value('receivables_id')) {
  252. $this->error = '回款已经已经关联了其他回款,不能重复关联!';
  253. return false;
  254. }
  255. // 处理部门、员工、附件、多选类型字段
  256. $arrFieldAtt = $fieldModel->getArrayField('crm_receivables');
  257. foreach ($arrFieldAtt as $k=>$v) {
  258. $param[$v] = arrayToString($param[$v]);
  259. }
  260. // 处理日期(date)类型
  261. $dateField = $fieldModel->getFieldByFormType('crm_receivables', 'date');
  262. if (!empty($dateField)) {
  263. foreach ($param AS $key => $value) {
  264. if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
  265. }
  266. }
  267. if ($this->data($param)->allowField(true)->save()) {
  268. //站内信
  269. $send_user_id = stringToArray($param['check_user_id']);
  270. if ($send_user_id && empty($param['check_status'])) {
  271. (new Message())->send(
  272. Message::RECEIVABLES_TO_DO,
  273. [
  274. 'title' => $param['number'],
  275. 'action_id' => $this->receivables_id
  276. ],
  277. $send_user_id
  278. );
  279. }
  280. $data = [];
  281. $data['receivables_id'] = $this->receivables_id;
  282. //修改记录
  283. updateActionLog($param['create_user_id'], 'crm_receivables', $this->receivables_id, '', '', '创建了回款');
  284. RecordActionLog($param['create_user_id'],'crm_receivables','save',$param['number'],'','','新增了回款'.$param['number']);
  285. # 添加活动记录
  286. Db::name('crm_activity')->insert([
  287. 'type' => 2,
  288. 'activity_type' => 7,
  289. 'activity_type_id' => $data['receivables_id'],
  290. 'content' => $param['number'],
  291. 'create_user_id' => $param['create_user_id'],
  292. 'update_time' => time(),
  293. 'create_time' => time(),
  294. 'customer_ids' => ',' . $param['customer_id'] . ',',
  295. 'contract_ids' => ',' . $param['contract_id'] . ','
  296. ]);
  297. # 创建待办事项的关联数据
  298. $checkUserIds = db('crm_receivables')->where('receivables_id', $data['receivables_id'])->value('check_user_id');
  299. $checkUserIdArray = stringToArray($checkUserIds);
  300. $dealtData = [];
  301. foreach ($checkUserIdArray AS $kk => $vv) {
  302. $dealtData[] = [
  303. 'types' => 'crm_receivables',
  304. 'types_id' => $data['receivables_id'],
  305. 'user_id' => $vv
  306. ];
  307. }
  308. if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData);
  309. return $data;
  310. } else {
  311. $this->error = '添加失败';
  312. return false;
  313. }
  314. }
  315. /**
  316. * 根据对象ID 获取该年各个月回款情况
  317. * @param [year] [哪一年]
  318. * @param [owner_user_id] [哪个员工]
  319. * @param [start_time] [开始时间]
  320. * @param [end_time] [结束时间]
  321. */
  322. public function getDataByUserId($param)
  323. {
  324. if ($param['obj_type']) {
  325. if ($param['obj_type'] == 1) { //部门
  326. $userModel = new \app\admin\model\User();
  327. $str = $userModel->getSubUserByStr($param['obj_id'], 1) ? : ['-1'];
  328. $map['owner_user_id'] = array('in',$str);
  329. } else { //员工
  330. $map['owner_user_id'] = $param['obj_id'];
  331. }
  332. }
  333. //审核状态
  334. $start = date('Y-m-d',$param['start_time']);
  335. $stop = date('Y-m-d',$param['end_time']);
  336. $map['check_status'] = 2;
  337. $data = $this->where($map)->where(['return_time' => ['between',[$start,$stop]]])->sum('money');
  338. return $data;
  339. }
  340. /**
  341. * 编辑回款主表信息
  342. * @author Michael_xu
  343. * @param
  344. * @return
  345. */
  346. public function updateDataById($param, $receivables_id = '')
  347. {
  348. $userModel = new \app\admin\model\User();
  349. $dataInfo = db('crm_receivables')->where(['receivables_id' => $receivables_id])->find();
  350. if (!$dataInfo) {
  351. $this->error = '数据不存在或已删除';
  352. return false;
  353. }
  354. $param['receivables_id'] = $receivables_id;
  355. //过滤不能修改的字段
  356. $unUpdateField = ['create_user_id','is_deleted','delete_time','delete_user_id'];
  357. foreach ($unUpdateField as $v) {
  358. unset($param[$v]);
  359. }
  360. $fieldModel = new \app\admin\model\Field();
  361. // 自动验证
  362. // $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
  363. $validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
  364. $validate = new Validate($validateArr['rule'], $validateArr['message']);
  365. $result = $validate->check($param);
  366. if (!$result) {
  367. $this->error = $validate->getError();
  368. return false;
  369. }
  370. // 处理部门、员工、附件、多选类型字段
  371. $arrFieldAtt = $fieldModel->getArrayField('crm_receivables');
  372. foreach ($arrFieldAtt as $k=>$v) {
  373. if (isset($param[$v])) $param[$v] = arrayToString($param[$v]);
  374. }
  375. // 处理日期(date)类型
  376. $dateField = $fieldModel->getFieldByFormType('crm_receivables', 'date');
  377. if (!empty($dateField)) {
  378. foreach ($param AS $key => $value) {
  379. if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
  380. }
  381. }
  382. if ($this->update($param, ['receivables_id' => $receivables_id], true)) {
  383. //修改记录
  384. updateActionLog($param['user_id'], 'crm_receivables', $receivables_id, $dataInfo, $param);
  385. RecordActionLog($param['user_id'], 'crm_receivables', 'update',$dataInfo['number'], $dataInfo, $param);
  386. //站内信
  387. $send_user_id = stringToArray($param['check_user_id']);
  388. if ($send_user_id && empty($param['check_status'])) {
  389. (new Message())->send(
  390. Message::RECEIVABLES_TO_DO,
  391. [
  392. 'title' => $param['number'],
  393. 'action_id' => $receivables_id
  394. ],
  395. $send_user_id
  396. );
  397. }
  398. $data = [];
  399. $data['receivables_id'] = $receivables_id;
  400. # 删除待办事项的关联数据
  401. db('crm_dealt_relation')->where(['types' => ['eq', 'crm_receivables'], 'types_id' => ['eq', $data['receivables_id']]])->delete();
  402. # 创建待办事项的关联数据
  403. $checkUserIds = db('crm_receivables')->where('receivables_id', $data['receivables_id'])->value('check_user_id');
  404. $checkUserIdArray = stringToArray($checkUserIds);
  405. $dealtData = [];
  406. foreach ($checkUserIdArray AS $kk => $vv) {
  407. $dealtData[] = [
  408. 'types' => 'crm_receivables',
  409. 'types_id' => $data['receivables_id'],
  410. 'user_id' => $vv
  411. ];
  412. }
  413. if (!empty($dealtData)) db('crm_dealt_relation')->insertAll($dealtData);
  414. return $data;
  415. } else {
  416. $this->error = '编辑失败';
  417. return false;
  418. }
  419. }
  420. /**
  421. * 回款数据
  422. *
  423. * @param string $id
  424. * @return Common|array|bool|\PDOStatement|string|\think\Model|null
  425. * @throws \think\db\exception\DataNotFoundException
  426. * @throws \think\db\exception\ModelNotFoundException
  427. * @throws \think\exception\DbException
  428. */
  429. public function getDataById($id = '', $userId = 0)
  430. {
  431. $map['receivables_id'] = $id;
  432. $dataInfo = db('crm_receivables')->where($map)->find();
  433. if (!$dataInfo) {
  434. $this->error = '暂无此数据';
  435. return false;
  436. }
  437. $userModel = new \app\admin\model\User();
  438. $dataInfo['create_user_id_info'] = isset($dataInfo['create_user_id']) ? $userModel->getUserById($dataInfo['create_user_id']) : [];
  439. $dataInfo['owner_user_id_info'] = isset($dataInfo['owner_user_id']) ? $userModel->getUserById($dataInfo['owner_user_id']) : [];
  440. $dataInfo['create_user_name'] = !empty($dataInfo['create_user_id_info']['realname']) ? $dataInfo['create_user_id_info']['realname'] : '';
  441. $dataInfo['owner_user_name'] = !empty($dataInfo['owner_user_id_info']['realname']) ? $dataInfo['owner_user_id_info']['realname'] : '';
  442. $dataInfo['customer_id_info'] = $dataInfo['customer_id'] ? db('crm_customer')->where(['customer_id' => $dataInfo['customer_id']])->field('customer_id,name')->find() : [];
  443. $dataInfo['contract_id_info'] = $dataInfo['contract_id'] ? db('crm_contract')->where(['contract_id' => $dataInfo['contract_id']])->field('contract_id,name,money')->find() : [];
  444. $dataInfo['receivables_id'] = $id;
  445. # 处理时间格式
  446. $fieldModel = new \app\admin\model\Field();
  447. $datetimeField = $fieldModel->getFieldByFormType('crm_receivables', 'datetime'); //日期时间类型
  448. foreach ($datetimeField as $key => $val) {
  449. $dataInfo[$val] = !empty($dataInfo[$val]) ? date('Y-m-d H:i:s', $dataInfo[$val]) : null;
  450. }
  451. $dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;
  452. $dataInfo['update_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
  453. // 字段授权
  454. if (!empty($userId)) {
  455. $grantData = getFieldGrantData($userId);
  456. $userLevel = isSuperAdministrators($userId);
  457. foreach ($dataInfo AS $key => $value) {
  458. if (!$userLevel && !empty($grantData['crm_receivables'])) {
  459. $status = getFieldGrantStatus($key, $grantData['crm_receivables']);
  460. # 查看权限
  461. if ($status['read'] == 0) unset($dataInfo[$key]);
  462. }
  463. }
  464. if (!$userLevel && !empty($grantData['crm_receivables'])) {
  465. # 客户名称
  466. $customerStatus = getFieldGrantStatus('customer_id', $grantData['crm_receivables']);
  467. if ($customerStatus['read'] == 0) {
  468. $dataInfo['customer_name'] = '';
  469. $dataInfo['customer_id_info'] = [];
  470. }
  471. # 合同金额
  472. $contractMoneyStatus = getFieldGrantStatus('contract_money', $grantData['crm_receivables']);
  473. if ($contractMoneyStatus['read'] == 0) $dataInfo['contract_id_info']['money'] = '';
  474. # 合同名称
  475. $contractMoneyStatus = getFieldGrantStatus('contract_money', $grantData['crm_receivables']);
  476. if ($contractMoneyStatus['read'] == 0) $dataInfo['contract_id_info']['money'] = '';
  477. }
  478. }
  479. return $dataInfo;
  480. }
  481. /**
  482. * 回款&&合同统计(列表)
  483. * @param
  484. * @return
  485. */
  486. public function getstatisticsData($request)
  487. {
  488. $userModel = new \app\admin\model\User();
  489. $structureModel = new \app\admin\model\Structure();
  490. $fieldModel = new \app\admin\model\Field();
  491. $contractModel = new \app\crm\model\Contract();
  492. $adminModel = new \app\admin\model\Admin();
  493. $perUserIds = $userModel->getUserByPer('bi', 'receivables', 'read'); //权限范围内userIds
  494. $whereData = $adminModel->getWhere($param, '', $perUserIds); //统计条件
  495. $userIds = $whereData['userIds'];
  496. if (!$request['year']) {
  497. $request['year'] = date('Y');
  498. }
  499. if ($request['month']) {
  500. $start = strtotime($request['year'].'-'.$request['month'].'-01');
  501. if ($request['month'] == '12') {
  502. $next_year = $request['year']+1;
  503. $end = strtotime($next_year.'-01-01');
  504. } else {
  505. $next_month = $request['month']+1;
  506. $end = strtotime($request['year'].'-'.$next_month.'-01');
  507. }
  508. } else {
  509. $next_year = $request['year']+1;
  510. $start = strtotime($request['year'].'-01-01');
  511. $end = strtotime($next_year.'-01-01');
  512. }
  513. $map['owner_user_id'] = ['in',$userIds];
  514. //$map['rec.check_status'] = 3;
  515. $map['create_time'] = array('between',array($start,$end));
  516. //合同有多个回款
  517. //根据时间查合同
  518. if( $request['type'] == '1'){
  519. $map_type['contract.owner_user_id'] = ['in',$userIds];
  520. $map_type['contract.create_time'] = array('between',array($start,$end));
  521. $userField = $fieldModel->getFieldByFormType('crm_contract', 'user');
  522. $structureField = $fieldModel->getFieldByFormType('crm_contract', 'structure'); //部门类型
  523. $list = Db::name('CrmContract')->alias('contract')
  524. ->join('__CRM_CUSTOMER__ customer','contract.customer_id = customer.customer_id','LEFT')
  525. ->join('__CRM_BUSINESS__ business','contract.contract_id = business.business_id','LEFT')
  526. ->join('__CRM_CONTACTS__ contacts','contract.contract_id = contacts.contacts_id','LEFT')
  527. ->field('contract.*,customer.name as customer_name,business.name as business_name,contacts.name as contacts_name')
  528. ->where($map_type)->select();
  529. if($list){
  530. foreach ($list as $k=>$v) {
  531. $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
  532. $list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
  533. foreach ($userField as $key => $val) {
  534. $list[$k][$val.'_info'] = isset($v[$val]) ? $userModel->getListByStr($v[$val]) : [];
  535. }
  536. foreach ($structureField as $key => $val) {
  537. $list[$k][$val.'_info'] = isset($v[$val]) ? $structureModel->getDataByStr($v[$val]) : [];
  538. }
  539. $list[$k]['business_id_info']['business_id'] = $v['business_id'];
  540. $list[$k]['business_id_info']['name'] = $v['business_name'];
  541. $list[$k]['customer_id_info']['customer_id'] = $v['customer_id'];
  542. $list[$k]['customer_id_info']['name'] = $v['customer_name'];
  543. $list[$k]['contacts_id_info']['customer_id'] = $v['contacts_id'];
  544. $list[$k]['contacts_id_info']['name'] = $v['contacts_name'];
  545. $list[$k]['check_status_info'] = $this->statusArr[$v['check_status']];
  546. }
  547. return $list;
  548. } else {
  549. return array();
  550. }
  551. } else { //回款
  552. $map_rec['receivables.owner_user_id'] = ['in',$userIds];
  553. //$map['rec.check_status'] = 3;
  554. $map_rec['receivables.create_time'] = array('between',array($start,$end));
  555. $map_rec['receivables.check_status'] = 2;
  556. $userField = $fieldModel->getFieldByFormType('crm_receivables', 'user');
  557. $structureField = $fieldModel->getFieldByFormType('crm_receivables', 'structure'); //部门类型
  558. $list = db('crm_receivables')
  559. ->alias('receivables')
  560. ->join('__CRM_CUSTOMER__ customer','receivables.customer_id = customer.customer_id','LEFT')
  561. ->join('__CRM_CONTRACT__ contract','receivables.contract_id = contract.contract_id','LEFT')
  562. ->where($map_rec)
  563. ->field('receivables.*,customer.name as customer_name,contract.name as contract_name,contract.num as contract_num,contract.money as contract_money')
  564. ->select();
  565. foreach ($list as $k=>$v) {
  566. $list[$k]['create_user_id_info'] = $v['create_user_id'] ? $userModel->getUserById($v['create_user_id']) : [];
  567. $list[$k]['owner_user_id_info'] = $v['owner_user_id'] ? $userModel->getUserById($v['owner_user_id']) : [];
  568. $list[$k]['customer_id_info']['customer_id'] = $v['customer_id'] ? : '';
  569. $list[$k]['customer_id_info']['name'] = $v['customer_name'] ? : '';
  570. $list[$k]['contract_id_info']['contract_id'] = $v['contract_id'] ? : '';
  571. $list[$k]['contract_id_info']['name'] = $v['contract_name'] ? : '';
  572. $list[$k]['contract_id_info']['money'] = $v['contract_money'] ? : '0.00';
  573. $list[$k]['contract_money'] = $v['contract_money'] ? : '0.00';
  574. foreach ($userField as $key => $val) {
  575. $list[$k][$val.'_info'] = isset($v[$val]) ? $userModel->getListByStr($v[$val]) : [];
  576. }
  577. foreach ($structureField as $key => $val) {
  578. $list[$k][$val.'_info'] = isset($v[$val]) ? $structureModel->getDataByStr($v[$val]) : [];
  579. }
  580. $list[$k]['check_status_info'] = $this->statusArr[$v['check_status']];
  581. }
  582. return $list;
  583. }
  584. }
  585. /**
  586. * [回款统计] 柱状图
  587. * @author Michael_xu
  588. * @param request [查询条件]
  589. * @param
  590. * @return [array]
  591. */
  592. public function getStatistics($request)
  593. {
  594. $userModel = new \app\admin\model\User();
  595. $userIds = $request['userIds'];
  596. $charMonthArr = []; //按照月份
  597. $charQuarterArr = []; //按照季度
  598. $quarter = 0;
  599. $contractMoneyTotal = '';
  600. $receivablesMoneyTotal = '';
  601. //按照月份
  602. for ($i = 1; $i < 13; $i++) {
  603. $contractMoney = '0.00';
  604. $receivablesMoney = '0.00';
  605. $conQuarterMoney = '0.00';
  606. $reQuarterMoney = '0.00';
  607. $start_time = strtotime($request['year'].'-'.$i.'-01');
  608. $next_i = $i+1;
  609. $end_time = strtotime($request['year'].'-'.$next_i.'-01')-1;
  610. if ($i == 12) {
  611. $next_year = $request['year']+1;
  612. $end_time = strtotime($next_year.'-01-01')-1;
  613. }
  614. $where_receivables = [];
  615. $where_contract = [];
  616. $where_contract['owner_user_id'] = ['in',$userIds];
  617. $where_receivables['owner_user_id'] = ['in',$userIds];
  618. $where_contract['create_time'] = array('between',array($start_time,$end_time));
  619. $where_receivables['return_time'] = array('between',array( date('Y-m-d',$start_time),date('Y-m-d',$end_time)));
  620. $where_receivables['owner_user_id'] = ['in',$userIds];
  621. $where_receivables['check_status'] = $where_contract['check_status'] = 2; //审核通过
  622. $contractMoney = db('crm_contract')->where($where_contract)->sum('money');
  623. $receivablesMoney = db('crm_receivables')->where($where_receivables)->sum('money');
  624. $conQuarterMoney += $charMonthArr[$i]['contractMoney'] = $contractMoney;
  625. $reQuarterMoney += $charMonthArr[$i]['receivablesMoney'] = $receivablesMoney;
  626. if (in_array($i, array('3','4','6','9','12'))) {
  627. //季度
  628. $quarter++;
  629. $charQuarterArr[$quarter]['conQuarterMoney'] = $conQuarterMoney;
  630. $charQuarterArr[$quarter]['reQuarterMoney'] = $reQuarterMoney;
  631. $conQuarterMoney = '0.00';
  632. $reQuarterMoney = '0.00';
  633. }
  634. $contractMoneyTotal += $contractMoney;
  635. $receivablesMoneyTotal += $receivablesMoney;
  636. }
  637. $data['charMonthArr'] = $charMonthArr; //月度统计
  638. $data['charQuarterArr'] = $charQuarterArr; //季度统计
  639. $data['contractMoneyTotal'] = $contractMoneyTotal ? : 0.00;
  640. $data['receivablesMoneyTotal'] = $receivablesMoneyTotal ? : 0.00;
  641. return $data;
  642. }
  643. /**
  644. * [合同回款金额]
  645. * @author Michael_xu
  646. * @param contract_id 合同ID
  647. * @param
  648. * @return
  649. */
  650. public function getMoneyByContractId($contract_id)
  651. {
  652. $doneMoney = $this->where(['contract_id' => $contract_id,'check_status' => 2])->sum('money');
  653. $contractMoney = db('crm_contract')->where(['contract_id' => $contract_id])->value('money');
  654. $unMoney = $contractMoney-$doneMoney;
  655. $data['doneMoney'] = $doneMoney ? : '0.00';
  656. $data['unMoney'] = (int)$unMoney>0 ? (int)$unMoney : '0.00';
  657. $data['contractMoney'] = $contractMoney ? : '0.00';
  658. return $data;
  659. }
  660. /**
  661. * 获取系统信息
  662. *
  663. * @param $id
  664. * @return array
  665. * @throws \think\db\exception\DataNotFoundException
  666. * @throws \think\db\exception\ModelNotFoundException
  667. * @throws \think\exception\DbException
  668. */
  669. public function getSystemInfo($id)
  670. {
  671. # 回款
  672. $receivables = Db::name('crm_receivables')->field(['create_user_id', 'create_time', 'update_time'])->where('receivables_id', $id)->find();
  673. # 创建人
  674. $realname = Db::name('admin_user')->where('id', $receivables['create_user_id'])->value('realname');
  675. return [
  676. 'create_user_id' => $realname,
  677. 'create_time' => date('Y-m-d H:i:s', $receivables['create_time']),
  678. 'update_time' => date('Y-m-d H:i:s', $receivables['update_time'])
  679. ];
  680. }
  681. }