Product.php 46KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | Description: 产品
  4. // +----------------------------------------------------------------------
  5. // | Author: Michael_xu | gengxiaoxu@5kcrm.com
  6. // +----------------------------------------------------------------------
  7. namespace app\crm\model;
  8. use app\admin\traits\FieldVerificationTrait;
  9. use think\Db;
  10. use app\admin\model\Common;
  11. use app\admin\model\User as UserModel;
  12. use traits\model\SoftDelete;
  13. class Product extends Common
  14. {
  15. use SoftDelete, FieldVerificationTrait;
  16. protected $deleteTime = 'delete_time';
  17. /**
  18. * 为了数据库的整洁,同时又不影响Model和Controller的名称
  19. * 我们约定每个模块的数据表都加上相同的前缀,比如CRM模块用crm作为数据表前缀
  20. */
  21. protected $name = 'crm_product';
  22. protected $createTime = 'create_time';
  23. protected $updateTime = 'update_time';
  24. protected $autoWriteTimestamp = true;
  25. /**
  26. * [getDataList 产品list]
  27. *
  28. * @param $request
  29. * @return array
  30. */
  31. public function getDataList($request)
  32. {
  33. $userModel = new \app\admin\model\User();
  34. $structureModel = new \app\admin\model\Structure();
  35. $fieldModel = new \app\admin\model\Field();
  36. $search = $request['search'];
  37. $user_id = $request['user_id'];
  38. $is_excel = $request['is_excel']; //导出
  39. $scene_id = (int)$request['scene_id'];
  40. $order_field = $request['order_field'];
  41. $order_type = $request['order_type'];
  42. $isStatus = !empty($request['is_status']) ? $request['is_status'] : 0;
  43. unset($request['scene_id']);
  44. unset($request['search']);
  45. unset($request['user_id']);
  46. unset($request['order_field']);
  47. unset($request['order_type']);
  48. unset($request['is_status']);
  49. $request = $this->fmtRequest($request);
  50. $requestMap = $request['map'] ?: [];
  51. $sceneModel = new \app\admin\model\Scene();
  52. if ($scene_id) {
  53. //自定义场景
  54. $sceneMap = $sceneModel->getDataById($scene_id, $user_id, 'product') ?: [];
  55. } else {
  56. //默认场景
  57. $sceneMap = $sceneModel->getDefaultData('crm_product', $user_id) ?: [];
  58. }
  59. if ($search || $search == '0') {
  60. //普通筛选
  61. $sceneMap['name'] = ['condition' => 'contains', 'value' => $search, 'form_type' => 'text', 'name' => '产品名称'];
  62. }
  63. //优先级:普通筛选>高级筛选>场景
  64. $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
  65. //高级筛选
  66. $map = advancedQuery($map, 'crm', 'product', 'index');
  67. if (!empty($isStatus)) {
  68. $map['product.status'] = '上架';
  69. }
  70. if (empty($map['product.delete_user_id'])) {
  71. $map['product.delete_user_id'] = 0;
  72. }
  73. //权限
  74. $a = 'index';
  75. if ($is_excel) $a = 'excelExport';
  76. $auth_user_ids = $userModel->getUserByPer('crm', 'product', $a);
  77. //过滤权限
  78. if (isset($map['product.owner_user_id']) && $map['product.owner_user_id'][0] != 'like') {
  79. if (!is_array($map['product.owner_user_id'][1])) {
  80. $map['product.owner_user_id'][1] = [$map['product.owner_user_id'][1]];
  81. }
  82. if (in_array($map['product.owner_user_id'][0], ['neq', 'notin'])) {
  83. $auth_user_ids = array_diff($auth_user_ids, $map['product.owner_user_id'][1]) ?: []; //取差集
  84. } else {
  85. $auth_user_ids = array_intersect($map['product.owner_user_id'][1], $auth_user_ids) ?: []; //取交集
  86. }
  87. unset($map['product.owner_user_id']);
  88. }
  89. $auth_user_ids = array_merge(array_unique(array_filter($auth_user_ids))) ?: ['-1'];
  90. //负责人
  91. $authMap['product.owner_user_id'] = ['in', $auth_user_ids];
  92. //列表展示字段
  93. $indexField = $fieldModel->getIndexField('crm_product', $user_id, 1) ?: ['name'];
  94. $userField = $fieldModel->getFieldByFormType('crm_product', 'user'); //人员类型
  95. $structureField = $fieldModel->getFieldByFormType('crm_product', 'structure'); //部门类型
  96. $datetimeField = $fieldModel->getFieldByFormType('crm_product', 'datetime'); //日期时间类型
  97. $booleanField = $fieldModel->getFieldByFormType('crm_product', 'boolean_value'); //布尔值
  98. $dateIntervalField = $fieldModel->getFieldByFormType('crm_product', 'date_interval'); // 日期区间类型字段
  99. $positionField = $fieldModel->getFieldByFormType('crm_product', 'position'); // 地址类型字段
  100. $handwritingField = $fieldModel->getFieldByFormType('crm_product', 'handwriting_sign'); // 手写签名类型字段
  101. $locationField = $fieldModel->getFieldByFormType('crm_product', 'location'); // 定位类型字段
  102. $boxField = $fieldModel->getFieldByFormType('crm_product', 'checkbox'); // 多选类型字段
  103. $floatField = $fieldModel->getFieldByFormType('crm_product', 'floatnumber'); // 货币类型字段
  104. # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
  105. $temporaryField = str_replace('_name', '', $order_field);
  106. if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
  107. $order_field = $temporaryField;
  108. }
  109. //排序
  110. if ($order_type && $order_field) {
  111. $order = $fieldModel->getOrderByFormtype('crm_product', 'product', $order_field, $order_type);
  112. } else {
  113. $order = 'product.update_time desc';
  114. }
  115. $join = [
  116. ['__CRM_PRODUCT_CATEGORY__ product_category', 'product_category.category_id = product.category_id', 'LEFT'],
  117. ];
  118. $map['product.delete_user_id'] = 0;
  119. $list = db('crm_product')->alias('product')
  120. ->join($join)
  121. ->where($map)
  122. ->where($authMap)
  123. ->limit($request['offset'], $request['length'])
  124. ->field($indexField)
  125. ->field('product.*,product_category.name as category_name')
  126. ->orderRaw($order)
  127. ->select();
  128. $dataCount = db('crm_product')->alias('product')
  129. ->where($map)->where($authMap)
  130. ->count('product_id');
  131. # 扩展数据
  132. $extraData = [];
  133. $product_id_list = !empty($list) ? array_column($list, 'product_id') : [];
  134. $extraList = db('crm_product_data')->whereIn('product_id', $product_id_list)->select();
  135. foreach ($extraList AS $key => $value) {
  136. $extraData[$value['product_id']][$value['field']] = $value['content'];
  137. }
  138. $grantData = getFieldGrantData($user_id);
  139. foreach ($grantData['crm_product'] as $key => $value) {
  140. foreach ($value as $ke => $va) {
  141. if($va['maskType']!=0){
  142. $fieldGrant[$ke]['maskType'] = $va['maskType'];
  143. $fieldGrant[$ke]['form_type'] = $va['form_type'];
  144. $fieldGrant[$ke]['field'] = $va['field'];
  145. }
  146. }
  147. }
  148. foreach ($list as $k => $v) {
  149. $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
  150. $list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
  151. $list[$k]['create_user_name'] = !empty($list[$k]['create_user_id_info']['realname']) ? $list[$k]['create_user_id_info']['realname'] : '';
  152. $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
  153. foreach ($userField as $key => $val) {
  154. $usernameField = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
  155. $list[$k][$val . '_name'] = implode($usernameField, ',');
  156. }
  157. foreach ($structureField as $key => $val) {
  158. $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
  159. $list[$k][$val . '_name'] = implode($structureNameField, ',');
  160. }
  161. foreach ($datetimeField as $key => $val) {
  162. $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
  163. }
  164. foreach ($booleanField as $key => $val) {
  165. $list[$k][$val] = !empty($v[$val]) ? (string)$v[$val] : '0';
  166. }
  167. // 处理日期区间类型字段的格式
  168. foreach ($dateIntervalField AS $key => $val) {
  169. $list[$k][$val] = !empty($extraData[$v['product_id']][$val]) ? json_decode($extraData[$v['product_id']][$val], true) : null;
  170. }
  171. // 处理地址类型字段的格式
  172. foreach ($positionField AS $key => $val) {
  173. $list[$k][$val] = !empty($extraData[$v['product_id']][$val]) ? json_decode($extraData[$v['product_id']][$val], true) : null;
  174. }
  175. // 手写签名类型字段
  176. foreach ($handwritingField AS $key => $val) {
  177. $handwritingData = !empty($v[$val]) ? db('admin_file')->where('file_id', $v[$val])->value('file_path') : null;
  178. $list[$k][$val] = ['url' => !empty($handwritingData) ? getFullPath($handwritingData) : null];
  179. }
  180. // 定位类型字段
  181. foreach ($locationField AS $key => $val) {
  182. $list[$k][$val] = !empty($extraData[$v['product_id']][$val]) ? json_decode($extraData[$v['product_id']][$val], true) : null;
  183. }
  184. // 多选框类型字段
  185. foreach ($boxField AS $key => $val) {
  186. $list[$k][$val] = !empty($v[$val]) ? trim($v[$val], ',') : null;
  187. }
  188. // 货币类型字段
  189. foreach ($floatField AS $key => $val) {
  190. $list[$k][$val] = $v[$val]!='0.00' ? (string)$v[$val] : null;
  191. }
  192. //掩码相关类型字段
  193. foreach ($fieldGrant AS $key => $val){
  194. //掩码相关类型字段
  195. if ($val['maskType']!=0 && $val['form_type'] == 'mobile') {
  196. $pattern = "/(1[3458]{1}[0-9])[0-9]{4}([0-9]{4})/i";
  197. $rs = preg_replace($pattern, "$1****$2", $v[$val['field']]);
  198. $list[$k][$val['field']] = !empty($v[$val['field']]) ? (string)$rs : null;
  199. } elseif ($val['maskType']!=0 && $val['form_type'] == 'email') {
  200. $email_array = explode("@", $v[$val['field']]);
  201. $prevfix = (strlen($email_array[0]) < 4) ? "" : substr($v[$val['field']], 0, 2); //邮箱前缀
  202. $str = preg_replace('/([\d\w+_-]{0,100})@/', "***@", $v[$val['field']], -1, $count);
  203. $rs = $prevfix . $str;
  204. $list[$k][$val['field']] = !empty($v[$val['field']]) ?$rs: null;
  205. } elseif ($val['maskType']!=0 && in_array($val['form_type'],['position','floatnumber'])) {
  206. $list[$k][$val['field']] = !empty($v[$val['field']]) ? (string)substr_replace($v[$val['field']], '*****',0,strlen($v[$val['field']])) : null;
  207. }
  208. }
  209. //产品类型
  210. $list[$k]['category_id_info'] = $v['category_name'];
  211. # 处理日期格式
  212. $list[$k]['create_time'] = !empty($v['create_time']) ? date('Y-m-d H:i:s', $v['create_time']) : null;
  213. $list[$k]['update_time'] = !empty($v['update_time']) ? date('Y-m-d H:i:s', $v['update_time']) : null;
  214. # 系统字段 负责人部门 zjf 20210726
  215. $list[$k]['owner_user_structure_name'] = $list[$k]['owner_user_id_info']['structure_name'];
  216. }
  217. $data = [];
  218. $data['list'] = $list;
  219. $data['dataCount'] = $dataCount ?: 0;
  220. return $data;
  221. }
  222. /**
  223. * 创建产品主表信息
  224. * @param
  225. * @return
  226. * @author Michael_xu
  227. */
  228. public function createData($param)
  229. {
  230. // 产品扩展表数据
  231. $productData = [];
  232. $fieldModel = new \app\admin\model\Field();
  233. $productCategoryModel = model('ProductCategory');
  234. $productStatus = false;
  235. if (!empty($param['excel'])) {
  236. $productStatus = db('crm_product')->where(['name' => $param['name'], 'delete_user_id' => 0])->value('product_id');
  237. }
  238. // 数据验证
  239. if (empty($param['excel']) || $productStatus) {
  240. $validateResult = $this->fieldDataValidate($param, $this->name, $param['create_user_id']);
  241. if (!empty($validateResult)) {
  242. $this->error = $validateResult;
  243. return false;
  244. }
  245. }
  246. unset($param['excel']);
  247. // 处理部门、员工、附件、多选类型字段
  248. $arrFieldAtt = $fieldModel->getArrayField('crm_product');
  249. foreach ($arrFieldAtt as $k => $v) {
  250. $param[$v] = arrayToString($param[$v]);
  251. }
  252. // 处理日期(date)类型
  253. $dateField = $fieldModel->getFieldByFormType('crm_product', 'date');
  254. if (!empty($dateField)) {
  255. foreach ($param as $key => $value) {
  256. if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
  257. }
  258. }
  259. // 处理手写签名类型
  260. $handwritingField = $fieldModel->getFieldByFormType('crm_product', 'handwriting_sign');
  261. if (!empty($handwritingField)) {
  262. foreach ($param AS $key => $value) {
  263. if (in_array($key, $handwritingField)) {
  264. $param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
  265. }
  266. }
  267. }
  268. // 处理地址、定位、日期区间、明细表格类型字段
  269. $positionField = $fieldModel->getFieldByFormType($this->name, 'position');
  270. $locationField = $fieldModel->getFieldByFormType($this->name, 'location');
  271. $dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
  272. $detailTableField = $fieldModel->getFieldByFormType($this->name, 'detail_table');
  273. foreach ($param AS $key => $value) {
  274. // 处理地址类型字段数据
  275. if (in_array($key, $positionField)) {
  276. if (!empty($value)) {
  277. $productData[] = [
  278. 'field' => $key,
  279. 'content' => json_encode($value, JSON_NUMERIC_CHECK),
  280. 'create_time' => time()
  281. ];
  282. $positionNames = array_column($value, 'name');
  283. $param[$key] = implode(',', $positionNames);
  284. } else {
  285. $param[$key] = '';
  286. }
  287. }
  288. // 处理定位类型字段数据
  289. if (in_array($key, $locationField)) {
  290. if (!empty($value)) {
  291. $productData[] = [
  292. 'field' => $key,
  293. 'content' => json_encode($value, JSON_NUMERIC_CHECK),
  294. 'create_time' => time()
  295. ];
  296. $param[$key] = $value['address'];
  297. } else {
  298. $param[$key] = '';
  299. }
  300. }
  301. // 处理日期区间类型字段数据
  302. if (in_array($key, $dateIntervalField)) {
  303. if (!empty($value)) {
  304. $productData[] = [
  305. 'field' => $key,
  306. 'content' => json_encode($value, JSON_NUMERIC_CHECK),
  307. 'create_time' => time()
  308. ];
  309. $param[$key] = implode('_', $value);
  310. } else {
  311. $param[$key] = '';
  312. }
  313. }
  314. // 处理明细表格类型字段数据
  315. if (in_array($key, $detailTableField)) {
  316. if (!empty($value)) {
  317. $productData[] = [
  318. 'field' => $key,
  319. 'content' => json_encode($value, JSON_NUMERIC_CHECK),
  320. 'create_time' => time()
  321. ];
  322. $param[$key] = $key;
  323. } else {
  324. $param[$key] = '';
  325. }
  326. }
  327. }
  328. //产品分类
  329. $category_id = $param['category_id'];
  330. if (is_array($category_id)) {
  331. $param['category_id'] = $productCategoryModel->getIdByStr($category_id);
  332. $param['category_str'] = arrayToString($category_id);
  333. }
  334. if (!is_int($category_id)) {
  335. $list = db('crm_product_category')->column('category_id', 'name');
  336. foreach ($list as $k => $v) {
  337. if ($k == $param['category_id']) {
  338. $param['category_id'] = $v;
  339. }
  340. }
  341. }
  342. if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
  343. $data['product_id'] = $this->product_id;
  344. updateActionLog($param['create_user_id'], 'crm_product', $this->product_id, '', '', '创建了产品');
  345. RecordActionLog($param['create_user_id'], 'crm_product', 'save', $param['name'], '', '', '新增了产品' . $param['name']);
  346. // 添加产品扩展数据
  347. array_walk($productData, function (&$val) use ($data) {
  348. $val['product_id'] = $data['product_id'];
  349. });
  350. db('crm_product_data')->insertAll($productData);
  351. return $data;
  352. } else {
  353. $this->error = '添加失败';
  354. return false;
  355. }
  356. }
  357. /**
  358. * 编辑产品主表信息
  359. * @param
  360. * @return
  361. * @author Michael_xu
  362. */
  363. public function updateDataById($param, $product_id = '')
  364. {
  365. // 产品扩展表数据
  366. $productData = [];
  367. $userModel = new \app\admin\model\User();
  368. $dataInfo = $this->getDataById($product_id);
  369. $productCategoryModel = model('ProductCategory');
  370. if (!$dataInfo) {
  371. $this->error = '数据不存在或已删除';
  372. return false;
  373. }
  374. //判断权限
  375. $auth_user_ids = $userModel->getUserByPer('crm', 'product', 'update');
  376. if (!in_array($dataInfo['owner_user_id'], $auth_user_ids)) {
  377. $this->error = '无权操作';
  378. return false;
  379. }
  380. $param['product_id'] = $product_id;
  381. //过滤不能修改的字段
  382. $unUpdateField = ['create_user_id', 'is_deleted'];
  383. foreach ($unUpdateField as $v) {
  384. unset($param[$v]);
  385. }
  386. $fieldModel = new \app\admin\model\Field();
  387. // 数据验证
  388. $validateResult = $this->fieldDataValidate($param, $this->name, $param['user_id'], $param['product_id']);
  389. if (!empty($validateResult)) {
  390. $this->error = $validateResult;
  391. return false;
  392. }
  393. // 处理部门、员工、附件、多选类型字段
  394. $arrFieldAtt = $fieldModel->getArrayField('crm_product');
  395. foreach ($arrFieldAtt as $k => $v) {
  396. if (isset($param[$v])) $param[$v] = arrayToString($param[$v]);
  397. }
  398. // 处理日期(date)类型
  399. $dateField = $fieldModel->getFieldByFormType('crm_product', 'date');
  400. if (!empty($dateField)) {
  401. foreach ($param as $key => $value) {
  402. if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
  403. }
  404. }
  405. // 处理手写签名类型
  406. $handwritingField = $fieldModel->getFieldByFormType('crm_product', 'handwriting_sign');
  407. if (!empty($handwritingField)) {
  408. foreach ($param AS $key => $value) {
  409. if (in_array($key, $handwritingField)) {
  410. $param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
  411. }
  412. }
  413. }
  414. // 处理地址、定位、日期区间、明细表格类型字段
  415. $positionField = $fieldModel->getFieldByFormType($this->name, 'position');
  416. $locationField = $fieldModel->getFieldByFormType($this->name, 'location');
  417. $dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
  418. $detailTableField = $fieldModel->getFieldByFormType($this->name, 'detail_table');
  419. foreach ($param AS $key => $value) {
  420. // 处理地址类型字段数据
  421. if (in_array($key, $positionField)) {
  422. if (!empty($value)) {
  423. $productData[] = [
  424. 'field' => $key,
  425. 'content' => json_encode($value, JSON_NUMERIC_CHECK),
  426. 'create_time' => time()
  427. ];
  428. $positionNames = array_column($value, 'name');
  429. $param[$key] = implode(',', $positionNames);
  430. } else {
  431. $param[$key] = '';
  432. }
  433. }
  434. // 处理定位类型字段数据
  435. if (in_array($key, $locationField)) {
  436. if (!empty($value)) {
  437. $productData[] = [
  438. 'field' => $key,
  439. 'content' => json_encode($value, JSON_NUMERIC_CHECK),
  440. 'create_time' => time()
  441. ];
  442. $param[$key] = $value['address'];
  443. } else {
  444. $param[$key] = '';
  445. }
  446. }
  447. // 处理日期区间类型字段数据
  448. if (in_array($key, $dateIntervalField)) {
  449. if (!empty($value)) {
  450. $productData[] = [
  451. 'field' => $key,
  452. 'content' => json_encode($value, JSON_NUMERIC_CHECK),
  453. 'create_time' => time()
  454. ];
  455. $param[$key] = implode('_', $value);
  456. } else {
  457. $param[$key] = '';
  458. }
  459. }
  460. // 处理明细表格类型字段数据
  461. if (in_array($key, $detailTableField)) {
  462. if (!empty($value)) {
  463. $productData[] = [
  464. 'field' => $key,
  465. 'content' => json_encode($value, JSON_NUMERIC_CHECK),
  466. 'create_time' => time()
  467. ];
  468. $param[$key] = $key;
  469. } else {
  470. $param[$key] = '';
  471. }
  472. }
  473. }
  474. //产品分类
  475. $category_id = $param['category_id'];
  476. // if (is_array($category_id)) {
  477. // $param['category_id'] = $productCategoryModel->getIdByStr($category_id);
  478. // $param['category_str'] = arrayToString($category_id);
  479. // }
  480. if (!is_int($category_id)) {
  481. $list = db('crm_product_category')->column('category_id', 'name');
  482. $param['category_id'] = 1;
  483. foreach ($list as $k => $v) {
  484. if ($k == $category_id) {
  485. $param['category_id'] = $v;
  486. }
  487. }
  488. }
  489. if ($this->update($param, ['product_id' => $product_id], true)) {
  490. $data['product_id'] = $product_id;
  491. //修改记录
  492. updateActionLog($param['user_id'], 'crm_product', $product_id, $dataInfo, $param);
  493. RecordActionLog($param['user_id'], 'crm_product', 'update', $dataInfo['name'], $dataInfo, $param);
  494. // 添加产品扩展数据
  495. db('crm_product_data')->where('product_id', $product_id)->delete();
  496. array_walk($productData, function (&$val) use ($product_id) {
  497. $val['product_id'] = $product_id;
  498. });
  499. db('crm_product_data')->insertAll($productData);
  500. return $data;
  501. } else {
  502. $this->rollback();
  503. $this->error = '编辑失败';
  504. return false;
  505. }
  506. }
  507. /**
  508. * 产品数据
  509. *
  510. * @param string $id
  511. * @return Common|array|bool|\PDOStatement|string|\think\Model|null
  512. * @throws \think\db\exception\DataNotFoundException
  513. * @throws \think\db\exception\ModelNotFoundException
  514. * @throws \think\exception\DbException
  515. */
  516. public function getDataById($id = '', $userId = 0,$model='')
  517. {
  518. $map['product_id'] = $id;
  519. $map['delete_user_id'] = 0;
  520. $dataInfo = db('crm_product')->where($map)->find();
  521. if (!$dataInfo) {
  522. $this->error = '暂无此数据';
  523. return false;
  524. }
  525. if(empty($model) && $model!='update'){
  526. $grantData = getFieldGrantData($userId);
  527. foreach ($grantData['crm_product'] as $key => $value) {
  528. foreach ($value as $ke => $va) {
  529. if($va['maskType']!=0){
  530. $fieldGrant[$ke]['maskType'] = $va['maskType'];
  531. $fieldGrant[$ke]['form_type'] = $va['form_type'];
  532. $fieldGrant[$ke]['field'] = $va['field'];
  533. }
  534. }
  535. }
  536. foreach ($fieldGrant AS $key => $val){
  537. //掩码相关类型字段
  538. if ($val['maskType']!=0 && $val['form_type'] == 'mobile') {
  539. $pattern = "/(1[3458]{1}[0-9])[0-9]{4}([0-9]{4})/i";
  540. $rs = preg_replace($pattern, "$1****$2", $dataInfo[$val['field']]);
  541. $dataInfo[$val['field']] = !empty($dataInfo[$val['field']]) ? (string)$rs : null;
  542. } elseif ($val['maskType']!=0 && $val['form_type'] == 'email') {
  543. $email_array = explode("@", $dataInfo[$val['field']]);
  544. $prevfix = (strlen($email_array[0]) < 4) ? "" : substr($dataInfo[$val['field']], 0, 2); //邮箱前缀
  545. $str = preg_replace('/([\d\w+_-]{0,100})@/', "***@", $dataInfo[$val['field']], -1, $count);
  546. $rs = $prevfix . $str;
  547. $dataInfo[$val['field']] = !empty($dataInfo[$val['field']]) ?$rs: null;
  548. } elseif ($val['maskType']!=0 && in_array($val['form_type'],['position','floatnumber'])) {
  549. $dataInfo[$val['field']] = !empty($dataInfo[$val['field']]) ? (string)substr_replace($dataInfo[$val['field']], '*****',0,strlen($dataInfo[$val['field']])) : null;
  550. }
  551. }
  552. }
  553. # 获取封面图片
  554. $dataInfo['cover_images'] = $this->getProductImages($dataInfo['cover_images']);
  555. # 获取详情图片
  556. $dataInfo['details_images'] = $this->getProductImages($dataInfo['details_images']);
  557. $userModel = new \app\admin\model\User();
  558. $dataInfo['create_user_id_info'] = $userModel->getUserById($dataInfo['create_user_id']);
  559. $dataInfo['category_id_info'] = db('crm_product_category')->where(['category_id' => $dataInfo['category_id']])->value('name');
  560. # 处理日期格式
  561. $fieldModel = new \app\admin\model\Field();
  562. $datetimeField = $fieldModel->getFieldByFormType('crm_product', 'datetime'); //日期时间类型
  563. foreach ($datetimeField as $key => $val) {
  564. $dataInfo[$val] = !empty($dataInfo[$val]) ? date('Y-m-d H:i:s', $dataInfo[$val]) : null;
  565. }
  566. $dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;
  567. $dataInfo['update_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
  568. // 字段授权
  569. if (!empty($userId)) {
  570. $grantData = getFieldGrantData($userId);
  571. $userLevel = isSuperAdministrators($userId);
  572. foreach ($dataInfo as $key => $value) {
  573. if (!$userLevel && !empty($grantData['crm_product'])) {
  574. $status = getFieldGrantStatus($key, $grantData['crm_product']);
  575. # 查看权限
  576. if ($status['read'] == 0) unset($dataInfo[$key]);
  577. }
  578. }
  579. }
  580. return $dataInfo;
  581. }
  582. /**
  583. * 获取产品图片
  584. *
  585. * @param $fileIds
  586. * @return array
  587. * @throws \think\db\exception\DataNotFoundException
  588. * @throws \think\db\exception\ModelNotFoundException
  589. * @throws \think\exception\DbException
  590. */
  591. private function getProductImages($fileIds)
  592. {
  593. $files = Db::name('admin_file')->whereIn('file_id', $fileIds)->select();
  594. foreach ($files as $key => $value) {
  595. $files[$key]['file_path'] = getFullPath($value['file_path']);
  596. $files[$key]['file_path_thumb'] = getFullPath($value['file_path_thumb']);
  597. $files[$key]['size'] = format_bytes($value['size']);
  598. }
  599. return $files;
  600. }
  601. /**
  602. * 相关产品创建(商机、合同相关产品数据)
  603. * @param types 类型
  604. * @param param['product'] 产品相关数据
  605. * @param price 产品单价
  606. * @param sales_price 销售价格
  607. * @param num 数量
  608. * @param discount 折扣
  609. * @param subtotal 小计(折扣后价格)
  610. * @param unit 单位
  611. * @param total_price 折扣后整单总价
  612. * @param discount_rate 整单折扣
  613. * @param objId 关联对象ID
  614. * @return
  615. */
  616. public function createObject($types, $param, $objId)
  617. {
  618. switch ($types) {
  619. case 'crm_business' :
  620. $db = 'crm_business_product';
  621. $rDb = 'crm_business';
  622. $db_id = 'business_id';
  623. break;
  624. case 'crm_contract' :
  625. $db = 'crm_contract_product';
  626. $rDb = 'crm_contract';
  627. $db_id = 'contract_id';
  628. break;
  629. default :
  630. $this->error = '参数错误';
  631. return false;
  632. break;
  633. }
  634. $total_price = 0;
  635. if ($param['product']) {
  636. $product = [];
  637. // 启动事务
  638. Db::startTrans();
  639. try {
  640. foreach ($param['product'] as $key => $value) {
  641. $discount = 0;
  642. // $discount = ((100 - $value['discount']) > 0) ? (100 - $value['discount'])/100 : 0; //折扣
  643. $product[$key]['product_id'] = $value['product_id'];
  644. $product[$key]['price'] = $value['price']; //产品单价
  645. $product[$key]['sales_price'] = $value['sales_price']; //售价
  646. $product[$key]['num'] = $value['num']; //数量
  647. $product[$key]['discount'] = $value['discount']; //折扣
  648. $product[$key]['unit'] = $value['unit'] ?: ''; //单位
  649. $product[$key]['subtotal'] = $value['subtotal'];
  650. // $total_price += $product[$key]['subtotal'] = round(($value['price'] * $value['num']) * $discount); //总价
  651. $product[$key][$db_id] = $objId;
  652. }
  653. //删除
  654. db($db)->where([$db_id => $objId])->delete(); //原数据删除
  655. //新增
  656. db($db)->insertAll($product);
  657. $rData = [];
  658. //产品合计
  659. $rData['discount_rate'] = !empty($param['discount_rate']) ? $param['discount_rate'] : 0.00; //整单折扣
  660. $discount_rate = ((100 - $rData['discount_rate']) > 0) ? (100 - $rData['discount_rate']) / 100 : 0;
  661. // $rData['total_price'] = $total_price ? $total_price*$discount_rate : '0.00'; //整单合计
  662. $rData['total_price'] = $param['total_price'] ?: '0.00'; //整单合计
  663. db($rDb)->where([$db_id => $objId])->update($rData);
  664. // 提交事务
  665. Db::commit();
  666. return true;
  667. } catch (\Exception $e) {
  668. $this->error = '产品数据创建出错';
  669. // 回滚事务
  670. Db::rollback();
  671. return false;
  672. }
  673. } else {
  674. //删除产品信息
  675. db($db)->where([$db_id => $objId])->delete();
  676. return true;
  677. }
  678. }
  679. /**
  680. * [产品统计]
  681. *
  682. * @param $param
  683. * @return mixed
  684. * @throws \think\db\exception\DataNotFoundException
  685. * @throws \think\db\exception\ModelNotFoundException
  686. * @throws \think\exception\DbException
  687. */
  688. public function getStatistics($param)
  689. {
  690. $userModel = new \app\admin\model\User();
  691. $adminModel = new \app\admin\model\Admin();
  692. $perUserIds = $userModel->getUserByPer('bi', 'product', 'read'); //权限范围内userIds
  693. $whereData = $adminModel->getWhere($param, '', $perUserIds); //统计条件
  694. $userIds = $whereData['userIds'];
  695. $between_time = $whereData['between_time'];
  696. $where = [];
  697. //时间段
  698. $where['contract.create_time'] = ['between', $between_time];
  699. $where['contract.owner_user_id'] = ['in', $userIds];
  700. $join = [
  701. ['__CRM_CONTRACT__ contract', 'contract.contract_id = a.contract_id', 'LEFT'],
  702. ['__CRM_PRODUCT__ product', 'product.product_id = a.product_id', 'LEFT'],
  703. ['__CRM_PRODUCT_CATEGORY__ product_category', 'product_category.category_id = product.category_id', 'LEFT'],
  704. ];
  705. $sql = db('crm_contract_product')
  706. ->alias('a')
  707. ->where($where)
  708. ->join($join)
  709. ->field([
  710. 'a.contract_id,
  711. a.product_id,
  712. product.name as product_name,
  713. contract.owner_user_id,
  714. product_category.category_id,
  715. product_category.name as category_id_info,
  716. count(a.r_id) as contract_product_sum,
  717. sum(contract.money)as contract_money,
  718. sum(a.num) as product_sum'
  719. ])
  720. ->group('product.product_id')
  721. ->order('category_id,product_name')
  722. ->fetchSql()
  723. ->select();
  724. $dataCount=db('crm_contract_product')
  725. ->alias('a')
  726. ->where($where)
  727. ->join($join)
  728. ->group('product.category_id')->count();
  729. $list = queryCache($sql);
  730. $contract_product_sum = 0;
  731. $product_sum = 0;
  732. $contract_money = 0;
  733. foreach ($list as $k => $v) {
  734. $contract_product_sum += $v['contract_product_sum'];
  735. $product_sum += (int)$v['product_sum'];
  736. $contract_money += $v['contract_money'];
  737. }
  738. $data=[];
  739. $data['list']=$list;
  740. $data['count']=$dataCount;
  741. $data['total'] = [
  742. 'realname' => '总计',
  743. 'contract_product_sum' => $contract_product_sum,
  744. 'product_sum' => $product_sum,
  745. 'contract_money' => $contract_money];
  746. return $data;
  747. }
  748. /**
  749. * 产品销售分析列表
  750. * @param $param
  751. *
  752. * @author alvin guogaobo
  753. * @version 1.0 版本号
  754. * @since 2021/4/20 0020 16:14
  755. */
  756. public function listProduct($param){
  757. $userModel = new \app\admin\model\User();
  758. $fieldModel = new \app\admin\model\Field();
  759. $receivablesModel = new \app\crm\model\Receivables();
  760. $adminModel = new \app\admin\model\Admin();
  761. $perUserIds = $userModel->getUserByPer('bi', 'product', 'read'); //权限范围内userIds
  762. $whereData = $adminModel->getWhere($param, '', $perUserIds); //统计条件
  763. $userIds = $whereData['userIds'];
  764. $between_time = $whereData['between_time'];
  765. $where = [];
  766. //时间段
  767. $where['contract.create_time'] = ['between', $between_time];
  768. $where['contract.owner_user_id'] = ['in', $userIds];
  769. $search=$param['search'];
  770. $join = [
  771. ['__CRM_BUSINESS__ business','contract.business_id = business.business_id','LEFT'],
  772. ['CrmReceivables receivables','receivables.contract_id = contract.contract_id AND receivables.check_status = 2','LEFT'],
  773. ['__CRM_CONTACTS__ contacts','contract.contacts_id = contacts.contacts_id','LEFT'],
  774. ['__CRM_CUSTOMER__ customer','contract.customer_id = customer.customer_id','LEFT'],
  775. ];
  776. //列表展示字段
  777. $indexField = $fieldModel->getIndexField('crm_contract', '', 1) ? : array('name');
  778. foreach ($indexField AS $kk => $vv) {
  779. if ($vv == 'contract.customer_name') unset($indexField[(int)$kk]);
  780. if ($vv == 'contract.business_name') unset($indexField[(int)$kk]);
  781. }
  782. if ($search) {
  783. //普通筛选
  784. $searchWhere = function ($query) use ($search) {
  785. $query->where(function ($query) use ($search){
  786. $query->whereLike('customer.name', '%' . $search . '%');
  787. })->whereOr(function ($query) use ($search) {
  788. $query->whereLike('contract.num', '%' . $search . '%');
  789. })->whereOr(function ($query) use ($search) {
  790. $query->whereLike('contract.name', '%' . $search . '%');
  791. });
  792. };
  793. }
  794. $contract_product=db('crm_contract_product')
  795. ->where('product_id',$param['product_id'])
  796. ->column('contract_id');
  797. $list=db('crm_contract')
  798. ->alias('contract')
  799. ->join($join)
  800. ->where($where)
  801. ->where('contract.contract_id',['in',trim(arrayToString($contract_product),',')])
  802. ->where($searchWhere)
  803. ->field(array_merge($indexField, [
  804. 'customer.name' => 'customer_name',
  805. 'business.name' => 'business_name',
  806. 'contacts.name' => 'contacts_name',
  807. 'ifnull(SUM(receivables.money), 0)' => 'done_money',
  808. '(contract.money - ifnull(SUM(receivables.money), 0))' => 'un_money',
  809. ]))
  810. ->group('contract.contract_id')
  811. ->page($param['page'],$param['limit'])
  812. ->select();
  813. $dataCount=db('crm_contract')
  814. ->alias('contract')
  815. ->join($join)
  816. ->where($where)
  817. ->where('contract.contract_id',['in',trim(arrayToString($contract_product),',')])
  818. ->where($searchWhere)
  819. ->count();
  820. $userField = $fieldModel->getFieldByFormType('crm_contract', 'user');
  821. $structureField = $fieldModel->getFieldByFormType('crm_contract', 'structure'); //部门类型
  822. $datetimeField = $fieldModel->getFieldByFormType('crm_contract', 'datetime'); //日期时间类型
  823. $readAuthIds = $userModel->getUserByPer('crm', 'contract', 'read');
  824. $updateAuthIds = $userModel->getUserByPer('crm', 'contract', 'update');
  825. $deleteAuthIds = $userModel->getUserByPer('crm', 'contract', 'delete');
  826. foreach ($list as $k=>$v) {
  827. $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
  828. $list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
  829. $list[$k]['create_user_name'] = !empty($list[$k]['create_user_id_info']['realname']) ? $list[$k]['create_user_id_info']['realname'] : '';
  830. $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
  831. foreach ($userField as $key => $val) {
  832. $usernameField = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
  833. $list[$k][$val.'_name'] = implode($usernameField, ',');
  834. }
  835. foreach ($structureField as $key => $val) {
  836. $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
  837. $list[$k][$val.'_name'] = implode($structureNameField, ',');
  838. }
  839. foreach ($datetimeField as $key => $val) {
  840. $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
  841. }
  842. $list[$k]['business_id_info']['business_id'] = $v['business_id'];
  843. $list[$k]['business_id_info']['name'] = $v['business_name'];
  844. $list[$k]['customer_id_info']['customer_id'] = $v['customer_id'];
  845. $list[$k]['customer_id_info']['name'] = $v['customer_name'];
  846. $list[$k]['contacts_id_info']['contacts_id'] = $v['contacts_id'];
  847. $list[$k]['contacts_id_info']['name'] = $v['contacts_name'];
  848. $moneyInfo = [];
  849. $moneyInfo = $receivablesModel->getMoneyByContractId($v['contract_id']);
  850. $list[$k]['unMoney'] = $moneyInfo['doneMoney'] ? : '0.00';
  851. if ($list[$k]['un_money'] < 0) $list[$k]['un_money'] = '0.00';
  852. $planInfo = [];
  853. $planInfo = db('crm_receivables_plan')->where(['contract_id' => $v['contract_id']])->find();
  854. $list[$k]['receivables_id'] = $planInfo['receivables_id'] ? : '';
  855. $list[$k]['remind_date'] = $planInfo['remind_date'] ? : '';
  856. $list[$k]['return_date'] = $planInfo['return_date'] ? : '';
  857. //权限
  858. $roPre = $userModel->rwPre($user_id, $v['ro_user_id'], $v['rw_user_id'], 'read');
  859. $rwPre = $userModel->rwPre($user_id, $v['ro_user_id'], $v['rw_user_id'], 'update');
  860. $permission = [];
  861. $is_read = 0;
  862. $is_update = 0;
  863. $is_delete = 0;
  864. if (in_array($v['owner_user_id'],$readAuthIds) || $roPre || $rwPre) $is_read = 1;
  865. if (in_array($v['owner_user_id'],$updateAuthIds) || $rwPre) $is_update = 1;
  866. if (in_array($v['owner_user_id'],$deleteAuthIds)) $is_delete = 1;
  867. $permission['is_read'] = $is_read;
  868. $permission['is_update'] = $is_update;
  869. $permission['is_delete'] = $is_delete;
  870. $list[$k]['permission'] = $permission;
  871. # 下次联系时间
  872. $list[$k]['next_time'] = !empty($v['next_time']) ? date('Y-m-d H:i:s', $v['next_time']) : null;
  873. # 日期
  874. $list[$k]['create_time'] = !empty($v['create_time']) ? date('Y-m-d H:i:s', $v['create_time']) : null;
  875. $list[$k]['update_time'] = !empty($v['update_time']) ? date('Y-m-d H:i:s', $v['update_time']) : null;
  876. $list[$k]['last_time'] = !empty($v['last_time']) ? date('Y-m-d H:i:s', $v['last_time']) : null;
  877. $list[$k]['order_date'] = ($v['order_date']!='0000-00-00') ? $v['order_date'] : null;
  878. $list[$k]['start_time'] = ($v['start_time']!='0000-00-00') ? $v['start_time'] : null;
  879. $list[$k]['end_time'] = ($v['end_time']!='0000-00-00') ? $v['end_time'] : null;
  880. # 签约人姓名
  881. $orderNames = Db::name('admin_user')->whereIn('id', trim($v['order_user_id'], ','))->column('realname');
  882. $list[$k]['order_user_name'] = implode(',', $orderNames);
  883. }
  884. $data = [];
  885. $data['list'] = $list;
  886. $data['dataCount'] = $dataCount ? : 0;
  887. return $data;
  888. }
  889. /**
  890. * [根据产品类别ID,查询父级ID]
  891. * @param
  892. * @return
  893. * @author Michael_xu
  894. */
  895. public function getPidStr($category_id, $idArr, $first = '')
  896. {
  897. if ($first == 1) $idArr = [];
  898. $idArr[] = $category_id;
  899. $pid = db('crm_product_category')->where(['category_id' => $category_id])->value('pid');
  900. if ($pid) {
  901. $idArr[] = $pid;
  902. $this->getPidStr($pid, $idArr);
  903. }
  904. $arr = array_reverse($idArr);
  905. $resStr = ',' . implode(',', $arr) . ',';
  906. return $resStr;
  907. }
  908. /**
  909. * 删除当前的记录
  910. *
  911. * @overwrite 重写 traits\model\SoftDelete\delete
  912. * @param boolean $force 是否强制删除
  913. * @return integer
  914. * @author Ymob
  915. * @datetime 2019-10-24 15:02:22
  916. */
  917. public function delete($force = false)
  918. {
  919. if (false === $this->trigger('before_delete', $this)) {
  920. return false;
  921. }
  922. $name = $this->getDeleteTimeField();
  923. if ($name && !$force) {
  924. // 软删除
  925. $this->data[$name] = $this->autoWriteTimestamp($name);
  926. $this->data['delete_user_id'] = UserModel::userInfo('id');
  927. $result = $this->isUpdate()->save();
  928. } else {
  929. // 强制删除当前模型数据
  930. $result = $this->getQuery()->where($this->getWhere())->delete();
  931. }
  932. // 关联删除
  933. if (!empty($this->relationWrite)) {
  934. foreach ($this->relationWrite as $key => $name) {
  935. $name = is_numeric($key) ? $name : $key;
  936. $result = $this->getRelation($name);
  937. if ($result instanceof Model) {
  938. $result->delete();
  939. } elseif ($result instanceof Collection || is_array($result)) {
  940. foreach ($result as $model) {
  941. $model->delete();
  942. }
  943. }
  944. }
  945. }
  946. $this->trigger('after_delete', $this);
  947. // 清空原始数据
  948. $this->origin = [];
  949. return $result;
  950. }
  951. /**
  952. * 获取系统信息
  953. *
  954. * @param $id
  955. * @return array
  956. * @throws \think\db\exception\DataNotFoundException
  957. * @throws \think\db\exception\ModelNotFoundException
  958. * @throws \think\exception\DbException
  959. */
  960. public function getSystemInfo($id)
  961. {
  962. # 产品
  963. $product = Db::name('crm_product')->field(['create_user_id','owner_user_id', 'create_time', 'update_time'])->where('product_id', $id)->find();
  964. # 创建人
  965. $realname = Db::name('admin_user')->where('id', $product['create_user_id'])->value('realname');
  966. # zjf 20210726
  967. $userModel = new \app\admin\model\User();
  968. $ownerUserInfo = $userModel->getUserById($product['owner_user_id']);
  969. # 负责人部门
  970. $ownerStructureName = $ownerUserInfo['structure_name'];
  971. # 负责人
  972. $ownerUserName = $ownerUserInfo['realname'];
  973. return [
  974. 'create_user_id' => $realname,
  975. 'owner_user_id' => $ownerUserName,
  976. 'create_time' => date('Y-m-d H:i:s', $product['create_time']),
  977. 'update_time' => date('Y-m-d H:i:s', $product['update_time']),
  978. 'owner_user_structure_name' => $ownerStructureName
  979. ];
  980. }
  981. /**
  982. * 转移
  983. *
  984. * @param $param
  985. * @return int|string
  986. * @throws \think\Exception
  987. * @throws \think\exception\PDOException
  988. */
  989. public function transfer($param)
  990. {
  991. return Db::name('crm_product')->whereIn('product_id', $param['product_id'])->update(['owner_user_id' => $param['owner_user_id']]);
  992. }
  993. }