Merchant.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use think\Db;
  5. use think\Request;
  6. use function fast\e;
  7. /**
  8. * 商户产品
  9. */
  10. class Merchant extends Api
  11. {
  12. protected $noNeedLogin = ['*'];
  13. protected $noNeedRight = ['*'];
  14. /**
  15. * 商户列表
  16. * @return \think\response\Json
  17. * @throws \think\Exception
  18. * @throws \think\db\exception\DataNotFoundException
  19. * @throws \think\db\exception\ModelNotFoundException
  20. * @throws \think\exception\DbException
  21. */
  22. public function merchantList()
  23. {
  24. // 验证请求方法
  25. if (!$this->request->isGet()) {
  26. $this->error('请求错误');
  27. }
  28. // 获取并验证参数
  29. $param = $this->request->param();
  30. $page = max(1, intval($param['page'] ?? 1));
  31. $limit = max(20, min(100, intval($param['limit'] ?? 20)));
  32. $where = ['deleteTime' => null];
  33. // 添加搜索条件
  34. if (!empty($param['merchant_name'])) {
  35. $where[] = ['merchant_name|merchant_code', 'like', '%' . trim($param['search']) . '%'];
  36. }
  37. // 查询总数
  38. $count = \db('product_merchant')
  39. ->where($where)
  40. ->count();
  41. // 查询分页数据
  42. $list = \db('product_merchant')
  43. ->field([
  44. 'id',
  45. 'merchant_name as 商户名',
  46. 'merchant_code as 商户编码',
  47. 'contact_person as 联系人',
  48. 'contact_phone as 联系电话',
  49. 'address as 地址',
  50. 'email as 邮箱',
  51. 'status',
  52. 'remark as 备注',
  53. 'createTime as 创建时间',
  54. 'createName as 创建人',
  55. 'updateTime as 更新时间'
  56. ])
  57. ->where($where)
  58. ->page($page, $limit)
  59. ->order('id', 'desc')
  60. ->select();
  61. // 处理状态显示转换
  62. if ($list) {
  63. $statusMap = [
  64. 0 => ['text' => '禁用', 'type' => 'danger'],
  65. 1 => ['text' => '正常', 'type' => 'success']
  66. ];
  67. foreach ($list as &$item) {
  68. // 转换状态显示
  69. if (isset($item['status']) && array_key_exists($item['status'], $statusMap)) {
  70. $item['状态'] = $statusMap[$item['status']]['text'];
  71. $item['status_type'] = $statusMap[$item['status']]['type'];
  72. $item['status_value'] = $item['status'];
  73. } else {
  74. $item['状态'] = '未知';
  75. $item['status_type'] = 'info';
  76. $item['status_value'] = $item['status'] ?? -1;
  77. }
  78. if (!empty($item['创建时间'])) {
  79. $item['创建时间'] = date('Y-m-d H:i', strtotime($item['创建时间']));
  80. }
  81. if (!empty($item['更新时间'])) {
  82. $item['更新时间'] = date('Y-m-d H:i', strtotime($item['更新时间']));
  83. }
  84. }
  85. unset($item);
  86. }
  87. $data = [
  88. 'count' => $count,
  89. 'data' => $list
  90. ];
  91. $this->success('成功', $data);
  92. }
  93. /**
  94. * 商户详情
  95. * @return \think\response\Json
  96. * @throws \think\Exception
  97. * @throws \think\db\exception\DataNotFoundException
  98. * @throws \think\db\exception\ModelNotFoundException
  99. * @throws \think\exception\DbException
  100. */
  101. public function merchantDetail()
  102. {
  103. if (!$this->request->isGet()) {
  104. $this->error('请求错误');
  105. }
  106. $id = $this->request->param('id');
  107. if (empty($id)) {
  108. $this->error('参数错误');
  109. }
  110. $merchant = \db('product_merchant')
  111. ->field([
  112. 'id',
  113. 'merchant_name as 商户名称',
  114. 'merchant_code as 商户编码',
  115. 'contact_person as 联系人',
  116. 'contact_phone as 联系号码',
  117. 'address as 地址',
  118. 'email as 邮箱',
  119. 'remark as 备注'
  120. ])
  121. ->where([
  122. 'id' => $id,
  123. 'deleteTime' => null
  124. ])
  125. ->find();
  126. if (!$merchant) {
  127. $this->error('商户不存在或已被删除');
  128. }
  129. $this->success('success', $merchant);
  130. }
  131. /**
  132. * 商户添加
  133. * @return \think\response\Json
  134. */
  135. public function merchantAdd()
  136. {
  137. if (!$this->request->isPost()) {
  138. $this->error('请求错误');
  139. }
  140. $param = $this->request->post();
  141. // 移除参数两端的空格
  142. $param = array_map(function ($value) {
  143. return is_string($value) ? trim($value) : $value;
  144. }, $param);
  145. // 定义验证规则
  146. $validateRules = [
  147. 'merchant_name' => 'require|max:100',
  148. 'merchant_code' => 'require|max:20|unique:product_merchant',
  149. 'contact_person' => 'max:50',
  150. 'contact_phone' => 'max:20',
  151. 'email' => 'email',
  152. 'createName' => 'require|max:50',
  153. ];
  154. // 定义验证错误信息
  155. $validateMessages = [
  156. 'merchant_name.require' => '商户名称不能为空',
  157. 'merchant_name.max' => '商户名称最多100个字符',
  158. 'merchant_code.require' => '商户编码不能为空',
  159. 'merchant_code.max' => '商户编码最多20个字符',
  160. 'merchant_code.unique' => '商户编码已存在',
  161. 'contact_person.max' => '联系人最多50个字符',
  162. 'contact_phone.max' => '联系电话最多20个字符',
  163. 'email.email' => '邮箱格式不正确',
  164. 'createName.require' => '创建人不能为空',
  165. 'createName.max' => '创建人最多50个字符',
  166. ];
  167. // 实例化验证器
  168. $validate = new \think\Validate($validateRules, $validateMessages);
  169. // 执行验证
  170. if (!$validate->check($param)) {
  171. $this->error($validate->getError());
  172. }
  173. // 使用事务确保数据一致性
  174. Db::startTrans();
  175. try {
  176. // 准备商户数据
  177. $merchantData = [
  178. 'merchant_name' => $param['merchant_name'],
  179. 'merchant_code' => $param['merchant_code'],
  180. 'contact_person' => $param['contact_person'] ?? '',
  181. 'contact_phone' => $param['contact_phone'] ?? '',
  182. 'address' => $param['address'] ?? '',
  183. 'email' => $param['email'] ?? '',
  184. 'status' => isset($param['status']) ? intval($param['status']) : 1,
  185. 'remark' => $param['remark'] ?? '',
  186. 'createName' => $param['createName'],
  187. 'createTime' => date('Y-m-d H:i:s'),
  188. 'updateTime' => date('Y-m-d H:i:s')
  189. ];
  190. // 插入商户数据
  191. $merchantId = \db('product_merchant')->insertGetId($merchantData);
  192. if (!$merchantId) {
  193. throw new \Exception('商户信息插入失败');
  194. }
  195. // 准备日志数据
  196. $logData = [
  197. 'ModifyUser' => $param['createName'],
  198. 'UserCode' => $param['createCode'],
  199. 'ModifyTime' => date('Y-m-d H:i:s'),
  200. 'MerchantName' => $param['merchant_name'],
  201. 'MerchantCode' => $param['merchant_code'],
  202. 'Type' => '新增商户',
  203. ];
  204. // 插入日志数据
  205. $logResult = \db('merchant_log')->insert($logData);
  206. if (!$logResult) {
  207. throw new \Exception('操作日志记录失败');
  208. }
  209. // 提交事务
  210. Db::commit();
  211. $result = true;
  212. } catch (\Exception $e) {
  213. Db::rollback();
  214. $errorMsg = $e->getMessage();
  215. }
  216. if ($result) {
  217. $this->success('添加成功');
  218. } else {
  219. $this->error('添加失败:' . $errorMsg);
  220. }
  221. }
  222. /**
  223. * 商户修改
  224. * @return \think\response\Json
  225. */
  226. public function merchantEdit()
  227. {
  228. if (!$this->request->isPost()) {
  229. $this->error('请求错误');
  230. }
  231. $param = $this->request->post();
  232. // 移除参数两端的空格
  233. $param = array_map(function ($value) {
  234. return is_string($value) ? trim($value) : $value;
  235. }, $param);
  236. // 验证必填字段
  237. if (empty($param['id'])) {
  238. $this->error('商户ID不能为空');
  239. }
  240. $id = intval($param['id']);
  241. // 检查商户是否存在并获取原始数据
  242. $originalData = \db('product_merchant')
  243. ->where([
  244. 'id' => $id,
  245. 'deleteTime' => null
  246. ])
  247. ->find();
  248. if (!$originalData) {
  249. $this->error('商户不存在或已被删除');
  250. }
  251. // 定义验证规则
  252. $validateRules = [
  253. 'merchant_name' => 'require|max:100',
  254. 'merchant_code' => 'require|max:20|unique:product_merchant,merchant_code,' . $id,
  255. 'contact_person' => 'max:50',
  256. 'contact_phone' => 'max:20',
  257. 'email' => 'email',
  258. 'status' => 'in:0,1',
  259. ];
  260. // 定义验证错误信息
  261. $validateMessages = [
  262. 'merchant_name.require' => '商户名称不能为空',
  263. 'merchant_name.max' => '商户名称最多100个字符',
  264. 'merchant_code.require' => '商户编码不能为空',
  265. 'merchant_code.max' => '商户编码最多20个字符',
  266. 'merchant_code.unique' => '商户编码已存在',
  267. 'contact_person.max' => '联系人最多50个字符',
  268. 'contact_phone.max' => '联系电话最多20个字符',
  269. 'email.email' => '邮箱格式不正确',
  270. ];
  271. // 实例化验证器
  272. $validate = new \think\Validate($validateRules, $validateMessages);
  273. // 执行验证
  274. if (!$validate->check($param)) {
  275. $this->error($validate->getError());
  276. }
  277. // 使用事务确保数据一致性
  278. Db::startTrans();
  279. try {
  280. // 准备更新数据
  281. $updateData = [
  282. 'merchant_name' => $param['merchant_name'],
  283. 'merchant_code' => $param['merchant_code'],
  284. 'contact_person' => $param['contact_person'] ?? '',
  285. 'contact_phone' => $param['contact_phone'] ?? '',
  286. 'address' => $param['address'] ?? '',
  287. 'email' => $param['email'] ?? '',
  288. 'remark' => $param['remark'] ?? '',
  289. 'updateTime' => date('Y-m-d H:i:s')
  290. ];
  291. // 检查是否有实际修改(排除更新时间字段)
  292. $checkUpdateData = $updateData;
  293. unset($checkUpdateData['updateTime']);
  294. $hasChanges = false;
  295. foreach ($checkUpdateData as $key => $newValue) {
  296. $oldValue = $originalData[$key] ?? '';
  297. if ($newValue != $oldValue) {
  298. $hasChanges = true;
  299. break;
  300. }
  301. }
  302. // 如果没有实际修改,直接返回成功
  303. if (!$hasChanges) {
  304. Db::rollback(); // 不需要提交事务
  305. $this->success('数据未发生变化');
  306. }
  307. // 执行更新操作
  308. $result = \db('product_merchant')
  309. ->where('id', $id)
  310. ->update($updateData);
  311. if ($result === false) {
  312. throw new \Exception('商户信息更新失败');
  313. }
  314. // 获取操作人信息(可以根据业务需要调整)
  315. $operator = $param['updateName'] ?? $param['createName'] ?? '系统';
  316. // 准备日志数据
  317. $logData = [
  318. 'ModifyUser' => $operator,
  319. 'UserCode' => $param['createCode'],
  320. 'ModifyTime' => date('Y-m-d H:i:s'),
  321. 'MerchantName' => $param['merchant_name'],
  322. 'MerchantCode' => $param['merchant_code'],
  323. 'Type' => '修改商户',
  324. 'OldValue' => $this->prepareOldValueForLog($originalData, $checkUpdateData),
  325. 'NewValue' => $this->prepareNewValueForLog($checkUpdateData, $originalData),
  326. ];
  327. // 插入日志数据
  328. $logResult = \db('merchant_log')->insert($logData);
  329. if (!$logResult) {
  330. throw new \Exception('操作日志记录失败');
  331. }
  332. // 提交事务
  333. Db::commit();
  334. $result = true;
  335. } catch (\Exception $e) {
  336. Db::rollback();
  337. $errorMsg = $e->getMessage();
  338. }
  339. // 事务结束后再返回结果
  340. if ($result) {
  341. $this->success('修改成功');
  342. } else {
  343. $this->error('修改失败:' . $errorMsg);
  344. }
  345. }
  346. private function codeList($key)
  347. {
  348. $data = [
  349. 'merchant_name' => '商户名称',
  350. 'merchant_code' => '商户编码',
  351. 'contact_person' => '联系人',
  352. 'contact_phone' => '联系电话',
  353. 'address' => '地址',
  354. 'email' => '邮箱',
  355. 'status' => '状态',
  356. 'remark' => '备注',
  357. ];
  358. return $data[$key] ?? '';
  359. }
  360. /**
  361. * 准备日志中的旧值(只记录有变化的字段)
  362. * @param array $originalData 原始数据
  363. * @param array $newData 新数据
  364. * @return string JSON格式的旧值
  365. */
  366. private function prepareOldValueForLog($originalData, $newData)
  367. {
  368. $changedFields = [];
  369. foreach ($newData as $key => $newValue) {
  370. $oldValue = $originalData[$key] ?? '';
  371. if ($newValue != $oldValue) {
  372. $item = $this->codeList($key);
  373. $changedFields[$item] = $oldValue;
  374. }
  375. }
  376. return !empty($changedFields) ? json_encode($changedFields, JSON_UNESCAPED_UNICODE) : '';
  377. }
  378. /**
  379. * 准备日志中的新值(只记录有变化的字段)
  380. * @param array $newData 新数据
  381. * @param array $originalData 原始数据
  382. * @return string JSON格式的新值
  383. */
  384. private function prepareNewValueForLog($newData, $originalData)
  385. {
  386. $changedFields = [];
  387. foreach ($newData as $key => $newValue) {
  388. $oldValue = $originalData[$key] ?? '';
  389. if ($newValue != $oldValue) {
  390. $item = $this->codeList($key);
  391. $changedFields[$item] = $newValue;
  392. }
  393. }
  394. return !empty($changedFields) ? json_encode($changedFields, JSON_UNESCAPED_UNICODE) : '';
  395. }
  396. /**
  397. * 商户删除
  398. * @return \think\response\Json
  399. */
  400. public function merchantDelete()
  401. {
  402. if (!$this->request->isGet()) {
  403. $this->error('请求错误');
  404. }
  405. $param = $this->request->param();
  406. // 移除参数两端的空格
  407. $param = array_map(function ($value) {
  408. return is_string($value) ? trim($value) : $value;
  409. }, $param);
  410. if (empty($param['id'])) {
  411. $this->error('请选择要删除的商户');
  412. }
  413. // 获取操作人信息(可以根据业务需要调整)
  414. $operator = $param['operator'] ?? $param['updateName'] ?? $param['createName'] ?? '系统';
  415. // 支持单个ID或逗号分隔的多个ID
  416. if (is_string($param['id'])) {
  417. $idList = explode(',', $param['id']);
  418. $idList = array_filter(array_map('intval', $idList));
  419. } else {
  420. $idList = [intval($param['id'])];
  421. }
  422. if (empty($idList)) {
  423. $this->error('参数错误:商户ID无效');
  424. }
  425. // 使用事务确保数据一致性
  426. Db::startTrans();
  427. try {
  428. // 查询要删除的商户信息(用于日志记录)
  429. $merchantList = \db('product_merchant')
  430. ->whereIn('id', $idList)
  431. ->whereNull('deleteTime')
  432. ->field(['id', 'merchant_name', 'merchant_code', 'contact_person', 'status'])
  433. ->select();
  434. if (empty($merchantList)) {
  435. Db::rollback();
  436. $this->error('未找到要删除的商户记录或商户已被删除');
  437. }
  438. $deleteTime = date('Y-m-d H:i:s');
  439. // 执行软删除操作
  440. $result = \db('product_merchant')
  441. ->whereIn('id', $idList)
  442. ->whereNull('deleteTime')
  443. ->update([
  444. 'deleteTime' => $deleteTime,
  445. 'updateTime' => $deleteTime
  446. ]);
  447. if ($result === false) {
  448. throw new \Exception('商户信息删除失败');
  449. }
  450. // 批量记录删除日志
  451. $logData = [];
  452. foreach ($merchantList as $merchant) {
  453. $logData[] = [
  454. 'ModifyUser' => $operator,
  455. 'UserCode' => $param['createCode'],
  456. 'ModifyTime' => $deleteTime,
  457. 'MerchantName' => $merchant['merchant_name'] ?? '未知商户',
  458. 'MerchantCode' => $merchant['merchant_code'] ?? '',
  459. 'Type' => '删除商户'
  460. ];
  461. }
  462. // 批量插入日志数据
  463. if (!empty($logData)) {
  464. $logResult = \db('merchant_log')->insertAll($logData);
  465. if (!$logResult) {
  466. throw new \Exception('操作日志记录失败');
  467. }
  468. }
  469. // 提交事务
  470. Db::commit();
  471. // 返回成功信息
  472. $successCount = count($merchantList);
  473. $res = true;
  474. } catch (\Exception $e) {
  475. Db::rollback();
  476. $errorMsg = $e->getMessage();
  477. }
  478. // 事务结束后再返回结果
  479. if ($res) {
  480. $this->success('删除成功','成功'.$successCount.'条');
  481. } else {
  482. $this->error('删除失败:' . $errorMsg);
  483. }
  484. }
  485. /**
  486. * 商户状态修改
  487. * 用于单独修改商户的启用/禁用状态
  488. *
  489. * @return \think\response\Json
  490. */
  491. public function merchantChangeStatus()
  492. {
  493. if (!$this->request->isGet()) {
  494. $this->error('请求错误');
  495. }
  496. $param = $this->request->param();
  497. // 移除参数两端的空格
  498. $param = array_map(function ($value) {
  499. return is_string($value) ? trim($value) : $value;
  500. }, $param);
  501. // 验证必填字段
  502. if (empty($param['id'])) {
  503. $this->error('商户ID不能为空');
  504. }
  505. if (!isset($param['status'])) {
  506. $this->error('状态值不能为空');
  507. }
  508. $id = intval($param['id']);
  509. $status = intval($param['status']);
  510. // 验证状态值合法性
  511. if (!in_array($status, [0, 1])) {
  512. $this->error('状态值无效,只能为0(禁用)或1(启用)');
  513. }
  514. // 检查商户是否存在
  515. $originalData = \db('product_merchant')
  516. ->where([
  517. 'id' => $id,
  518. 'deleteTime' => null])
  519. ->field(['id', 'merchant_name', 'merchant_code', 'status', 'contact_person'])
  520. ->find();
  521. if (!$originalData) {
  522. $this->error('商户不存在或已被删除');
  523. }
  524. // 检查状态是否有变化
  525. $oldStatus = intval($originalData['status']);
  526. if ($oldStatus === $status) {
  527. $this->error('状态未发生变化');
  528. }
  529. // 获取操作人信息
  530. $operator = $param['operator'] ?? $param['updateName'] ?? $param['createName'] ?? '系统';
  531. // 获取状态描述
  532. $statusMap = [
  533. 0 => '禁用',
  534. 1 => '正常'
  535. ];
  536. $oldStatusText = $statusMap[$oldStatus] ?? '未知';
  537. $newStatusText = $statusMap[$status] ?? '未知';
  538. // 使用事务确保数据一致性
  539. Db::startTrans();
  540. try {
  541. $updateTime = date('Y-m-d H:i:s');
  542. // 执行状态更新
  543. $result = \db('product_merchant')
  544. ->where('id', $id)
  545. ->whereNull('deleteTime')
  546. ->update([
  547. 'status' => $status,
  548. 'updateTime' => $updateTime
  549. ]);
  550. if ($result === false) {
  551. throw new \Exception('状态更新失败');
  552. }
  553. // 准备日志数据
  554. $logData = [
  555. 'ModifyUser' => $operator,
  556. 'UserCode' => $param['code'],
  557. 'ModifyTime' => $updateTime,
  558. 'MerchantName' => $originalData['merchant_name'],
  559. 'MerchantCode' => $originalData['merchant_code'],
  560. 'Type' => '修改状态',
  561. 'OldValue' => json_encode([
  562. '状态' => $oldStatusText,
  563. '商户名称' => $originalData['merchant_name'] ?? '',
  564. '商户编码' => $originalData['merchant_code'] ?? ''
  565. ], JSON_UNESCAPED_UNICODE),
  566. 'NewValue' => json_encode([
  567. '状态' => $newStatusText,
  568. '商户名称' => $originalData['merchant_name'] ?? '',
  569. '商户编码' => $originalData['merchant_code'] ?? '',
  570. '修改时间' => $updateTime
  571. ], JSON_UNESCAPED_UNICODE),
  572. ];
  573. // 插入日志数据
  574. $logResult = \db('merchant_log')->insert($logData);
  575. if (!$logResult) {
  576. throw new \Exception('操作日志记录失败');
  577. }
  578. // 提交事务
  579. Db::commit();
  580. $result = true;
  581. } catch (\Exception $e) {
  582. Db::rollback();
  583. $errorMsg = $e->getMessage();
  584. }
  585. // 事务结束后再返回结果
  586. if ($result) {
  587. $this->success('更新状态成功');
  588. } else {
  589. $this->error('更新状态失败:' . $errorMsg);
  590. }
  591. }
  592. /**
  593. * 批量修改商户状态
  594. * 用于同时修改多个商户的状态
  595. *
  596. * @return \think\response\Json
  597. */
  598. public function merchantBatchChangeStatus()
  599. {
  600. if (!$this->request->isGet()) {
  601. $this->error('请求错误');
  602. }
  603. $param = $this->request->param();
  604. // 移除参数两端的空格
  605. $param = array_map(function ($value) {
  606. return is_string($value) ? trim($value) : $value;
  607. }, $param);
  608. // 验证必填字段
  609. if (empty($param['ids'])) {
  610. $this->error('请选择要修改的商户');
  611. }
  612. if (!isset($param['status'])) {
  613. $this->error('状态值不能为空');
  614. }
  615. // 解析商户ID列表
  616. if (is_string($param['ids'])) {
  617. $idList = explode(',', $param['ids']);
  618. $idList = array_filter(array_map('intval', $idList));
  619. } elseif (is_array($param['ids'])) {
  620. $idList = array_filter(array_map('intval', $param['ids']));
  621. } else {
  622. $this->error('商户ID参数格式错误');
  623. }
  624. if (empty($idList)) {
  625. $this->error('请选择有效的商户');
  626. }
  627. $status = intval($param['status']);
  628. // 验证状态值合法性
  629. if (!in_array($status, [0, 1])) {
  630. $this->error('状态值无效,只能为0(禁用)或1(启用)');
  631. }
  632. // 获取操作人信息
  633. $operator = $param['operator'] ?? $param['updateName'] ?? $param['createName'] ?? '系统';
  634. // 获取状态描述
  635. $statusMap = [
  636. 0 => '禁用',
  637. 1 => '正常'
  638. ];
  639. $newStatusText = $statusMap[$status] ?? '未知';
  640. // 使用事务确保数据一致性
  641. Db::startTrans();
  642. try {
  643. // 查询要修改的商户信息
  644. $merchantList = \db('product_merchant')
  645. ->whereIn('id', $idList)
  646. ->whereNull('deleteTime')
  647. ->field(['id', 'merchant_name', 'merchant_code', 'status', 'contact_person'])
  648. ->select();
  649. if (empty($merchantList)) {
  650. Db::rollback();
  651. $this->error('未找到有效的商户记录或商户已被删除');
  652. }
  653. $updateTime = date('Y-m-d H:i:s');
  654. // 执行批量状态更新
  655. $result = \db('product_merchant')
  656. ->whereIn('id', $idList)
  657. ->whereNull('deleteTime')
  658. ->update([
  659. 'status' => $status,
  660. 'updateTime' => $updateTime
  661. ]);
  662. if ($result === false) {
  663. throw new \Exception('批量状态更新失败');
  664. }
  665. // 批量记录操作日志
  666. $logData = [];
  667. $successCount = 0;
  668. $statusChangedCount = 0;
  669. foreach ($merchantList as $merchant) {
  670. $oldStatus = intval($merchant['status']);
  671. // 如果状态没有变化,不记录日志
  672. if ($oldStatus === $status) {
  673. $successCount++;
  674. continue;
  675. }
  676. $oldStatusText = $statusMap[$oldStatus] ?? '未知';
  677. $logData[] = [
  678. 'ModifyUser' => $operator,
  679. 'UserCode' => $param['code'],
  680. 'ModifyTime' => $updateTime,
  681. 'MerchantName' => $merchant['merchant_name'],
  682. 'MerchantCode' => $merchant['merchant_code'],
  683. 'Type' => '批量修改状态',
  684. 'OldValue' => json_encode([
  685. '状态' => $oldStatusText,
  686. '商户名称' => $merchant['merchant_name'] ?? '',
  687. '商户编码' => $merchant['merchant_code'] ?? ''
  688. ], JSON_UNESCAPED_UNICODE),
  689. 'NewValue' => json_encode([
  690. '状态' => $newStatusText,
  691. '商户名称' => $merchant['merchant_name'] ?? '',
  692. '商户编码' => $merchant['merchant_code'] ?? '',
  693. '修改时间' => $updateTime
  694. ], JSON_UNESCAPED_UNICODE)
  695. ];
  696. $successCount++;
  697. $statusChangedCount++;
  698. }
  699. // 如果有状态变化的记录,插入日志
  700. if (!empty($logData)) {
  701. $logResult = \db('merchant_log')->insertAll($logData);
  702. if (!$logResult) {
  703. throw new \Exception('操作日志记录失败');
  704. }
  705. }
  706. // 提交事务
  707. Db::commit();
  708. // 返回操作结果
  709. $message = "操作完成,共处理 {$successCount} 个商户";
  710. if ($statusChangedCount > 0) {
  711. $message .= ",其中 {$statusChangedCount} 个商户状态已修改为 {$newStatusText}";
  712. } else {
  713. $message .= ",状态均未发生变化";
  714. }
  715. $result = true;
  716. } catch (\Exception $e) {
  717. Db::rollback();
  718. $errorMsg = $e->getMessage();
  719. }
  720. // 事务结束后再返回结果
  721. if ($result) {
  722. $this->success('更新状态成功', $message);
  723. } else {
  724. $this->error('更新状态失败:' . $errorMsg);
  725. }
  726. }
  727. /**
  728. * 操作日志数据列表
  729. * @return void
  730. * @throws \think\db\exception\DataNotFoundException
  731. * @throws \think\db\exception\ModelNotFoundException
  732. * @throws \think\exception\DbException
  733. */
  734. public function LogList()
  735. {
  736. if (!$this->request->isGet()) {
  737. $this->error('请求错误');
  738. }
  739. $param = $this->request->param();
  740. if (!isset($param['code'])) {
  741. $this->error('参数错误');
  742. }
  743. $logList = \db('merchant_log')
  744. ->where('UserCode',$param['code'])
  745. ->field([
  746. 'UserCode as 操作用户账号',
  747. 'ModifyUser as 操作用户名',
  748. 'MerchantName as 被操作商户',
  749. 'OldValue as 原数据',
  750. 'NewValue as 操作后数据',
  751. 'Type as 操作类型',
  752. 'ModifyTime as 操作时间',
  753. ])
  754. ->order('ModifyTime DESC')
  755. ->select();
  756. if (empty($logList)) {
  757. $this->error('没有商户操作日志');
  758. }else{
  759. $this->success('成功', $logList);
  760. }
  761. }
  762. }