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