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