Merchant.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  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. $result = false;
  279. $errorMsg = '';
  280. // 事务
  281. Db::startTrans();
  282. try {
  283. // 准备更新数据
  284. $updateData = [
  285. 'merchant_name' => $param['merchant_name'],
  286. 'merchant_code' => $param['merchant_code'],
  287. 'contact_person' => $param['contact_person'] ?? '',
  288. 'contact_phone' => $param['contact_phone'] ?? '',
  289. 'address' => $param['address'] ?? '',
  290. 'email' => $param['email'] ?? '',
  291. 'status' => isset($param['status']) ? intval($param['status']) : $originalData['status'],
  292. 'remark' => $param['remark'] ?? '',
  293. 'updateTime' => date('Y-m-d H:i:s')
  294. ];
  295. // 检查是否真的有修改(核心修复:空值和null统一对比)
  296. $checkUpdateData = $updateData;
  297. unset($checkUpdateData['updateTime']);
  298. $hasChanges = false;
  299. foreach ($checkUpdateData as $key => $newVal) {
  300. $oldVal = $originalData[$key] ?? '';
  301. // 统一转成字符串对比,解决 null / 0 / '' 对比不一致问题
  302. $newVal = (string)$newVal;
  303. $oldVal = (string)$oldVal;
  304. if ($newVal !== $oldVal) {
  305. $hasChanges = true;
  306. break;
  307. }
  308. }
  309. // ====================== 核心修复 ======================
  310. // 没有任何修改 → 直接返回成功!
  311. if (!$hasChanges) {
  312. Db::rollback();
  313. $this->success('数据未发生变化');
  314. }
  315. // 执行更新
  316. $updateResult = \db('product_merchant')
  317. ->where('id', $id)
  318. ->update($updateData);
  319. if ($updateResult === false) {
  320. throw new \Exception('商户信息更新失败');
  321. }
  322. // 操作人
  323. $operator = $param['createName'] ?? '系统';
  324. $operatorCode = $param['createCode'] ?? '';
  325. // 日志内容(兼容方法不存在)
  326. if (method_exists($this, 'prepareOldValueForLog')) {
  327. $oldValue = $this->prepareOldValueForLog($originalData, $checkUpdateData);
  328. $newValue = $this->prepareNewValueForLog($checkUpdateData, $originalData);
  329. } else {
  330. $oldValue = json_encode($originalData, JSON_UNESCAPED_UNICODE);
  331. $newValue = json_encode($checkUpdateData, JSON_UNESCAPED_UNICODE);
  332. }
  333. // 日志
  334. $logData = [
  335. 'ModifyUser' => $operator,
  336. 'UserCode' => $operatorCode,
  337. 'ModifyTime' => date('Y-m-d H:i:s'),
  338. 'MerchantName' => $param['merchant_name'],
  339. 'MerchantCode' => $param['merchant_code'],
  340. 'Type' => '修改商户',
  341. 'OldValue' => $oldValue,
  342. 'NewValue' => $newValue,
  343. ];
  344. $logResult = \db('merchant_log')->insert($logData);
  345. if (!$logResult) {
  346. throw new \Exception('操作日志记录失败');
  347. }
  348. Db::commit();
  349. $result = true;
  350. } catch (\Exception $e) {
  351. Db::rollback();
  352. $errorMsg = $e->getMessage();
  353. }
  354. $this->success('修改成功');
  355. }
  356. private function codeList($key)
  357. {
  358. $data = [
  359. 'merchant_name' => '商户名称',
  360. 'merchant_code' => '商户编码',
  361. 'contact_person' => '联系人',
  362. 'contact_phone' => '联系电话',
  363. 'address' => '地址',
  364. 'email' => '邮箱',
  365. 'status' => '状态',
  366. 'remark' => '备注',
  367. ];
  368. return $data[$key] ?? '';
  369. }
  370. /**
  371. * 准备日志中的旧值(只记录有变化的字段)
  372. * @param array $originalData 原始数据
  373. * @param array $newData 新数据
  374. * @return string JSON格式的旧值
  375. */
  376. private function prepareOldValueForLog($originalData, $newData)
  377. {
  378. $changedFields = [];
  379. foreach ($newData as $key => $newValue) {
  380. $oldValue = $originalData[$key] ?? '';
  381. if ($newValue != $oldValue) {
  382. $item = $this->codeList($key);
  383. $changedFields[$item] = $oldValue;
  384. }
  385. }
  386. return !empty($changedFields) ? json_encode($changedFields, JSON_UNESCAPED_UNICODE) : '';
  387. }
  388. /**
  389. * 准备日志中的新值(只记录有变化的字段)
  390. * @param array $newData 新数据
  391. * @param array $originalData 原始数据
  392. * @return string JSON格式的新值
  393. */
  394. private function prepareNewValueForLog($newData, $originalData)
  395. {
  396. $changedFields = [];
  397. foreach ($newData as $key => $newValue) {
  398. $oldValue = $originalData[$key] ?? '';
  399. if ($newValue != $oldValue) {
  400. $item = $this->codeList($key);
  401. $changedFields[$item] = $newValue;
  402. }
  403. }
  404. return !empty($changedFields) ? json_encode($changedFields, JSON_UNESCAPED_UNICODE) : '';
  405. }
  406. /**
  407. * 商户删除
  408. * @return \think\response\Json
  409. */
  410. public function merchantDelete()
  411. {
  412. if (!$this->request->isGet()) {
  413. $this->error('请求错误');
  414. }
  415. $param = $this->request->param();
  416. // 移除参数两端的空格
  417. $param = array_map(function ($value) {
  418. return is_string($value) ? trim($value) : $value;
  419. }, $param);
  420. if (empty($param['id'])) {
  421. $this->error('请选择要删除的商户');
  422. }
  423. // 获取操作人信息(可以根据业务需要调整)
  424. $operator = $param['operator'] ?? $param['updateName'] ?? $param['createName'] ?? '系统';
  425. // 支持单个ID或逗号分隔的多个ID
  426. if (is_string($param['id'])) {
  427. $idList = explode(',', $param['id']);
  428. $idList = array_filter(array_map('intval', $idList));
  429. } else {
  430. $idList = [intval($param['id'])];
  431. }
  432. if (empty($idList)) {
  433. $this->error('参数错误:商户ID无效');
  434. }
  435. // 使用事务确保数据一致性
  436. Db::startTrans();
  437. try {
  438. // 查询要删除的商户信息(用于日志记录)
  439. $merchantList = \db('product_merchant')
  440. ->whereIn('id', $idList)
  441. ->whereNull('deleteTime')
  442. ->field(['id', 'merchant_name', 'merchant_code', 'contact_person', 'status'])
  443. ->select();
  444. if (empty($merchantList)) {
  445. Db::rollback();
  446. $this->error('未找到要删除的商户记录或商户已被删除');
  447. }
  448. $deleteTime = date('Y-m-d H:i:s');
  449. // 执行软删除操作
  450. $result = \db('product_merchant')
  451. ->whereIn('id', $idList)
  452. ->whereNull('deleteTime')
  453. ->update([
  454. 'deleteTime' => $deleteTime,
  455. 'updateTime' => $deleteTime
  456. ]);
  457. if ($result === false) {
  458. throw new \Exception('商户信息删除失败');
  459. }
  460. // 批量记录删除日志
  461. $logData = [];
  462. foreach ($merchantList as $merchant) {
  463. $logData[] = [
  464. 'ModifyUser' => $operator,
  465. 'UserCode' => $param['createCode'],
  466. 'ModifyTime' => $deleteTime,
  467. 'MerchantName' => $merchant['merchant_name'] ?? '未知商户',
  468. 'MerchantCode' => $merchant['merchant_code'] ?? '',
  469. 'Type' => '删除商户'
  470. ];
  471. }
  472. // 批量插入日志数据
  473. if (!empty($logData)) {
  474. $logResult = \db('merchant_log')->insertAll($logData);
  475. if (!$logResult) {
  476. throw new \Exception('操作日志记录失败');
  477. }
  478. }
  479. // 提交事务
  480. Db::commit();
  481. // 返回成功信息
  482. $successCount = count($merchantList);
  483. $res = true;
  484. } catch (\Exception $e) {
  485. Db::rollback();
  486. $errorMsg = $e->getMessage();
  487. }
  488. // 事务结束后再返回结果
  489. if ($res) {
  490. $this->success('删除成功','成功'.$successCount.'条');
  491. } else {
  492. $this->error('删除失败:' . $errorMsg);
  493. }
  494. }
  495. /**
  496. * 商户状态修改
  497. * 用于单独修改商户的启用/禁用状态
  498. *
  499. * @return \think\response\Json
  500. */
  501. public function merchantChangeStatus()
  502. {
  503. if (!$this->request->isGet()) {
  504. $this->error('请求错误');
  505. }
  506. $param = $this->request->param();
  507. // 移除参数两端的空格
  508. $param = array_map(function ($value) {
  509. return is_string($value) ? trim($value) : $value;
  510. }, $param);
  511. // 验证必填字段
  512. if (empty($param['id'])) {
  513. $this->error('商户ID不能为空');
  514. }
  515. if (!isset($param['status'])) {
  516. $this->error('状态值不能为空');
  517. }
  518. $id = intval($param['id']);
  519. $status = intval($param['status']);
  520. // 验证状态值合法性
  521. if (!in_array($status, [0, 1])) {
  522. $this->error('状态值无效,只能为0(禁用)或1(启用)');
  523. }
  524. // 检查商户是否存在
  525. $originalData = \db('product_merchant')
  526. ->where([
  527. 'id' => $id,
  528. 'deleteTime' => null])
  529. ->field(['id', 'merchant_name', 'merchant_code', 'status', 'contact_person'])
  530. ->find();
  531. if (!$originalData) {
  532. $this->error('商户不存在或已被删除');
  533. }
  534. // 检查状态是否有变化
  535. $oldStatus = intval($originalData['status']);
  536. if ($oldStatus === $status) {
  537. $this->error('状态未发生变化');
  538. }
  539. // 获取操作人信息
  540. $operator = $param['operator'] ?? $param['updateName'] ?? $param['createName'] ?? '系统';
  541. // 获取状态描述
  542. $statusMap = [
  543. 0 => '禁用',
  544. 1 => '正常'
  545. ];
  546. $oldStatusText = $statusMap[$oldStatus] ?? '未知';
  547. $newStatusText = $statusMap[$status] ?? '未知';
  548. // 使用事务确保数据一致性
  549. Db::startTrans();
  550. try {
  551. $updateTime = date('Y-m-d H:i:s');
  552. // 执行状态更新
  553. $result = \db('product_merchant')
  554. ->where('id', $id)
  555. ->whereNull('deleteTime')
  556. ->update([
  557. 'status' => $status,
  558. 'updateTime' => $updateTime
  559. ]);
  560. if ($result === false) {
  561. throw new \Exception('状态更新失败');
  562. }
  563. // 准备日志数据
  564. $logData = [
  565. 'ModifyUser' => $operator,
  566. 'UserCode' => $param['code'],
  567. 'ModifyTime' => $updateTime,
  568. 'MerchantName' => $originalData['merchant_name'],
  569. 'MerchantCode' => $originalData['merchant_code'],
  570. 'Type' => '修改状态',
  571. 'OldValue' => json_encode([
  572. '状态' => $oldStatusText,
  573. '商户名称' => $originalData['merchant_name'] ?? '',
  574. '商户编码' => $originalData['merchant_code'] ?? ''
  575. ], JSON_UNESCAPED_UNICODE),
  576. 'NewValue' => json_encode([
  577. '状态' => $newStatusText,
  578. '商户名称' => $originalData['merchant_name'] ?? '',
  579. '商户编码' => $originalData['merchant_code'] ?? '',
  580. '修改时间' => $updateTime
  581. ], JSON_UNESCAPED_UNICODE),
  582. ];
  583. // 插入日志数据
  584. $logResult = \db('merchant_log')->insert($logData);
  585. if (!$logResult) {
  586. throw new \Exception('操作日志记录失败');
  587. }
  588. // 提交事务
  589. Db::commit();
  590. $result = true;
  591. } catch (\Exception $e) {
  592. Db::rollback();
  593. $errorMsg = $e->getMessage();
  594. }
  595. // 事务结束后再返回结果
  596. if ($result) {
  597. $this->success('更新状态成功');
  598. } else {
  599. $this->error('更新状态失败:' . $errorMsg);
  600. }
  601. }
  602. /**
  603. * 批量修改商户状态
  604. * 用于同时修改多个商户的状态
  605. *
  606. * @return \think\response\Json
  607. */
  608. public function merchantBatchChangeStatus()
  609. {
  610. if (!$this->request->isGet()) {
  611. $this->error('请求错误');
  612. }
  613. $param = $this->request->param();
  614. // 移除参数两端的空格
  615. $param = array_map(function ($value) {
  616. return is_string($value) ? trim($value) : $value;
  617. }, $param);
  618. // 验证必填字段
  619. if (empty($param['ids'])) {
  620. $this->error('请选择要修改的商户');
  621. }
  622. if (!isset($param['status'])) {
  623. $this->error('状态值不能为空');
  624. }
  625. // 解析商户ID列表
  626. if (is_string($param['ids'])) {
  627. $idList = explode(',', $param['ids']);
  628. $idList = array_filter(array_map('intval', $idList));
  629. } elseif (is_array($param['ids'])) {
  630. $idList = array_filter(array_map('intval', $param['ids']));
  631. } else {
  632. $this->error('商户ID参数格式错误');
  633. }
  634. if (empty($idList)) {
  635. $this->error('请选择有效的商户');
  636. }
  637. $status = intval($param['status']);
  638. // 验证状态值合法性
  639. if (!in_array($status, [0, 1])) {
  640. $this->error('状态值无效,只能为0(禁用)或1(启用)');
  641. }
  642. // 获取操作人信息
  643. $operator = $param['operator'] ?? $param['updateName'] ?? $param['createName'] ?? '系统';
  644. // 获取状态描述
  645. $statusMap = [
  646. 0 => '禁用',
  647. 1 => '正常'
  648. ];
  649. $newStatusText = $statusMap[$status] ?? '未知';
  650. // 使用事务确保数据一致性
  651. Db::startTrans();
  652. try {
  653. // 查询要修改的商户信息
  654. $merchantList = \db('product_merchant')
  655. ->whereIn('id', $idList)
  656. ->whereNull('deleteTime')
  657. ->field(['id', 'merchant_name', 'merchant_code', 'status', 'contact_person'])
  658. ->select();
  659. if (empty($merchantList)) {
  660. Db::rollback();
  661. $this->error('未找到有效的商户记录或商户已被删除');
  662. }
  663. $updateTime = date('Y-m-d H:i:s');
  664. // 执行批量状态更新
  665. $result = \db('product_merchant')
  666. ->whereIn('id', $idList)
  667. ->whereNull('deleteTime')
  668. ->update([
  669. 'status' => $status,
  670. 'updateTime' => $updateTime
  671. ]);
  672. if ($result === false) {
  673. throw new \Exception('批量状态更新失败');
  674. }
  675. // 批量记录操作日志
  676. $logData = [];
  677. $successCount = 0;
  678. $statusChangedCount = 0;
  679. foreach ($merchantList as $merchant) {
  680. $oldStatus = intval($merchant['status']);
  681. // 如果状态没有变化,不记录日志
  682. if ($oldStatus === $status) {
  683. $successCount++;
  684. continue;
  685. }
  686. $oldStatusText = $statusMap[$oldStatus] ?? '未知';
  687. $logData[] = [
  688. 'ModifyUser' => $operator,
  689. 'UserCode' => $param['code'],
  690. 'ModifyTime' => $updateTime,
  691. 'MerchantName' => $merchant['merchant_name'],
  692. 'MerchantCode' => $merchant['merchant_code'],
  693. 'Type' => '批量修改状态',
  694. 'OldValue' => json_encode([
  695. '状态' => $oldStatusText,
  696. '商户名称' => $merchant['merchant_name'] ?? '',
  697. '商户编码' => $merchant['merchant_code'] ?? ''
  698. ], JSON_UNESCAPED_UNICODE),
  699. 'NewValue' => json_encode([
  700. '状态' => $newStatusText,
  701. '商户名称' => $merchant['merchant_name'] ?? '',
  702. '商户编码' => $merchant['merchant_code'] ?? '',
  703. '修改时间' => $updateTime
  704. ], JSON_UNESCAPED_UNICODE)
  705. ];
  706. $successCount++;
  707. $statusChangedCount++;
  708. }
  709. // 如果有状态变化的记录,插入日志
  710. if (!empty($logData)) {
  711. $logResult = \db('merchant_log')->insertAll($logData);
  712. if (!$logResult) {
  713. throw new \Exception('操作日志记录失败');
  714. }
  715. }
  716. // 提交事务
  717. Db::commit();
  718. // 返回操作结果
  719. $message = "操作完成,共处理 {$successCount} 个商户";
  720. if ($statusChangedCount > 0) {
  721. $message .= ",其中 {$statusChangedCount} 个商户状态已修改为 {$newStatusText}";
  722. } else {
  723. $message .= ",状态均未发生变化";
  724. }
  725. $result = true;
  726. } catch (\Exception $e) {
  727. Db::rollback();
  728. $errorMsg = $e->getMessage();
  729. }
  730. // 事务结束后再返回结果
  731. if ($result) {
  732. $this->success('更新状态成功', $message);
  733. } else {
  734. $this->error('更新状态失败:' . $errorMsg);
  735. }
  736. }
  737. /**
  738. * 操作日志数据列表
  739. * @return void
  740. * @throws \think\db\exception\DataNotFoundException
  741. * @throws \think\db\exception\ModelNotFoundException
  742. * @throws \think\exception\DbException
  743. */
  744. public function LogList()
  745. {
  746. if (!$this->request->isGet()) {
  747. $this->error('请求错误');
  748. }
  749. $param = $this->request->param();
  750. if (!isset($param['code'])) {
  751. $this->error('参数错误');
  752. }
  753. $logList = \db('merchant_log')
  754. ->where('UserCode',$param['code'])
  755. ->field([
  756. 'UserCode as 操作用户账号',
  757. 'ModifyUser as 操作用户名',
  758. 'MerchantName as 被操作商户',
  759. 'OldValue as 原数据',
  760. 'NewValue as 操作后数据',
  761. 'Type as 操作类型',
  762. 'ModifyTime as 操作时间',
  763. ])
  764. ->order('ModifyTime DESC')
  765. ->select();
  766. if (empty($logList)) {
  767. $this->error('没有商户操作日志');
  768. }else{
  769. $this->success('成功', $logList);
  770. }
  771. }
  772. }