Product.php 33KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  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\admin\model\Common;
  10. use app\admin\model\User as UserModel;
  11. use app\admin\model\File as FileModel;
  12. use think\Request;
  13. use think\Validate;
  14. use traits\model\SoftDelete;
  15. class Product extends Common
  16. {
  17. use SoftDelete;
  18. protected $deleteTime = 'delete_time';
  19. /**
  20. * 为了数据库的整洁,同时又不影响Model和Controller的名称
  21. * 我们约定每个模块的数据表都加上相同的前缀,比如CRM模块用crm作为数据表前缀
  22. */
  23. protected $name = 'crm_product';
  24. protected $createTime = 'create_time';
  25. protected $updateTime = 'update_time';
  26. protected $autoWriteTimestamp = true;
  27. /**
  28. * [getDataList 产品list]
  29. *
  30. * @param $request
  31. * @return array
  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. $search = $request['search'];
  39. $user_id = $request['user_id'];
  40. $is_excel = $request['is_excel']; //导出
  41. $scene_id = (int)$request['scene_id'];
  42. $order_field = $request['order_field'];
  43. $order_type = $request['order_type'];
  44. $isStatus = !empty($request['is_status']) ? $request['is_status'] : 0;
  45. unset($request['scene_id']);
  46. unset($request['search']);
  47. unset($request['user_id']);
  48. unset($request['order_field']);
  49. unset($request['order_type']);
  50. unset($request['is_status']);
  51. $request = $this->fmtRequest($request);
  52. $requestMap = $request['map'] ?: [];
  53. $sceneModel = new \app\admin\model\Scene();
  54. if ($scene_id) {
  55. //自定义场景
  56. $sceneMap = $sceneModel->getDataById($scene_id, $user_id, 'product') ?: [];
  57. } else {
  58. //默认场景
  59. $sceneMap = $sceneModel->getDefaultData('crm_product', $user_id) ?: [];
  60. }
  61. if ($search || $search == '0') {
  62. //普通筛选
  63. $sceneMap['name'] = ['condition' => 'contains', 'value' => $search, 'form_type' => 'text', 'name' => '产品名称'];
  64. }
  65. //优先级:普通筛选>高级筛选>场景
  66. $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
  67. //高级筛选
  68. $map = where_arr($map, 'crm', 'product', 'index');
  69. if (!empty($isStatus)) {
  70. $map['product.status'] = '上架';
  71. }
  72. if (empty($map['product.delete_user_id'])) {
  73. $map['product.delete_user_id'] = 0;
  74. }
  75. //权限
  76. $a = 'index';
  77. if ($is_excel) $a = 'excelExport';
  78. $auth_user_ids = $userModel->getUserByPer('crm', 'product', $a);
  79. //过滤权限
  80. if (isset($map['product.owner_user_id']) && $map['product.owner_user_id'][0] != 'like') {
  81. if (!is_array($map['product.owner_user_id'][1])) {
  82. $map['product.owner_user_id'][1] = [$map['product.owner_user_id'][1]];
  83. }
  84. if (in_array($map['product.owner_user_id'][0], ['neq', 'notin'])) {
  85. $auth_user_ids = array_diff($auth_user_ids, $map['product.owner_user_id'][1]) ?: []; //取差集
  86. } else {
  87. $auth_user_ids = array_intersect($map['product.owner_user_id'][1], $auth_user_ids) ?: []; //取交集
  88. }
  89. unset($map['product.owner_user_id']);
  90. }
  91. $auth_user_ids = array_merge(array_unique(array_filter($auth_user_ids))) ?: ['-1'];
  92. //负责人
  93. $authMap['product.owner_user_id'] = ['in', $auth_user_ids];
  94. //列表展示字段
  95. $indexField = $fieldModel->getIndexField('crm_product', $user_id, 1) ?: ['name'];
  96. $userField = $fieldModel->getFieldByFormType('crm_product', 'user'); //人员类型
  97. $structureField = $fieldModel->getFieldByFormType('crm_product', 'structure'); //部门类型
  98. $datetimeField = $fieldModel->getFieldByFormType('crm_product', 'datetime'); //日期时间类型
  99. # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
  100. $temporaryField = str_replace('_name', '', $order_field);
  101. if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
  102. $order_field = $temporaryField;
  103. }
  104. //排序
  105. if ($order_type && $order_field) {
  106. $order = $fieldModel->getOrderByFormtype('crm_product', 'product', $order_field, $order_type);
  107. } else {
  108. $order = 'product.update_time desc';
  109. }
  110. $join = [
  111. ['__CRM_PRODUCT_CATEGORY__ product_category', 'product_category.category_id = product.category_id', 'LEFT'],
  112. ];
  113. $map['product.delete_user_id'] = 0;
  114. $list = db('crm_product')->alias('product')
  115. ->join($join)
  116. ->where($map)
  117. ->where($authMap)
  118. ->limit($request['offset'], $request['length'])
  119. ->field($indexField)
  120. ->field('product.*,product_category.name as category_name')
  121. ->orderRaw($order)
  122. ->select();
  123. $dataCount = db('crm_product')->alias('product')
  124. ->where($map)->where($authMap)
  125. ->count('product_id');
  126. foreach ($list as $k => $v) {
  127. $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
  128. $list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
  129. $list[$k]['create_user_name'] = !empty($list[$k]['create_user_id_info']['realname']) ? $list[$k]['create_user_id_info']['realname'] : '';
  130. $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
  131. foreach ($userField as $key => $val) {
  132. $usernameField = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
  133. $list[$k][$val . '_name'] = implode($usernameField, ',');
  134. }
  135. foreach ($structureField as $key => $val) {
  136. $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
  137. $list[$k][$val . '_name'] = implode($structureNameField, ',');
  138. }
  139. foreach ($datetimeField as $key => $val) {
  140. $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
  141. }
  142. //产品类型
  143. $list[$k]['category_id_info'] = $v['category_name'];
  144. # 处理日期格式
  145. $list[$k]['create_time'] = !empty($v['create_time']) ? date('Y-m-d H:i:s', $v['create_time']) : null;
  146. $list[$k]['update_time'] = !empty($v['update_time']) ? date('Y-m-d H:i:s', $v['update_time']) : null;
  147. }
  148. $data = [];
  149. $data['list'] = $list;
  150. $data['dataCount'] = $dataCount ?: 0;
  151. return $data;
  152. }
  153. /**
  154. * 创建产品主表信息
  155. * @param
  156. * @return
  157. * @author Michael_xu
  158. */
  159. public function createData($param)
  160. {
  161. $fieldModel = new \app\admin\model\Field();
  162. $productCategoryModel = model('ProductCategory');
  163. $dataInfo = db('crm_product')->where(['name' => $param['name'], 'delete_user_id' => 0])->find();
  164. if (isset($dataInfo)) {
  165. // 自动验证
  166. $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
  167. $validate = new Validate($validateArr['rule'], $validateArr['message']);
  168. $result = $validate->check($param);
  169. if (!$result) {
  170. $this->error = $validate->getError();
  171. return false;
  172. }
  173. }
  174. // 处理部门、员工、附件、多选类型字段
  175. $arrFieldAtt = $fieldModel->getArrayField('crm_product');
  176. foreach ($arrFieldAtt as $k => $v) {
  177. $param[$v] = arrayToString($param[$v]);
  178. }
  179. // 处理日期(date)类型
  180. $dateField = $fieldModel->getFieldByFormType('crm_product', 'date');
  181. if (!empty($dateField)) {
  182. foreach ($param as $key => $value) {
  183. if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
  184. }
  185. }
  186. //产品分类
  187. $category_id = $param['category_id'];
  188. if (is_array($category_id)) {
  189. $param['category_id'] = $productCategoryModel->getIdByStr($category_id);
  190. $param['category_str'] = arrayToString($category_id);
  191. }
  192. if (!is_int($category_id)) {
  193. $list = db('crm_product_category')->column('category_id', 'name');
  194. foreach ($list as $k => $v) {
  195. if ($k == $param['category_id']) {
  196. $param['category_id'] = $v;
  197. }
  198. }
  199. }
  200. if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
  201. updateActionLog($param['create_user_id'], 'crm_product', $this->product_id, '', '', '创建了产品');
  202. RecordActionLog($param['create_user_id'], 'crm_product', 'save', $param['name'], '', '', '新增了产品' . $param['name']);
  203. $data = [];
  204. $data['product_id'] = $this->product_id;
  205. return $data;
  206. } else {
  207. $this->error = '添加失败';
  208. return false;
  209. }
  210. }
  211. /**
  212. * 编辑产品主表信息
  213. * @param
  214. * @return
  215. * @author Michael_xu
  216. */
  217. public function updateDataById($param, $product_id = '')
  218. {
  219. $userModel = new \app\admin\model\User();
  220. $dataInfo = $this->getDataById($product_id);
  221. $productCategoryModel = model('ProductCategory');
  222. if (!$dataInfo) {
  223. $this->error = '数据不存在或已删除';
  224. return false;
  225. }
  226. //判断权限
  227. $auth_user_ids = $userModel->getUserByPer('crm', 'product', 'update');
  228. if (!in_array($dataInfo['owner_user_id'], $auth_user_ids)) {
  229. $this->error = '无权操作';
  230. return false;
  231. }
  232. $param['product_id'] = $product_id;
  233. //过滤不能修改的字段
  234. $unUpdateField = ['create_user_id', 'is_deleted'];
  235. foreach ($unUpdateField as $v) {
  236. unset($param[$v]);
  237. }
  238. $fieldModel = new \app\admin\model\Field();
  239. // 自动验证
  240. // $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
  241. $validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
  242. $validate = new Validate($validateArr['rule'], $validateArr['message']);
  243. $result = $validate->check($param);
  244. if (!$result) {
  245. $this->error = $validate->getError();
  246. return false;
  247. }
  248. // 处理部门、员工、附件、多选类型字段
  249. $arrFieldAtt = $fieldModel->getArrayField('crm_product');
  250. foreach ($arrFieldAtt as $k => $v) {
  251. if (isset($param[$v])) $param[$v] = arrayToString($param[$v]);
  252. }
  253. // 处理日期(date)类型
  254. $dateField = $fieldModel->getFieldByFormType('crm_product', 'date');
  255. if (!empty($dateField)) {
  256. foreach ($param as $key => $value) {
  257. if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
  258. }
  259. }
  260. //产品分类
  261. $category_id = $param['category_id'];
  262. // if (is_array($category_id)) {
  263. // $param['category_id'] = $productCategoryModel->getIdByStr($category_id);
  264. // $param['category_str'] = arrayToString($category_id);
  265. // }
  266. if (!is_int($category_id)) {
  267. $list = db('crm_product_category')->column('category_id', 'name');
  268. $param['category_id'] = 1;
  269. foreach ($list as $k => $v) {
  270. if ($k == $category_id) {
  271. $param['category_id'] = $v;
  272. }
  273. }
  274. }
  275. if ($this->update($param, ['product_id' => $product_id], true)) {
  276. //修改记录
  277. updateActionLog($param['user_id'], 'crm_product', $product_id, $dataInfo, $param);
  278. RecordActionLog($param['user_id'], 'crm_product', 'update', $dataInfo['name'], $dataInfo, $param);
  279. $data = [];
  280. $data['product_id'] = $product_id;
  281. return $data;
  282. } else {
  283. $this->rollback();
  284. $this->error = '编辑失败';
  285. return false;
  286. }
  287. }
  288. /**
  289. * 产品数据
  290. *
  291. * @param string $id
  292. * @return Common|array|bool|\PDOStatement|string|\think\Model|null
  293. * @throws \think\db\exception\DataNotFoundException
  294. * @throws \think\db\exception\ModelNotFoundException
  295. * @throws \think\exception\DbException
  296. */
  297. public function getDataById($id = '', $userId = 0)
  298. {
  299. $map['product_id'] = $id;
  300. $map['delete_user_id'] = 0;
  301. $dataInfo = db('crm_product')->where($map)->find();
  302. if (!$dataInfo) {
  303. $this->error = '暂无此数据';
  304. return false;
  305. }
  306. # 获取封面图片
  307. $dataInfo['cover_images'] = $this->getProductImages($dataInfo['cover_images']);
  308. # 获取详情图片
  309. $dataInfo['details_images'] = $this->getProductImages($dataInfo['details_images']);
  310. $userModel = new \app\admin\model\User();
  311. $dataInfo['create_user_id_info'] = $userModel->getUserById($dataInfo['create_user_id']);
  312. $dataInfo['category_id_info'] = db('crm_product_category')->where(['category_id' => $dataInfo['category_id']])->value('name');
  313. # 处理日期格式
  314. $fieldModel = new \app\admin\model\Field();
  315. $datetimeField = $fieldModel->getFieldByFormType('crm_product', 'datetime'); //日期时间类型
  316. foreach ($datetimeField as $key => $val) {
  317. $dataInfo[$val] = !empty($dataInfo[$val]) ? date('Y-m-d H:i:s', $dataInfo[$val]) : null;
  318. }
  319. $dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;
  320. $dataInfo['update_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
  321. // 字段授权
  322. if (!empty($userId)) {
  323. $grantData = getFieldGrantData($userId);
  324. $userLevel = isSuperAdministrators($userId);
  325. foreach ($dataInfo as $key => $value) {
  326. if (!$userLevel && !empty($grantData['crm_product'])) {
  327. $status = getFieldGrantStatus($key, $grantData['crm_product']);
  328. # 查看权限
  329. if ($status['read'] == 0) unset($dataInfo[$key]);
  330. }
  331. }
  332. }
  333. return $dataInfo;
  334. }
  335. /**
  336. * 获取产品图片
  337. *
  338. * @param $fileIds
  339. * @return array
  340. * @throws \think\db\exception\DataNotFoundException
  341. * @throws \think\db\exception\ModelNotFoundException
  342. * @throws \think\exception\DbException
  343. */
  344. private function getProductImages($fileIds)
  345. {
  346. $files = Db::name('admin_file')->whereIn('file_id', $fileIds)->select();
  347. foreach ($files as $key => $value) {
  348. $files[$key]['file_path'] = getFullPath($value['file_path']);
  349. $files[$key]['file_path_thumb'] = getFullPath($value['file_path_thumb']);
  350. $files[$key]['size'] = format_bytes($value['size']);
  351. }
  352. return $files;
  353. }
  354. /**
  355. * 相关产品创建(商机、合同相关产品数据)
  356. * @param types 类型
  357. * @param param['product'] 产品相关数据
  358. * @param price 产品单价
  359. * @param sales_price 销售价格
  360. * @param num 数量
  361. * @param discount 折扣
  362. * @param subtotal 小计(折扣后价格)
  363. * @param unit 单位
  364. * @param total_price 折扣后整单总价
  365. * @param discount_rate 整单折扣
  366. * @param objId 关联对象ID
  367. * @return
  368. */
  369. public function createObject($types, $param, $objId)
  370. {
  371. switch ($types) {
  372. case 'crm_business' :
  373. $db = 'crm_business_product';
  374. $rDb = 'crm_business';
  375. $db_id = 'business_id';
  376. break;
  377. case 'crm_contract' :
  378. $db = 'crm_contract_product';
  379. $rDb = 'crm_contract';
  380. $db_id = 'contract_id';
  381. break;
  382. default :
  383. $this->error = '参数错误';
  384. return false;
  385. break;
  386. }
  387. $total_price = 0;
  388. if ($param['product']) {
  389. $product = [];
  390. // 启动事务
  391. Db::startTrans();
  392. try {
  393. foreach ($param['product'] as $key => $value) {
  394. $discount = 0;
  395. // $discount = ((100 - $value['discount']) > 0) ? (100 - $value['discount'])/100 : 0; //折扣
  396. $product[$key]['product_id'] = $value['product_id'];
  397. $product[$key]['price'] = $value['price']; //产品单价
  398. $product[$key]['sales_price'] = $value['sales_price']; //售价
  399. $product[$key]['num'] = $value['num']; //数量
  400. $product[$key]['discount'] = $value['discount']; //折扣
  401. $product[$key]['unit'] = $value['unit'] ?: ''; //单位
  402. $product[$key]['subtotal'] = $value['subtotal'];
  403. // $total_price += $product[$key]['subtotal'] = round(($value['price'] * $value['num']) * $discount); //总价
  404. $product[$key][$db_id] = $objId;
  405. }
  406. //删除
  407. db($db)->where([$db_id => $objId])->delete(); //原数据删除
  408. //新增
  409. db($db)->insertAll($product);
  410. $rData = [];
  411. //产品合计
  412. $rData['discount_rate'] = !empty($param['discount_rate']) ? $param['discount_rate'] : 0.00; //整单折扣
  413. $discount_rate = ((100 - $rData['discount_rate']) > 0) ? (100 - $rData['discount_rate']) / 100 : 0;
  414. // $rData['total_price'] = $total_price ? $total_price*$discount_rate : '0.00'; //整单合计
  415. $rData['total_price'] = $param['total_price'] ?: '0.00'; //整单合计
  416. db($rDb)->where([$db_id => $objId])->update($rData);
  417. // 提交事务
  418. Db::commit();
  419. return true;
  420. } catch (\Exception $e) {
  421. $this->error = '产品数据创建出错';
  422. // 回滚事务
  423. Db::rollback();
  424. return false;
  425. }
  426. } else {
  427. //删除产品信息
  428. db($db)->where([$db_id => $objId])->delete();
  429. return true;
  430. }
  431. }
  432. /**
  433. * [产品统计]
  434. *
  435. * @param $param
  436. * @return mixed
  437. * @throws \think\db\exception\DataNotFoundException
  438. * @throws \think\db\exception\ModelNotFoundException
  439. * @throws \think\exception\DbException
  440. */
  441. public function getStatistics($param)
  442. {
  443. $userModel = new \app\admin\model\User();
  444. $adminModel = new \app\admin\model\Admin();
  445. $perUserIds = $userModel->getUserByPer('bi', 'product', 'read'); //权限范围内userIds
  446. $whereData = $adminModel->getWhere($param, '', $perUserIds); //统计条件
  447. $userIds = $whereData['userIds'];
  448. $between_time = $whereData['between_time'];
  449. $where = [];
  450. //时间段
  451. $where['contract.create_time'] = ['between', $between_time];
  452. $where['contract.owner_user_id'] = ['in', $userIds];
  453. $join = [
  454. ['__CRM_CONTRACT__ contract', 'contract.contract_id = a.contract_id', 'LEFT'],
  455. ['__CRM_PRODUCT__ product', 'product.product_id = a.product_id', 'LEFT'],
  456. ['__CRM_PRODUCT_CATEGORY__ product_category', 'product_category.category_id = product.category_id', 'LEFT'],
  457. ];
  458. $sql = db('crm_contract_product')
  459. ->alias('a')
  460. ->where($where)
  461. ->join($join)
  462. ->field([
  463. 'a.contract_id,
  464. a.product_id,
  465. product.name as product_name,
  466. contract.owner_user_id,
  467. product_category.category_id,
  468. product_category.name as category_id_info,
  469. count(a.r_id) as contract_product_sum,
  470. sum(contract.money)as contract_money,
  471. sum(a.num) as product_sum'
  472. ])
  473. ->group('product.product_id')
  474. ->order('category_id,product_name')
  475. ->fetchSql()
  476. ->select();
  477. $dataCount=db('crm_contract_product')
  478. ->alias('a')
  479. ->where($where)
  480. ->join($join)
  481. ->group('product.category_id')->count();
  482. $list = queryCache($sql);
  483. $contract_product_sum = 0;
  484. $product_sum = 0;
  485. $contract_money = 0;
  486. foreach ($list as $k => $v) {
  487. $contract_product_sum += $v['contract_product_sum'];
  488. $product_sum += (int)$v['product_sum'];
  489. $contract_money += $v['contract_money'];
  490. }
  491. $data=[];
  492. $data['list']=$list;
  493. $data['count']=$dataCount;
  494. $data['total'] = [
  495. 'realname' => '总计',
  496. 'contract_product_sum' => $contract_product_sum,
  497. 'product_sum' => $product_sum,
  498. 'contract_money' => $contract_money];
  499. return $data;
  500. }
  501. /**
  502. * 产品销售分析列表
  503. * @param $param
  504. *
  505. * @author alvin guogaobo
  506. * @version 1.0 版本号
  507. * @since 2021/4/20 0020 16:14
  508. */
  509. public function listProduct($param){
  510. $userModel = new \app\admin\model\User();
  511. $fieldModel = new \app\admin\model\Field();
  512. $receivablesModel = new \app\crm\model\Receivables();
  513. $adminModel = new \app\admin\model\Admin();
  514. $perUserIds = $userModel->getUserByPer('bi', 'product', 'read'); //权限范围内userIds
  515. $whereData = $adminModel->getWhere($param, '', $perUserIds); //统计条件
  516. $userIds = $whereData['userIds'];
  517. $between_time = $whereData['between_time'];
  518. $where = [];
  519. //时间段
  520. $where['contract.create_time'] = ['between', $between_time];
  521. $where['contract.owner_user_id'] = ['in', $userIds];
  522. $search=$param['search'];
  523. $join = [
  524. ['__CRM_BUSINESS__ business','contract.business_id = business.business_id','LEFT'],
  525. ['CrmReceivables receivables','receivables.contract_id = contract.contract_id AND receivables.check_status = 2','LEFT'],
  526. ['__CRM_CONTACTS__ contacts','contract.contacts_id = contacts.contacts_id','LEFT'],
  527. ['__CRM_CUSTOMER__ customer','contract.customer_id = customer.customer_id','LEFT'],
  528. ];
  529. //列表展示字段
  530. $indexField = $fieldModel->getIndexField('crm_contract', '', 1) ? : array('name');
  531. foreach ($indexField AS $kk => $vv) {
  532. if ($vv == 'contract.customer_name') unset($indexField[(int)$kk]);
  533. if ($vv == 'contract.business_name') unset($indexField[(int)$kk]);
  534. }
  535. if ($search) {
  536. //普通筛选
  537. $searchWhere = function ($query) use ($search) {
  538. $query->where(function ($query) use ($search){
  539. $query->whereLike('customer.name', '%' . $search . '%');
  540. })->whereOr(function ($query) use ($search) {
  541. $query->whereLike('contract.num', '%' . $search . '%');
  542. })->whereOr(function ($query) use ($search) {
  543. $query->whereLike('contract.name', '%' . $search . '%');
  544. });
  545. };
  546. }
  547. $contract_product=db('crm_contract_product')
  548. ->where('product_id',$param['product_id'])
  549. ->column('contract_id');
  550. $list=db('crm_contract')
  551. ->alias('contract')
  552. ->join($join)
  553. ->where($where)
  554. ->where('contract.contract_id',['in',trim(arrayToString($contract_product),',')])
  555. ->where($searchWhere)
  556. ->field(array_merge($indexField, [
  557. 'customer.name' => 'customer_name',
  558. 'business.name' => 'business_name',
  559. 'contacts.name' => 'contacts_name',
  560. 'ifnull(SUM(receivables.money), 0)' => 'done_money',
  561. '(contract.money - ifnull(SUM(receivables.money), 0))' => 'un_money',
  562. ]))
  563. ->group('contract.contract_id')
  564. ->page($param['page'],$param['limit'])
  565. ->select();
  566. $dataCount=db('crm_contract')
  567. ->alias('contract')
  568. ->join($join)
  569. ->where($where)
  570. ->where('contract.contract_id',['in',trim(arrayToString($contract_product),',')])
  571. ->where($searchWhere)
  572. ->count();
  573. $userField = $fieldModel->getFieldByFormType('crm_contract', 'user');
  574. $structureField = $fieldModel->getFieldByFormType('crm_contract', 'structure'); //部门类型
  575. $datetimeField = $fieldModel->getFieldByFormType('crm_contract', 'datetime'); //日期时间类型
  576. $readAuthIds = $userModel->getUserByPer('crm', 'contract', 'read');
  577. $updateAuthIds = $userModel->getUserByPer('crm', 'contract', 'update');
  578. $deleteAuthIds = $userModel->getUserByPer('crm', 'contract', 'delete');
  579. foreach ($list as $k=>$v) {
  580. $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
  581. $list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
  582. $list[$k]['create_user_name'] = !empty($list[$k]['create_user_id_info']['realname']) ? $list[$k]['create_user_id_info']['realname'] : '';
  583. $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
  584. foreach ($userField as $key => $val) {
  585. $usernameField = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
  586. $list[$k][$val.'_name'] = implode($usernameField, ',');
  587. }
  588. foreach ($structureField as $key => $val) {
  589. $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
  590. $list[$k][$val.'_name'] = implode($structureNameField, ',');
  591. }
  592. foreach ($datetimeField as $key => $val) {
  593. $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
  594. }
  595. $list[$k]['business_id_info']['business_id'] = $v['business_id'];
  596. $list[$k]['business_id_info']['name'] = $v['business_name'];
  597. $list[$k]['customer_id_info']['customer_id'] = $v['customer_id'];
  598. $list[$k]['customer_id_info']['name'] = $v['customer_name'];
  599. $list[$k]['contacts_id_info']['contacts_id'] = $v['contacts_id'];
  600. $list[$k]['contacts_id_info']['name'] = $v['contacts_name'];
  601. $moneyInfo = [];
  602. $moneyInfo = $receivablesModel->getMoneyByContractId($v['contract_id']);
  603. $list[$k]['unMoney'] = $moneyInfo['doneMoney'] ? : '0.00';
  604. if ($list[$k]['un_money'] < 0) $list[$k]['un_money'] = '0.00';
  605. $planInfo = [];
  606. $planInfo = db('crm_receivables_plan')->where(['contract_id' => $v['contract_id']])->find();
  607. $list[$k]['receivables_id'] = $planInfo['receivables_id'] ? : '';
  608. $list[$k]['remind_date'] = $planInfo['remind_date'] ? : '';
  609. $list[$k]['return_date'] = $planInfo['return_date'] ? : '';
  610. //权限
  611. $roPre = $userModel->rwPre($user_id, $v['ro_user_id'], $v['rw_user_id'], 'read');
  612. $rwPre = $userModel->rwPre($user_id, $v['ro_user_id'], $v['rw_user_id'], 'update');
  613. $permission = [];
  614. $is_read = 0;
  615. $is_update = 0;
  616. $is_delete = 0;
  617. if (in_array($v['owner_user_id'],$readAuthIds) || $roPre || $rwPre) $is_read = 1;
  618. if (in_array($v['owner_user_id'],$updateAuthIds) || $rwPre) $is_update = 1;
  619. if (in_array($v['owner_user_id'],$deleteAuthIds)) $is_delete = 1;
  620. $permission['is_read'] = $is_read;
  621. $permission['is_update'] = $is_update;
  622. $permission['is_delete'] = $is_delete;
  623. $list[$k]['permission'] = $permission;
  624. # 下次联系时间
  625. $list[$k]['next_time'] = !empty($v['next_time']) ? date('Y-m-d H:i:s', $v['next_time']) : null;
  626. # 日期
  627. $list[$k]['create_time'] = !empty($v['create_time']) ? date('Y-m-d H:i:s', $v['create_time']) : null;
  628. $list[$k]['update_time'] = !empty($v['update_time']) ? date('Y-m-d H:i:s', $v['update_time']) : null;
  629. $list[$k]['last_time'] = !empty($v['last_time']) ? date('Y-m-d H:i:s', $v['last_time']) : null;
  630. $list[$k]['order_date'] = ($v['order_date']!='0000-00-00') ? $v['order_date'] : null;
  631. $list[$k]['start_time'] = ($v['start_time']!='0000-00-00') ? $v['start_time'] : null;
  632. $list[$k]['end_time'] = ($v['end_time']!='0000-00-00') ? $v['end_time'] : null;
  633. # 签约人姓名
  634. $orderNames = Db::name('admin_user')->whereIn('id', trim($v['order_user_id'], ','))->column('realname');
  635. $list[$k]['order_user_name'] = implode(',', $orderNames);
  636. }
  637. $data = [];
  638. $data['list'] = $list;
  639. $data['dataCount'] = $dataCount ? : 0;
  640. return $data;
  641. }
  642. /**
  643. * [根据产品类别ID,查询父级ID]
  644. * @param
  645. * @return
  646. * @author Michael_xu
  647. */
  648. public function getPidStr($category_id, $idArr, $first = '')
  649. {
  650. if ($first == 1) $idArr = [];
  651. $idArr[] = $category_id;
  652. $pid = db('crm_product_category')->where(['category_id' => $category_id])->value('pid');
  653. if ($pid) {
  654. $idArr[] = $pid;
  655. $this->getPidStr($pid, $idArr);
  656. }
  657. $arr = array_reverse($idArr);
  658. $resStr = ',' . implode(',', $arr) . ',';
  659. return $resStr;
  660. }
  661. /**
  662. * 删除当前的记录
  663. *
  664. * @overwrite 重写 traits\model\SoftDelete\delete
  665. * @param boolean $force 是否强制删除
  666. * @return integer
  667. * @author Ymob
  668. * @datetime 2019-10-24 15:02:22
  669. */
  670. public function delete($force = false)
  671. {
  672. if (false === $this->trigger('before_delete', $this)) {
  673. return false;
  674. }
  675. $name = $this->getDeleteTimeField();
  676. if ($name && !$force) {
  677. // 软删除
  678. $this->data[$name] = $this->autoWriteTimestamp($name);
  679. $this->data['delete_user_id'] = UserModel::userInfo('id');
  680. $result = $this->isUpdate()->save();
  681. } else {
  682. // 强制删除当前模型数据
  683. $result = $this->getQuery()->where($this->getWhere())->delete();
  684. }
  685. // 关联删除
  686. if (!empty($this->relationWrite)) {
  687. foreach ($this->relationWrite as $key => $name) {
  688. $name = is_numeric($key) ? $name : $key;
  689. $result = $this->getRelation($name);
  690. if ($result instanceof Model) {
  691. $result->delete();
  692. } elseif ($result instanceof Collection || is_array($result)) {
  693. foreach ($result as $model) {
  694. $model->delete();
  695. }
  696. }
  697. }
  698. }
  699. $this->trigger('after_delete', $this);
  700. // 清空原始数据
  701. $this->origin = [];
  702. return $result;
  703. }
  704. /**
  705. * 获取系统信息
  706. *
  707. * @param $id
  708. * @return array
  709. * @throws \think\db\exception\DataNotFoundException
  710. * @throws \think\db\exception\ModelNotFoundException
  711. * @throws \think\exception\DbException
  712. */
  713. public function getSystemInfo($id)
  714. {
  715. # 产品
  716. $product = Db::name('crm_product')->field(['create_user_id', 'create_time', 'update_time'])->where('product_id', $id)->find();
  717. # 创建人
  718. $realname = Db::name('admin_user')->where('id', $product['create_user_id'])->value('realname');
  719. return [
  720. 'create_user_id' => $realname,
  721. 'create_time' => date('Y-m-d H:i:s', $product['create_time']),
  722. 'update_time' => date('Y-m-d H:i:s', $product['update_time'])
  723. ];
  724. }
  725. /**
  726. * 转移
  727. *
  728. * @param $param
  729. * @return int|string
  730. * @throws \think\Exception
  731. * @throws \think\exception\PDOException
  732. */
  733. public function transfer($param)
  734. {
  735. return Db::name('crm_product')->whereIn('product_id', $param['product_id'])->update(['owner_user_id' => $param['owner_user_id']]);
  736. }
  737. }