Customer.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. <?php
  2. namespace app\admin\controller;
  3. use app\admin\model\Customer as CustomerModel;
  4. use app\common\controller\Backend;
  5. use think\Db;
  6. use think\exception\PDOException;
  7. use think\exception\ValidateException;
  8. use Exception;
  9. /**
  10. * 客户管理(customer 表,含 H5 登录账号)
  11. *
  12. * @icon fa fa-circle-o
  13. */
  14. class Customer extends Backend
  15. {
  16. /**
  17. * @var \app\admin\model\Customer
  18. */
  19. protected $model = null;
  20. /** 顶部搜索框:多字段模糊匹配(OR + LIKE) */
  21. protected $searchFields = 'company_name,username,account,email,phone,company_type,status';
  22. protected $noNeedRight = ['company_type_options', 'companyTypeOptions'];
  23. public function _initialize()
  24. {
  25. parent::_initialize();
  26. $this->ensureMonthlyScoreColumn();
  27. $this->model = new CustomerModel;
  28. $this->view->assign('statusList', $this->model->getStatusList());
  29. $action = strtolower((string)$this->request->action());
  30. if (in_array($action, ['add', 'edit'], true)) {
  31. try {
  32. $list = $this->collectDistinctCompanyTypes();
  33. } catch (\Throwable $e) {
  34. $list = [];
  35. }
  36. $this->assign('companyTypeOptions', $list);
  37. }
  38. }
  39. /** customer.monthly_score 月度评分 */
  40. protected function ensureMonthlyScoreColumn(): void
  41. {
  42. try {
  43. $cols = Db::query("SHOW COLUMNS FROM `customer` LIKE 'monthly_score'");
  44. if (!is_array($cols) || $cols === []) {
  45. Db::execute(
  46. "ALTER TABLE `customer` ADD COLUMN `monthly_score` int DEFAULT NULL COMMENT '月度评分' AFTER `score`"
  47. );
  48. }
  49. } catch (\Throwable $e) {
  50. }
  51. }
  52. /**
  53. * @return int|null
  54. */
  55. protected function parseCustomerScoreInt($raw, string $label)
  56. {
  57. $raw = trim((string)$raw);
  58. if ($raw === '') {
  59. return null;
  60. }
  61. if (!preg_match('/^-?\d+$/', $raw)) {
  62. $this->error($label . '须为整数');
  63. }
  64. return (int)$raw;
  65. }
  66. public function companyTypeOptions()
  67. {
  68. try {
  69. $list = $this->collectDistinctCompanyTypes();
  70. } catch (\Throwable $e) {
  71. $list = [];
  72. }
  73. return json(['code' => 1, 'msg' => '', 'data' => ['list' => $list]]);
  74. }
  75. /**
  76. * @return string[]
  77. */
  78. protected function collectDistinctCompanyTypes(): array
  79. {
  80. $rows = Db::name('customer')->column('company_type');
  81. if (!is_array($rows)) {
  82. return [];
  83. }
  84. $set = [];
  85. foreach ($rows as $v) {
  86. $v = trim((string)$v);
  87. if ($v === '') {
  88. continue;
  89. }
  90. foreach (preg_split('/[、,,]+/u', $v) as $p) {
  91. $p = trim($p);
  92. if ($p !== '') {
  93. $set[$p] = true;
  94. }
  95. }
  96. }
  97. $list = array_keys($set);
  98. sort($list, SORT_STRING);
  99. return $list;
  100. }
  101. public function index()
  102. {
  103. $this->relationSearch = false;
  104. $this->request->filter(['strip_tags', 'trim']);
  105. if ($this->request->isAjax()) {
  106. if ($this->request->request('keyField')) {
  107. return $this->selectpage();
  108. }
  109. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  110. $list = $this->model
  111. ->where($where)
  112. ->order($sort, $order)
  113. ->paginate($limit);
  114. foreach ($list as $row) {
  115. $row->visible([
  116. 'id', 'company_name', 'username', 'account', 'email', 'phone', 'score', 'monthly_score', 'company_type',
  117. 'createtime', 'updatetime', 'status',
  118. ]);
  119. }
  120. return json(['total' => $list->total(), 'rows' => $list->items()]);
  121. }
  122. return $this->view->fetch();
  123. }
  124. public function add()
  125. {
  126. if (false === $this->request->isPost()) {
  127. return $this->view->fetch();
  128. }
  129. $params = $this->request->post('row/a');
  130. if (empty($params)) {
  131. $this->error(__('Parameter %s can not be empty', ''));
  132. }
  133. $params = $this->preExcludeFields($params);
  134. $phone = trim((string)($params['phone'] ?? ''));
  135. $phone = str_replace([',', ';', ';', '|', '|', "\n", "\r", "\t"], ',', $phone);
  136. if (strpos($phone, ',') !== false) {
  137. $phone = trim(explode(',', $phone)[0]);
  138. }
  139. if ($phone === '') {
  140. $this->error('请填写手机号');
  141. }
  142. if (!preg_match('/^1\d{10}$/', $phone)) {
  143. $this->error('手机号须为11位');
  144. }
  145. $account = trim((string)($params['account'] ?? ''));
  146. if ($account === '') {
  147. $account = $phone;
  148. }
  149. if (!preg_match('/^1\d{10}$/', $account)) {
  150. $this->error('登录账号须为11位手机号');
  151. }
  152. if (Db::name('customer')->where('phone', $phone)->find()) {
  153. $this->error('该手机号已存在');
  154. }
  155. if (Db::name('customer')->where('account', $account)->find()) {
  156. $this->error('该登录账号已存在');
  157. }
  158. $email = trim((string)($params['email'] ?? ''));
  159. $email = str_replace([',', ';', ';', '|', '|', "\n", "\r", "\t"], ',', $email);
  160. if (strpos($email, ',') !== false) {
  161. $email = trim(explode(',', $email)[0]);
  162. }
  163. $pwd = trim((string)($params['password'] ?? ''));
  164. if ($pwd === '') {
  165. $pwd = $phone;
  166. }
  167. $status = isset($params['status']) ? (string)$params['status'] : '';
  168. if ($status === '') {
  169. $status = '1';
  170. }
  171. $score = $this->parseCustomerScoreInt($params['score'] ?? '', '综合评分');
  172. $monthlyScore = $this->parseCustomerScoreInt($params['monthly_score'] ?? '', '月度评分');
  173. $now = date('Y-m-d H:i:s');
  174. $data = [
  175. 'company_name' => trim((string)($params['company_name'] ?? '')),
  176. 'username' => trim((string)($params['username'] ?? '')),
  177. 'phone' => $phone,
  178. 'account' => $account,
  179. 'email' => $email,
  180. 'password' => md5(md5($pwd)),
  181. 'score' => $score,
  182. 'monthly_score' => $monthlyScore,
  183. 'company_type' => trim((string)($params['company_type'] ?? '')),
  184. 'status' => $status,
  185. 'createtime' => $now,
  186. 'updatetime' => $now,
  187. ];
  188. if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
  189. $data[$this->dataLimitField] = $this->auth->id;
  190. }
  191. $v = validate('app\\admin\\validate\\Customer');
  192. if (!$v->scene('add')->check($data)) {
  193. $this->error($v->getError());
  194. }
  195. try {
  196. Db::name('customer')->insert($data);
  197. } catch (PDOException|Exception $e) {
  198. $this->error($e->getMessage());
  199. }
  200. $this->success();
  201. }
  202. public function edit($ids = null)
  203. {
  204. $row = $this->model->get($ids);
  205. if (!$row) {
  206. $this->error(__('No Results were found'));
  207. }
  208. $adminIds = $this->getDataLimitAdminIds();
  209. if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
  210. $this->error(__('You have no permission'));
  211. }
  212. if (false === $this->request->isPost()) {
  213. $this->view->assign('row', $row);
  214. return $this->view->fetch();
  215. }
  216. $params = $this->request->post('row/a');
  217. if (empty($params)) {
  218. $this->error(__('Parameter %s can not be empty', ''));
  219. }
  220. $params = $this->preExcludeFields($params);
  221. $rowId = (int)$row['id'];
  222. $phone = trim((string)($params['phone'] ?? ''));
  223. $phone = str_replace([',', ';', ';', '|', '|', "\n", "\r", "\t"], ',', $phone);
  224. if (strpos($phone, ',') !== false) {
  225. $phone = trim(explode(',', $phone)[0]);
  226. }
  227. if ($phone === '') {
  228. $this->error('请填写手机号');
  229. }
  230. if (!preg_match('/^1\d{10}$/', $phone)) {
  231. $this->error('手机号须为11位');
  232. }
  233. $account = trim((string)($params['account'] ?? ''));
  234. if ($account === '') {
  235. $account = $phone;
  236. }
  237. if (!preg_match('/^1\d{10}$/', $account)) {
  238. $this->error('登录账号须为11位手机号');
  239. }
  240. if (Db::name('customer')->where('phone', $phone)->where('id', '<>', $rowId)->find()) {
  241. $this->error('该手机号已存在');
  242. }
  243. if (Db::name('customer')->where('account', $account)->where('id', '<>', $rowId)->find()) {
  244. $this->error('该登录账号已存在');
  245. }
  246. $email = trim((string)($params['email'] ?? ''));
  247. $email = str_replace([',', ';', ';', '|', '|', "\n", "\r", "\t"], ',', $email);
  248. if (strpos($email, ',') !== false) {
  249. $email = trim(explode(',', $email)[0]);
  250. }
  251. $status = isset($params['status']) ? (string)$params['status'] : '1';
  252. if ($status === '') {
  253. $status = '1';
  254. }
  255. $score = $this->parseCustomerScoreInt($params['score'] ?? '', '综合评分');
  256. $monthlyScore = $this->parseCustomerScoreInt($params['monthly_score'] ?? '', '月度评分');
  257. $data = [
  258. 'id' => $rowId,
  259. 'company_name' => trim((string)($params['company_name'] ?? '')),
  260. 'username' => trim((string)($params['username'] ?? '')),
  261. 'phone' => $phone,
  262. 'account' => $account,
  263. 'email' => $email,
  264. 'score' => $score,
  265. 'monthly_score' => $monthlyScore,
  266. 'company_type' => trim((string)($params['company_type'] ?? '')),
  267. 'status' => $status,
  268. 'updatetime' => date('Y-m-d H:i:s'),
  269. ];
  270. $pwd = trim((string)($params['password'] ?? ''));
  271. if ($pwd !== '') {
  272. $data['password'] = md5(md5($pwd));
  273. }
  274. $v = validate('app\\admin\\validate\\Customer');
  275. if (!$v->scene('edit')->check($data)) {
  276. $this->error($v->getError());
  277. }
  278. unset($data['id']);
  279. try {
  280. $aff = Db::name('customer')->where('id', $rowId)->update($data);
  281. } catch (PDOException|Exception $e) {
  282. $this->error($e->getMessage());
  283. }
  284. if ($aff === false) {
  285. $this->error(__('No rows were updated'));
  286. }
  287. $this->success();
  288. }
  289. }